diff --git a/.bazelci/aspect.yml b/.bazelci/aspect.yml index be4fa26a482..f170a74bf13 100644 --- a/.bazelci/aspect.yml +++ b/.bazelci/aspect.yml @@ -1,50 +1,6 @@ --- tasks: - Aspect-internal-stable: - name: Aspect Tests for IJ Internal Stable - platform: ubuntu2204 - build_flags: - - --define=ij_product=intellij-latest - build_targets: - - //aspect:aspect_files - test_flags: - - --define=ij_product=intellij-latest - - --test_output=errors - - --notrim_test_configuration - test_targets: - - //aspect/testing/... - skip_use_bazel_version_for_test: true - Aspect-internal-beta: - name: Aspect Tests for IJ Internal Beta - platform: ubuntu2204 - build_flags: - - --define=ij_product=intellij-beta - build_targets: - - //aspect:aspect_files - test_flags: - - --define=ij_product=intellij-beta - - --test_output=errors - - --notrim_test_configuration - test_targets: - - //aspect/testing/... - skip_use_bazel_version_for_test: true - Aspect-internal-under-dev: - name: Aspect Tests for IJ Internal Under Development - platform: ubuntu2204 - build_flags: - - --define=ij_product=intellij-under-dev - build_targets: - - //aspect:aspect_files - test_flags: - - --define=ij_product=intellij-under-dev - - --test_output=errors - - --notrim_test_configuration - test_targets: - - //aspect/testing/... - soft_fail: - - exit_status: 1 - skip_use_bazel_version_for_test: true - Aspect-oss-oldest-stable: + Aspect-OSS-oldest-stable: name: Aspect Tests for IJ OSS Oldest Stable platform: ubuntu2204 build_flags: @@ -58,7 +14,7 @@ tasks: test_targets: - //aspect/testing/... skip_use_bazel_version_for_test: true - Aspect-oss-latest-stable: + Aspect-OSS-latest-stable: name: Aspect Tests for IJ OSS Latest Stable platform: ubuntu2204 build_flags: @@ -72,7 +28,7 @@ tasks: test_targets: - //aspect/testing/... skip_use_bazel_version_for_test: true - Aspect-oss-under-dev: + Aspect-OSS-under-dev: name: Aspect Tests for IJ OSS Under Development platform: ubuntu2204 build_flags: diff --git a/.bazelci/intellij-ue.yml b/.bazelci/intellij-ue.yml index c965dfb49d2..e045463efca 100644 --- a/.bazelci/intellij-ue.yml +++ b/.bazelci/intellij-ue.yml @@ -47,4 +47,15 @@ tasks: - //ijwb/... soft_fail: - exit_status: 1 - + Querysync: + name: Querysync Library + platform: ubuntu2204 + build_flags: + - --define=ij_product=intellij-ue-oss-under-dev + build_targets: + - //querysync/... + test_flags: + - --define=ij_product=intellij-ue-oss-under-dev + - --test_output=errors + test_targets: + - //querysync/... diff --git a/MODULE.bazel b/MODULE.bazel index 342e054b2d7..fc942784828 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -96,11 +96,12 @@ maven.install( "com.google.code.findbugs:jsr305:3.0.2", "com.google.code.gson:gson:2.10.1", "com.google.errorprone:error_prone_annotations:2.20.0", - "com.google.guava:guava:33.0.0-jre", # changed to jre - "com.google.truth:truth:1.1.5", - "com.google.truth.extensions:truth-java8-extension:1.1.5", + "com.google.guava:guava:33.3.1-jre", # changed to jre + "com.google.truth:truth:1.4.4", + "com.google.truth.extensions:truth-java8-extension:1.4.4", "com.google.j2objc:j2objc-annotations:2.8", "com.google.guava:failureaccess:1.0.2", + "org.hamcrest:hamcrest-core:3.0", ], fail_if_repin_required = True, generate_compat_repositories = True, @@ -130,6 +131,7 @@ use_repo( objenesis = "org_objenesis_objenesis", truth = "com_google_truth_truth", truth8 = "com_google_truth_extensions_truth_java8_extension", + hamcrest = "org_hamcrest_hamcrest_core", ) bazel_dep(name = "rules_go", version = "0.50.1", repo_name = "io_bazel_rules_go") diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index db3c6982fb4..f4482bd3edc 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -843,17 +843,16 @@ "@@rules_bazel_integration_test~//:extensions.bzl%bazel_binaries": { "general": { "bzlTransitiveDigest": "ruMfvWwZzwPPkk+exdpYAe94RD+4erzc4ePrZ08MuKc=", - "usagesDigest": "NOmZNyUfHK4TOR2tGFP4OfRYOHmgVVZiVibKj0w/wws=", + "usagesDigest": "Bza4kzE3khAS7/tTZCxkdEtfe4yCTUM9EmFpONsGN84=", "recordedFileInputs": {}, "recordedDirentsInputs": {}, "envVariables": {}, "generatedRepoSpecs": { - "build_bazel_bazel_7_2_1": { + "bazel_binaries_bazelisk": { "bzlFile": "@@rules_bazel_integration_test~//bazel_integration_test/private:bazel_binaries.bzl", - "ruleClassName": "bazel_binary", + "ruleClassName": "bazelisk_binary", "attributes": { - "version": "7.2.1", - "bazelisk": "@bazel_binaries_bazelisk//:bazelisk" + "version": "1.18.0" } }, "build_bazel_bazel_5_4_1": { @@ -872,11 +871,12 @@ "bazelisk": "@bazel_binaries_bazelisk//:bazelisk" } }, - "bazel_binaries_bazelisk": { + "build_bazel_bazel_7_4_0": { "bzlFile": "@@rules_bazel_integration_test~//bazel_integration_test/private:bazel_binaries.bzl", - "ruleClassName": "bazelisk_binary", + "ruleClassName": "bazel_binary", "attributes": { - "version": "1.18.0" + "version": "7.4.0", + "bazelisk": "@bazel_binaries_bazelisk//:bazelisk" } }, "bazel_binaries": { @@ -886,9 +886,9 @@ "version_to_repo": { "5.4.1": "build_bazel_bazel_5_4_1", "6.5.0": "build_bazel_bazel_6_5_0", - "7.2.1": "build_bazel_bazel_7_2_1" + "7.4.0": "build_bazel_bazel_7_4_0" }, - "current_version": "7.2.1" + "current_version": "7.4.0" } } }, @@ -898,7 +898,7 @@ "bazel_binaries_bazelisk", "build_bazel_bazel_5_4_1", "build_bazel_bazel_6_5_0", - "build_bazel_bazel_7_2_1", + "build_bazel_bazel_7_4_0", "bazel_binaries" ], "useAllRepos": "NO", diff --git a/aspect/BUILD b/aspect/BUILD index 5453342892d..9f7690b40a8 100644 --- a/aspect/BUILD +++ b/aspect/BUILD @@ -28,10 +28,22 @@ filegroup( # the aspect files that will be bundled with the final plugin zip filegroup( name = "aspect_files", + srcs = [ + ":aspect_files_only", + ":aspect_tools", + ], + visibility = ["//visibility:public"], +) + +# Separate different targets as they are put into different directories +filegroup( + name = "aspect_files_only", srcs = [ "WORKSPACE", "artifacts.bzl", + "build_compose_dependencies.bzl", "build_dependencies.bzl", + "build_dependencies_deps.bzl", "fast_build_info_bundled.bzl", "flag_hack.bzl", "intellij_info.bzl", @@ -40,6 +52,13 @@ filegroup( "java_classpath.bzl", "make_variables.bzl", ":BUILD.bazel", + ], + visibility = ["//visibility:public"], +) + +filegroup( + name = "aspect_tools", + srcs = [ "//aspect/tools:CreateAar", "//aspect/tools:JarFilter_deploy.jar", "//aspect/tools:PackageParser_deploy.jar", diff --git a/aspect/build_compose_dependencies.bzl b/aspect/build_compose_dependencies.bzl new file mode 100644 index 00000000000..f83873f2569 --- /dev/null +++ b/aspect/build_compose_dependencies.bzl @@ -0,0 +1,37 @@ +"""Aspects to build and collect project's compose dependencies.""" + +load("//third_party/bazel_rules/rules_java/java:defs.bzl", "JavaInfo") + +ComposeDependenciesInfo = provider( + "The compose dependencies", + fields = { + "render_jars": "a list of render jars generated for project files and external dependencies", + }, +) + +def _package_compose_dependencies_impl(target, ctx): # @unused + return [OutputGroupInfo( + render_jars = target[ComposeDependenciesInfo].render_jars.to_list(), + )] + +package_compose_dependencies = aspect( + implementation = _package_compose_dependencies_impl, + required_aspect_providers = [[ComposeDependenciesInfo]], +) + +def _collect_compose_dependencies_impl(target, ctx): # @unused + if JavaInfo not in target: + return [ComposeDependenciesInfo( + render_jars = depset(), + )] + return [ + ComposeDependenciesInfo( + render_jars = depset([], transitive = [target[JavaInfo].transitive_runtime_jars]), + ), + ] + +collect_compose_dependencies = aspect( + implementation = _collect_compose_dependencies_impl, + provides = [ComposeDependenciesInfo], + attr_aspects = ["deps", "exports", "_android_sdk"], +) diff --git a/aspect/build_dependencies.bzl b/aspect/build_dependencies.bzl index 7f45c79f53d..d76308fd877 100644 --- a/aspect/build_dependencies.bzl +++ b/aspect/build_dependencies.bzl @@ -1,9 +1,13 @@ """Aspects to build and collect project dependencies.""" +# Load external dependencies of this aspect. These are loaded in a separate file and re-exported as necessary +# to make supporting other versions of bazel easier, by replacing build_dependencies_deps.bzl. load( - "@bazel_tools//tools/build_defs/cc:action_names.bzl", - "CPP_COMPILE_ACTION_NAME", - "C_COMPILE_ACTION_NAME", + ":build_dependencies_deps.bzl", + "ANDROID_IDE_INFO", + "ZIP_TOOL_LABEL", + _ide_cc_not_validated = "IDE_CC", + _ide_kotlin_not_validated = "IDE_KOTLIN", ) ALWAYS_BUILD_RULES = "java_proto_library,java_lite_proto_library,java_mutable_proto_library,kt_proto_library_helper,_java_grpc_library,_java_lite_grpc_library,kt_grpc_library_helper,java_stubby_library,kt_stubby_library_helper,aar_import,java_import" @@ -15,60 +19,101 @@ PROTO_RULE_KINDS = [ "kt_proto_library_helper", ] -def java_info_in_target(target): - return JavaInfo in target +def _rule_function(rule): + return [] + +def _unique(values): + return {k: None for k in values}.keys() + +def _validate_ide(unvalidated, template): + "Basic validation that a provided implementation conforms to a given template" + for a in dir(template): + if not hasattr(unvalidated, a): + fail("attribute missing: ", a, unvalidated) + elif type(getattr(unvalidated, a)) != type(getattr(template, a)): + fail("attribute type mismatch: ", a, type(getattr(unvalidated, a)), type(getattr(template, a))) + return struct(**{a: getattr(unvalidated, a) for a in dir(template) if a not in dir(struct())}) + +IDE_KOTLIN = _validate_ide( + _ide_kotlin_not_validated, + template = struct( + srcs_attributes = [], # Additional srcs like attributes. + follow_attributes = [], # Additional attributes for the aspect to follow and request DependenciesInfo provider. + follow_additional_attributes = [], # Additional attributes for the aspect to follow without requesting DependenciesInfo provider. + followed_dependencies = _rule_function, # A function that takes a rule and returns a list of dependencies (targets or toolchain containers). + toolchains_aspects = [], # Toolchain types for the aspect to follow. + ), +) -def get_java_info(target): - if JavaInfo in target: - return target[JavaInfo] +IDE_CC = _validate_ide( + _ide_cc_not_validated, + template = struct( + c_compile_action_name = "", # An action named to be used with cc_common.get_memory_inefficient_command_line or similar. + cpp_compile_action_name = "", # An action named to be used with cc_common.get_memory_inefficient_command_line or similar. + follow_attributes = ["_cc_toolchain"], # Additional attributes for the aspect to follow and request DependenciesInfo provider. + toolchains_aspects = [], # Toolchain types for the aspect to follow. + toolchain_target = _rule_function, # A function that takes a rule and returns a toolchain target (or a toolchain container). + ), +) -def java_info_reference(): - return [JavaInfo] +JAVA_SRC_ATTRS = ["srcs", "java_srcs", "java_test_srcs"] +JVM_SRC_ATTRS = _unique(JAVA_SRC_ATTRS + IDE_KOTLIN.srcs_attributes) def _package_dependencies_impl(target, ctx): java_info_file = _write_java_target_info(target, ctx) cc_info_file = _write_cc_target_info(target, ctx) + dep_info = target[DependenciesInfo] return [OutputGroupInfo( - qsync_jars = target[DependenciesInfo].compile_time_jars.to_list(), + qsync_jars = dep_info.compile_time_jars.to_list() if dep_info.compile_time_jars else [], artifact_info_file = java_info_file, - qsync_aars = target[DependenciesInfo].aars.to_list(), - qsync_gensrcs = target[DependenciesInfo].gensrcs.to_list(), - cc_headers = target[DependenciesInfo].cc_headers.to_list(), - cc_info_file = cc_info_file + [target[DependenciesInfo].cc_toolchain_info.file] if target[DependenciesInfo].cc_toolchain_info else [], + qsync_aars = dep_info.aars.to_list() if dep_info.aars else [], + qsync_gensrcs = dep_info.gensrcs.to_list() if dep_info.gensrcs else [], + cc_headers = dep_info.cc_headers.to_list() if dep_info.cc_headers else [], + cc_info_file = cc_info_file + [dep_info.cc_toolchain_info.file] if dep_info.cc_toolchain_info else [], )] -def _write_java_target_info(target, ctx): - if not target[DependenciesInfo].target_to_artifacts: +def _write_java_target_info(target, ctx, custom_prefix = ""): + """Write java target info to a file in proto format. + + The proto format used is defined by proto bazel.intellij.JavaArtifacts. + """ + target_to_artifacts = target[DependenciesInfo].target_to_artifacts + if not target_to_artifacts: return [] - file_name = target.label.name + ".java-info.txt" + file_name = custom_prefix + target.label.name + ".java-info.txt" artifact_info_file = ctx.actions.declare_file(file_name) ctx.actions.write( artifact_info_file, - _encode_target_info_proto(target[DependenciesInfo].target_to_artifacts), + _encode_target_info_proto(target_to_artifacts), ) return [artifact_info_file] def _write_cc_target_info(target, ctx): - if not target[DependenciesInfo].cc_info: + """Write CC target info to a file in proto format. + + The proto format used defined by proto bazel.intellij.CcCompilationInfo. + """ + if not target[DependenciesInfo].cc_compilation_info: return [] cc_info_file_name = target.label.name + ".cc-info.txt" cc_info_file = ctx.actions.declare_file(cc_info_file_name) ctx.actions.write( cc_info_file, - _encode_cc_info_proto(target.label, target[DependenciesInfo].cc_info), + _encode_cc_compilation_info_proto(target.label, target[DependenciesInfo].cc_compilation_info), ) return [cc_info_file] DependenciesInfo = provider( "The out-of-project dependencies", fields = { + "label": "the label of a target it describes", "compile_time_jars": "a list of jars generated by targets", "target_to_artifacts": "a map between a target and all its artifacts", "aars": "a list of aars with resource files", "gensrcs": "a list of sources generated by project targets", "expand_sources": "boolean, true if the sources for this target should be expanded when it appears inside another rules srcs list", - "cc_info": "a structure containing info required to compile cc sources", + "cc_compilation_info": "a structure containing info required to compile cc sources", "cc_headers": "a depset of generated headers required to compile cc sources", "cc_toolchain_info": "struct containing cc toolchain info, with keys file (the output file) and id (unique ID for the toolchain info, referred to from elsewhere)", "test_mode_own_files": "a structure describing Java artifacts required when the target is requested within the project scope", @@ -77,39 +122,122 @@ DependenciesInfo = provider( ) def create_dependencies_info( + label, compile_time_jars = depset(), target_to_artifacts = {}, aars = depset(), gensrcs = depset(), expand_sources = False, - cc_info = None, + cc_compilation_info = None, cc_headers = depset(), cc_toolchain_info = None, test_mode_own_files = None, test_mode_cc_src_deps = depset()): """A helper function to create a DependenciesInfo provider instance.""" return DependenciesInfo( + label = label, compile_time_jars = compile_time_jars, target_to_artifacts = target_to_artifacts, aars = aars, gensrcs = gensrcs, expand_sources = expand_sources, - cc_info = cc_info, + cc_compilation_info = cc_compilation_info, cc_headers = cc_headers, cc_toolchain_info = cc_toolchain_info, test_mode_own_files = test_mode_own_files, test_mode_cc_src_deps = test_mode_cc_src_deps, ) +def create_java_dependencies_info( + compile_time_jars, + target_to_artifacts, + aars, + gensrcs, + expand_sources, + test_mode_own_files): + """A helper function to create a DependenciesInfo provider instance.""" + return struct( + compile_time_jars = compile_time_jars, + target_to_artifacts = target_to_artifacts, + aars = aars, + gensrcs = gensrcs, + expand_sources = expand_sources, + test_mode_own_files = test_mode_own_files, + ) + +def create_cc_dependencies_info( + cc_compilation_info = None, + cc_headers = depset(), + cc_toolchain_info = None, + test_mode_cc_src_deps = depset()): + """A helper function to create a DependenciesInfo provider instance.""" + return struct( + cc_compilation_info = cc_compilation_info, + cc_headers = cc_headers, + cc_toolchain_info = cc_toolchain_info, + test_mode_cc_src_deps = test_mode_cc_src_deps, + ) + +def create_cc_toolchain_info( + cc_toolchain_info = None, + test_mode_cc_src_deps = depset()): + """A helper function to create a DependenciesInfo provider instance.""" + return struct( + cc_toolchain_info = cc_toolchain_info, + test_mode_cc_src_deps = test_mode_cc_src_deps, + ) + +def merge_dependencies_info(target, ctx, java_dep_info, cc_dep_info, cc_toolchain_dep_info): + """Merge multiple DependenciesInfo providers into one. + + Depsets and dicts are merged. For members such as `cc_compilation_info`, we require that at most one of the + DependenciesInfo's defines this which should always be the case. + """ + + if not java_dep_info and not cc_dep_info and not cc_toolchain_dep_info: + return [] + + if cc_dep_info and cc_toolchain_dep_info: + test_mode_cc_src_deps = depset(transitive = [cc_dep_info.test_mode_cc_src_deps, cc_toolchain_dep_info.test_mode_cc_src_deps]) + elif cc_dep_info: + test_mode_cc_src_deps = cc_dep_info.test_mode_cc_src_deps + elif cc_toolchain_dep_info: + test_mode_cc_src_deps = cc_toolchain_dep_info.test_mode_cc_src_deps + else: + test_mode_cc_src_deps = None + + merged = create_dependencies_info( + label = target.label, + compile_time_jars = java_dep_info.compile_time_jars if java_dep_info else None, + target_to_artifacts = java_dep_info.target_to_artifacts if java_dep_info else None, + aars = java_dep_info.aars if java_dep_info else None, + gensrcs = java_dep_info.gensrcs if java_dep_info else None, + expand_sources = java_dep_info.expand_sources if java_dep_info else None, + cc_compilation_info = cc_dep_info.cc_compilation_info if cc_dep_info else None, + cc_headers = cc_dep_info.cc_headers if cc_dep_info else None, + cc_toolchain_info = cc_toolchain_dep_info.cc_toolchain_info if cc_toolchain_dep_info else None, + test_mode_own_files = java_dep_info.test_mode_own_files if java_dep_info else None, + test_mode_cc_src_deps = test_mode_cc_src_deps, + ) + return merged + +def one_of(a, b): + """Returns whichever of a or b is not None, None if both are, or fails if neither are.""" + if a == None: + return b + if b == None: + return a + fail("Expected at most one, but got both", a, b) + def _encode_target_info_proto(target_to_artifacts): contents = [] for label, target_info in target_to_artifacts.items(): contents.append( struct( target = label, - jars = target_info["jars"], - ide_aars = target_info["ide_aars"], - gen_srcs = target_info["gen_srcs"], + jars = _encode_file_list(target_info["jars"]) if "jars" in target_info else [], + ide_aars = _encode_file_list(target_info["ide_aars"]), + gen_srcs = _encode_file_list(target_info["gen_srcs"]), srcs = target_info["srcs"], srcjars = target_info["srcjars"], android_resources_package = target_info["android_resources_package"], @@ -117,18 +245,32 @@ def _encode_target_info_proto(target_to_artifacts): ) return proto.encode_text(struct(artifacts = contents)) -def _encode_cc_info_proto(label, cc_info): +def _encode_file_list(files): + """Encodes a list of files as a struct. + + Returns: + A list fo structs matching the bazel.intellij.OutputArtifact proto message. + """ + r = [] + for f in files: + if f.is_directory: + r.append(struct(directory = f.path)) + else: + r.append(struct(file = f.path)) + return r + +def _encode_cc_compilation_info_proto(label, cc_compilation_info): return proto.encode_text( struct(targets = [ struct( label = str(label), - defines = cc_info.transitive_defines, - include_directories = cc_info.transitive_include_directory, - quote_include_directories = cc_info.transitive_quote_include_directory, - system_include_directories = cc_info.transitive_system_include_directory, - framework_include_directories = cc_info.framework_include_directory, - gen_hdrs = cc_info.gen_headers, - toolchain_id = cc_info.toolchain_id, + defines = cc_compilation_info.transitive_defines, + include_directories = cc_compilation_info.transitive_include_directory, + quote_include_directories = cc_compilation_info.transitive_quote_include_directory, + system_include_directories = cc_compilation_info.transitive_system_include_directory, + framework_include_directories = cc_compilation_info.framework_include_directory, + gen_hdrs = _encode_file_list(cc_compilation_info.gen_headers), + toolchain_id = cc_compilation_info.toolchain_id, ), ]), ) @@ -157,7 +299,9 @@ def declares_android_resources(target, ctx): return hasattr(ctx.rule.attr, "resource_files") and len(ctx.rule.attr.resource_files) > 0 def _get_android_provider(target): - if hasattr(android_common, "AndroidIdeInfo"): + if ANDROID_IDE_INFO and ANDROID_IDE_INFO in target: + return target[ANDROID_IDE_INFO] + elif hasattr(android_common, "AndroidIdeInfo"): if android_common.AndroidIdeInfo in target: return target[android_common.AndroidIdeInfo] else: @@ -213,38 +357,90 @@ def _collect_all_dependencies_for_tests_impl(target, ctx): exclude = None, always_build_rules = ALWAYS_BUILD_RULES, generate_aidl_classes = None, - use_generated_srcjars = False, + use_generated_srcjars = True, test_mode = True, ) +def collect_dependencies_for_test(target, ctx, include = []): + return _collect_dependencies_core_impl( + target, + ctx, + include = ",".join(include), + exclude = "", + always_build_rules = ALWAYS_BUILD_RULES, + generate_aidl_classes = None, + use_generated_srcjars = True, + test_mode = False, + ) + +def _package_prefix_match(package, prefix): + if (package == prefix): + return True + if package.startswith(prefix) and package[len(prefix)] == "/": + return True + return False + +def _get_repo_name(label): + # The API to get the repo name changed between bazel versions. Use whichever exists: + return label.repo_name if "repo_name" in dir(label) else label.workspace_name + def _target_within_project_scope(label, include, exclude): + repo = _get_repo_name(label) + package = label.package result = False if include: for inc in include.split(","): - if label.startswith(inc): - if label[len(inc)] in [":", "/"]: - result = True - break + # This is not a valid label, but can be passed to aspect when `directories: .` is set in the projectview + if (inc == "//"): + result = True + break + + inc = Label(inc) + if _get_repo_name(inc) == repo and _package_prefix_match(package, inc.package): + result = True + break + if result and len(exclude) > 0: for exc in exclude.split(","): - if label.startswith(exc): - if label[len(exc)] in [":", "/"]: - result = False - break + # Same as for includes + if (exc == "//"): + result = False + break + + exc = Label(exc) + if _get_repo_name(exc) == repo and _package_prefix_match(package, exc.package): + result = False + break + return result +def _get_dependency_attribute(rule, attr): + if hasattr(rule.attr, attr): + to_add = getattr(rule.attr, attr) + if type(to_add) == "list": + return [t for t in to_add if type(t) == "Target"] + elif type(to_add) == "Target": + return [to_add] + return [] + +def _get_followed_java_proto_dependencies(rule): + deps = [] + if rule.kind in ["proto_lang_toolchain", "java_rpc_toolchain"]: + deps.extend(_get_dependency_attribute(rule, "runtime")) + if rule.kind in ["_java_grpc_library", "_java_lite_grpc_library"]: + deps.extend(_get_dependency_attribute(rule, "_toolchain")) + return deps + def _get_followed_java_dependency_infos(rule): deps = [] - for (attr, kinds) in FOLLOW_JAVA_ATTRIBUTES_BY_RULE_KIND: - if hasattr(rule.attr, attr) and (not kinds or rule.kind in kinds): - to_add = getattr(rule.attr, attr) - if type(to_add) == "list": - deps += [t for t in to_add if type(t) == "Target"] - elif type(to_add) == "Target": - deps.append(to_add) + for attr in FOLLOW_JAVA_ATTRIBUTES: + deps.extend(_get_dependency_attribute(rule, attr)) + + deps.extend(_get_followed_java_proto_dependencies(rule)) + deps.extend(IDE_KOTLIN.followed_dependencies(rule)) return { - str(dep.label): dep[DependenciesInfo] + str(dep[DependenciesInfo].label): dep[DependenciesInfo] # NOTE: This handles duplicates. for dep in deps if DependenciesInfo in dep and dep[DependenciesInfo].target_to_artifacts } @@ -252,17 +448,13 @@ def _get_followed_java_dependency_infos(rule): def _collect_own_java_artifacts( target, ctx, - dependency_infos, + can_follow_dependencies, always_build_rules, generate_aidl_classes, use_generated_srcjars, target_is_within_project_scope): rule = ctx.rule - # Toolchains are collected for proto targets via aspect traversal, but jars - # produced for proto deps of the underlying proto_library are not - can_follow_dependencies = bool(dependency_infos) and not ctx.rule.kind in PROTO_RULE_KINDS - must_build_main_artifacts = ( not target_is_within_project_scope or rule.kind in always_build_rules.split(",") ) @@ -283,19 +475,24 @@ def _collect_own_java_artifacts( # This is done primarily for rules like proto, whose toolchain classes # are collected via attribute traversal, but still requires jars for any # proto deps of the underlying proto_library. - java_info = get_java_info(target) - if java_info: + if JavaInfo in target: if can_follow_dependencies: - own_jar_depsets.append(java_info.compile_jars) + own_jar_depsets.append(target[JavaInfo].compile_jars) else: - own_jar_depsets.append(java_info.transitive_compile_time_jars) + own_jar_depsets.append(target[JavaInfo].transitive_compile_time_jars) if declares_android_resources(target, ctx): ide_aar = _get_ide_aar_file(target, ctx) if ide_aar: - own_ide_aar_files.append(ide_aar) + # TODO(mathewi) - handle source aars + if not ide_aar.is_source: + own_ide_aar_files.append(ide_aar) elif declares_aar_import(ctx): - own_ide_aar_files.append(rule.attr.aar.files.to_list()[0]) + ide_aar = rule.attr.aar.files.to_list()[0] + + # TODO(mathewi) - handle source aars + if not ide_aar.is_source: + own_ide_aar_files.append(ide_aar) else: android = _get_android_provider(target) @@ -324,10 +521,9 @@ def _collect_own_java_artifacts( # Add generated java_outputs (e.g. from annotation processing) generated_class_jars = [] - java_info = get_java_info(target) - if java_info: - for java_output in java_info.java_outputs: - # Prefer source jars if they exist: + if JavaInfo in target: + for java_output in target[JavaInfo].java_outputs: + # Prefer source jars if they exist and are requested: if use_generated_srcjars and java_output.generated_source_jar: own_gensrc_files.append(java_output.generated_source_jar) elif java_output.generated_class_jar: @@ -337,30 +533,27 @@ def _collect_own_java_artifacts( own_jar_files += generated_class_jars # Add generated sources for included targets - if hasattr(rule.attr, "srcs"): - for src in rule.attr.srcs: - for file in src.files.to_list(): - if not file.is_source: - expand_sources = False - if str(file.owner) in dependency_infos: - src_depinfo = dependency_infos[str(file.owner)] - expand_sources = src_depinfo.expand_sources - - # If the target that generates this source specifies that - # the sources should be expanded, we ignore the generated - # sources - the IDE will substitute the target sources - # themselves instead. - if not expand_sources: - own_gensrc_files.append(file) + for src_attr in JVM_SRC_ATTRS: + if hasattr(rule.attr, src_attr): + for src in getattr(rule.attr, src_attr): + # If the target that generates this source specifies that + # the sources should be expanded, we ignore the generated + # sources - the IDE will substitute the target sources + # themselves instead. + if not (DependenciesInfo in src and src[DependenciesInfo].expand_sources): + for file in src.files.to_list(): + if not file.is_source: + own_gensrc_files.append(file) if not target_is_within_project_scope: - if hasattr(rule.attr, "srcs"): - for src in rule.attr.srcs: - for file in src.files.to_list(): - if file.is_source: - own_src_files.append(file.path) - else: - own_gensrc_files.append(file) + for src_attr in JVM_SRC_ATTRS: + if hasattr(rule.attr, src_attr): + for src in getattr(rule.attr, src_attr): + for file in src.files.to_list(): + if file.is_source: + own_src_files.append(file.path) + else: + own_gensrc_files.append(file) if hasattr(rule.attr, "srcjar"): if rule.attr.srcjar and type(rule.attr.srcjar) == "Target": for file in rule.attr.srcjar.files.to_list(): @@ -379,6 +572,27 @@ def _collect_own_java_artifacts( android_resources_package = resource_package, ) +def _target_to_artifact_entry( + jars = [], + ide_aars = [], + gen_srcs = [], + srcs = [], + srcjars = [], + android_resources_package = ""): + return { + "jars": jars, + "ide_aars": ide_aars, + "gen_srcs": gen_srcs, + "srcs": srcs, + "srcjars": srcjars, + "android_resources_package": android_resources_package, + } + +def _can_follow_dependencies(ctx): + # Toolchains are collected for proto targets via aspect traversal, but jars + # produced for proto deps of the underlying proto_library are not + return not ctx.rule.kind in PROTO_RULE_KINDS + def _collect_own_and_dependency_java_artifacts( target, ctx, @@ -387,10 +601,12 @@ def _collect_own_and_dependency_java_artifacts( generate_aidl_classes, use_generated_srcjars, target_is_within_project_scope): + can_follow_dependencies = _can_follow_dependencies(ctx) + own_files = _collect_own_java_artifacts( target, ctx, - dependency_infos, + can_follow_dependencies, always_build_rules, generate_aidl_classes, use_generated_srcjars, @@ -409,19 +625,20 @@ def _collect_own_and_dependency_java_artifacts( target_to_artifacts = {} if has_own_artifacts: + # Pass the following lists through depset() to to remove any duplicates. jars = depset(own_files.jars, transitive = own_files.jar_depsets).to_list() - - # Pass the following lists through depset() too to remove any duplicates. ide_aars = depset(own_files.ide_aars).to_list() gen_srcs = depset(own_files.gensrcs).to_list() - target_to_artifacts[str(target.label)] = { - "jars": [_output_relative_path(file.path) for file in jars], - "ide_aars": [_output_relative_path(file.path) for file in ide_aars], - "gen_srcs": [_output_relative_path(file.path) for file in gen_srcs], - "srcs": own_files.srcs, - "srcjars": own_files.srcjars, - "android_resources_package": own_files.android_resources_package, - } + target_to_artifacts[str(target.label)] = _target_to_artifact_entry( + jars = jars, + ide_aars = ide_aars, + gen_srcs = gen_srcs, + srcs = own_files.srcs, + srcjars = own_files.srcjars, + android_resources_package = own_files.android_resources_package, + ) + elif target_is_within_project_scope: + target_to_artifacts[str(target.label)] = _target_to_artifact_entry() own_and_transitive_jar_depsets = list(own_files.jar_depsets) # Copy to prevent changes to own_jar_depsets. own_and_transitive_ide_aar_depsets = [] @@ -440,14 +657,14 @@ def _collect_own_and_dependency_java_artifacts( depset(own_files.gensrcs, transitive = own_and_transitive_gensrc_depsets), ) -def _get_followed_cc_dependency_info(rule): - if hasattr(rule.attr, "_cc_toolchain"): - cc_toolchain_target = getattr(rule.attr, "_cc_toolchain") - if DependenciesInfo in cc_toolchain_target: - return cc_toolchain_target[DependenciesInfo] +def _get_cc_toolchain_dependency_info(rule): + cc_toolchain_target = IDE_CC.toolchain_target(rule) + if cc_toolchain_target and DependenciesInfo in cc_toolchain_target: + return cc_toolchain_target[DependenciesInfo] return None -def _collect_own_and_dependency_cc_info(target, dependency_info, test_mode): +def _collect_own_and_dependency_cc_info(target, rule, test_mode): + dependency_info = _get_cc_toolchain_dependency_info(rule) compilation_context = target[CcInfo].compilation_context cc_toolchain_info = None test_mode_cc_src_deps = depset() @@ -471,9 +688,14 @@ def _collect_own_and_dependency_cc_info(target, dependency_info, test_mode): transitive_defines = compilation_context.defines.to_list(), transitive_include_directory = compilation_context.includes.to_list(), transitive_quote_include_directory = compilation_context.quote_includes.to_list(), - transitive_system_include_directory = compilation_context.system_includes.to_list() + compilation_context.external_includes.to_list(), + transitive_system_include_directory = ( + compilation_context.system_includes.to_list() + ( + # external_includes was added in newer versions of bazel + compilation_context.external_includes.to_list() if hasattr(compilation_context, "external_includes") else [] + ) + ), framework_include_directory = compilation_context.framework_includes.to_list(), - gen_headers = [f.path for f in gen_headers.to_list()], + gen_headers = gen_headers.to_list(), toolchain_id = cc_toolchain_info.id if cc_toolchain_info else None, ) return struct( @@ -492,7 +714,7 @@ def _collect_dependencies_core_impl( generate_aidl_classes, use_generated_srcjars, test_mode): - dep_infos = _collect_java_dependencies_core_impl( + java_dep_info = _collect_java_dependencies_core_impl( target, ctx, include, @@ -502,11 +724,13 @@ def _collect_dependencies_core_impl( use_generated_srcjars, test_mode, ) + cc_dep_info = None if CcInfo in target: - dep_infos.append(_collect_cc_dependencies_core_impl(target, ctx, test_mode)) + cc_dep_info = _collect_cc_dependencies_core_impl(target, ctx, test_mode) + cc_toolchain_dep_info = None if cc_common.CcToolchainInfo in target: - dep_infos.append(_collect_cc_toolchain_info(target, ctx)) - return dep_infos + cc_toolchain_dep_info = _collect_cc_toolchain_info(target, ctx) + return merge_dependencies_info(target, ctx, java_dep_info, cc_dep_info, cc_toolchain_dep_info) def _collect_java_dependencies_core_impl( target, @@ -517,7 +741,7 @@ def _collect_java_dependencies_core_impl( generate_aidl_classes, use_generated_srcjars, test_mode): - target_is_within_project_scope = _target_within_project_scope(str(target.label), include, exclude) and not test_mode + target_is_within_project_scope = _target_within_project_scope(target.label, include, exclude) and not test_mode dependency_infos = _get_followed_java_dependency_infos(ctx.rule) target_to_artifacts, compile_jars, aars, gensrcs = _collect_own_and_dependency_java_artifacts( @@ -532,10 +756,11 @@ def _collect_java_dependencies_core_impl( test_mode_own_files = None if test_mode: + can_follow_dependencies = _can_follow_dependencies(ctx) within_scope_own_files = _collect_own_java_artifacts( target, ctx, - dependency_infos, + can_follow_dependencies, always_build_rules, generate_aidl_classes, use_generated_srcjars, @@ -552,24 +777,20 @@ def _collect_java_dependencies_core_impl( if "ij-ignore-source-transform" in ctx.rule.attr.tags: expand_sources = True - return [ - create_dependencies_info( - target_to_artifacts = target_to_artifacts, - compile_time_jars = compile_jars, - aars = aars, - gensrcs = gensrcs, - expand_sources = expand_sources, - test_mode_own_files = test_mode_own_files, - ), - ] + return create_java_dependencies_info( + target_to_artifacts = target_to_artifacts, + compile_time_jars = compile_jars, + aars = aars, + gensrcs = gensrcs, + expand_sources = expand_sources, + test_mode_own_files = test_mode_own_files, + ) def _collect_cc_dependencies_core_impl(target, ctx, test_mode): - dependency_info = _get_followed_cc_dependency_info(ctx.rule) - - cc_info = _collect_own_and_dependency_cc_info(target, dependency_info, test_mode) + cc_info = _collect_own_and_dependency_cc_info(target, ctx.rule, test_mode) - return create_dependencies_info( - cc_info = cc_info.compilation_info, + return create_cc_dependencies_info( + cc_compilation_info = cc_info.compilation_info, cc_headers = cc_info.gen_headers, cc_toolchain_info = cc_info.cc_toolchain_info, test_mode_cc_src_deps = cc_info.test_mode_cc_src_deps, @@ -610,12 +831,12 @@ def _collect_cc_toolchain_info(target, ctx): ) c_options = cc_common.get_memory_inefficient_command_line( feature_configuration = feature_config, - action_name = C_COMPILE_ACTION_NAME, + action_name = IDE_CC.c_compile_action_name, variables = c_variables, ) cpp_options = cc_common.get_memory_inefficient_command_line( feature_configuration = feature_config, - action_name = CPP_COMPILE_ACTION_NAME, + action_name = IDE_CC.cpp_compile_action_name, variables = cpp_variables, ) toolchain_id = str(target.label) + "%" + toolchain_info.target_gnu_system_name @@ -640,7 +861,7 @@ def _collect_cc_toolchain_info(target, ctx): ), ) - return create_dependencies_info( + return create_cc_toolchain_info( cc_toolchain_info = struct(file = cc_toolchain_file, id = toolchain_id), test_mode_cc_src_deps = depset([f for f in toolchain_info.all_files.to_list() if f.is_source]), ) @@ -719,40 +940,27 @@ def _package_ide_aar(ctx, aar, file_map): arguments = ["c", aar.path] + files_map_args, ) -def _output_relative_path(path): - """Get file path relative to the output path. - - Args: - path: path of artifact path = (../repo_name)? + (root_fragment)? + relative_path - - Returns: - path relative to the output path - """ - if (path.startswith("blaze-out/")) or (path.startswith("bazel-out/")): - # len("blaze-out/") or len("bazel-out/") - path = path[10:] - return path - # List of tuples containing: # 1. An attribute for the aspect to traverse # 2. A list of rule kinds to specify which rules for which the attribute labels # need to be added as dependencies. If empty, the attribute is followed for # all rules. -FOLLOW_JAVA_ATTRIBUTES_BY_RULE_KIND = [ - ("deps", []), - ("exports", []), - ("srcs", []), - ("_junit", []), - ("_aspect_proto_toolchain_for_javalite", []), - ("_aspect_java_proto_toolchain", []), - ("runtime", ["proto_lang_toolchain", "java_rpc_toolchain"]), - ("_toolchain", ["_java_grpc_library", "_java_lite_grpc_library", "kt_jvm_library_helper", "android_library", "kt_android_library"]), - ("kotlin_libs", ["kt_jvm_toolchain"]), -] +FOLLOW_JAVA_ATTRIBUTES = [ + "deps", + "exports", + "srcs", + "_junit", + "_aspect_proto_toolchain_for_javalite", + "_aspect_java_proto_toolchain", +] + IDE_KOTLIN.follow_attributes + +FOLLOW_CC_ATTRIBUTES = IDE_CC.follow_attributes -FOLLOW_CC_ATTRIBUTES = ["_cc_toolchain"] +FOLLOW_ADDITIONAL_ATTRIBUTES = ["runtime", "_toolchain"] + IDE_KOTLIN.follow_additional_attributes -FOLLOW_ATTRIBUTES = [attr for (attr, _) in FOLLOW_JAVA_ATTRIBUTES_BY_RULE_KIND] + FOLLOW_CC_ATTRIBUTES +FOLLOW_ATTRIBUTES = _unique(FOLLOW_JAVA_ATTRIBUTES + FOLLOW_CC_ATTRIBUTES + FOLLOW_ADDITIONAL_ATTRIBUTES) + +TOOLCHAINS_ASPECTS = IDE_KOTLIN.toolchains_aspects + IDE_CC.toolchains_aspects collect_dependencies = aspect( implementation = _collect_dependencies_impl, @@ -783,10 +991,13 @@ collect_dependencies = aspect( allow_files = True, cfg = "exec", executable = True, - default = "@@bazel_tools//tools/zip:zipper", + default = ZIP_TOOL_LABEL, ), }, fragments = ["cpp"], + **{ + "toolchains_aspects": TOOLCHAINS_ASPECTS, + } if TOOLCHAINS_ASPECTS else {} ) collect_all_dependencies_for_tests = aspect( @@ -806,8 +1017,72 @@ collect_all_dependencies_for_tests = aspect( allow_files = True, cfg = "exec", executable = True, - default = "@@bazel_tools//tools/zip:zipper", + default = ZIP_TOOL_LABEL, ), }, fragments = ["cpp"], ) + +def _write_java_info_txt_impl(ctx): + info_txt_files = [] + for dep in ctx.attr.deps: + info_txt_files.extend(_write_java_target_info(dep, ctx, custom_prefix = ctx.label.name + ".")) + return DefaultInfo(files = depset(info_txt_files)) + +def collect_dependencies_aspect_for_tests(custom_aspect_impl): + """Creates a custom aspect for use in test code. + + This is used to run the `collect_dependencies` aspect with a custom set of project includes. + It's necessary to create a custom aspect to do this, as when invoking as aspect from a build + rule it's not possible to give arbitrary values to their parameters. + + This is necessary as bazel requires that all aspects are assigned to top level build vars. + + Args: + custom_aspect_impl: A method that invokes `collect_dependencies_for_test` passing the + required set of project includes. This should be defined thus: + + def custom_aspect_impl(target, ctx): + return collect_dependencies_for_test(target, ctx, include=[ + "//package/path/to/include", + ]) + + The `includes` are bazel packages corresponding to the `directories` in a `.bazelproject`. + + Returns: + An aspect for use with `write_java_info_txt_rule_for_tests`. + """ + return aspect( + implementation = custom_aspect_impl, + attr_aspects = FOLLOW_ATTRIBUTES, + provides = [DependenciesInfo], + ) + +def write_java_info_txt_rule_for_tests(aspect_name): + """Create a rule to run the aspect for use in test code. + + This is used in conjunction with `collect_dependencies_aspect_for_tests` to run the collect + dependencies aspect and write the resulting `.java-info.txt` files to an artifact. + + Args: + aspect_name: The name that the return value from `write_java_info_txt_aspect_for_tests` + as written to. + + Returns: + A custom run implementation that should be assigned to a variable inside a `.bzl` file + and them subsequently used thus: + + custom_aspect_rule( + name = "java_info", + deps = [":my_target"], + ) + + This will run the aspect as if an "enable analysis" action was run from the IDE on the + targets given in `deps`. + """ + return rule( + implementation = _write_java_info_txt_impl, + attrs = { + "deps": attr.label_list(aspects = [aspect_name]), + }, + ) diff --git a/aspect/build_dependencies_deps.bzl b/aspect/build_dependencies_deps.bzl new file mode 100644 index 00000000000..a7fc235f4d5 --- /dev/null +++ b/aspect/build_dependencies_deps.bzl @@ -0,0 +1,60 @@ +"""Loads and re-exports dependencies of build_dependencies.bzl to support different versions of bazel""" + +load( + "@@bazel_tools//tools/build_defs/cc:action_names.bzl", + _CPP_COMPILE_ACTION_NAME = "CPP_COMPILE_ACTION_NAME", + _C_COMPILE_ACTION_NAME = "C_COMPILE_ACTION_NAME", +) + +ZIP_TOOL_LABEL = "@@bazel_tools//tools/zip:zipper" + +ANDROID_IDE_INFO = None + +# KOTLIN + +def _get_dependency_attribute(rule, attr): + if hasattr(rule.attr, attr): + to_add = getattr(rule.attr, attr) + if type(to_add) == "list": + return [t for t in to_add if type(t) == "Target"] + elif type(to_add) == "Target": + return [to_add] + return [] + +def _get_followed_kotlin_dependencies(rule): + deps = [] + if rule.kind in ["kt_jvm_library_helper", "kt_android_library", "android_library"]: + deps.extend(_get_dependency_attribute(rule, "_toolchain")) + if rule.kind in ["kt_jvm_toolchain"]: + deps.extend(_get_dependency_attribute(rule, "kotlin_libs")) + return deps + +IDE_KOTLIN = struct( + srcs_attributes = [ + "kotlin_srcs", + "kotlin_test_srcs", + "common_srcs", + ], + follow_attributes = [], + follow_additional_attributes = [ + "_toolchain", + "kotlin_libs", + ], + followed_dependencies = _get_followed_kotlin_dependencies, + toolchains_aspects = [], +) + +# CC + +def _get_cc_toolchain_target(rule): + if hasattr(rule.attr, "_cc_toolchain"): + return getattr(rule.attr, "_cc_toolchain") + return None + +IDE_CC = struct( + c_compile_action_name = _C_COMPILE_ACTION_NAME, + cpp_compile_action_name = _CPP_COMPILE_ACTION_NAME, + follow_attributes = ["_cc_toolchain"], + toolchains_aspects = [], + toolchain_target = _get_cc_toolchain_target, +) diff --git a/aspect/intellij_info_impl.bzl b/aspect/intellij_info_impl.bzl index 6dc96ace39d..d1fb3b1d12e 100644 --- a/aspect/intellij_info_impl.bzl +++ b/aspect/intellij_info_impl.bzl @@ -56,7 +56,7 @@ DEPS = [ "exports", "java_lib", # From old proto_library rules "_android_sdk", # from android rules - "_aidl_lib", # from android_library + "aidl_lib", # from android_sdk "_scala_toolchain", # From scala rules "test_app", # android_instrumentation_test "instruments", # android_instrumentation_test @@ -221,6 +221,10 @@ def collect_targets_from_attrs(rule_attrs, attrs): _collect_target_from_attr(rule_attrs, attr_name, result) return [target for target in result if is_valid_aspect_target(target)] +def targets_to_labels(targets): + """Returns a set of label strings for the given targets.""" + return depset([str(target.label) for target in targets]) + def list_omit_none(value): """Returns a list of the value, or the empty list if None.""" return [value] if value else [] @@ -843,6 +847,8 @@ def _build_filtered_gen_jar(ctx, target, java_outputs, gen_java_sources, srcjars for jar in java_outputs: if jar.ijar: jar_artifacts.append(jar.ijar) + elif jar.class_jar: + jar_artifacts.append(jar.class_jar) if hasattr(jar, "source_jars") and jar.source_jars: source_jar_artifacts.extend(_list_or_depset_to_list(jar.source_jars)) elif hasattr(jar, "source_jar") and jar.source_jar: @@ -915,28 +921,6 @@ def collect_android_info(target, ctx, semantics, ide_info, ide_info_file, output update_sync_output_groups(output_groups, "intellij-info-android", depset([ide_info_file])) return handled -def _get_android_ide_info(target): - """Returns the AndroidIdeInfo provider for the given target.""" - - if hasattr(android_common, "AndroidIdeInfo"): - return target[android_common.AndroidIdeInfo] - - # Backwards compatibility: supports android struct provider - legacy_android = getattr(target, "android") - - # Transform into AndroidIdeInfo form - return struct( - java_package = legacy_android.java_package, - manifest = legacy_android.manifest, - idl_source_jar = getattr(legacy_android.idl.output, "source_jar", None), - idl_class_jar = getattr(legacy_android.idl.output, "class_jar", None), - defines_android_resources = legacy_android.defines_resources, - idl_import_root = getattr(legacy_android.idl, "import_root", None), - resource_jar = legacy_android.resource_jar, - signed_apk = legacy_android.apk, - apks_under_test = legacy_android.apks_under_test, - ) - def _collect_android_ide_info(target, ctx, semantics, ide_info, ide_info_file, output_groups): """Populates ide_info proto and intellij_resolve_android output group @@ -951,7 +935,24 @@ def _collect_android_ide_info(target, ctx, semantics, ide_info, ide_info_file, o android_semantics = semantics.android if hasattr(semantics, "android") else None extra_ide_info = android_semantics.extra_ide_info(target, ctx) if android_semantics else {} - android = _get_android_ide_info(target) + if hasattr(android_common, "AndroidIdeInfo"): + android = target[android_common.AndroidIdeInfo] + else: + # Backwards compatibility: supports android struct provider + legacy_android = getattr(target, "android") + + # Transform into AndroidIdeInfo form + android = struct( + java_package = legacy_android.java_package, + manifest = legacy_android.manifest, + idl_source_jar = getattr(legacy_android.idl.output, "source_jar", None), + idl_class_jar = getattr(legacy_android.idl.output, "class_jar", None), + defines_android_resources = legacy_android.defines_resources, + idl_import_root = getattr(legacy_android.idl, "import_root", None), + resource_jar = legacy_android.resource_jar, + signed_apk = legacy_android.apk, + apks_under_test = legacy_android.apks_under_test, + ) output_jar = struct( class_jar = android.idl_class_jar, @@ -1114,15 +1115,13 @@ def collect_java_toolchain_info(target, ide_info, ide_info_file, output_groups): def artifact_to_path(artifact): return artifact.root_execution_path_fragment + "/" + artifact.relative_path -def collect_kotlin_toolchain_info(target, ctx, ide_info, ide_info_file, output_groups): +def collect_kotlin_toolchain_info(target, ide_info, ide_info_file, output_groups): """Updates kotlin_toolchain-relevant output groups, returns false if not a kotlin_toolchain target.""" - if ctx.rule.kind == "_kt_toolchain" and platform_common.ToolchainInfo in target: - kt = target[platform_common.ToolchainInfo] - elif hasattr(target, "kt") and hasattr(target.kt, "language_version"): - kt = target.kt # Legacy struct provider mechanism - else: + if not hasattr(target, "kt"): + return False + kt = target.kt + if not hasattr(kt, "language_version"): return False - ide_info["kt_toolchain_ide_info"] = struct( language_version = kt.language_version, ) @@ -1292,7 +1291,7 @@ def intellij_info_aspect_impl(target, ctx, semantics): handled = collect_java_info(target, ctx, semantics, ide_info, ide_info_file, output_groups) or handled handled = collect_java_toolchain_info(target, ide_info, ide_info_file, output_groups) or handled handled = collect_android_info(target, ctx, semantics, ide_info, ide_info_file, output_groups) or handled - handled = collect_kotlin_toolchain_info(target, ctx, ide_info, ide_info_file, output_groups) or handled + handled = collect_kotlin_toolchain_info(target, ide_info, ide_info_file, output_groups) or handled # Any extra ide info if hasattr(semantics, "extra_ide_info"): diff --git a/aspect/testing/rules/BUILD b/aspect/testing/rules/BUILD index 835b5cad74b..88401028b64 100644 --- a/aspect/testing/rules/BUILD +++ b/aspect/testing/rules/BUILD @@ -47,7 +47,7 @@ java_library( "//intellij_platform_sdk:jsr305", "//proto:common_java_proto", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) @@ -86,6 +86,6 @@ java_library( deps = [ ":fast_build_aspect_test_fixture_java_proto", "//aspect/testing:guava", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/rules/fast_build_aspect_test_fixture.proto b/aspect/testing/rules/fast_build_aspect_test_fixture.proto index 47b5d51cc99..5ea4fe91eee 100644 --- a/aspect/testing/rules/fast_build_aspect_test_fixture.proto +++ b/aspect/testing/rules/fast_build_aspect_test_fixture.proto @@ -22,4 +22,4 @@ option java_package = "com.google.devtools.intellij.aspect"; message FastBuildAspectTestFixture { repeated FastBuildBlazeData target = 1; -} +} \ No newline at end of file diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/ccbinary/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/ccbinary/BUILD index f5a1b75f9e2..2e2c0361ef6 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/ccbinary/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/ccbinary/BUILD @@ -27,6 +27,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cclibrary/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cclibrary/BUILD index 9a0ec318064..3e4aa18673f 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cclibrary/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cclibrary/BUILD @@ -66,6 +66,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cctest/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cctest/BUILD index 441ae43cd39..74e091f576c 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cctest/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cctest/BUILD @@ -28,6 +28,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cctoolchain/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cctoolchain/BUILD index 5f2842a887c..61bd16d4221 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cctoolchain/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/cctoolchain/BUILD @@ -28,6 +28,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/coptsmakevars/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/coptsmakevars/BUILD index 91226febb4e..e3b260faee4 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/coptsmakevars/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/cpp/coptsmakevars/BUILD @@ -33,6 +33,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/alias/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/alias/BUILD index be24d4bec88..61c07bf6706 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/alias/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/alias/BUILD @@ -43,6 +43,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/analysistest/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/analysistest/BUILD index dc23f814058..06c3059cdcf 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/analysistest/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/analysistest/BUILD @@ -35,6 +35,6 @@ java_test( "//aspect/testing:BazelIntellijAspectTest", "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/artifacts/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/artifacts/BUILD index 8d9de8be671..18c02783c95 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/artifacts/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/artifacts/BUILD @@ -43,6 +43,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/build/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/build/BUILD index faa3a2b5f33..e2fbeb4c3e3 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/build/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/build/BUILD @@ -27,6 +27,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/noide/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/noide/BUILD index 3b1be88c97a..9078a67ed7c 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/noide/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/noide/BUILD @@ -45,6 +45,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/tags/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/tags/BUILD index aeb73664b86..819cd78e3d0 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/tags/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/general/tags/BUILD @@ -35,6 +35,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/go/go_proto_library/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/go/go_proto_library/BUILD index 9a9b164fa4c..1234310d8c7 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/go/go_proto_library/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/go/go_proto_library/BUILD @@ -46,6 +46,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/dependencies/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/dependencies/BUILD index ec2f2177916..8fbf89ea801 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/dependencies/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/dependencies/BUILD @@ -115,6 +115,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/filteredgenjar/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/filteredgenjar/BUILD index 4a2b4ccbcb1..8ec7d53d767 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/filteredgenjar/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/filteredgenjar/BUILD @@ -60,6 +60,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/genjars/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/genjars/BUILD index e8d6664c2f7..576c6ea8c6b 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/genjars/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/genjars/BUILD @@ -19,7 +19,7 @@ intellij_aspect_test_fixture( java_library( name = "has_plugin", srcs = ["Foo.java"], - deps = ["//third_party/auto_value"], + deps = ["//third_party/java/auto_value"], ) intellij_aspect_test_fixture( @@ -41,6 +41,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javabinary/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javabinary/BUILD index c0db35f8749..bf77b0823a6 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javabinary/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javabinary/BUILD @@ -34,6 +34,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javalibrary/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javalibrary/BUILD index 13258abd30a..ca3b0c87b85 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javalibrary/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javalibrary/BUILD @@ -73,6 +73,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javaplugin/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javaplugin/BUILD index c1e532294a4..f2a1d193534 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javaplugin/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javaplugin/BUILD @@ -28,6 +28,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javatest/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javatest/BUILD index 1edfa3a3aba..094ebf0bad8 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javatest/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/javatest/BUILD @@ -14,7 +14,7 @@ java_test( name = "FooTest", size = "large", srcs = ["FooTest.java"], - deps = ["@junit//jar"], + deps = ["//third_party/java/junit"], ) intellij_aspect_test_fixture( @@ -33,7 +33,7 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) @@ -41,7 +41,7 @@ java_test( name = "FooTestNoLauncher", srcs = ["FooTest.java"], test_class = "com.google.idea.blaze.aspect.java.javatest.FooTest", - deps = ["@junit//jar"], + deps = ["//third_party/java/junit"], ) fast_build_aspect_test_fixture( @@ -59,7 +59,7 @@ java_test( srcs = ["FooTest.java"], launcher = ":custom_java_launcher", test_class = "com.google.idea.blaze.aspect.java.javatest.FooTest", - deps = ["@junit//jar"], + deps = ["//third_party/java/junit"], ) fast_build_aspect_test_fixture( @@ -73,7 +73,7 @@ java_test( main_class = "com.google.idea.blaze.aspect.java.javatest.fake.TestRunner", tags = ["manual"], # This test is not meant to be ran on its own. The main class represents a custom test runner. test_class = "com.google.idea.blaze.aspect.java.javatest.FooTest", - deps = ["@junit//jar"], + deps = ["//third_party/java/junit"], ) fast_build_aspect_test_fixture( @@ -95,6 +95,6 @@ java_test( "//aspect/testing/rules:fast_build_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:fast_build_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/pluginprocessorjars/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/pluginprocessorjars/BUILD index 1999af193ba..2cbe4043170 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/pluginprocessorjars/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/java/pluginprocessorjars/BUILD @@ -13,13 +13,13 @@ java_library( java_library( name = "has_plugin", srcs = ["Foo.java"], - plugins = ["//third_party/auto_value:auto_value_plugin"], + deps = ["//third_party/java/auto_value"], ) java_library( name = "has_plugin_deps", srcs = ["Foo.java"], - deps = ["//third_party/auto_value"], + deps = ["//third_party/java/auto_value"], ) intellij_aspect_test_fixture( @@ -57,6 +57,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/proto/jpl/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/proto/jpl/BUILD index 14836e16729..60a447e2974 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/proto/jpl/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/proto/jpl/BUILD @@ -48,6 +48,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pybinary/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pybinary/BUILD index 9062e117250..46d4afe70f0 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pybinary/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pybinary/BUILD @@ -94,6 +94,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pylibrary/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pylibrary/BUILD index 9a050e016b1..b5063b3f691 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pylibrary/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pylibrary/BUILD @@ -29,6 +29,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pytest/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pytest/BUILD index 27b929db763..4b25c8187cf 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pytest/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/python/pytest/BUILD @@ -30,6 +30,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalabinary/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalabinary/BUILD index 485aacdd2b2..3e8c4c7699f 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalabinary/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalabinary/BUILD @@ -38,6 +38,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalalibrary/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalalibrary/BUILD index 19b71b77b12..d067a7ebc29 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalalibrary/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalalibrary/BUILD @@ -29,6 +29,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalamacrolibrary/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalamacrolibrary/BUILD index 3e77908a74c..a899a0c5f90 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalamacrolibrary/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalamacrolibrary/BUILD @@ -29,6 +29,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalatest/BUILD b/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalatest/BUILD index 058fbdde30d..41cc5c75d05 100644 --- a/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalatest/BUILD +++ b/aspect/testing/tests/src/com/google/idea/blaze/aspect/scala/scalatest/BUILD @@ -31,6 +31,6 @@ java_test( "//aspect/testing/rules:intellij_aspect_test_fixture_java_proto", "//intellij_platform_sdk:test_libs", "//proto:intellij_ide_info_java_proto", - "@junit//jar", + "//third_party/java/junit", ], ) diff --git a/aspect/tools/BUILD b/aspect/tools/BUILD index ab8510f0167..2f7a47a4e99 100644 --- a/aspect/tools/BUILD +++ b/aspect/tools/BUILD @@ -9,16 +9,23 @@ package(default_visibility = ["//aspect:__pkg__"]) licenses(["notice"]) +# To prevent versioning conflicts when developing internally, we always use the same +# guava version bundled with the IntelliJ plugin API. +java_library( + name = "guava", + visibility = ["//visibility:private"], + exports = ["//intellij_platform_sdk:guava"], +) + java_library( name = "lib", srcs = glob(["src/**/*.java"]), javacopts = ["-source 8 -target 8"], deps = [ - "//proto:proto_deps", + ":guava", "//third_party/bazel/src/main/protobuf:worker_protocol_java_proto", - "@com_google_guava_failureaccess//jar", - "@com_google_guava_guava//jar", "@jsr305_annotations//jar", + "//proto:proto_deps", ], ) @@ -56,10 +63,10 @@ java_library( exports = [ ":guava", ":lib", + "//proto:proto_deps", + "//third_party/java/junit", "//intellij_platform_sdk:jsr305", "//intellij_platform_sdk:truth", - "//proto:proto_deps", - "@junit//jar", ], ) @@ -78,6 +85,7 @@ java_test( test_class = "com.google.idea.blaze.aspect.PackageParserTest", deps = [ ":test_lib", + "//intellij_platform_sdk:plugin_api", "@error_prone_annotations//jar", ], ) diff --git a/aswb/BUILD b/aswb/BUILD index 00dc5767df5..c7ddae541bc 100644 --- a/aswb/BUILD +++ b/aswb/BUILD @@ -2,7 +2,7 @@ # Description: Builds ASwB for blaze and bazel # -load("@rules_java//java:defs.bzl", "java_library") +load("@bazel_skylib//rules:build_test.bzl", "build_test") load( "//:build-visibility.bzl", "ASWB_PACKAGES_VISIBILITY", @@ -11,9 +11,9 @@ load( "DEFAULT_TEST_VISIBILITY", "TEST_ASWB_SUBPACKAGES_VISIBILITY", ) -load("//:version.bzl", "VERSION") load( "//build_defs:build_defs.bzl", + "combine_visibilities", "intellij_plugin", "intellij_plugin_library", "optional_plugin_xml", @@ -21,20 +21,21 @@ load( "repackaged_files", "stamped_plugin_xml", ) + +# BEGIN-REPO load( - "//build_defs:intellij_plugin_debug_target.bzl", - "intellij_plugin_debug_target", + "//build_defs:restrictions.bzl", + "ALLOWED_EXTERNAL_TEST_DEPENDENCIES", + "EXISTING_EXTERNAL_TEST_VIOLATIONS", + "validate_test_dependencies", ) + +# END-REPO load( "//testing:test_defs.bzl", "intellij_integration_test_suite", "intellij_unit_test_suite", ) -load( - "//intellij_platform_sdk:build_defs.bzl", - "combine_visibilities", - "select_for_plugin_api", -) optional_plugin_xml( name = "optional_ndk_xml", @@ -60,23 +61,13 @@ stamped_plugin_xml( since_build_numbers = {"212": "212.5080.55"}, stamp_since_build = True, stamp_until_build = True, - version = VERSION, + version_file = ":plugin_version.txt", ) java_library( name = "unit_test_utils", testonly = 1, - srcs = glob(["tests/utils/unit/**/*.java"]) + select_for_plugin_api({ - "android-studio-2022.3": [ - "tests/utils/sdkcompat/as223/com/android/ide/common/repository/GoogleMavenArtifactIdCompat.java", - ], - "android-studio-2023.1": [ - "tests/utils/sdkcompat/as231/com/android/ide/common/repository/GoogleMavenArtifactIdCompat.java", - ], - "android-studio-2023.2": [ - "tests/utils/sdkcompat/as232/com/android/ide/common/repository/GoogleMavenArtifactIdCompat.java", - ], - }), + srcs = glob(["tests/utils/unit/**/*.java"]), visibility = combine_visibilities(TEST_ASWB_SUBPACKAGES_VISIBILITY, DEFAULT_TEST_VISIBILITY), deps = [ ":aswb_lib", @@ -90,61 +81,34 @@ java_library( java_library( name = "integration_test_utils", testonly = 1, - srcs = glob(["tests/utils/integration/**/*.java"]) + select_for_plugin_api({ - "android-studio-2022.3": [ - "sdkcompat/as223/com/android/tools/rendering/RenderResultCompat.java", - "tests/utils/sdkcompat/as223/com/android/tools/idea/sdk/IdeSdksCompat.java", - "tests/utils/sdkcompat/as223/com/google/idea/blaze/android/functional/AndroidDeviceCompat.java", - "tests/utils/sdkcompat/as223/com/google/idea/blaze/android/tools/idea/run/editor/AndroidDebuggerCompat.java", - ], - "android-studio-2023.1": [ - "sdkcompat/as231/com/android/tools/rendering/RenderResultCompat.java", - "tests/utils/sdkcompat/as231/com/android/tools/idea/sdk/IdeSdksCompat.java", - "tests/utils/sdkcompat/as231/com/google/idea/blaze/android/functional/AndroidDeviceCompat.java", - "tests/utils/sdkcompat/as231/com/google/idea/blaze/android/tools/idea/run/editor/AndroidDebuggerCompat.java", - ], - "android-studio-2023.2": [ - "sdkcompat/as232/com/android/tools/rendering/RenderResultCompat.java", - "tests/utils/sdkcompat/as232/com/android/tools/idea/sdk/IdeSdksCompat.java", - "tests/utils/sdkcompat/as232/com/google/idea/blaze/android/functional/AndroidDeviceCompat.java", - "tests/utils/sdkcompat/as232/com/google/idea/blaze/android/tools/idea/run/editor/AndroidDebuggerCompat.java", - ], - }), + srcs = glob(["tests/utils/integration/**/*.java"]), visibility = TEST_ASWB_SUBPACKAGES_VISIBILITY, deps = [ ":aswb_lib", - ":unit_test_utils", "//base", "//base:integration_test_utils", "//base:unit_test_utils", "//cpp", - "//intellij_platform_sdk:jsr305", - "//intellij_platform_sdk:plugin_api_for_tests", # unuseddeps: keep - "//intellij_platform_sdk:test_libs", "//java", "//shared:artifact", "//testing:lib", + "//third_party/java/junit", + "//intellij_platform_sdk:plugin_api", + "//intellij_platform_sdk:jsr305", + "//intellij_platform_sdk:plugin_api_for_tests", # unuseddeps: keep + "//intellij_platform_sdk:test_libs", "@com_google_guava_guava//jar", - "@error_prone_annotations//jar", - "@junit//jar", ], ) java_library( name = "aswb_lib", srcs = glob( - ["src/**/*.java"], - # These source files below should be omitted for versions < 2023.1.1.11 - exclude = ["src/com/google/idea/blaze/android/run/binary/tasks/*.java"], - ) + select_for_plugin_api({ - "android-studio-2022.3": glob(["sdkcompat/as223/**/*.java"]), - "android-studio-2023.1": glob(["sdkcompat/as231/**/*.java"] + [ - "src/com/google/idea/blaze/android/run/binary/tasks/*.java", - ]), - "android-studio-2023.2": glob(["sdkcompat/as232/**/*.java"] + [ + [ + "src/**/*.java", "src/com/google/idea/blaze/android/run/binary/tasks/*.java", - ]), - }), + ], + ), resources = glob(["resources/**/*"]), visibility = combine_visibilities( ASWB_SUBPACKAGES_VISIBILITY, @@ -154,16 +118,15 @@ java_library( "//base", "//common/experiments", "//cpp", - "//intellij_platform_sdk:jsr305", # unuseddeps: keep - "//intellij_platform_sdk:kotlin", - "//intellij_platform_sdk:plugin_api", "//java", "//proto:proto_deps", "//querysync", "//shared", "//shared:artifact", - "//third_party/auto_value", - "@gson//jar", + "//third_party/java/auto_value", + "//intellij_platform_sdk:plugin_api", + "//intellij_platform_sdk:jsr305", # unuseddeps: keep + "//intellij_platform_sdk:kotlin", ], ) @@ -173,12 +136,9 @@ intellij_unit_test_suite( ["tests/unittests/**/*.java"], exclude = [ "tests/unittests/com/google/idea/blaze/android/sync/model/idea/BlazeClassJarProviderTest.java", # b/145809318 - ] + glob(["tests/unittests/sdkcompat/**"]), - ) + select_for_plugin_api({ - "android-studio-2022.3": glob(["tests/unittests/sdkcompat/as223/**/*.java"]), - "android-studio-2023.1": glob(["tests/unittests/sdkcompat/as231/**/*.java"]), - "android-studio-2023.2": glob(["tests/unittests/sdkcompat/as232/**/*.java"]), - }), + ], + ), + tags = ["noci:studio-win"], test_package_root = "com.google.idea.blaze.android", visibility = DEFAULT_TEST_VISIBILITY, deps = [ @@ -188,16 +148,16 @@ intellij_unit_test_suite( "//base:unit_test_utils", "//common/experiments", "//common/experiments:unit_test_utils", - "//intellij_platform_sdk:jsr305", - "//intellij_platform_sdk:plugin_api_for_tests", - "//intellij_platform_sdk:test_libs", "//java", "//proto:proto_deps", "//shared", "//shared:artifact", "//testing:lib", + "//third_party/java/junit", + "//intellij_platform_sdk:jsr305", + "//intellij_platform_sdk:plugin_api_for_tests", + "//intellij_platform_sdk:test_libs", "@com_google_guava_guava//jar", - "@junit//jar", ], ) @@ -219,25 +179,16 @@ intellij_integration_test_suite( exclude = [ "tests/integrationtests/com/google/idea/blaze/android/plugin/NdkDependenciesTest.java", # Extracted to separate target "tests/integrationtests/com/google/idea/blaze/android/functional/AswbMergedManifestTest.java", #b/222322106 - ] + glob(["tests/integrationtests/sdkcompat/**"]), - ) + select_for_plugin_api({ - "android-studio-2022.3": glob(["tests/integrationtests/sdkcompat/as223/**/*.java"]), - "android-studio-2023.1": glob(["tests/integrationtests/sdkcompat/as231/**/*.java"]), - "android-studio-2023.2": glob(["tests/integrationtests/sdkcompat/as232/**/*.java"]), - "default": [], - }), - additional_class_rules = select_for_plugin_api({ - "android-studio-2022.3": ["com.google.idea.blaze.android.NormalIntegrationTestSetupRule"], - "android-studio-2023.1": ["com.google.idea.blaze.android.NormalIntegrationTestSetupRule"], - "android-studio-2023.2": ["com.google.idea.blaze.android.NormalIntegrationTestSetupRule"], - "default": [], - }), + ], + ), + additional_class_rules = [], data = [ "testdata/golden.png", "testdata/ic_banner.png", "tools/adt/idea/android/annotations/empty_file", ], required_plugins = "com.google.idea.bazel.aswb,com.android.tools.ndk", + tags = ["noci:studio-win"], test_package_root = "com.google.idea.blaze.android", runtime_deps = [ ":aswb_bazel", @@ -254,15 +205,15 @@ intellij_integration_test_suite( "//common/experiments", "//common/experiments:unit_test_utils", "//cpp", - "//intellij_platform_sdk:jsr305", - "//intellij_platform_sdk:plugin_api_for_tests", - "//intellij_platform_sdk:test_libs", "//java", "//proto:proto_deps", "//shared:artifact", + "//third_party/java/junit", + "//intellij_platform_sdk:plugin_api", + "//intellij_platform_sdk:jsr305", + "//intellij_platform_sdk:plugin_api_for_tests", + "//intellij_platform_sdk:test_libs", "@com_google_guava_guava//jar", - "@gson//jar", - "@junit//jar", ], ) @@ -270,6 +221,7 @@ intellij_integration_test_suite( name = "NdkDependenciesTest", srcs = ["tests/integrationtests/com/google/idea/blaze/android/plugin/NdkDependenciesTest.java"], required_plugins = "com.google.idea.bazel.aswb", + tags = ["noci:studio-win"], test_package_root = "com.google.idea.blaze.android", runtime_deps = [ ":aswb_bazel", @@ -281,10 +233,10 @@ intellij_integration_test_suite( "//base", "//base:integration_test_utils", "//base:unit_test_utils", + "//proto:proto_deps", + "//third_party/java/junit", "//intellij_platform_sdk:plugin_api_for_tests", "//intellij_platform_sdk:test_libs", - "//proto:proto_deps", - "@junit//jar", ], ) @@ -302,9 +254,6 @@ intellij_plugin( "//java:plugin_library", "//kotlin:plugin_library", "//plugin_dev:plugin_library", - # BEGIN-EXTERNAL - "//python:plugin_library", - # END-EXTERNAL "//skylark:plugin_library", "//terminal:plugin_library", ], @@ -319,42 +268,70 @@ repackaged_files( repackaged_files( name = "aspect_directory", srcs = ["//aspect:aspect_files"], + # Build aspect tools with Java 8 so they can work with any Java version in users workspace. + java_copts = [ + "-source", + "8", + "-target", + "8", + ], prefix = "aswb/aspect", strip_prefix = "/aspect", visibility = ASWB_PACKAGES_VISIBILITY, - java_copts = ["-source", "8", "-target", "8"], -) - -repackaged_files( - name = "fast_build_javac", - srcs = ["//java:fast_build_javac"], - prefix = "aswb/lib", - visibility = ASWB_PACKAGES_VISIBILITY, - java_copts = ["-source", "8", "-target", "8"], -) - -intellij_plugin_debug_target( - name = "aswb_bazel_dev", - deps = [ - ":aspect_directory", - ":fast_build_javac", - ":plugin_jar", - ], ) plugin_deploy_zip( name = "aswb_bazel_zip", srcs = [ ":aspect_directory", - ":fast_build_javac", ":plugin_jar", ], visibility = ["//visibility:public"], zip_filename = "aswb_bazel.zip", ) +build_test( + name = "aswb_bazel_build_test", + targets = [ + ":aswb_bazel_zip", + ], +) + genrule( name = "create_empty_annotations_folder", outs = ["tools/adt/idea/android/annotations/empty_file"], cmd = "echo \"No contents\" > $@", ) + +# BEGIN-REPO +validate_test_dependencies( + name = "validate_test_dependencies", + allowed_external_dependencies = ALLOWED_EXTERNAL_TEST_DEPENDENCIES, + existing_external_violations = EXISTING_EXTERNAL_TEST_VIOLATIONS, + deps = [ + "//:aswb_tests", + "//aswb:aswb_bazel_build_test", + "//common/experiments:unit_tests", + "//common/ui/properties:unit_tests", + "//common/util:CommandLineTaskTest", + "//querysync:cli_tools_build_test", + "//shared:tests", + ], +) +# END-REPO + +# Dump the plugin version to a file to be used in stamping the plugin xml +genrule( + name = "plugin_version", + outs = ["plugin_version.txt"], + cmd = """ +# bazel-out/stable-status.txt is created when stamp = True +# Value of BUILD_EMBED_LABEL key comes from --embed_label on the command line +version="$$(grep BUILD_EMBED_LABEL bazel-out/stable-status.txt | cut -d ' ' -f 2)" +# Set a default version if --embed_label was not specified +if [ -z "$$version" ]; then version="9999"; fi + +echo "$$version" > $@ +""", + stamp = True, +) diff --git a/aswb/aswb.iml b/aswb/aswb.iml deleted file mode 100644 index 37230b3044b..00000000000 --- a/aswb/aswb.iml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/aswb/sdkcompat/as223/com/android/tools/idea/rendering/RenderErrorContributorCompat.java b/aswb/sdkcompat/as223/com/android/tools/idea/rendering/RenderErrorContributorCompat.java deleted file mode 100644 index cb3193e1072..00000000000 --- a/aswb/sdkcompat/as223/com/android/tools/idea/rendering/RenderErrorContributorCompat.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.idea.rendering; - -import com.android.tools.idea.ui.designer.EditorDesignSurface; -import com.android.tools.rendering.RenderResultCompat; -import com.intellij.openapi.actionSystem.DataContext; -import org.jetbrains.annotations.Nullable; - -/** Contribute blaze specific render errors. */ -public class RenderErrorContributorCompat extends RenderErrorContributor { - public RenderErrorContributorCompat( - EditorDesignSurface surface, RenderResultCompat result, @Nullable DataContext dataContext) { - super(surface, result.get(), dataContext); - } -} diff --git a/aswb/sdkcompat/as223/com/android/tools/idea/run/tasks/DeployTasksCompat.java b/aswb/sdkcompat/as223/com/android/tools/idea/run/tasks/DeployTasksCompat.java deleted file mode 100644 index 500a6786340..00000000000 --- a/aswb/sdkcompat/as223/com/android/tools/idea/run/tasks/DeployTasksCompat.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2020 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.idea.run.tasks; - -import com.android.tools.idea.run.ApkInfo; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTaskWrapper; -import com.google.idea.common.experiments.BoolExperiment; -import com.intellij.openapi.project.Project; -import java.util.Collection; - -/** Compat class for {@link DeployTask} */ -public class DeployTasksCompat { - private static final BoolExperiment updateCodeViaJvmti = - new BoolExperiment("android.apply.changes", false); - - private DeployTasksCompat() {} - - public static BlazeLaunchTask createDeployTask( - Project project, Collection packages, LaunchOptions launchOptions) { - // We don't have a device information, fallback to the most conservative - // install option. - return new BlazeLaunchTaskWrapper( - new DeployTask( - project, - packages, - launchOptions.getPmInstallOptions(/* device= */ null), - launchOptions.getInstallOnAllUsers(), - launchOptions.getAlwaysInstallWithPm())); - } -} - diff --git a/aswb/sdkcompat/as223/com/android/tools/rendering/RenderLoggerCompat.java b/aswb/sdkcompat/as223/com/android/tools/rendering/RenderLoggerCompat.java deleted file mode 100644 index e1a83953327..00000000000 --- a/aswb/sdkcompat/as223/com/android/tools/rendering/RenderLoggerCompat.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.rendering; - -import com.android.tools.idea.rendering.RenderLogger; -import java.util.Map; -import java.util.Set; - -/** Compat class for RenderLogger. */ -public class RenderLoggerCompat { - private final RenderLogger renderLogger; - - public RenderLoggerCompat(RenderResultCompat result) { - renderLogger = result.getLogger(); - } - - public boolean hasErrors() { - return renderLogger.hasErrors(); - } - - public Map getBrokenClasses() { - return renderLogger.getBrokenClasses(); - } - - public Set getMissingClasses() { - return renderLogger.getMissingClasses(); - } - - public static void resetFidelityErrorsFilters() { - RenderLogger.resetFidelityErrorsFilters(); - } -} diff --git a/aswb/sdkcompat/as223/com/android/tools/rendering/RenderResultCompat.java b/aswb/sdkcompat/as223/com/android/tools/rendering/RenderResultCompat.java deleted file mode 100644 index 8892c2fe813..00000000000 --- a/aswb/sdkcompat/as223/com/android/tools/rendering/RenderResultCompat.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.rendering; - -import com.android.tools.idea.rendering.RenderErrorContributor; -import com.android.tools.idea.rendering.RenderErrorModelFactory; -import com.android.tools.idea.rendering.RenderLogger; -import com.android.tools.idea.rendering.RenderResult; -import com.android.tools.idea.rendering.RenderResults; -import com.android.tools.idea.rendering.errors.ui.RenderErrorModel; -import com.android.tools.idea.ui.designer.EditorDesignSurface; -import com.google.idea.blaze.android.rendering.BlazeRenderErrorContributor; -import com.google.idea.blaze.base.settings.Blaze; -import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiFile; -import org.jetbrains.annotations.Nullable; - -/** Compat class for {@link RenderResult} */ -public final class RenderResultCompat { - private RenderResult result; - - public static RenderResultCompat createBlank(PsiFile file) { - return new RenderResultCompat(RenderResults.createBlank(file)); - } - - public RenderErrorModel createErrorModel() { - return RenderErrorModelFactory.createErrorModel(null, result, null); - } - - public RenderResult get() { - return result; - } - - public RenderLogger getLogger() { - return result.getLogger(); - } - - public Module getModule() { - return result.getModule(); - } - - public RenderResultCompat(RenderResult result) { - this.result = result; - } - - private RenderResultCompat() {} - - /** Extension to provide {@link BlazeRenderErrorContributor}. */ - public static class BlazeProvider extends RenderErrorContributor.Provider { - @Override - public boolean isApplicable(Project project) { - return Blaze.isBlazeProject(project); - } - - @Override - public RenderErrorContributor getContributor( - @Nullable EditorDesignSurface surface, - RenderResult result, - @Nullable DataContext dataContext) { - return new BlazeRenderErrorContributor(surface, new RenderResultCompat(result), dataContext); - } - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java deleted file mode 100644 index 7aa210d0595..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.cppimpl.debug; - -import com.android.ddmlib.Client; -import com.android.tools.ndk.run.editor.AutoAndroidDebuggerState; -import com.intellij.execution.ExecutionException; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.xdebugger.XDebugSession; - -/** Shim for #api212 compat. */ -public class BlazeAutoAndroidDebugger extends BlazeAutoAndroidDebuggerBase { - @Override - public XDebugSession attachToClient( - Project project, Client client, AutoAndroidDebuggerState state) throws ExecutionException { - if (isNativeProject(project)) { - log.info("Project has native development enabled. Attaching native debugger."); - return nativeDebugger.attachToClient(project, client, state); - } else { - return super.attachToClient(project, client, state); - } - } - - @Override - protected boolean isNativeDeployment(Project project, Module debuggeeModule) { - return isNativeProject(project); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebuggerBase.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebuggerBase.java deleted file mode 100644 index 911d90b7711..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebuggerBase.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2020 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.cppimpl.debug; - -import com.android.tools.ndk.run.editor.NativeAndroidDebugger; -import com.google.idea.blaze.base.model.BlazeProjectData; -import com.google.idea.blaze.base.model.primitives.LanguageClass; -import com.google.idea.blaze.base.settings.Blaze; -import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager; -import com.intellij.openapi.project.Project; - -/** - * Extension of {@link NativeAndroidDebugger} with the following key differences compared to {@link - * NativeAndroidDebugger}. - * - *
    - *
  • Overrides {@link #supportsProject} so native debugger is only enabled for native support is - * enabled. - *
- */ -public class BlazeNativeAndroidDebuggerBase extends NativeAndroidDebugger { - /** - * This ID needs to be lexicographically larger than "Java" so it come after the "Java" debugger - * when sorted lexicographically in the "Attach Debugger to Android Process" dialog. See {@link - * org.jetbrains.android.actions.AndroidProcessChooserDialog#populateDebuggerTypeCombo}. - */ - public static final String ID = "Native" + Blaze.defaultBuildSystemName(); - - @Override - public String getId() { - return ID; - } - - @Override - public String getDisplayName() { - return "Native Only"; - } - - @Override - public boolean supportsProject(Project project) { - BlazeProjectData blazeProjectData = - BlazeProjectDataManager.getInstance(project).getBlazeProjectData(); - return blazeProjectData != null - && blazeProjectData.getWorkspaceLanguageSettings().isLanguageActive(LanguageClass.C); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/projectsystem/BlazeModuleSystem.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/projectsystem/BlazeModuleSystem.java deleted file mode 100644 index 162fd8f1793..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/projectsystem/BlazeModuleSystem.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2020 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.projectsystem; - -import com.android.tools.idea.projectsystem.AndroidModuleSystem; -import com.intellij.openapi.module.Module; - -/** Blaze implementation of {@link AndroidModuleSystem}. */ -public class BlazeModuleSystem extends BlazeModuleSystemBase { - - BlazeModuleSystem(Module module) { - super(module); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/projectsystem/BlazeProjectSystem.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/projectsystem/BlazeProjectSystem.java deleted file mode 100755 index 4aa6e3b854d..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/projectsystem/BlazeProjectSystem.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright 2017 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.projectsystem; - -import static com.android.tools.idea.projectsystem.SourceProvidersKt.emptySourceProvider; -import static org.jetbrains.android.facet.SourceProviderUtil.createSourceProvidersForLegacyModule; - -import com.android.tools.apk.analyzer.AaptInvoker; -import com.android.tools.idea.log.LogWrapper; -import com.android.tools.idea.model.AndroidModel; -import com.android.tools.idea.model.ClassJarProvider; -import com.android.tools.idea.projectsystem.AndroidModuleSystem; -import com.android.tools.idea.projectsystem.AndroidProjectSystem; -import com.android.tools.idea.projectsystem.NamedIdeaSourceProvider; -import com.android.tools.idea.projectsystem.ProjectSystemBuildManager; -import com.android.tools.idea.projectsystem.ProjectSystemSyncManager; -import com.android.tools.idea.projectsystem.ScopeType; -import com.android.tools.idea.projectsystem.SourceProviderManager; -import com.android.tools.idea.projectsystem.SourceProviders; -import com.android.tools.idea.projectsystem.SourceProvidersFactory; -import com.android.tools.idea.projectsystem.SourceProvidersImpl; -import com.android.tools.idea.res.AndroidInnerClassFinder; -import com.android.tools.idea.res.AndroidResourceClassPsiElementFinder; -import com.android.tools.idea.sdk.AndroidSdks; -import com.google.common.collect.ImmutableList; -import com.google.idea.blaze.android.resources.BlazeLightResourceClassService; -import com.google.idea.blaze.android.sync.model.idea.BlazeAndroidModel; -import com.google.idea.blaze.android.sync.model.idea.BlazeClassJarProvider; -import com.google.idea.blaze.base.settings.Blaze; -import com.google.idea.blaze.base.settings.BlazeImportSettings.ProjectType; -import com.intellij.facet.ProjectFacetManager; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiElementFinder; -import com.intellij.psi.search.GlobalSearchScope; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.annotations.NotNull; - -/** - * Base class to implement common methods in {@link AndroidProjectSystem} for blaze with different - * sdk - */ -public class BlazeProjectSystem implements AndroidProjectSystem { - protected final Project project; - protected final ProjectSystemSyncManager syncManager; - protected final List myFinders; - private final BlazeProjectSystemBuildManager buildManager; - - public BlazeProjectSystem(Project project) { - this.project = project; - syncManager = new BlazeProjectSystemSyncManager(project); - buildManager = new BlazeProjectSystemBuildManager(project); - - myFinders = - Arrays.asList( - AndroidInnerClassFinder.INSTANCE, - new AndroidResourceClassPsiElementFinder(getLightResourceClassService())); - } - - public Project getProject() { - return project; - } - - @Override - public boolean allowsFileCreation() { - return true; - } - - @Nullable - @Override - public VirtualFile getDefaultApkFile() { - return null; - } - - @Override - public Path getPathToAapt() { - return AaptInvoker.getPathToAapt( - AndroidSdks.getInstance().tryToChooseSdkHandler(), - new LogWrapper(BlazeProjectSystem.class)); - } - - @Override - public ProjectSystemBuildManager getBuildManager() { - return buildManager; - } - - @Override - public AndroidModuleSystem getModuleSystem(Module module) { - return BlazeModuleSystem.getInstance(module); - } - - @Override - public ProjectSystemSyncManager getSyncManager() { - return syncManager; - } - - @Override - public Collection getPsiElementFinders() { - return myFinders; - } - - @Override - public BlazeLightResourceClassService getLightResourceClassService() { - return BlazeLightResourceClassService.getInstance(project); - } - - @Override - public SourceProvidersFactory getSourceProvidersFactory() { - return new SourceProvidersFactory() { - @Override - public SourceProviders createSourceProvidersFor(AndroidFacet facet) { - BlazeAndroidModel model = ((BlazeAndroidModel) AndroidModel.get(facet)); - if (model != null) { - return createForModel(model); - } else { - return createSourceProvidersForLegacyModule(facet); - } - } - - private SourceProviders createForModel(BlazeAndroidModel model) { - NamedIdeaSourceProvider mainSourceProvider = model.getDefaultSourceProvider(); - if (Blaze.getProjectType(project).equals(ProjectType.QUERY_SYNC)) { - return new SourceProvidersImpl( - mainSourceProvider, - ImmutableList.of(mainSourceProvider), - ImmutableList.of(), - ImmutableList.of(), - ImmutableList.of(), - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - emptySourceProvider(ScopeType.MAIN), - emptySourceProvider(ScopeType.UNIT_TEST), - emptySourceProvider(ScopeType.ANDROID_TEST), - emptySourceProvider(ScopeType.TEST_FIXTURES)); - } else { - return new SourceProvidersImpl( - mainSourceProvider, - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - emptySourceProvider(ScopeType.MAIN), - emptySourceProvider(ScopeType.UNIT_TEST), - emptySourceProvider(ScopeType.ANDROID_TEST), - emptySourceProvider(ScopeType.TEST_FIXTURES)); - } - } - }; - } - - @Override - public ClassJarProvider getClassJarProvider() { - return new BlazeClassJarProvider(project); - } - - @Override - public Collection getAndroidFacetsWithPackageName( - Project project, String packageName) { - return getAndroidFacetsWithPackageName( - project, packageName, GlobalSearchScope.projectScope(project)); - } - - private Collection getAndroidFacetsWithPackageName( - Project project, String packageName, GlobalSearchScope scope) { - List facets = ProjectFacetManager.getInstance(project).getFacets(AndroidFacet.ID); - return facets.stream() - .filter(facet -> hasPackageName(facet, packageName)) - .filter( - facet -> { - VirtualFile file = SourceProviderManager.getInstance(facet).getMainManifestFile(); - if (file == null) { - return false; - } else { - return scope.contains(file); - } - }) - .collect(Collectors.toList()); - } - - @Override - public Collection getSubmodules() { - return ImmutableList.of(); - } - - @Override - public Collection getBootClasspath(@NotNull Module module) { - // TODO: b/266586669 - return ImmutableList.of(); - } - - private static boolean hasPackageName(AndroidFacet facet, String packageName) { - String nameFromFacet = PackageNameUtils.getPackageName(facet.getModule()); - if (nameFromFacet == null) { - return false; - } - return nameFromFacet.equals(packageName); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java deleted file mode 100644 index 81504173f22..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright 2020 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.projectsystem; - -import static java.util.stream.Collectors.joining; - -import com.android.tools.idea.projectsystem.ClassFileFinder; -import com.android.tools.idea.projectsystem.ClassFileFinderUtil; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableSet; -import com.google.idea.blaze.android.libraries.RenderJarCache; -import com.google.idea.blaze.android.sync.model.AndroidResourceModule; -import com.google.idea.blaze.android.sync.model.AndroidResourceModuleRegistry; -import com.google.idea.blaze.android.targetmaps.TargetToBinaryMap; -import com.google.idea.blaze.base.ideinfo.TargetIdeInfo; -import com.google.idea.blaze.base.ideinfo.TargetKey; -import com.google.idea.blaze.base.io.VirtualFileSystemProvider; -import com.google.idea.blaze.base.model.BlazeProjectData; -import com.google.idea.blaze.base.qsync.QuerySync; -import com.google.idea.blaze.base.qsync.QuerySyncManager; -import com.google.idea.blaze.base.qsync.RenderJarArtifactTracker; -import com.google.idea.blaze.base.settings.Blaze; -import com.google.idea.blaze.base.settings.BlazeImportSettings.ProjectType; -import com.google.idea.blaze.base.sync.BlazeSyncModificationTracker; -import com.google.idea.blaze.base.sync.data.BlazeDataStorage; -import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager; -import com.google.idea.common.experiments.BoolExperiment; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.JarFileSystem; -import com.intellij.openapi.vfs.VirtualFile; -import java.io.File; -import java.util.regex.Pattern; -import org.jetbrains.annotations.Nullable; - -/** - * A {@link ClassFileFinder} that uses deploy JAR like artifacts (called render jar henceforth) for - * class files. - * - *

The render JAR contains all runtime dependencies of a binary target. - * - *

The Blaze targets that go into creating a resource module is known. Consequently, it is - * possible to determine which binaries in the projectview depend on the resource declaring blaze - * targets that constitutes the module. This class calculates the binary targets and attempts to - * find classes from the render JARs. - * - *

This only works for resource modules (i.e. not the .workspace module). For .workspace module, - * we try to find the class in all binary targets in projectview - * - *

NOTE: Blaze targets that constitutes the resource module will be called "resource target(s)" - * in comments below. - */ -public class RenderJarClassFileFinder implements ClassFileFinder { - /** Experiment to control whether class file finding from render jars should be enabled. */ - private static final BoolExperiment enabled = - new BoolExperiment("aswb.renderjar.cff.enabled.3", true); - - /** - * Experiment to toggle whether resource resolution is allowed from Render JARs. Render JARs - * should not resolve resources by default. - */ - @VisibleForTesting - static final BoolExperiment resolveResourceClasses = - new BoolExperiment("aswb.resolve.resources.render.jar", false); - - private static final Logger log = Logger.getInstance(RenderJarClassFileFinder.class); - - private static final String INTERNAL_PACKAGE = "_layoutlib_._internal_."; - - // matches foo.bar.R or foo.bar.R$baz - private static final Pattern RESOURCE_CLASS_NAME = Pattern.compile(".+\\.R(\\$[^.]+)?$"); - - private final Module module; - private final Project project; - - // tracks the binary targets that depend resource targets - // will be recalculated after every sync - private ImmutableSet binaryTargets = ImmutableSet.of(); - - // tracks the value of {@link BlazeSyncModificationTracker} when binaryTargets is calculated - // binaryTargets is calculated when the value of {@link BlazeSyncModificationTracker} does not - // equal lastSyncCount - long lastSyncCount = -1; - - // true if the current module is the .workspace Module - private final boolean isWorkspaceModule; - - public RenderJarClassFileFinder(Module module) { - this.module = module; - this.project = module.getProject(); - this.isWorkspaceModule = BlazeDataStorage.WORKSPACE_MODULE_NAME.equals(module.getName()); - } - - @Nullable - @Override - public VirtualFile findClassFile(String fqcn) { - if (!isEnabled()) { - return null; - } - - // Ever since Compose support was introduced in AS, finding class files is invoked during the - // normal course of opening an editor. The contract for this method requires that it shouldn't - // throw any exceptions, but we've had a few bugs where this method threw an exception, which - // resulted in users not being able to open Kotlin files at all. In order to avoid this - // scenario, we wrap the underlying call and ensure that no exceptions are thrown. - try { - return findClass(fqcn); - } catch (Error e) { - log.warn( - String.format( - "Unexpected error while finding the class file for `%1$s`: %2$s", - fqcn, Throwables.getRootCause(e).getMessage())); - return null; - } - } - - @Nullable - public VirtualFile findClass(String fqcn) { - // Render JAR should not resolve any resources. All resources should be available to the IDE - // through ResourceRepository. Attempting to resolve resources from Render JAR indicates that - // ASwB hasn't properly set up resources for the project. - if (isResourceClass(fqcn) && !resolveResourceClasses.getValue()) { - log.warn(String.format("Attempting to load resource '%s' from RenderJAR.", fqcn)); - return null; - } - - if (Blaze.getProjectType(project).equals(ProjectType.QUERY_SYNC)) { - if (QuerySync.isComposeEnabled(project)) { - RenderJarArtifactTracker renderJarArtifactTracker = - QuerySyncManager.getInstance(project).getRenderJarArtifactTracker(); - // TODO(b/283280194): Setup fqcn -> target and target -> Render jar mappings to avoid - // iterating over all render jars when trying to locate class for fqcn. - // TODO(b/284002836): Collect metrics on time taken to iterate over the jars - for (File renderJar : renderJarArtifactTracker.getRenderJars()) { - VirtualFile renderResolveJarVf = - VirtualFileSystemProvider.getInstance().getSystem().findFileByIoFile(renderJar); - if (renderResolveJarVf != null) { - return findClassInJar(renderResolveJarVf, fqcn); - } - log.warn(String.format("Could not find class `%1$s` with Query Sync", fqcn)); - return null; - } - } else { - // Disable this class for Query Sync if Compose is not enabled - return null; - } - } - - BlazeProjectData projectData = - BlazeProjectDataManager.getInstance(project).getBlazeProjectData(); - if (projectData == null) { - log.warn("Could not find BlazeProjectData for project " + project.getName()); - return null; - } - - ImmutableSet binaryTargets = getBinaryTargets(); - if (binaryTargets.isEmpty()) { - log.warn( - String.format( - "No binaries for module %s. Adding a binary target to the projectview and resyncing" - + " might fix the issue.", - module.getName())); - return null; - } - - // Remove internal package prefix if present - fqcn = StringUtil.trimStart(fqcn, INTERNAL_PACKAGE); - - // Look through render resolve JARs of the binaries that depend on the given - // androidResourceModule. One androidResourceModule can comprise of multiple resource targets. - // The binaries can depend on any subset of these resource targets. Generally, we only - // expect one, or a small number of binaries here. - for (TargetKey binaryTarget : binaryTargets) { - VirtualFile classFile = getClassFromRenderResolveJar(projectData, fqcn, binaryTarget); - if (classFile != null) { - return classFile; - } - } - - log.warn(String.format("Could not find class `%1$s` (module: `%2$s`)", fqcn, module.getName())); - return null; - } - - @VisibleForTesting - static boolean isResourceClass(String fqcn) { - return RESOURCE_CLASS_NAME.matcher(fqcn).matches(); - } - - /** - * Returns the cached list of binary targets that depend on resource targets. The cache is - * recalculated if the project has been synced since last calculation - */ - private ImmutableSet getBinaryTargets() { - long currentSyncCount = - BlazeSyncModificationTracker.getInstance(project).getModificationCount(); - if (currentSyncCount == lastSyncCount) { - // Return the cached set if there hasn't been a sync since last calculation - return binaryTargets; - } - lastSyncCount = currentSyncCount; - - AndroidResourceModule androidResourceModule = - AndroidResourceModuleRegistry.getInstance(project).get(module); - if (androidResourceModule != null) { - binaryTargets = - TargetToBinaryMap.getInstance(project) - .getBinariesDependingOn(androidResourceModule.sourceTargetKeys); - } else if (isWorkspaceModule) { - binaryTargets = TargetToBinaryMap.getInstance(project).getSourceBinaryTargets(); - } else { - binaryTargets = ImmutableSet.of(); - log.warn("Could not find AndroidResourceModule for " + module.getName()); - } - log.info( - String.format( - "Binary targets for module `%1$s`: %2$s", - module.getName(), - binaryTargets.stream() - .limit(5) - .map(t -> t.getLabel().toString()) - .collect(joining(", ")))); - return binaryTargets; - } - - /** - * Returns class file for fqcn if found in the render JAR corresponding to {@code binaryTarget}. - * Returns null if something goes wrong or if render JAR does not contain fqcn - */ - @Nullable - private VirtualFile getClassFromRenderResolveJar( - BlazeProjectData projectData, String fqcn, TargetKey binaryTarget) { - TargetIdeInfo ideInfo = projectData.getTargetMap().get(binaryTarget); - if (ideInfo == null) { - return null; - } - - File renderResolveJarFile = - RenderJarCache.getInstance(project) - .getCachedJarForBinaryTarget(projectData.getArtifactLocationDecoder(), ideInfo); - - if (renderResolveJarFile == null) { - return null; - } - - VirtualFile renderResolveJarVF = - VirtualFileSystemProvider.getInstance().getSystem().findFileByIoFile(renderResolveJarFile); - if (renderResolveJarVF == null) { - return null; - } - - return findClassInJar(renderResolveJarVF, fqcn); - } - - @Nullable - private static VirtualFile findClassInJar(final VirtualFile classJar, String fqcn) { - VirtualFile jarRoot = getJarRootForLocalFile(classJar); - if (jarRoot == null) { - return null; - } - return ClassFileFinderUtil.findClassFileInOutputRoot(jarRoot, fqcn); - } - - /** Test aware method to redirect JARs to {@link VirtualFileSystemProvider} for tests */ - private static VirtualFile getJarRootForLocalFile(VirtualFile file) { - return ApplicationManager.getApplication().isUnitTestMode() - ? VirtualFileSystemProvider.getInstance() - .getSystem() - .findFileByPath(file.getPath() + JarFileSystem.JAR_SEPARATOR) - : JarFileSystem.getInstance().getJarRootForLocalFile(file); - } - - public static boolean isEnabled() { - return enabled.getValue(); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/rendering/BlazeRenderSecurityManagerOverrides.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/rendering/BlazeRenderSecurityManagerOverrides.java deleted file mode 100644 index a1fd771fddc..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/rendering/BlazeRenderSecurityManagerOverrides.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2018 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.rendering; - -import com.android.tools.idea.rendering.RenderSecurityManagerOverrides; - -/** Overrides some security restrictions used by the render sandbox. */ -public class BlazeRenderSecurityManagerOverrides implements RenderSecurityManagerOverrides { - @Override - public boolean allowsPropertiesAccess() { - // System properties access is needed for SystemPropertyExperimentLoader - return true; - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/resources/BlazeLightResourceClassServiceBase.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/resources/BlazeLightResourceClassServiceBase.java deleted file mode 100644 index 21516076cc2..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/resources/BlazeLightResourceClassServiceBase.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.resources; - -import com.android.tools.idea.projectsystem.LightResourceClassService; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.idea.blaze.base.sync.data.BlazeDataStorage; -import com.google.idea.common.experiments.FeatureRolloutExperiment; -import com.intellij.openapi.module.Module; -import com.intellij.psi.PsiClass; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -/** Implementation of {@link LightResourceClassService} set up at Blaze sync time. */ -public abstract class BlazeLightResourceClassServiceBase implements LightResourceClassService { - - @VisibleForTesting - public static final FeatureRolloutExperiment workspaceResourcesFeature = - new FeatureRolloutExperiment("aswb.workspace.light.class.enabled"); - - Map rClasses = Maps.newHashMap(); - Map rClassesByModule = Maps.newHashMap(); - final Set allRClasses = Sets.newHashSet(); - - @Override - public Collection getLightRClassesAccessibleFromModule( - Module module, boolean includeTest) { - if (workspaceResourcesFeature.isEnabled() - && module.getName().equals(BlazeDataStorage.WORKSPACE_MODULE_NAME)) { - // Returns all the packages in resource modules, and all the workspace packages that - // have previously been asked for. All `res/` directories in our project should belong to a - // resource module. For java sources, IntelliJ will ask for explicit resource package by - // calling `getLightRClasses` at which point we can create the package. This is not completely - // correct and the autocomplete will be slightly off when initial `R` is typed in the editor, - // but this workaround is being used to mitigate issues (b/136685602) while resources - // are re-worked. - return allRClasses; - } else { - return rClasses.values(); - } - } - - @Override - public Collection getLightRClassesDefinedByModule( - Module module, boolean includeTestClasses) { - BlazeRClass rClass = rClassesByModule.get(module); - return rClass == null ? ImmutableSet.of() : ImmutableSet.of(rClass); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/resources/BlazeRClass.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/resources/BlazeRClass.java deleted file mode 100644 index 5a8cbf8e450..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/resources/BlazeRClass.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2018 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.resources; - -import static org.jetbrains.android.AndroidResolveScopeEnlarger.LIGHT_CLASS_KEY; -import static org.jetbrains.android.AndroidResolveScopeEnlarger.MODULE_POINTER_KEY; - -import com.android.ide.common.rendering.api.ResourceNamespace; -import com.android.tools.idea.res.LocalResourceRepository; -import com.android.tools.idea.res.ResourceRepositoryRClass; -import com.android.tools.idea.res.StudioResourceRepositoryManager; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModulePointerManager; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiManager; -import org.jetbrains.android.augment.AndroidLightField; -import org.jetbrains.android.facet.AndroidFacet; - -/** Blaze implementation of an R class based on resource repositories. */ -public class BlazeRClass extends ResourceRepositoryRClass { - - private final AndroidFacet androidFacet; - - public BlazeRClass(PsiManager psiManager, AndroidFacet androidFacet, String packageName) { - super( - psiManager, - new ResourcesSource() { - @Override - public String getPackageName() { - return packageName; - } - - @Override - public Transitivity getTransitivity() { - return Transitivity.TRANSITIVE; - } - - @Override - public StudioResourceRepositoryManager getResourceRepositoryManager() { - return StudioResourceRepositoryManager.getInstance(androidFacet); - } - - @Override - public LocalResourceRepository getResourceRepository() { - return StudioResourceRepositoryManager.getAppResources(androidFacet); - } - - @Override - public ResourceNamespace getResourceNamespace() { - return ResourceNamespace.RES_AUTO; - } - - @Override - public AndroidLightField.FieldModifier getFieldModifier() { - return AndroidLightField.FieldModifier.NON_FINAL; - } - }); - this.androidFacet = androidFacet; - setModuleInfo(getModule(), false); - VirtualFile virtualFile = myFile.getViewProvider().getVirtualFile(); - virtualFile.putUserData( - MODULE_POINTER_KEY, ModulePointerManager.getInstance(getProject()).create(getModule())); - virtualFile.putUserData(LIGHT_CLASS_KEY, ResourceRepositoryRClass.class); - } - - public Module getModule() { - return androidFacet.getModule(); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryApplicationLaunchTaskProvider.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryApplicationLaunchTaskProvider.java deleted file mode 100644 index 8a74f3d458f..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryApplicationLaunchTaskProvider.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.activity.StartActivityFlagsProvider; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTaskWrapper; -import com.android.tools.idea.run.tasks.AndroidDeepLinkLaunchTask; -import com.android.tools.idea.run.tasks.DefaultActivityLaunchTask; -import com.android.tools.idea.run.tasks.SpecificActivityLaunchTask; -import com.google.idea.blaze.android.manifest.ManifestParser; -import com.intellij.execution.ExecutionException; -import com.intellij.openapi.diagnostic.Logger; - -/** Provides the launch task for android_binary */ -public class BlazeAndroidBinaryApplicationLaunchTaskProvider { - private static final Logger LOG = - Logger.getInstance(BlazeAndroidBinaryApplicationLaunchTaskProvider.class); - - public static BlazeLaunchTask getApplicationLaunchTask( - ApplicationIdProvider applicationIdProvider, - ManifestParser.ParsedManifest mergedManifestParsedManifest, - BlazeAndroidBinaryRunConfigurationState configState, - StartActivityFlagsProvider startActivityFlagsProvider) - throws ExecutionException { - try { - String applicationId = applicationIdProvider.getPackageName(); - - switch (configState.getMode()) { - case BlazeAndroidBinaryRunConfigurationState.LAUNCH_DEFAULT_ACTIVITY: - BlazeDefaultActivityLocator activityLocator = - new BlazeDefaultActivityLocator(mergedManifestParsedManifest); - return new BlazeLaunchTaskWrapper( - new DefaultActivityLaunchTask( - applicationId, activityLocator, startActivityFlagsProvider)); - case BlazeAndroidBinaryRunConfigurationState.LAUNCH_SPECIFIC_ACTIVITY: - return new BlazeLaunchTaskWrapper( - new SpecificActivityLaunchTask( - applicationId, configState.getActivityClass(), startActivityFlagsProvider)); - case BlazeAndroidBinaryRunConfigurationState.LAUNCH_DEEP_LINK: - return new BlazeLaunchTaskWrapper( - new AndroidDeepLinkLaunchTask(configState.getDeepLink(), startActivityFlagsProvider)); - case BlazeAndroidBinaryRunConfigurationState.DO_NOTHING: - default: - return null; - } - } catch (ApkProvisionException e) { - throw new ExecutionException("Unable to identify application id"); - } - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java deleted file mode 100644 index 6b2d10e2dac..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2019 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import static com.android.tools.idea.run.tasks.DefaultConnectDebuggerTaskKt.getBaseDebuggerTask; - -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.activity.DefaultStartActivityFlagsProvider; -import com.android.tools.idea.run.activity.StartActivityFlagsProvider; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.tasks.ConnectDebuggerTask; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.project.Project; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; - -/** Compat for #api212 */ -public class BlazeAndroidBinaryNormalBuildRunContext - extends BlazeAndroidBinaryNormalBuildRunContextBase { - BlazeAndroidBinaryNormalBuildRunContext( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - super(project, facet, runConfiguration, env, configState, buildStep, launchId); - } - - @Override - public BlazeLaunchTask getApplicationLaunchTask( - LaunchOptions launchOptions, @Nullable Integer userId, String contributorsAmStartOptions) - throws ExecutionException { - String extraFlags = UserIdHelper.getFlagsFromUserId(userId); - if (!contributorsAmStartOptions.isEmpty()) { - extraFlags += (extraFlags.isEmpty() ? "" : " ") + contributorsAmStartOptions; - } - - final StartActivityFlagsProvider startActivityFlagsProvider = - new DefaultStartActivityFlagsProvider(project, launchOptions.isDebug(), extraFlags); - - BlazeAndroidDeployInfo deployInfo; - try { - deployInfo = buildStep.getDeployInfo(); - } catch (ApkProvisionException e) { - throw new ExecutionException(e); - } - - return BlazeAndroidBinaryApplicationLaunchTaskProvider.getApplicationLaunchTask( - applicationIdProvider, - deployInfo.getMergedManifest(), - configState, - startActivityFlagsProvider); - } - - @Nullable - @Override - @SuppressWarnings("unchecked") - public ConnectDebuggerTask getDebuggerTask( - AndroidDebugger androidDebugger, AndroidDebuggerState androidDebuggerState) { - return getBaseDebuggerTask(androidDebugger, androidDebuggerState, env, facet); - } - - @Override - public Executor getExecutor() { - return env.getExecutor(); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java deleted file mode 100644 index 0dac5606ada..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import static com.google.idea.blaze.android.run.runner.BlazeAndroidLaunchTasksProvider.NATIVE_DEBUGGING_ENABLED; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.gradle.util.DynamicAppUtils; -import com.android.tools.idea.run.ApkFileUnit; -import com.android.tools.idea.run.ApkInfo; -import com.android.tools.idea.run.ApkProvider; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.ConsoleProvider; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; -import com.android.tools.idea.run.editor.ProfilerState; -import com.android.tools.idea.run.tasks.DeployTasksCompat; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.idea.blaze.android.run.deployinfo.BlazeApkProviderService; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.android.run.runner.BlazeAndroidDeviceSelector; -import com.google.idea.blaze.android.run.runner.BlazeAndroidLaunchTasksProvider; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunContext; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.project.Project; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.annotations.NotNull; - -/** Run context for android_binary. */ -public abstract class BlazeAndroidBinaryNormalBuildRunContextBase - implements BlazeAndroidRunContext { - protected final Project project; - protected final AndroidFacet facet; - protected final RunConfiguration runConfiguration; - protected final ExecutionEnvironment env; - protected final BlazeAndroidBinaryRunConfigurationState configState; - protected final ConsoleProvider consoleProvider; - protected final ApkBuildStep buildStep; - protected final ApkProvider apkProvider; - protected final ApplicationIdProvider applicationIdProvider; - private final String launchId; - - BlazeAndroidBinaryNormalBuildRunContextBase( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - this.project = project; - this.facet = facet; - this.runConfiguration = runConfiguration; - this.env = env; - this.configState = configState; - this.consoleProvider = new BlazeAndroidBinaryConsoleProvider(project); - this.buildStep = buildStep; - this.apkProvider = BlazeApkProviderService.getInstance().getApkProvider(project, buildStep); - this.applicationIdProvider = new BlazeAndroidBinaryApplicationIdProvider(buildStep); - this.launchId = launchId; - } - - @Override - public BlazeAndroidDeviceSelector getDeviceSelector() { - return new BlazeAndroidDeviceSelector.NormalDeviceSelector(); - } - - @Override - public void augmentLaunchOptions(LaunchOptions.Builder options) { - options.setDeploy(true).setOpenLogcatAutomatically(configState.showLogcatAutomatically()); - options.addExtraOptions( - ImmutableMap.of( - "android.profilers.state", // Not used after #api211 - configState.getProfilerState(), - NATIVE_DEBUGGING_ENABLED, - configState.getCommonState().isNativeDebuggingEnabled())); - } - - @Override - public ConsoleProvider getConsoleProvider() { - return consoleProvider; - } - - @Override - public ApplicationIdProvider getApplicationIdProvider() { - return applicationIdProvider; - } - - @Override - public ApkBuildStep getBuildStep() { - return buildStep; - } - - @Nullable - @Override - public Integer getUserId(IDevice device) throws ExecutionException { - return UserIdHelper.getUserIdFromConfigurationState(project, device, configState); - } - - @Override - public BlazeLaunchTasksProvider getLaunchTasksProvider(LaunchOptions.Builder launchOptionsBuilder) - throws ExecutionException { - return new BlazeAndroidLaunchTasksProvider( - project, this, applicationIdProvider, launchOptionsBuilder); - } - - @Override - public String getAmStartOptions() { - return configState.getAmStartOptions(); - } - - @Override - public ProfilerState getProfileState() { - return configState.getProfilerState(); - } - - @Nullable - @Override - public ImmutableList getDeployTasks(IDevice device, LaunchOptions launchOptions) - throws ExecutionException { - BlazeLaunchTask deployTask = - DeployTasksCompat.createDeployTask( - project, getApkInfoToInstall(device, launchOptions, apkProvider), launchOptions); - return ImmutableList.of(new DeploymentTimingReporterTask(launchId, deployTask)); - } - - /** Returns a list of APKs excluding any APKs for features that are disabled. */ - public static List getApkInfoToInstall( - IDevice device, LaunchOptions launchOptions, ApkProvider apkProvider) - throws ExecutionException { - Collection apks; - try { - apks = apkProvider.getApks(device); - } catch (ApkProvisionException e) { - throw new ExecutionException(e); - } - List disabledFeatures = launchOptions.getDisabledDynamicFeatures(); - return apks.stream() - .map(apk -> getApkInfoToInstall(apk, disabledFeatures)) - .collect(Collectors.toList()); - } - - @NotNull - private static ApkInfo getApkInfoToInstall(ApkInfo apkInfo, List disabledFeatures) { - if (apkInfo.getFiles().size() > 1) { - List filteredApks = - apkInfo.getFiles().stream() - .filter(feature -> DynamicAppUtils.isFeatureEnabled(disabledFeatures, feature)) - .collect(Collectors.toList()); - return new ApkInfo(filteredApks, apkInfo.getApplicationId()); - } else { - return apkInfo; - } - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextCompat.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextCompat.java deleted file mode 100644 index d54c472c84b..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextCompat.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import static com.android.tools.idea.run.tasks.DefaultConnectDebuggerTaskKt.getBaseDebuggerTask; - -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.run.tasks.ConnectDebuggerTask; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.project.Project; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; - -/** Compat class for {@link BlazeAndroidBinaryNormalBuildRunContext}. */ -public class BlazeAndroidBinaryNormalBuildRunContextCompat - extends BlazeAndroidBinaryNormalBuildRunContext { - - BlazeAndroidBinaryNormalBuildRunContextCompat( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - super(project, facet, runConfiguration, env, configState, buildStep, launchId); - } - - @Nullable - @Override - @SuppressWarnings("unchecked") - public ConnectDebuggerTask getDebuggerTask( - AndroidDebugger androidDebugger, AndroidDebuggerState androidDebuggerState) { - return getBaseDebuggerTask(androidDebugger, androidDebuggerState, env, facet); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryProgramRunner.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryProgramRunner.java deleted file mode 100644 index 50f42d4b2dd..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryProgramRunner.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import static com.intellij.openapi.application.ModalityState.NON_MODAL; - -import com.android.tools.idea.profilers.ProfileRunExecutor; -import com.android.tools.idea.run.configuration.execution.AndroidConfigurationExecutor; -import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationHandler; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.ExecutionResult; -import com.intellij.execution.Executor; -import com.intellij.execution.configurations.RunProfile; -import com.intellij.execution.configurations.RunProfileState; -import com.intellij.execution.configurations.RunnerSettings; -import com.intellij.execution.executors.DefaultDebugExecutor; -import com.intellij.execution.executors.DefaultRunExecutor; -import com.intellij.execution.runners.AsyncProgramRunner; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.runners.RunContentBuilder; -import com.intellij.execution.ui.RunContentDescriptor; -import com.intellij.openapi.application.ActionsKt; -import com.intellij.openapi.fileEditor.FileDocumentManager; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.progress.Task; -import org.jetbrains.concurrency.AsyncPromise; -import org.jetbrains.concurrency.Promise; - -/** Program runner for configurations from {@link BlazeAndroidBinaryRunConfigurationHandler}. */ -public class BlazeAndroidBinaryProgramRunner extends AsyncProgramRunner { - @Override - public boolean canRun(String executorId, RunProfile profile) { - BlazeAndroidRunConfigurationHandler handler = - BlazeAndroidRunConfigurationHandler.getHandlerFrom(profile); - if (!(handler instanceof BlazeAndroidBinaryRunConfigurationHandler)) { - return false; - } - return (DefaultDebugExecutor.EXECUTOR_ID.equals(executorId) - || DefaultRunExecutor.EXECUTOR_ID.equals(executorId) - || ProfileRunExecutor.EXECUTOR_ID.equals(executorId)); - } - - @Override - protected Promise execute( - ExecutionEnvironment environment, RunProfileState state) { - FileDocumentManager.getInstance().saveAllDocuments(); - - AsyncPromise promise = new AsyncPromise<>(); - - ProgressManager.getInstance() - .run( - new Task.Backgroundable(environment.getProject(), "Launching ${runProfile.name}") { - @Override - public void run(ProgressIndicator indicator) { - try { - RunContentDescriptor descriptor; - if (state instanceof AndroidConfigurationExecutor) { - AndroidConfigurationExecutor configurationExecutor = - (AndroidConfigurationExecutor) state; - Executor executor = environment.getExecutor(); - if (executor.getId().equals(DefaultDebugExecutor.EXECUTOR_ID)) { - descriptor = configurationExecutor.debug(indicator); - } else if (executor.getId().equals(DefaultRunExecutor.EXECUTOR_ID) - || executor.getId().equals(ProfileRunExecutor.EXECUTOR_ID)) { - descriptor = configurationExecutor.run(indicator); - } else { - throw new ExecutionException("Unsupported executor"); - } - } else { - descriptor = doExecute(state, environment); - } - promise.setResult(descriptor); - } catch (ExecutionException e) { - boolean unused = promise.setError(e); - } - } - - @Override - public void onCancel() { - super.onCancel(); - promise.setResult(null); - } - }); - - return promise; - } - - private RunContentDescriptor doExecute( - final RunProfileState state, final ExecutionEnvironment env) throws ExecutionException { - ExecutionResult result = state.execute(env.getExecutor(), this); - return ActionsKt.invokeAndWaitIfNeeded( - NON_MODAL, - () -> new RunContentBuilder(result, env).showRunContent(env.getContentToReuse())); - } - - @Override - public String getRunnerId() { - return "AndroidBinaryProgramRunner"; - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerCompat.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerCompat.java deleted file mode 100644 index 296c3ea57af..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerCompat.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import static com.android.tools.idea.run.deployment.DeviceAndSnapshotComboBoxAction.DEPLOYS_TO_LOCAL_DEVICE; - -import com.google.common.annotations.VisibleForTesting; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.google.idea.blaze.base.settings.Blaze; -import com.intellij.openapi.project.Project; - -/** Compat class for {@link BlazeAndroidBinaryRunConfigurationHandlerCompat}. */ -public class BlazeAndroidBinaryRunConfigurationHandlerCompat { - protected final Project project; - protected final BlazeAndroidBinaryRunConfigurationState configState; - - @VisibleForTesting - protected BlazeAndroidBinaryRunConfigurationHandlerCompat( - BlazeCommandRunConfiguration configuration) { - project = configuration.getProject(); - configState = - new BlazeAndroidBinaryRunConfigurationState( - Blaze.buildSystemName(configuration.getProject())); - configuration.putUserData(DEPLOYS_TO_LOCAL_DEVICE, true); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java deleted file mode 100644 index 81696ad5b1e..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2021 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import com.android.tools.idea.run.blaze.BlazeLaunchContext; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.google.common.base.Stopwatch; -import com.google.idea.blaze.android.run.LaunchMetrics; -import com.intellij.execution.ExecutionException; - -/** A wrapper launch task that wraps the given deployment task and logs the deployment latency. */ -public class DeploymentTimingReporterTask implements BlazeLaunchTask { - private final BlazeLaunchTask deployTask; - private final String launchId; - - public DeploymentTimingReporterTask(String launchId, BlazeLaunchTask deployTask) { - this.launchId = launchId; - this.deployTask = deployTask; - } - - @Override - public void run(BlazeLaunchContext launchContext) throws ExecutionException { - Stopwatch s = Stopwatch.createStarted(); - try { - deployTask.run(launchContext); - LaunchMetrics.logDeploymentTime(launchId, s.elapsed(), true); - } catch (ExecutionException e) { - LaunchMetrics.logDeploymentTime(launchId, s.elapsed(), false); - throw e; - } - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java deleted file mode 100644 index c49082cfdaa..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary.mobileinstall; - -import static com.android.tools.idea.run.tasks.DefaultConnectDebuggerTaskKt.getBaseDebuggerTask; - -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.activity.DefaultStartActivityFlagsProvider; -import com.android.tools.idea.run.activity.StartActivityFlagsProvider; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.tasks.ConnectDebuggerTask; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryApplicationLaunchTaskProvider; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryRunConfigurationState; -import com.google.idea.blaze.android.run.binary.UserIdHelper; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.project.Project; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; - -/** Run Context for mobile install launches, #api4.0 compat. */ -public class BlazeAndroidBinaryMobileInstallRunContext - extends BlazeAndroidBinaryMobileInstallRunContextBase { - public BlazeAndroidBinaryMobileInstallRunContext( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - super(project, facet, runConfiguration, env, configState, buildStep, launchId); - } - - @SuppressWarnings("unchecked") // upstream API - @Override - public BlazeLaunchTask getApplicationLaunchTask( - LaunchOptions launchOptions, @Nullable Integer userId, String contributorsAmStartOptions) - throws ExecutionException { - - String extraFlags = UserIdHelper.getFlagsFromUserId(userId); - if (!contributorsAmStartOptions.isEmpty()) { - extraFlags += (extraFlags.isEmpty() ? "" : " ") + contributorsAmStartOptions; - } - - final StartActivityFlagsProvider startActivityFlagsProvider = - new DefaultStartActivityFlagsProvider(project, launchOptions.isDebug(), extraFlags); - BlazeAndroidDeployInfo deployInfo; - try { - deployInfo = buildStep.getDeployInfo(); - } catch (ApkProvisionException e) { - throw new ExecutionException(e); - } - - return BlazeAndroidBinaryApplicationLaunchTaskProvider.getApplicationLaunchTask( - applicationIdProvider, - deployInfo.getMergedManifest(), - configState, - startActivityFlagsProvider); - } - - @Nullable - @Override - @SuppressWarnings("unchecked") - public ConnectDebuggerTask getDebuggerTask( - AndroidDebugger androidDebugger, AndroidDebuggerState androidDebuggerState) { - return getBaseDebuggerTask(androidDebugger, androidDebuggerState, env, facet); - } - - @Override - public Executor getExecutor() { - return env.getExecutor(); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextBase.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextBase.java deleted file mode 100644 index b18f117f80f..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextBase.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary.mobileinstall; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.run.ApkFileUnit; -import com.android.tools.idea.run.ApkInfo; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.ConsoleProvider; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; -import com.android.tools.idea.run.editor.ProfilerState; -import com.android.tools.idea.run.tasks.DeployTasksCompat; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryApplicationIdProvider; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryConsoleProvider; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryRunConfigurationState; -import com.google.idea.blaze.android.run.binary.DeploymentTimingReporterTask; -import com.google.idea.blaze.android.run.binary.UserIdHelper; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.android.run.runner.BlazeAndroidDeviceSelector; -import com.google.idea.blaze.android.run.runner.BlazeAndroidLaunchTasksProvider; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunContext; -import com.google.idea.blaze.base.sync.data.BlazeDataStorage; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.project.Project; -import java.util.Collections; -import java.util.stream.Collectors; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; - -/** Run context for android_binary. */ -abstract class BlazeAndroidBinaryMobileInstallRunContextBase implements BlazeAndroidRunContext { - protected final Project project; - protected final AndroidFacet facet; - protected final RunConfiguration runConfiguration; - protected final ExecutionEnvironment env; - protected final BlazeAndroidBinaryRunConfigurationState configState; - protected final ConsoleProvider consoleProvider; - protected final ApplicationIdProvider applicationIdProvider; - protected final ApkBuildStep buildStep; - private final String launchId; - - public BlazeAndroidBinaryMobileInstallRunContextBase( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - this.project = project; - this.facet = facet; - this.runConfiguration = runConfiguration; - this.env = env; - this.configState = configState; - this.consoleProvider = new BlazeAndroidBinaryConsoleProvider(project); - this.buildStep = buildStep; - this.applicationIdProvider = new BlazeAndroidBinaryApplicationIdProvider(buildStep); - this.launchId = launchId; - } - - @Override - public BlazeAndroidDeviceSelector getDeviceSelector() { - return new BlazeAndroidDeviceSelector.NormalDeviceSelector(); - } - - @Override - public void augmentLaunchOptions(LaunchOptions.Builder options) { - options - .setDeploy(buildStep.needsIdeDeploy()) - .setOpenLogcatAutomatically(configState.showLogcatAutomatically()); - // This is needed for compatibility with #api211 - options.addExtraOptions( - ImmutableMap.of("android.profilers.state", configState.getProfilerState())); - } - - @Override - public ConsoleProvider getConsoleProvider() { - return consoleProvider; - } - - @Override - public ApplicationIdProvider getApplicationIdProvider() { - return applicationIdProvider; - } - - @Override - public ApkBuildStep getBuildStep() { - return buildStep; - } - - @Override - public ProfilerState getProfileState() { - return configState.getProfilerState(); - } - - @Override - public ImmutableList getDeployTasks(IDevice device, LaunchOptions launchOptions) - throws ExecutionException { - if (!buildStep.needsIdeDeploy()) { - return ImmutableList.of(); - } - - BlazeAndroidDeployInfo deployInfo; - try { - deployInfo = buildStep.getDeployInfo(); - } catch (ApkProvisionException e) { - throw new ExecutionException(e); - } - - String packageName = deployInfo.getMergedManifest().packageName; - if (packageName == null) { - throw new ExecutionException("Could not determine package name from deploy info"); - } - - ApkInfo info = - new ApkInfo( - deployInfo.getApksToDeploy().stream() - .map(file -> new ApkFileUnit(BlazeDataStorage.WORKSPACE_MODULE_NAME, file)) - .collect(Collectors.toList()), - packageName); - - BlazeLaunchTask deployTask = - DeployTasksCompat.createDeployTask(project, Collections.singletonList(info), launchOptions); - return ImmutableList.of(new DeploymentTimingReporterTask(launchId, deployTask)); - } - - @Nullable - @Override - public Integer getUserId(IDevice device) throws ExecutionException { - return UserIdHelper.getUserIdFromConfigurationState(project, device, configState); - } - - @Override - public BlazeLaunchTasksProvider getLaunchTasksProvider(LaunchOptions.Builder launchOptionsBuilder) - throws ExecutionException { - return new BlazeAndroidLaunchTasksProvider( - project, this, applicationIdProvider, launchOptionsBuilder); - } - - @Override - public String getAmStartOptions() { - return configState.getAmStartOptions(); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextCompat.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextCompat.java deleted file mode 100644 index 29411ebad5a..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextCompat.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary.mobileinstall; - -import static com.android.tools.idea.run.tasks.DefaultConnectDebuggerTaskKt.getBaseDebuggerTask; - -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.run.tasks.ConnectDebuggerTask; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryRunConfigurationState; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.project.Project; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; - -/** Compatct class for {@link BlazeAndroidBinaryMobileInstallRunContext}. */ -public class BlazeAndroidBinaryMobileInstallRunContextCompat - extends BlazeAndroidBinaryMobileInstallRunContext { - - public BlazeAndroidBinaryMobileInstallRunContextCompat( - Project project, - AndroidFacet facet, - BlazeCommandRunConfiguration configuration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - super(project, facet, configuration, env, configState, buildStep, launchId); - } - - @Nullable - @Override - @SuppressWarnings("unchecked") - public ConnectDebuggerTask getDebuggerTask( - AndroidDebugger androidDebugger, AndroidDebuggerState androidDebuggerState) { - return getBaseDebuggerTask(androidDebugger, androidDebuggerState, env, facet); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidDebuggerService.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidDebuggerService.java deleted file mode 100644 index c8658223baa..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidDebuggerService.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.execution.common.debug.impl.java.AndroidJavaDebugger; -import com.android.tools.ndk.run.editor.AutoAndroidDebuggerState; -import com.google.common.collect.ImmutableList; -import com.google.idea.blaze.android.cppimpl.debug.BlazeAutoAndroidDebugger; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.google.idea.blaze.base.model.primitives.WorkspaceRoot; -import com.intellij.ide.plugins.PluginManagerCore; -import com.intellij.openapi.project.Project; -import javax.annotation.Nullable; - -/** Provides android debuggers and debugger states for blaze projects. */ -public interface BlazeAndroidDebuggerService { - - static BlazeAndroidDebuggerService getInstance(Project project) { - return project.getService(BlazeAndroidDebuggerService.class); - } - - /** Returns the standard debugger for non-native (Java) debugging. */ - AndroidDebugger getDebugger(); - - /** Returns the standard debugger for native (C++) debugging. */ - AndroidDebugger getNativeDebugger(); - - /** - * Performs additional necessary setup for native debugging, incorporating info from {@link - * BlazeAndroidDeployInfo}. - */ - void configureNativeDebugger( - AndroidDebuggerState state, @Nullable BlazeAndroidDeployInfo deployInfo); - - /** Default debugger service. */ - class DefaultDebuggerService implements BlazeAndroidDebuggerService { - private final Project project; - - public DefaultDebuggerService(Project project) { - this.project = project; - } - - @Override - public AndroidDebugger getDebugger() { - return new AndroidJavaDebugger(); - } - - @Override - public AndroidDebugger getNativeDebugger() { - return new BlazeAutoAndroidDebugger(); - } - - @Override - public void configureNativeDebugger( - AndroidDebuggerState rawState, @Nullable BlazeAndroidDeployInfo deployInfo) { - if (!isNdkPluginLoaded() && !(rawState instanceof AutoAndroidDebuggerState)) { - return; - } - AutoAndroidDebuggerState state = (AutoAndroidDebuggerState) rawState; - - // Source code is always relative to the workspace root in a blaze project. - String workingDirPath = WorkspaceRoot.fromProject(project).directory().getPath(); - state.setWorkingDir(workingDirPath); - - // Remote built binaries may use /proc/self/cwd to represent the working directory, - // so we manually map /proc/self/cwd to the workspace root. We used to use - // `plugin.symbol-file.dwarf.comp-dir-symlink-paths = "/proc/self/cwd"` - // to automatically resolve this, but it's no longer supported in newer versions of - // LLDB. - String sourceMapToWorkspaceRootCommand = - "settings append target.source-map /proc/self/cwd/ " + workingDirPath; - - ImmutableList startupCommands = - ImmutableList.builder() - .addAll(state.getUserStartupCommands()) - .add(sourceMapToWorkspaceRootCommand) - .build(); - state.setUserStartupCommands(startupCommands); - - // NDK plugin will pass symbol directories to LLDB as `settings append - // target.exec-search-paths`. - if (deployInfo != null) { - state.setSymbolDirs( - deployInfo.getSymbolFiles().stream() - .map(symbol -> symbol.getParentFile().getAbsolutePath()) - .collect(ImmutableList.toImmutableList())); - } - } - } - - static boolean isNdkPluginLoaded() { - return PluginManagerCore.getLoadedPlugins().stream() - .anyMatch( - d -> d.isEnabled() && d.getPluginId().getIdString().equals("com.android.tools.ndk")); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java deleted file mode 100644 index 9ede8d06e50..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import static com.android.tools.idea.profilers.AndroidProfilerLaunchTaskContributor.isProfilerLaunch; - -import com.android.ddmlib.IDevice; -import com.android.tools.deployer.ApkVerifierTracker; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.profilers.AndroidProfilerLaunchTaskContributor; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTaskWrapper; -import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; -import com.android.tools.idea.run.tasks.ClearLogcatTask; -import com.android.tools.idea.run.tasks.ConnectDebuggerTask; -import com.android.tools.idea.run.tasks.DismissKeyguardTask; -import com.android.tools.idea.run.tasks.ShowLogcatTask; -import com.android.tools.ndk.run.editor.AutoAndroidDebuggerState; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.idea.blaze.android.run.binary.UserIdHelper; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.intellij.execution.ExecutionException; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.project.Project; -import java.util.List; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** Normal launch tasks provider. #api4.1 */ -public class BlazeAndroidLaunchTasksProvider implements BlazeLaunchTasksProvider { - public static final String NATIVE_DEBUGGING_ENABLED = "NATIVE_DEBUGGING_ENABLED"; - private static final Logger LOG = Logger.getInstance(BlazeAndroidLaunchTasksProvider.class); - - private final Project project; - private final BlazeAndroidRunContext runContext; - private final ApplicationIdProvider applicationIdProvider; - private final LaunchOptions.Builder launchOptionsBuilder; - - public BlazeAndroidLaunchTasksProvider( - Project project, - BlazeAndroidRunContext runContext, - ApplicationIdProvider applicationIdProvider, - LaunchOptions.Builder launchOptionsBuilder) { - this.project = project; - this.runContext = runContext; - this.applicationIdProvider = applicationIdProvider; - this.launchOptionsBuilder = launchOptionsBuilder; - } - - @NotNull - @Override - public List getTasks(@NotNull IDevice device) throws ExecutionException { - final List launchTasks = Lists.newArrayList(); - - String packageName; - try { - packageName = applicationIdProvider.getPackageName(); - } catch (ApkProvisionException e) { - throw new ExecutionException("Unable to determine application id: " + e); - } - - Integer userId = runContext.getUserId(device); - String userIdFlags = UserIdHelper.getFlagsFromUserId(userId); - String skipVerification = - ApkVerifierTracker.getSkipVerificationInstallationFlag(device, packageName); - String pmInstallOption; - if (skipVerification != null) { - pmInstallOption = userIdFlags + " " + skipVerification; - } else { - pmInstallOption = userIdFlags; - } - launchOptionsBuilder.setPmInstallOptions(d -> pmInstallOption); - - LaunchOptions launchOptions = launchOptionsBuilder.build(); - - // NOTE: Task for opening the profiler tool-window should come before deployment - // to ensure the tool-window opens correctly. This is required because starting - // the profiler session requires the tool-window to be open. - if (isProfilerLaunch(runContext.getExecutor())) { - launchTasks.add(new BlazeAndroidOpenProfilerWindowTask(project)); - } - - // TODO(kovalp): Check if there's any drawback to add these tasks with BlazeLaunchTaskWrapper - // since it's different with ag/21610897 - if (launchOptions.isClearLogcatBeforeStart()) { - launchTasks.add(new BlazeLaunchTaskWrapper(new ClearLogcatTask(project))); - } - - launchTasks.add(new BlazeLaunchTaskWrapper(new DismissKeyguardTask())); - - if (launchOptions.isDeploy()) { - ImmutableList deployTasks = runContext.getDeployTasks(device, launchOptions); - launchTasks.addAll(deployTasks); - } - - try { - if (launchOptions.isDebug()) { - launchTasks.add( - new CheckApkDebuggableTask(project, runContext.getBuildStep().getDeployInfo())); - } - - ImmutableList.Builder amStartOptions = ImmutableList.builder(); - amStartOptions.add(runContext.getAmStartOptions()); - if (isProfilerLaunch(runContext.getExecutor())) { - amStartOptions.add( - AndroidProfilerLaunchTaskContributor.getAmStartOptions( - project, - packageName, - runContext.getProfileState(), - device, - runContext.getExecutor())); - launchTasks.add( - new BlazeLaunchTaskWrapper( - new AndroidProfilerLaunchTaskContributor.AndroidProfilerToolWindowLaunchTask( - project, packageName))); - } - BlazeLaunchTask appLaunchTask = - runContext.getApplicationLaunchTask( - launchOptions, userId, String.join(" ", amStartOptions.build())); - if (appLaunchTask != null) { - launchTasks.add(appLaunchTask); - } - } catch (ApkProvisionException e) { - throw new ExecutionException("Unable to determine application id: " + e); - } - - if (launchOptions.isOpenLogcatAutomatically()) { - launchTasks.add(new BlazeLaunchTaskWrapper(new ShowLogcatTask(project, packageName))); - } - - return ImmutableList.copyOf(launchTasks); - } - - @Override - @Nullable - public ConnectDebuggerTask getConnectDebuggerTask() { - LaunchOptions launchOptions = launchOptionsBuilder.build(); - if (!launchOptions.isDebug()) { - return null; - } - - BlazeAndroidDeployInfo deployInfo; - try { - deployInfo = runContext.getBuildStep().getDeployInfo(); - } catch (ApkProvisionException e) { - LOG.error(e); - deployInfo = null; - } - - BlazeAndroidDebuggerService debuggerService = BlazeAndroidDebuggerService.getInstance(project); - if (isNativeDebuggingEnabled(launchOptions)) { - AndroidDebugger debugger = debuggerService.getNativeDebugger(); - // The below state type should be AutoAndroidDebuggerState, but referencing it will crash the - // task if the NDK plugin is not loaded. - AndroidDebuggerState state = debugger.createState(); - debuggerService.configureNativeDebugger(state, deployInfo); - return runContext.getDebuggerTask(debugger, state); - } else { - AndroidDebugger debugger = debuggerService.getDebugger(); - return runContext.getDebuggerTask(debugger, debugger.createState()); - } - } - - private boolean isNativeDebuggingEnabled(LaunchOptions launchOptions) { - Object flag = launchOptions.getExtraOption(NATIVE_DEBUGGING_ENABLED); - return flag instanceof Boolean && (Boolean) flag; - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java deleted file mode 100644 index 78728d9c46f..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.idea.blaze.android.run.runner; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.AppRunSettings; -import com.android.tools.idea.execution.common.ApplicationDeployer; -import com.android.tools.idea.execution.common.ComponentLaunchOptions; -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.run.ApkProvider; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.DeviceFutures; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeAndroidConfigurationExecutor; -import com.android.tools.idea.run.configuration.execution.AndroidComplicationConfigurationExecutor; -import com.android.tools.idea.run.configuration.execution.AndroidConfigurationExecutor; -import com.android.tools.idea.run.configuration.execution.AndroidConfigurationExecutorRunProfileState; -import com.android.tools.idea.run.configuration.execution.AndroidTileConfigurationExecutor; -import com.android.tools.idea.run.configuration.execution.AndroidWatchFaceConfigurationExecutor; -import com.android.tools.idea.run.configuration.execution.ComplicationLaunchOptions; -import com.android.tools.idea.run.configuration.execution.TileLaunchOptions; -import com.android.tools.idea.run.configuration.execution.WatchFaceLaunchOptions; -import com.android.tools.idea.run.editor.DeployTarget; -import com.android.tools.idea.run.editor.DeployTargetState; -import com.android.tools.idea.run.util.LaunchUtils; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.idea.blaze.android.run.binary.mobileinstall.MobileInstallBuildStep; -import com.google.idea.blaze.android.run.deployinfo.BlazeApkProviderService; -import com.google.idea.blaze.base.async.executor.ProgressiveTaskWithProgressIndicator; -import com.google.idea.blaze.base.command.BlazeInvocationContext.ContextType; -import com.google.idea.blaze.base.experiments.ExperimentScope; -import com.google.idea.blaze.base.issueparser.BlazeIssueParser; -import com.google.idea.blaze.base.model.primitives.WorkspaceRoot; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.google.idea.blaze.base.run.confighandler.BlazeCommandRunConfigurationRunner; -import com.google.idea.blaze.base.scope.BlazeContext; -import com.google.idea.blaze.base.scope.Scope; -import com.google.idea.blaze.base.scope.ScopedTask; -import com.google.idea.blaze.base.scope.output.IssueOutput; -import com.google.idea.blaze.base.scope.scopes.IdeaLogScope; -import com.google.idea.blaze.base.scope.scopes.ProblemsViewScope; -import com.google.idea.blaze.base.scope.scopes.ToolWindowScope; -import com.google.idea.blaze.base.settings.Blaze; -import com.google.idea.blaze.base.settings.BlazeUserSettings; -import com.google.idea.blaze.base.toolwindow.Task; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.configurations.RunProfileState; -import com.intellij.execution.executors.DefaultDebugExecutor; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Key; -import java.util.Collections; -import java.util.concurrent.CancellationException; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.android.util.AndroidBundle; -import org.jetbrains.annotations.NotNull; - -/** - * Supports the execution. Used by both android_binary and android_test. - * - *

Builds the APK and installs it, launches and debug tasks, etc. - * - *

Any indirection between android_binary/android_test, mobile-install, InstantRun etc. should - * come via the strategy class. - */ -public final class BlazeAndroidRunConfigurationRunner - implements BlazeCommandRunConfigurationRunner { - - private static final Logger LOG = Logger.getInstance(BlazeAndroidRunConfigurationRunner.class); - - private static final Key RUN_CONTEXT_KEY = - Key.create("blaze.run.context"); - public static final Key DEVICE_SESSION_KEY = - Key.create("blaze.device.session"); - - private final Module module; - private final BlazeAndroidRunContext runContext; - private final BlazeCommandRunConfiguration runConfig; - - public BlazeAndroidRunConfigurationRunner( - Module module, BlazeAndroidRunContext runContext, BlazeCommandRunConfiguration runConfig) { - this.module = module; - this.runContext = runContext; - this.runConfig = runConfig; - } - - @Override - @Nullable - public final RunProfileState getRunProfileState(final Executor executor, ExecutionEnvironment env) - throws ExecutionException { - - final AndroidFacet facet = AndroidFacet.getInstance(module); - assert facet != null : "Enforced by fatal validation check in createRunner."; - final Project project = env.getProject(); - - boolean isDebug = executor instanceof DefaultDebugExecutor; - - BlazeAndroidDeviceSelector deviceSelector = runContext.getDeviceSelector(); - BlazeAndroidDeviceSelector.DeviceSession deviceSession = - deviceSelector.getDevice(project, executor, env, isDebug, runConfig.getUniqueID()); - - if (deviceSession == null) { - return null; - } - - DeployTarget deployTarget = deviceSession.deployTarget; - if (deployTarget != null && deployTarget.hasCustomRunProfileState(executor)) { - return deployTarget.getRunProfileState(executor, env, DeployTargetState.DEFAULT_STATE); - } - - DeviceFutures deviceFutures = deviceSession.deviceFutures; - if (deviceFutures == null) { - // The user deliberately canceled, or some error was encountered and exposed by the chooser. - // Quietly exit. - return null; - } - - if (deviceFutures.get().isEmpty()) { - throw new ExecutionException(AndroidBundle.message("deployment.target.not.found")); - } - - if (isDebug) { - String error = canDebug(deviceFutures, facet, module.getName()); - if (error != null) { - throw new ExecutionException(error); - } - } - - LaunchOptions.Builder launchOptionsBuilder = getDefaultLaunchOptions().setDebug(isDebug); - runContext.augmentLaunchOptions(launchOptionsBuilder); - - // Store the run context on the execution environment so before-run tasks can access it. - env.putCopyableUserData(RUN_CONTEXT_KEY, runContext); - env.putCopyableUserData(DEVICE_SESSION_KEY, deviceSession); - - BlazeAndroidConfigurationExecutor runner = - new BlazeAndroidConfigurationExecutor( - runContext.getConsoleProvider(), - runContext.getApplicationIdProvider(), - env, - deviceFutures, - runContext.getLaunchTasksProvider(launchOptionsBuilder), - LaunchOptions.builder().build()); - return new AndroidConfigurationExecutorRunProfileState(runner); - } - - private RunProfileState getWearExecutor( - ComponentLaunchOptions launchOptions, ExecutionEnvironment env, DeployTarget deployTarget) - throws ExecutionException { - - AppRunSettings settings = - new AppRunSettings() { - @NotNull - @Override - public DeployOptions getDeployOptions() { - return new DeployOptions(Collections.emptyList(), "", true, true); - } - - @NotNull - @Override - public ComponentLaunchOptions getComponentLaunchOptions() { - return launchOptions; - } - - @Override - public Module getModule() { - return runConfig.getModules()[0]; - } - }; - - AndroidConfigurationExecutor configurationExecutor; - ApplicationIdProvider appIdProvider = runContext.getApplicationIdProvider(); - ApkProvider apkProvider = - BlazeApkProviderService.getInstance() - .getApkProvider(env.getProject(), runContext.getBuildStep()); - DeviceFutures deviceFutures = deployTarget.getDevices(env.getProject()); - - if (launchOptions instanceof TileLaunchOptions) { - configurationExecutor = - new AndroidTileConfigurationExecutor( - env, deviceFutures, settings, appIdProvider, apkProvider) { - @NotNull - @Override - public ApplicationDeployer getApplicationDeployer(@NotNull ConsoleView console) - throws ExecutionException { - if (runContext.getBuildStep() instanceof MobileInstallBuildStep) { - return new MobileInstallApplicationDeployer(console); - } - return super.getApplicationDeployer(console); - } - }; - } else if (launchOptions instanceof WatchFaceLaunchOptions) { - configurationExecutor = - new AndroidWatchFaceConfigurationExecutor( - env, deviceFutures, settings, appIdProvider, apkProvider) { - @NotNull - @Override - public ApplicationDeployer getApplicationDeployer(@NotNull ConsoleView console) - throws ExecutionException { - if (runContext.getBuildStep() instanceof MobileInstallBuildStep) { - return new MobileInstallApplicationDeployer(console); - } - return super.getApplicationDeployer(console); - } - }; - } else if (launchOptions instanceof ComplicationLaunchOptions) { - configurationExecutor = - new AndroidComplicationConfigurationExecutor( - env, deviceFutures, settings, appIdProvider, apkProvider) { - @NotNull - @Override - public ApplicationDeployer getApplicationDeployer(@NotNull ConsoleView console) - throws ExecutionException { - if (runContext.getBuildStep() instanceof MobileInstallBuildStep) { - return new MobileInstallApplicationDeployer(console); - } - return super.getApplicationDeployer(console); - } - }; - } else { - throw new RuntimeException("Unknown launch options " + launchOptions.getClass().getName()); - } - - return new AndroidConfigurationExecutorRunProfileState( - new BlazeWrapperForAndroidConfigurationExecutor(configurationExecutor)); - } - - @Nullable - private static String canDebug( - DeviceFutures deviceFutures, AndroidFacet facet, String moduleName) { - // If we are debugging on a device, then the app needs to be debuggable - for (ListenableFuture future : deviceFutures.get()) { - if (!future.isDone()) { - // this is an emulator, and we assume that all emulators are debuggable - continue; - } - IDevice device = Futures.getUnchecked(future); - if (!LaunchUtils.canDebugAppOnDevice(facet, device)) { - return AndroidBundle.message( - "android.cannot.debug.noDebugPermissions", moduleName, device.getName()); - } - } - return null; - } - - private static LaunchOptions.Builder getDefaultLaunchOptions() { - return LaunchOptionsCompat.getDefaultLaunchOptions(); - } - - @Override - public boolean executeBeforeRunTask(ExecutionEnvironment env) { - final Project project = env.getProject(); - BlazeUserSettings settings = BlazeUserSettings.getInstance(); - return Scope.root( - context -> { - context - .push(new ProblemsViewScope(project, settings.getShowProblemsViewOnRun())) - .push(new ExperimentScope()) - .push( - new ToolWindowScope.Builder( - project, new Task(project, "Build apk", Task.Type.BEFORE_LAUNCH)) - .setPopupBehavior(settings.getShowBlazeConsoleOnRun()) - .setIssueParsers( - BlazeIssueParser.defaultIssueParsers( - project, - WorkspaceRoot.fromProject(project), - ContextType.BeforeRunTask)) - .build()) - .push(new IdeaLogScope()); - - BlazeAndroidRunContext runContext = env.getCopyableUserData(RUN_CONTEXT_KEY); - if (runContext == null) { - IssueOutput.error("Could not find run context. Please try again").submit(context); - return false; - } - BlazeAndroidDeviceSelector.DeviceSession deviceSession = - env.getCopyableUserData(DEVICE_SESSION_KEY); - - ApkBuildStep buildStep = runContext.getBuildStep(); - ScopedTask buildTask = - new ScopedTask(context) { - @Override - protected Void execute(BlazeContext context) { - buildStep.build(context, deviceSession); - return null; - } - }; - - try { - ListenableFuture buildFuture = - ProgressiveTaskWithProgressIndicator.builder( - project, - String.format("Executing %s apk build", Blaze.buildSystemName(project))) - .submitTaskWithResult(buildTask); - Futures.getChecked(buildFuture, ExecutionException.class); - } catch (ExecutionException e) { - context.setHasError(); - } catch (CancellationException e) { - context.setCancelled(); - } catch (Exception e) { - LOG.error(e); - return false; - } - return context.shouldContinue(); - }); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidRunContext.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidRunContext.java deleted file mode 100644 index 327d7f4aeae..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeAndroidRunContext.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.ConsoleProvider; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; -import com.android.tools.idea.run.editor.ProfilerState; -import com.android.tools.idea.run.tasks.ConnectDebuggerTask; -import com.google.common.collect.ImmutableList; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import javax.annotation.Nullable; -import org.jetbrains.annotations.NotNull; - -/** Instantiated when the configuration wants to run. */ -public interface BlazeAndroidRunContext { - - BlazeAndroidDeviceSelector getDeviceSelector(); - - void augmentLaunchOptions(LaunchOptions.Builder options); - - ConsoleProvider getConsoleProvider(); - - ApkBuildStep getBuildStep(); - - ApplicationIdProvider getApplicationIdProvider(); - - BlazeLaunchTasksProvider getLaunchTasksProvider(LaunchOptions.Builder launchOptionsBuilder) - throws ExecutionException; - - /** Returns the tasks to deploy the application. */ - ImmutableList getDeployTasks(IDevice device, LaunchOptions launchOptions) - throws ExecutionException; - - /** Returns the task to launch the application. */ - @Nullable - BlazeLaunchTask getApplicationLaunchTask( - LaunchOptions launchOptions, - @Nullable Integer userId, - @NotNull String contributorsAmStartOptions) - throws ExecutionException; - - /** Returns the task to connect the debugger. */ - @Nullable - ConnectDebuggerTask getDebuggerTask( - AndroidDebugger androidDebugger, AndroidDebuggerState androidDebuggerState); - - @Nullable - Integer getUserId(IDevice device) throws ExecutionException; - - String getAmStartOptions(); - - Executor getExecutor(); - - ProfilerState getProfileState(); -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeWrapperForAndroidConfigurationExecutor.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeWrapperForAndroidConfigurationExecutor.java deleted file mode 100644 index be6f1f8552c..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/BlazeWrapperForAndroidConfigurationExecutor.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import com.android.tools.idea.run.DeviceFutures; -import com.android.tools.idea.run.configuration.execution.AndroidConfigurationExecutor; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.ui.RunContentDescriptor; -import com.intellij.openapi.progress.ProgressIndicator; -import org.jetbrains.annotations.NotNull; - -/** Implementation of {@code AndroidConfigurationExecutor} specific for Blaze project. */ -public class BlazeWrapperForAndroidConfigurationExecutor implements AndroidConfigurationExecutor { - private final AndroidConfigurationExecutor delegateExecutor; - - BlazeWrapperForAndroidConfigurationExecutor(@NotNull AndroidConfigurationExecutor executor) { - delegateExecutor = executor; - } - - @NotNull - @Override - public RunConfiguration getConfiguration() { - return delegateExecutor.getConfiguration(); - } - - @NotNull - @Override - public DeviceFutures getDeviceFutures() { - return delegateExecutor.getDeviceFutures(); - } - - @NotNull - @Override - public RunContentDescriptor run(@NotNull ProgressIndicator indicator) throws ExecutionException { - return delegateExecutor.run(indicator); - } - - @NotNull - @Override - public RunContentDescriptor debug(@NotNull ProgressIndicator indicator) - throws ExecutionException { - return delegateExecutor.debug(indicator); - } - - @NotNull - @Override - public RunContentDescriptor applyChanges(@NotNull ProgressIndicator indicator) { - throw new RuntimeException("Apply code changes is not supported for blaze"); - } - - @NotNull - @Override - public RunContentDescriptor applyCodeChanges(@NotNull ProgressIndicator indicator) { - throw new RuntimeException("Apply changes is not supported for blaze"); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/MobileInstallApplicationDeployer.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/MobileInstallApplicationDeployer.java deleted file mode 100644 index dad762309be..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/runner/MobileInstallApplicationDeployer.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import com.android.ddmlib.IDevice; -import com.android.tools.deployer.ApkParser; -import com.android.tools.deployer.Deployer; -import com.android.tools.deployer.DeployerException; -import com.android.tools.deployer.model.Apk; -import com.android.tools.deployer.model.App; -import com.android.tools.idea.execution.common.ApplicationDeployer; -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.run.ApkFileUnit; -import com.android.tools.idea.run.ApkInfo; -import com.android.tools.idea.run.configuration.execution.AdbCommandCaptureLoggerWithConsole; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.progress.ProgressIndicator; -import java.nio.file.Path; -import java.util.List; -import java.util.stream.Collectors; -import org.jetbrains.annotations.NotNull; - -/** Deploys mobile install application. */ -public class MobileInstallApplicationDeployer implements ApplicationDeployer { - private static final Logger LOG = Logger.getInstance(MobileInstallApplicationDeployer.class); - private final ConsoleView myConsole; - - public MobileInstallApplicationDeployer(ConsoleView console) { - myConsole = console; - } - - @NotNull - @Override - public Deployer.Result fullDeploy( - @NotNull IDevice device, - @NotNull ApkInfo apkInfo, - @NotNull DeployOptions deployOptions, - ProgressIndicator indicator) - throws DeployerException { - final List apkPaths = - apkInfo.getFiles().stream() - .map(ApkFileUnit::getApkPath) - .map(Path::toString) - .collect(Collectors.toList()); - final List apks = new ApkParser().parsePaths(apkPaths); - App app = - new App( - apkInfo.getApplicationId(), - apks, - device, - new AdbCommandCaptureLoggerWithConsole(LOG, myConsole)); - return new Deployer.Result(false, false, false, app); - } - - @NotNull - @Override - public Deployer.Result applyChangesDeploy( - @NotNull IDevice device, - @NotNull ApkInfo app, - @NotNull DeployOptions deployOptions, - ProgressIndicator indicator) - throws DeployerException { - throw new RuntimeException("Apply changes is not supported for mobile-install"); - } - - @NotNull - @Override - public Deployer.Result applyCodeChangesDeploy( - @NotNull IDevice device, - @NotNull ApkInfo app, - @NotNull DeployOptions deployOptions, - ProgressIndicator indicator) - throws DeployerException { - throw new RuntimeException("Apply code changes is not supported for mobile-install"); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/BlazeAndroidTestProgramRunner.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/BlazeAndroidTestProgramRunner.java deleted file mode 100644 index eab7b24890f..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/BlazeAndroidTestProgramRunner.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2018 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.test; - -import com.android.tools.idea.run.configuration.AndroidConfigurationProgramRunner; -import com.android.tools.idea.run.configuration.execution.AndroidConfigurationExecutor; -import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationHandler; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.google.idea.blaze.base.run.BlazeCommandRunConfigurationType; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.configurations.RunProfile; -import com.intellij.execution.configurations.RunProfileState; -import com.intellij.execution.executors.DefaultDebugExecutor; -import com.intellij.execution.executors.DefaultRunExecutor; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.RunContentDescriptor; -import com.intellij.openapi.progress.ProgressIndicator; -import java.util.Collections; -import java.util.List; -import org.jetbrains.annotations.NotNull; - -/** Program runner for configurations from {@link BlazeAndroidTestRunConfigurationHandler}. */ -public class BlazeAndroidTestProgramRunner extends AndroidConfigurationProgramRunner { - @Override - public boolean canRun(String executorId, RunProfile profile) { - BlazeAndroidRunConfigurationHandler handler = - BlazeAndroidRunConfigurationHandler.getHandlerFrom(profile); - if (!(handler instanceof BlazeAndroidTestRunConfigurationHandler)) { - return false; - } - if (!(profile instanceof BlazeCommandRunConfiguration)) { - return false; - } - return DefaultRunExecutor.EXECUTOR_ID.equals(executorId) - || DefaultDebugExecutor.EXECUTOR_ID.equals(executorId); - } - - @Override - public String getRunnerId() { - return "AndroidTestProgramRunner"; - } - - @Override - protected boolean canRunWithMultipleDevices(@NotNull String executorId) { - return true; - } - - @NotNull - @Override - protected List getSupportedConfigurationTypeIds() { - return Collections.singletonList(BlazeCommandRunConfigurationType.getInstance().getId()); - } - - @NotNull - @Override - protected RunContentDescriptor run( - @NotNull ExecutionEnvironment environment, - @NotNull RunProfileState state, - @NotNull ProgressIndicator indicator) - throws ExecutionException { - final AndroidConfigurationExecutor state1 = (AndroidConfigurationExecutor) state; - if (DefaultDebugExecutor.EXECUTOR_ID.equals(environment.getExecutor().getId())) { - return state1.debug(indicator); - } - if (DefaultRunExecutor.EXECUTOR_ID.equals(environment.getExecutor().getId())) { - return state1.run(indicator); - } - throw new RuntimeException("Unsupported executor"); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunConfigurationHandler.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunConfigurationHandler.java deleted file mode 100644 index 050ddc03fee..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunConfigurationHandler.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.test; - -import static com.android.tools.idea.run.deployment.DeviceAndSnapshotComboBoxAction.DEPLOYS_TO_LOCAL_DEVICE; - -import com.android.tools.idea.run.ValidationError; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.idea.blaze.android.run.ApkBuildStepProvider; -import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationCommonState; -import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationHandler; -import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationValidationUtil; -import com.google.idea.blaze.android.run.LaunchMetrics; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunConfigurationRunner; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunContext; -import com.google.idea.blaze.android.run.runner.FullApkBuildStep; -import com.google.idea.blaze.android.run.test.BlazeAndroidTestLaunchMethodsProvider.AndroidTestLaunchMethod; -import com.google.idea.blaze.base.command.BlazeCommandName; -import com.google.idea.blaze.base.command.BlazeInvocationContext; -import com.google.idea.blaze.base.model.primitives.Label; -import com.google.idea.blaze.base.model.primitives.TargetExpression; -import com.google.idea.blaze.base.projectview.ProjectViewManager; -import com.google.idea.blaze.base.projectview.ProjectViewSet; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.google.idea.blaze.base.run.BlazeConfigurationNameBuilder; -import com.google.idea.blaze.base.run.ExecutorType; -import com.google.idea.blaze.base.run.confighandler.BlazeCommandRunConfigurationRunner; -import com.google.idea.blaze.base.settings.Blaze; -import com.google.idea.blaze.base.sync.data.BlazeDataStorage; -import com.google.idea.blaze.base.sync.projectstructure.ModuleFinder; -import com.google.idea.blaze.java.AndroidBlazeRules; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.JavaExecutionUtil; -import com.intellij.execution.configurations.RuntimeConfigurationException; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import java.util.List; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; - -/** - * {@link com.google.idea.blaze.base.run.confighandler.BlazeCommandRunConfigurationHandler} for - * android_test targets. - */ -public class BlazeAndroidTestRunConfigurationHandler - implements BlazeAndroidRunConfigurationHandler { - private final Project project; - private final BlazeAndroidTestRunConfigurationState configState; - - BlazeAndroidTestRunConfigurationHandler(BlazeCommandRunConfiguration configuration) { - this.project = configuration.getProject(); - this.configState = - new BlazeAndroidTestRunConfigurationState( - Blaze.buildSystemName(configuration.getProject())); - configuration.putUserData(DEPLOYS_TO_LOCAL_DEVICE, true); - } - - @Override - public BlazeAndroidTestRunConfigurationState getState() { - return configState; - } - - @Override - public BlazeAndroidRunConfigurationCommonState getCommonState() { - return configState.getCommonState(); - } - - @Override - public BlazeCommandRunConfigurationRunner createRunner( - Executor executor, ExecutionEnvironment env) throws ExecutionException { - Project project = env.getProject(); - BlazeCommandRunConfiguration configuration = - BlazeAndroidRunConfigurationHandler.getCommandConfig(env); - - BlazeAndroidRunConfigurationValidationUtil.validate(project); - Module module = - ModuleFinder.getInstance(env.getProject()) - .findModuleByName(BlazeDataStorage.WORKSPACE_MODULE_NAME); - AndroidFacet facet = module != null ? AndroidFacet.getInstance(module) : null; - ProjectViewSet projectViewSet = ProjectViewManager.getInstance(project).getProjectViewSet(); - - ImmutableList blazeFlags = - configState - .getCommonState() - .getExpandedBuildFlags( - project, - projectViewSet, - BlazeCommandName.TEST, - BlazeInvocationContext.runConfigContext( - ExecutorType.fromExecutor(env.getExecutor()), configuration.getType(), false)); - ImmutableList exeFlags = - ImmutableList.copyOf( - configState.getCommonState().getExeFlagsState().getFlagsForExternalProcesses()); - - // We collect metrics from a few different locations. In order to tie them all - // together, we create a unique launch id. - String launchId = LaunchMetrics.newLaunchId(); - Label label = Label.create(configuration.getSingleTarget().toString()); - - ApkBuildStep buildStep = - getTestBuildStep( - project, configState, configuration, blazeFlags, exeFlags, launchId, label); - - BlazeAndroidRunContext runContext = - new BlazeAndroidTestRunContext( - project, facet, configuration, env, configState, label, blazeFlags, buildStep); - - LaunchMetrics.logTestLaunch( - launchId, configState.getLaunchMethod().name(), env.getExecutor().getId()); - - return new BlazeAndroidRunConfigurationRunner(module, runContext, configuration); - } - - private static ApkBuildStep getTestBuildStep( - Project project, - BlazeAndroidTestRunConfigurationState configState, - BlazeCommandRunConfiguration configuration, - ImmutableList blazeFlags, - ImmutableList exeFlags, - String launchId, - Label label) - throws ExecutionException { - if (configuration.getTargetKind() - == AndroidBlazeRules.RuleTypes.ANDROID_INSTRUMENTATION_TEST.getKind()) { - boolean useMobileInstall = - AndroidTestLaunchMethod.MOBILE_INSTALL.equals(configState.getLaunchMethod()); - return ApkBuildStepProvider.getInstance(Blaze.getBuildSystemName(project)) - .getAitBuildStep( - project, - useMobileInstall, - /* nativeDebuggingEnabled= */ false, - label, - blazeFlags, - exeFlags, - launchId); - } else { - // TODO(b/248317444): This path is only invoked for the deprecated {@code android_test} - // targets, and should eventually be removed. - return new FullApkBuildStep(project, label, blazeFlags, /* nativeDebuggingEnabled= */ false); - } - } - - @Override - public final void checkConfiguration() throws RuntimeConfigurationException { - BlazeAndroidRunConfigurationValidationUtil.throwTopConfigurationError(validate()); - } - - /** - * We collect errors rather than throwing to avoid missing fatal errors by exiting early for a - * warning. We use a separate method for the collection so the compiler prevents us from - * accidentally throwing. - */ - private List validate() { - List errors = Lists.newArrayList(); - errors.addAll(BlazeAndroidRunConfigurationValidationUtil.validateWorkspaceModule(project)); - errors.addAll(configState.validate(project)); - return errors; - } - - @Override - @Nullable - public String suggestedName(BlazeCommandRunConfiguration configuration) { - TargetExpression target = configuration.getSingleTarget(); - if (target == null) { - return null; - } - BlazeConfigurationNameBuilder nameBuilder = new BlazeConfigurationNameBuilder(configuration); - - boolean isClassTest = - configState.getTestingType() == BlazeAndroidTestRunConfigurationState.TEST_CLASS; - boolean isMethodTest = - configState.getTestingType() == BlazeAndroidTestRunConfigurationState.TEST_METHOD; - if ((isClassTest || isMethodTest) && configState.getClassName() != null) { - // Get the class name without the package. - String className = JavaExecutionUtil.getPresentableClassName(configState.getClassName()); - if (className != null) { - String targetString = className; - if (isMethodTest) { - targetString += "#" + configState.getMethodName(); - } - - if (getState().getLaunchMethod().equals(AndroidTestLaunchMethod.NON_BLAZE)) { - return targetString; - } else { - return nameBuilder.setTargetString(targetString).build(); - } - } - } - return nameBuilder.build(); - } - - @Override - @Nullable - public BlazeCommandName getCommandName() { - if (getState().getLaunchMethod().equals(AndroidTestLaunchMethod.BLAZE_TEST)) { - return BlazeCommandName.TEST; - } else if (getState().getLaunchMethod().equals(AndroidTestLaunchMethod.MOBILE_INSTALL)) { - return BlazeCommandName.MOBILE_INSTALL; - } - return null; - } - - @Override - public String getHandlerName() { - return "Android Test Handler"; - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java deleted file mode 100644 index 3caea8d6d81..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.test; - -import static com.android.tools.idea.run.tasks.DefaultConnectDebuggerTaskKt.getBaseDebuggerTask; -import static com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryNormalBuildRunContextBase.getApkInfoToInstall; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.run.ApkProvider; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.ConsoleProvider; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; -import com.android.tools.idea.run.editor.ProfilerState; -import com.android.tools.idea.run.tasks.ConnectDebuggerTask; -import com.android.tools.idea.run.tasks.DeployTasksCompat; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.google.idea.blaze.android.run.deployinfo.BlazeApkProviderService; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.android.run.runner.BlazeAndroidDeviceSelector; -import com.google.idea.blaze.android.run.runner.BlazeAndroidLaunchTasksProvider; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunContext; -import com.google.idea.blaze.android.run.test.BlazeAndroidTestLaunchMethodsProvider.AndroidTestLaunchMethod; -import com.google.idea.blaze.base.model.primitives.Label; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.google.idea.blaze.base.run.smrunner.BlazeTestUiSession; -import com.google.idea.blaze.base.run.testlogs.BlazeTestResultHolder; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.project.Project; -import java.util.List; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; - -/** Run context for android_test. */ -public class BlazeAndroidTestRunContext implements BlazeAndroidRunContext { - protected final Project project; - protected final AndroidFacet facet; - protected final BlazeCommandRunConfiguration runConfiguration; - protected final ExecutionEnvironment env; - protected final BlazeAndroidTestRunConfigurationState configState; - protected final Label label; - protected final ImmutableList blazeFlags; - protected final List launchTaskCompleteListeners = Lists.newArrayList(); - protected final ConsoleProvider consoleProvider; - protected final ApkBuildStep buildStep; - protected final ApplicationIdProvider applicationIdProvider; - protected final ApkProvider apkProvider; - private final BlazeTestResultHolder testResultsHolder = new BlazeTestResultHolder(); - - public BlazeAndroidTestRunContext( - Project project, - AndroidFacet facet, - BlazeCommandRunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidTestRunConfigurationState configState, - Label label, - ImmutableList blazeFlags, - ApkBuildStep buildStep) { - this.project = project; - this.facet = facet; - this.runConfiguration = runConfiguration; - this.env = env; - this.label = label; - this.configState = configState; - this.buildStep = buildStep; - this.blazeFlags = blazeFlags; - switch (configState.getLaunchMethod()) { - case MOBILE_INSTALL: - case NON_BLAZE: - consoleProvider = new AitIdeTestConsoleProvider(runConfiguration, configState); - break; - case BLAZE_TEST: - BlazeTestUiSession session = - BlazeTestUiSession.create(ImmutableList.of(), testResultsHolder); - this.consoleProvider = new AitBlazeTestConsoleProvider(project, runConfiguration, session); - break; - default: - throw new IllegalStateException( - "Unsupported launch method " + configState.getLaunchMethod()); - } - applicationIdProvider = new BlazeAndroidTestApplicationIdProvider(buildStep); - apkProvider = BlazeApkProviderService.getInstance().getApkProvider(project, buildStep); - } - - @Override - public BlazeAndroidDeviceSelector getDeviceSelector() { - return new BlazeAndroidDeviceSelector.NormalDeviceSelector(); - } - - @Override - public void augmentLaunchOptions(LaunchOptions.Builder options) { - options.setDeploy(!configState.getLaunchMethod().equals(AndroidTestLaunchMethod.BLAZE_TEST)); - } - - @Override - public ConsoleProvider getConsoleProvider() { - return consoleProvider; - } - - @Override - public ApplicationIdProvider getApplicationIdProvider() { - return applicationIdProvider; - } - - @Nullable - @Override - public ApkBuildStep getBuildStep() { - return buildStep; - } - - @Override - public ProfilerState getProfileState() { - return null; - } - - @Override - public BlazeLaunchTasksProvider getLaunchTasksProvider(LaunchOptions.Builder launchOptionsBuilder) - throws ExecutionException { - return new BlazeAndroidLaunchTasksProvider( - project, this, applicationIdProvider, launchOptionsBuilder); - } - - @Override - public ImmutableList getDeployTasks(IDevice device, LaunchOptions launchOptions) - throws ExecutionException { - if (configState.getLaunchMethod() != AndroidTestLaunchMethod.NON_BLAZE) { - return ImmutableList.of(); - } - return ImmutableList.of( - DeployTasksCompat.createDeployTask( - project, getApkInfoToInstall(device, launchOptions, apkProvider), launchOptions)); - } - - @Override - @Nullable - public BlazeLaunchTask getApplicationLaunchTask( - LaunchOptions launchOptions, @Nullable Integer userId, String contributorsAmStartOptions) - throws ExecutionException { - switch (configState.getLaunchMethod()) { - case BLAZE_TEST: - BlazeAndroidTestFilter testFilter = - new BlazeAndroidTestFilter( - configState.getTestingType(), - configState.getClassName(), - configState.getMethodName(), - configState.getPackageName()); - return new BlazeAndroidTestLaunchTask( - project, - label, - blazeFlags, - testFilter, - this, - launchOptions.isDebug(), - testResultsHolder); - case NON_BLAZE: - case MOBILE_INSTALL: - BlazeAndroidDeployInfo deployInfo; - try { - deployInfo = buildStep.getDeployInfo(); - } catch (ApkProvisionException e) { - throw new ExecutionException(e); - } - return StockAndroidTestLaunchTask.getStockTestLaunchTask( - configState, applicationIdProvider, launchOptions.isDebug(), deployInfo, project); - } - throw new AssertionError(); - } - - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) // Raw type from upstream. - public ConnectDebuggerTask getDebuggerTask( - AndroidDebugger androidDebugger, AndroidDebuggerState androidDebuggerState) { - switch (configState.getLaunchMethod()) { - case BLAZE_TEST: - return new ConnectBlazeTestDebuggerTask(this, androidDebugger, androidDebuggerState); - case NON_BLAZE: - case MOBILE_INSTALL: - return getBaseDebuggerTask(androidDebugger, androidDebuggerState, env, facet, 30); - } - throw new AssertionError(); - } - - void onLaunchTaskComplete() { - for (Runnable runnable : launchTaskCompleteListeners) { - runnable.run(); - } - } - - void addLaunchTaskCompleteListener(Runnable runnable) { - launchTaskCompleteListeners.add(runnable); - } - - @Override - public Executor getExecutor() { - return env.getExecutor(); - } - - @Nullable - @Override - public Integer getUserId(IDevice device) { - return null; - } - - @Override - public String getAmStartOptions() { - return ""; - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/ConnectBlazeTestDebuggerTask.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/ConnectBlazeTestDebuggerTask.java deleted file mode 100644 index 3ef2a6c9493..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/test/ConnectBlazeTestDebuggerTask.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.test; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.execution.common.debug.DebugSessionStarter; -import com.android.tools.idea.run.tasks.ConnectDebuggerTask; -import com.intellij.execution.process.ProcessHandler; -import com.intellij.execution.process.ProcessOutputTypes; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.xdebugger.impl.XDebugSessionImpl; -import java.io.OutputStream; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** Connects the blaze debugger during execution. */ -class ConnectBlazeTestDebuggerTask implements ConnectDebuggerTask { - - private final BlazeAndroidTestRunContext runContext; - private final AndroidDebugger myAndroidDebugger; - private final S myAndroidDebuggerState; - - public ConnectBlazeTestDebuggerTask( - BlazeAndroidTestRunContext runContext, - AndroidDebugger androidDebugger, - S androidDebuggerState) { - this.runContext = runContext; - myAndroidDebugger = androidDebugger; - myAndroidDebuggerState = androidDebuggerState; - } - - /** - * Wires up listeners to automatically reconnect the debugger for each test method. When you - * `blaze test` an android_test in debug mode, it kills the instrumentation process between each - * test method, disconnecting the debugger. We listen for the start of a new method waiting for a - * debugger, and reconnect. TODO: Support stopping Blaze from the UI. This is hard because we have - * no way to distinguish process handler termination/debug session ending initiated by the user. - * - * @return Promise with debug session or error - */ - @Override - public @NotNull XDebugSessionImpl perform( - @NotNull IDevice device, - @NotNull String applicationId, - @NotNull ExecutionEnvironment environment, - @NotNull ProgressIndicator progressIndicator, - ConsoleView console) { - final ProcessHandler masterProcessHandler = - new ProcessHandler() { - - @Override - protected void destroyProcessImpl() { - notifyProcessTerminated(0); - } - - @Override - protected void detachProcessImpl() { - notifyProcessDetached(); - } - - @Override - public boolean detachIsDefault() { - return false; - } - - @Override - public @Nullable OutputStream getProcessInput() { - return null; - } - }; - runContext.addLaunchTaskCompleteListener( - () -> { - masterProcessHandler.notifyTextAvailable( - "Test run completed.\n", ProcessOutputTypes.STDOUT); - masterProcessHandler.detachProcess(); - }); - return DebugSessionStarter.INSTANCE.attachReattachingDebuggerToStartedProcess( - device, - applicationId, - masterProcessHandler, - environment, - myAndroidDebugger, - myAndroidDebuggerState, - progressIndicator, - console, - Long.MAX_VALUE); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java deleted file mode 100644 index 1a7f9a4f621..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.testrecorder; - -import com.android.annotations.Nullable; -import com.android.ddmlib.IDevice; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunConfigurationRunner; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import java.util.List; - -/** Compat class for implementing TestRecorderBlazeCommandRunConfigurationProxy. */ -public class TestRecorderBlazeCommandRunConfigurationProxy - extends TestRecorderBlazeCommandRunConfigurationProxyBase { - - public TestRecorderBlazeCommandRunConfigurationProxy( - BlazeCommandRunConfiguration baseConfiguration) { - super(baseConfiguration); - } - - @Override - @Nullable - public List> getDeviceFutures(ExecutionEnvironment environment) { - return environment - .getCopyableUserData(BlazeAndroidRunConfigurationRunner.DEVICE_SESSION_KEY) - .deviceFutures - .get(); - } -} diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java b/aswb/sdkcompat/as223/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java deleted file mode 100644 index 00a9e4a94c9..00000000000 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2020 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.sync.model.idea; - -import com.android.tools.idea.model.AndroidModel; -import com.android.tools.idea.model.Namespacing; -import com.android.tools.idea.projectsystem.NamedIdeaSourceProvider; -import com.google.common.util.concurrent.ListenableFuture; -import com.intellij.openapi.project.Project; -import java.io.File; - -/** Blaze model for an android project. #api42. */ -public class BlazeAndroidModel extends BlazeAndroidModelBase { - private final NamedIdeaSourceProvider sourceProvider; - - public BlazeAndroidModel( - Project project, - File rootDirPath, - NamedIdeaSourceProvider sourceProvider, - ListenableFuture applicationId, - int minSdkVersion, - boolean desugarJava8Libs) { - super(project, rootDirPath, applicationId, minSdkVersion, desugarJava8Libs); - this.sourceProvider = sourceProvider; - } - - public NamedIdeaSourceProvider getDefaultSourceProvider() { - return sourceProvider; - } - - @Override - public Namespacing getNamespacing() { - return Namespacing.DISABLED; - } - - @Override - protected String uninitializedApplicationId() { - return AndroidModel.UNINITIALIZED_APPLICATION_ID; - } -} diff --git a/aswb/sdkcompat/as231/com/android/tools/idea/model/AndroidManifestIndexCompat.java b/aswb/sdkcompat/as231/com/android/tools/idea/model/AndroidManifestIndexCompat.java deleted file mode 100644 index 27f94f054c6..00000000000 --- a/aswb/sdkcompat/as231/com/android/tools/idea/model/AndroidManifestIndexCompat.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2023 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.idea.model; - -/** Compat class for {@link com.android.tools.idea.model.AndroidManifestIndex}. */ -public class AndroidManifestIndexCompat { - - private AndroidManifestIndexCompat() {} - - /** {@code indexEnabled} was removed in Studio 2021.2. #api211 */ - public static boolean indexEnabled() { - return true; - } -} diff --git a/aswb/sdkcompat/as231/com/android/tools/idea/progress/StudioLoggerProgressIndicatorCompat.java b/aswb/sdkcompat/as231/com/android/tools/idea/progress/StudioLoggerProgressIndicatorCompat.java deleted file mode 100644 index e581bd190d8..00000000000 --- a/aswb/sdkcompat/as231/com/android/tools/idea/progress/StudioLoggerProgressIndicatorCompat.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2023 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.idea.progress; - -/** Compat layer for StudioLoggerProgressIndicator which moved packages in 2021.2. #api211 */ -public class StudioLoggerProgressIndicatorCompat extends StudioLoggerProgressIndicator { - public StudioLoggerProgressIndicatorCompat(Class c) { - super(c); - } -} diff --git a/aswb/sdkcompat/as231/com/android/tools/idea/rendering/RenderErrorContributorCompat.java b/aswb/sdkcompat/as231/com/android/tools/idea/rendering/RenderErrorContributorCompat.java deleted file mode 100644 index f869496110c..00000000000 --- a/aswb/sdkcompat/as231/com/android/tools/idea/rendering/RenderErrorContributorCompat.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.idea.rendering; - -import com.android.tools.idea.ui.designer.EditorDesignSurface; -import com.android.tools.rendering.RenderResultCompat; -import com.intellij.openapi.actionSystem.DataContext; -import groovyjarjarantlr4.v4.runtime.misc.Nullable; - -/** Contribute blaze specific render errors. */ -public class RenderErrorContributorCompat extends RenderErrorContributor { - public RenderErrorContributorCompat( - EditorDesignSurface surface, RenderResultCompat result, @Nullable DataContext dataContext) { - super(surface, result.get()); - } -} diff --git a/aswb/sdkcompat/as231/com/android/tools/rendering/RenderLoggerCompat.java b/aswb/sdkcompat/as231/com/android/tools/rendering/RenderLoggerCompat.java deleted file mode 100644 index 96af24f48d3..00000000000 --- a/aswb/sdkcompat/as231/com/android/tools/rendering/RenderLoggerCompat.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.rendering; - -import java.util.Map; -import java.util.Set; - -/** Compat class for RenderLogger. */ -public class RenderLoggerCompat { - private final RenderLogger renderLogger; - - public RenderLoggerCompat(RenderResultCompat result) { - renderLogger = result.getLogger(); - } - - public RenderLogger get() { - return renderLogger; - } - - public boolean hasErrors() { - return renderLogger.hasErrors(); - } - - public Map getBrokenClasses() { - return renderLogger.getBrokenClasses(); - } - - public Set getMissingClasses() { - return renderLogger.getMissingClasses(); - } - - public static void resetFidelityErrorsFilters() { - RenderLogger.resetFidelityErrorsFilters(); - } -} diff --git a/aswb/sdkcompat/as231/com/android/tools/rendering/RenderResultCompat.java b/aswb/sdkcompat/as231/com/android/tools/rendering/RenderResultCompat.java deleted file mode 100644 index 75fc9c912b9..00000000000 --- a/aswb/sdkcompat/as231/com/android/tools/rendering/RenderResultCompat.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.rendering; - -import com.android.ide.common.rendering.api.Result; -import com.android.tools.idea.rendering.RenderErrorContributor; -import com.android.tools.idea.rendering.RenderErrorModelFactory; -import com.android.tools.idea.rendering.RenderResults; -import com.android.tools.idea.rendering.errors.ui.RenderErrorModel; -import com.android.tools.idea.ui.designer.EditorDesignSurface; -import com.android.tools.rendering.imagepool.ImagePool.Image; -import com.google.idea.blaze.android.rendering.BlazeRenderErrorContributor; -import com.google.idea.blaze.base.settings.Blaze; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiFile; -import org.jetbrains.annotations.Nullable; - -/** Compat class for {@link RenderResult} */ -public final class RenderResultCompat { - private RenderResult result; - - public RenderResultCompat(RenderResult result) { - this.result = result; - } - - public static RenderResultCompat createBlank(PsiFile file) { - return new RenderResultCompat(RenderResults.createBlank(file)); - } - - public RenderErrorModel createErrorModel() { - return RenderErrorModelFactory.createErrorModel(null, result, null); - } - - public RenderResult get() { - return result; - } - - public RenderLogger getLogger() { - return result.getLogger(); - } - - public Module getModule() { - return result.getModule(); - } - - public Result getRenderResult() { - return result.getRenderResult(); - } - - public Image getRenderedImage() { - return result.getRenderedImage(); - } - - private RenderResultCompat() {} - - /** Extension to provide {@link BlazeRenderErrorContributor}. */ - public static class BlazeProvider extends RenderErrorContributor.Provider { - @Override - public boolean isApplicable(Project project) { - return Blaze.isBlazeProject(project); - } - - @Override - public RenderErrorContributor getContributor( - @Nullable EditorDesignSurface surface, RenderResult result) { - return new BlazeRenderErrorContributor(surface, new RenderResultCompat(result), null); - } - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java deleted file mode 100644 index 7aa210d0595..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.cppimpl.debug; - -import com.android.ddmlib.Client; -import com.android.tools.ndk.run.editor.AutoAndroidDebuggerState; -import com.intellij.execution.ExecutionException; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.xdebugger.XDebugSession; - -/** Shim for #api212 compat. */ -public class BlazeAutoAndroidDebugger extends BlazeAutoAndroidDebuggerBase { - @Override - public XDebugSession attachToClient( - Project project, Client client, AutoAndroidDebuggerState state) throws ExecutionException { - if (isNativeProject(project)) { - log.info("Project has native development enabled. Attaching native debugger."); - return nativeDebugger.attachToClient(project, client, state); - } else { - return super.attachToClient(project, client, state); - } - } - - @Override - protected boolean isNativeDeployment(Project project, Module debuggeeModule) { - return isNativeProject(project); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java deleted file mode 100644 index bfa296e12e2..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2023 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.cppimpl.debug; - -/** - * API compat of {@link BlazeNativeAndroidDebuggerBase} with the following additions: - * - *

    - *
  • Creates a run-config setting using {@link BlazeAndroidNativeAttachConfiguration} instead of - * {@link AndroidNativeAttachConfiguration} to override counterproductive validations. - *
- * - * #api4.0 - */ -public class BlazeNativeAndroidDebugger extends BlazeNativeAndroidDebuggerBase {} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebuggerBase.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebuggerBase.java deleted file mode 100644 index 911d90b7711..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebuggerBase.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2020 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.cppimpl.debug; - -import com.android.tools.ndk.run.editor.NativeAndroidDebugger; -import com.google.idea.blaze.base.model.BlazeProjectData; -import com.google.idea.blaze.base.model.primitives.LanguageClass; -import com.google.idea.blaze.base.settings.Blaze; -import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager; -import com.intellij.openapi.project.Project; - -/** - * Extension of {@link NativeAndroidDebugger} with the following key differences compared to {@link - * NativeAndroidDebugger}. - * - *
    - *
  • Overrides {@link #supportsProject} so native debugger is only enabled for native support is - * enabled. - *
- */ -public class BlazeNativeAndroidDebuggerBase extends NativeAndroidDebugger { - /** - * This ID needs to be lexicographically larger than "Java" so it come after the "Java" debugger - * when sorted lexicographically in the "Attach Debugger to Android Process" dialog. See {@link - * org.jetbrains.android.actions.AndroidProcessChooserDialog#populateDebuggerTypeCombo}. - */ - public static final String ID = "Native" + Blaze.defaultBuildSystemName(); - - @Override - public String getId() { - return ID; - } - - @Override - public String getDisplayName() { - return "Native Only"; - } - - @Override - public boolean supportsProject(Project project) { - BlazeProjectData blazeProjectData = - BlazeProjectDataManager.getInstance(project).getBlazeProjectData(); - return blazeProjectData != null - && blazeProjectData.getWorkspaceLanguageSettings().isLanguageActive(LanguageClass.C); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/projectsystem/BlazeModuleSystem.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/projectsystem/BlazeModuleSystem.java deleted file mode 100644 index 162fd8f1793..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/projectsystem/BlazeModuleSystem.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2020 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.projectsystem; - -import com.android.tools.idea.projectsystem.AndroidModuleSystem; -import com.intellij.openapi.module.Module; - -/** Blaze implementation of {@link AndroidModuleSystem}. */ -public class BlazeModuleSystem extends BlazeModuleSystemBase { - - BlazeModuleSystem(Module module) { - super(module); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/projectsystem/BlazeProjectSystem.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/projectsystem/BlazeProjectSystem.java deleted file mode 100755 index df7e6246ef5..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/projectsystem/BlazeProjectSystem.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright 2017 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.projectsystem; - -import static com.android.tools.idea.projectsystem.SourceProvidersKt.emptySourceProvider; -import static org.jetbrains.android.facet.SourceProviderUtil.createSourceProvidersForLegacyModule; - -import com.android.tools.apk.analyzer.AaptInvoker; -import com.android.tools.idea.log.LogWrapper; -import com.android.tools.idea.model.AndroidModel; -import com.android.tools.idea.model.ClassJarProvider; -import com.android.tools.idea.projectsystem.AndroidProjectSystem; -import com.android.tools.idea.projectsystem.NamedIdeaSourceProvider; -import com.android.tools.idea.projectsystem.ProjectSystemBuildManager; -import com.android.tools.idea.projectsystem.ProjectSystemSyncManager; -import com.android.tools.idea.projectsystem.ScopeType; -import com.android.tools.idea.projectsystem.SourceProviderManager; -import com.android.tools.idea.projectsystem.SourceProviders; -import com.android.tools.idea.projectsystem.SourceProvidersFactory; -import com.android.tools.idea.projectsystem.SourceProvidersImpl; -import com.android.tools.idea.res.AndroidInnerClassFinder; -import com.android.tools.idea.res.AndroidResourceClassPsiElementFinder; -import com.android.tools.idea.sdk.AndroidSdks; -import com.google.common.collect.ImmutableList; -import com.google.idea.blaze.android.resources.BlazeLightResourceClassService; -import com.google.idea.blaze.android.sync.model.idea.BlazeAndroidModel; -import com.google.idea.blaze.android.sync.model.idea.BlazeClassJarProvider; -import com.google.idea.blaze.base.settings.Blaze; -import com.google.idea.blaze.base.settings.BlazeImportSettings.ProjectType; -import com.intellij.facet.ProjectFacetManager; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiElementFinder; -import com.intellij.psi.search.GlobalSearchScope; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.annotations.NotNull; - -/** - * Base class to implement common methods in {@link AndroidProjectSystem} for blaze with different - * sdk - */ -public class BlazeProjectSystem implements AndroidProjectSystem { - protected final Project project; - protected final ProjectSystemSyncManager syncManager; - protected final List myFinders; - private final BlazeProjectSystemBuildManager buildManager; - - public BlazeProjectSystem(Project project) { - this.project = project; - syncManager = new BlazeProjectSystemSyncManager(project); - buildManager = new BlazeProjectSystemBuildManager(project); - - myFinders = - Arrays.asList( - AndroidInnerClassFinder.INSTANCE, - new AndroidResourceClassPsiElementFinder(getLightResourceClassService())); - } - - public Project getProject() { - return project; - } - - @Override - public boolean allowsFileCreation() { - return true; - } - - @Nullable - @Override - public VirtualFile getDefaultApkFile() { - return null; - } - - @Override - public Path getPathToAapt() { - return AaptInvoker.getPathToAapt( - AndroidSdks.getInstance().tryToChooseSdkHandler(), - new LogWrapper(BlazeProjectSystem.class)); - } - - @Override - public ProjectSystemBuildManager getBuildManager() { - return buildManager; - } - - @Override - public BlazeModuleSystem getModuleSystem(Module module) { - return BlazeModuleSystem.getInstance(module); - } - - @Override - public ProjectSystemSyncManager getSyncManager() { - return syncManager; - } - - @Override - public Collection getPsiElementFinders() { - return myFinders; - } - - @Override - public BlazeLightResourceClassService getLightResourceClassService() { - return BlazeLightResourceClassService.getInstance(project); - } - - @Override - public SourceProvidersFactory getSourceProvidersFactory() { - return new SourceProvidersFactory() { - @Override - public SourceProviders createSourceProvidersFor(AndroidFacet facet) { - BlazeAndroidModel model = ((BlazeAndroidModel) AndroidModel.get(facet)); - if (model != null) { - return createForModel(model); - } else { - return createSourceProvidersForLegacyModule(facet); - } - } - - private SourceProviders createForModel(BlazeAndroidModel model) { - NamedIdeaSourceProvider mainSourceProvider = model.getDefaultSourceProvider(); - if (Blaze.getProjectType(project).equals(ProjectType.QUERY_SYNC)) { - return new SourceProvidersImpl( - mainSourceProvider, - ImmutableList.of(mainSourceProvider), - ImmutableList.of(), - ImmutableList.of(), - ImmutableList.of(), - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - emptySourceProvider(ScopeType.MAIN), - emptySourceProvider(ScopeType.UNIT_TEST), - emptySourceProvider(ScopeType.ANDROID_TEST), - emptySourceProvider(ScopeType.TEST_FIXTURES)); - } else { - return new SourceProvidersImpl( - mainSourceProvider, - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), - emptySourceProvider(ScopeType.MAIN), - emptySourceProvider(ScopeType.UNIT_TEST), - emptySourceProvider(ScopeType.ANDROID_TEST), - emptySourceProvider(ScopeType.TEST_FIXTURES)); - } - } - }; - } - - @Override - public ClassJarProvider getClassJarProvider() { - return new BlazeClassJarProvider(project); - } - - @Override - public Collection getAndroidFacetsWithPackageName( - Project project, String packageName) { - return getAndroidFacetsWithPackageName( - project, packageName, GlobalSearchScope.projectScope(project)); - } - - private Collection getAndroidFacetsWithPackageName( - Project project, String packageName, GlobalSearchScope scope) { - List facets = ProjectFacetManager.getInstance(project).getFacets(AndroidFacet.ID); - return facets.stream() - .filter(facet -> hasPackageName(facet, packageName)) - .filter( - facet -> { - VirtualFile file = SourceProviderManager.getInstance(facet).getMainManifestFile(); - if (file == null) { - return false; - } else { - return scope.contains(file); - } - }) - .collect(Collectors.toList()); - } - - @Override - public boolean isNamespaceOrParentPackage(@NotNull String packageName) { - List facets = ProjectFacetManager.getInstance(project).getFacets(AndroidFacet.ID); - GlobalSearchScope scope = GlobalSearchScope.projectScope(project); - for (AndroidFacet facet : facets) { - String moduleNamespace = PackageNameUtils.getPackageName(facet.getModule()); - if (moduleNamespace == null) { - continue; - } - // Check if the moduleNamespace is exactly the package name, or is a subpackage - if (!moduleNamespace.startsWith(packageName)) { - continue; - } - // packageName=com.example should not match moduleNamespace=com.example2 - if (moduleNamespace.length() > packageName.length() - && moduleNamespace.charAt(packageName.length()) != '.') { - continue; - } - VirtualFile file = SourceProviderManager.getInstance(facet).getMainManifestFile(); - if (file == null || !scope.contains(file)) { - continue; - } - return true; - } - return false; - } - - @Override - public Collection getSubmodules() { - return ImmutableList.of(); - } - - @Override - public Collection getBootClasspath(@NotNull Module module) { - // TODO: b/266586669 - return ImmutableList.of(); - } - - private static boolean hasPackageName(AndroidFacet facet, String packageName) { - String nameFromFacet = PackageNameUtils.getPackageName(facet.getModule()); - if (nameFromFacet == null) { - return false; - } - return nameFromFacet.equals(packageName); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java deleted file mode 100644 index 81504173f22..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright 2020 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.projectsystem; - -import static java.util.stream.Collectors.joining; - -import com.android.tools.idea.projectsystem.ClassFileFinder; -import com.android.tools.idea.projectsystem.ClassFileFinderUtil; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableSet; -import com.google.idea.blaze.android.libraries.RenderJarCache; -import com.google.idea.blaze.android.sync.model.AndroidResourceModule; -import com.google.idea.blaze.android.sync.model.AndroidResourceModuleRegistry; -import com.google.idea.blaze.android.targetmaps.TargetToBinaryMap; -import com.google.idea.blaze.base.ideinfo.TargetIdeInfo; -import com.google.idea.blaze.base.ideinfo.TargetKey; -import com.google.idea.blaze.base.io.VirtualFileSystemProvider; -import com.google.idea.blaze.base.model.BlazeProjectData; -import com.google.idea.blaze.base.qsync.QuerySync; -import com.google.idea.blaze.base.qsync.QuerySyncManager; -import com.google.idea.blaze.base.qsync.RenderJarArtifactTracker; -import com.google.idea.blaze.base.settings.Blaze; -import com.google.idea.blaze.base.settings.BlazeImportSettings.ProjectType; -import com.google.idea.blaze.base.sync.BlazeSyncModificationTracker; -import com.google.idea.blaze.base.sync.data.BlazeDataStorage; -import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager; -import com.google.idea.common.experiments.BoolExperiment; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.JarFileSystem; -import com.intellij.openapi.vfs.VirtualFile; -import java.io.File; -import java.util.regex.Pattern; -import org.jetbrains.annotations.Nullable; - -/** - * A {@link ClassFileFinder} that uses deploy JAR like artifacts (called render jar henceforth) for - * class files. - * - *

The render JAR contains all runtime dependencies of a binary target. - * - *

The Blaze targets that go into creating a resource module is known. Consequently, it is - * possible to determine which binaries in the projectview depend on the resource declaring blaze - * targets that constitutes the module. This class calculates the binary targets and attempts to - * find classes from the render JARs. - * - *

This only works for resource modules (i.e. not the .workspace module). For .workspace module, - * we try to find the class in all binary targets in projectview - * - *

NOTE: Blaze targets that constitutes the resource module will be called "resource target(s)" - * in comments below. - */ -public class RenderJarClassFileFinder implements ClassFileFinder { - /** Experiment to control whether class file finding from render jars should be enabled. */ - private static final BoolExperiment enabled = - new BoolExperiment("aswb.renderjar.cff.enabled.3", true); - - /** - * Experiment to toggle whether resource resolution is allowed from Render JARs. Render JARs - * should not resolve resources by default. - */ - @VisibleForTesting - static final BoolExperiment resolveResourceClasses = - new BoolExperiment("aswb.resolve.resources.render.jar", false); - - private static final Logger log = Logger.getInstance(RenderJarClassFileFinder.class); - - private static final String INTERNAL_PACKAGE = "_layoutlib_._internal_."; - - // matches foo.bar.R or foo.bar.R$baz - private static final Pattern RESOURCE_CLASS_NAME = Pattern.compile(".+\\.R(\\$[^.]+)?$"); - - private final Module module; - private final Project project; - - // tracks the binary targets that depend resource targets - // will be recalculated after every sync - private ImmutableSet binaryTargets = ImmutableSet.of(); - - // tracks the value of {@link BlazeSyncModificationTracker} when binaryTargets is calculated - // binaryTargets is calculated when the value of {@link BlazeSyncModificationTracker} does not - // equal lastSyncCount - long lastSyncCount = -1; - - // true if the current module is the .workspace Module - private final boolean isWorkspaceModule; - - public RenderJarClassFileFinder(Module module) { - this.module = module; - this.project = module.getProject(); - this.isWorkspaceModule = BlazeDataStorage.WORKSPACE_MODULE_NAME.equals(module.getName()); - } - - @Nullable - @Override - public VirtualFile findClassFile(String fqcn) { - if (!isEnabled()) { - return null; - } - - // Ever since Compose support was introduced in AS, finding class files is invoked during the - // normal course of opening an editor. The contract for this method requires that it shouldn't - // throw any exceptions, but we've had a few bugs where this method threw an exception, which - // resulted in users not being able to open Kotlin files at all. In order to avoid this - // scenario, we wrap the underlying call and ensure that no exceptions are thrown. - try { - return findClass(fqcn); - } catch (Error e) { - log.warn( - String.format( - "Unexpected error while finding the class file for `%1$s`: %2$s", - fqcn, Throwables.getRootCause(e).getMessage())); - return null; - } - } - - @Nullable - public VirtualFile findClass(String fqcn) { - // Render JAR should not resolve any resources. All resources should be available to the IDE - // through ResourceRepository. Attempting to resolve resources from Render JAR indicates that - // ASwB hasn't properly set up resources for the project. - if (isResourceClass(fqcn) && !resolveResourceClasses.getValue()) { - log.warn(String.format("Attempting to load resource '%s' from RenderJAR.", fqcn)); - return null; - } - - if (Blaze.getProjectType(project).equals(ProjectType.QUERY_SYNC)) { - if (QuerySync.isComposeEnabled(project)) { - RenderJarArtifactTracker renderJarArtifactTracker = - QuerySyncManager.getInstance(project).getRenderJarArtifactTracker(); - // TODO(b/283280194): Setup fqcn -> target and target -> Render jar mappings to avoid - // iterating over all render jars when trying to locate class for fqcn. - // TODO(b/284002836): Collect metrics on time taken to iterate over the jars - for (File renderJar : renderJarArtifactTracker.getRenderJars()) { - VirtualFile renderResolveJarVf = - VirtualFileSystemProvider.getInstance().getSystem().findFileByIoFile(renderJar); - if (renderResolveJarVf != null) { - return findClassInJar(renderResolveJarVf, fqcn); - } - log.warn(String.format("Could not find class `%1$s` with Query Sync", fqcn)); - return null; - } - } else { - // Disable this class for Query Sync if Compose is not enabled - return null; - } - } - - BlazeProjectData projectData = - BlazeProjectDataManager.getInstance(project).getBlazeProjectData(); - if (projectData == null) { - log.warn("Could not find BlazeProjectData for project " + project.getName()); - return null; - } - - ImmutableSet binaryTargets = getBinaryTargets(); - if (binaryTargets.isEmpty()) { - log.warn( - String.format( - "No binaries for module %s. Adding a binary target to the projectview and resyncing" - + " might fix the issue.", - module.getName())); - return null; - } - - // Remove internal package prefix if present - fqcn = StringUtil.trimStart(fqcn, INTERNAL_PACKAGE); - - // Look through render resolve JARs of the binaries that depend on the given - // androidResourceModule. One androidResourceModule can comprise of multiple resource targets. - // The binaries can depend on any subset of these resource targets. Generally, we only - // expect one, or a small number of binaries here. - for (TargetKey binaryTarget : binaryTargets) { - VirtualFile classFile = getClassFromRenderResolveJar(projectData, fqcn, binaryTarget); - if (classFile != null) { - return classFile; - } - } - - log.warn(String.format("Could not find class `%1$s` (module: `%2$s`)", fqcn, module.getName())); - return null; - } - - @VisibleForTesting - static boolean isResourceClass(String fqcn) { - return RESOURCE_CLASS_NAME.matcher(fqcn).matches(); - } - - /** - * Returns the cached list of binary targets that depend on resource targets. The cache is - * recalculated if the project has been synced since last calculation - */ - private ImmutableSet getBinaryTargets() { - long currentSyncCount = - BlazeSyncModificationTracker.getInstance(project).getModificationCount(); - if (currentSyncCount == lastSyncCount) { - // Return the cached set if there hasn't been a sync since last calculation - return binaryTargets; - } - lastSyncCount = currentSyncCount; - - AndroidResourceModule androidResourceModule = - AndroidResourceModuleRegistry.getInstance(project).get(module); - if (androidResourceModule != null) { - binaryTargets = - TargetToBinaryMap.getInstance(project) - .getBinariesDependingOn(androidResourceModule.sourceTargetKeys); - } else if (isWorkspaceModule) { - binaryTargets = TargetToBinaryMap.getInstance(project).getSourceBinaryTargets(); - } else { - binaryTargets = ImmutableSet.of(); - log.warn("Could not find AndroidResourceModule for " + module.getName()); - } - log.info( - String.format( - "Binary targets for module `%1$s`: %2$s", - module.getName(), - binaryTargets.stream() - .limit(5) - .map(t -> t.getLabel().toString()) - .collect(joining(", ")))); - return binaryTargets; - } - - /** - * Returns class file for fqcn if found in the render JAR corresponding to {@code binaryTarget}. - * Returns null if something goes wrong or if render JAR does not contain fqcn - */ - @Nullable - private VirtualFile getClassFromRenderResolveJar( - BlazeProjectData projectData, String fqcn, TargetKey binaryTarget) { - TargetIdeInfo ideInfo = projectData.getTargetMap().get(binaryTarget); - if (ideInfo == null) { - return null; - } - - File renderResolveJarFile = - RenderJarCache.getInstance(project) - .getCachedJarForBinaryTarget(projectData.getArtifactLocationDecoder(), ideInfo); - - if (renderResolveJarFile == null) { - return null; - } - - VirtualFile renderResolveJarVF = - VirtualFileSystemProvider.getInstance().getSystem().findFileByIoFile(renderResolveJarFile); - if (renderResolveJarVF == null) { - return null; - } - - return findClassInJar(renderResolveJarVF, fqcn); - } - - @Nullable - private static VirtualFile findClassInJar(final VirtualFile classJar, String fqcn) { - VirtualFile jarRoot = getJarRootForLocalFile(classJar); - if (jarRoot == null) { - return null; - } - return ClassFileFinderUtil.findClassFileInOutputRoot(jarRoot, fqcn); - } - - /** Test aware method to redirect JARs to {@link VirtualFileSystemProvider} for tests */ - private static VirtualFile getJarRootForLocalFile(VirtualFile file) { - return ApplicationManager.getApplication().isUnitTestMode() - ? VirtualFileSystemProvider.getInstance() - .getSystem() - .findFileByPath(file.getPath() + JarFileSystem.JAR_SEPARATOR) - : JarFileSystem.getInstance().getJarRootForLocalFile(file); - } - - public static boolean isEnabled() { - return enabled.getValue(); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/resources/BlazeLightResourceClassServiceBase.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/resources/BlazeLightResourceClassServiceBase.java deleted file mode 100644 index 21516076cc2..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/resources/BlazeLightResourceClassServiceBase.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.resources; - -import com.android.tools.idea.projectsystem.LightResourceClassService; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.idea.blaze.base.sync.data.BlazeDataStorage; -import com.google.idea.common.experiments.FeatureRolloutExperiment; -import com.intellij.openapi.module.Module; -import com.intellij.psi.PsiClass; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -/** Implementation of {@link LightResourceClassService} set up at Blaze sync time. */ -public abstract class BlazeLightResourceClassServiceBase implements LightResourceClassService { - - @VisibleForTesting - public static final FeatureRolloutExperiment workspaceResourcesFeature = - new FeatureRolloutExperiment("aswb.workspace.light.class.enabled"); - - Map rClasses = Maps.newHashMap(); - Map rClassesByModule = Maps.newHashMap(); - final Set allRClasses = Sets.newHashSet(); - - @Override - public Collection getLightRClassesAccessibleFromModule( - Module module, boolean includeTest) { - if (workspaceResourcesFeature.isEnabled() - && module.getName().equals(BlazeDataStorage.WORKSPACE_MODULE_NAME)) { - // Returns all the packages in resource modules, and all the workspace packages that - // have previously been asked for. All `res/` directories in our project should belong to a - // resource module. For java sources, IntelliJ will ask for explicit resource package by - // calling `getLightRClasses` at which point we can create the package. This is not completely - // correct and the autocomplete will be slightly off when initial `R` is typed in the editor, - // but this workaround is being used to mitigate issues (b/136685602) while resources - // are re-worked. - return allRClasses; - } else { - return rClasses.values(); - } - } - - @Override - public Collection getLightRClassesDefinedByModule( - Module module, boolean includeTestClasses) { - BlazeRClass rClass = rClassesByModule.get(module); - return rClass == null ? ImmutableSet.of() : ImmutableSet.of(rClass); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java deleted file mode 100644 index 96c4e9e34b3..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2019 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.execution.common.debug.DebugSessionStarter; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.activity.DefaultStartActivityFlagsProvider; -import com.android.tools.idea.run.activity.StartActivityFlagsProvider; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.xdebugger.XDebugSession; -import javax.annotation.Nullable; -import kotlin.Unit; -import kotlin.coroutines.EmptyCoroutineContext; -import kotlinx.coroutines.BuildersKt; -import org.jetbrains.android.facet.AndroidFacet; - -/** Compat for #api212 */ -public class BlazeAndroidBinaryNormalBuildRunContext - extends BlazeAndroidBinaryNormalBuildRunContextBase { - BlazeAndroidBinaryNormalBuildRunContext( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - super(project, facet, runConfiguration, env, configState, buildStep, launchId); - } - - @Override - public BlazeLaunchTask getApplicationLaunchTask( - boolean isDebug, @Nullable Integer userId, String contributorsAmStartOptions) - throws ExecutionException { - String extraFlags = UserIdHelper.getFlagsFromUserId(userId); - if (!contributorsAmStartOptions.isEmpty()) { - extraFlags += (extraFlags.isEmpty() ? "" : " ") + contributorsAmStartOptions; - } - if (isDebug) { - extraFlags += (extraFlags.isEmpty() ? "" : " ") + "-D"; - } - - final StartActivityFlagsProvider startActivityFlagsProvider = - new DefaultStartActivityFlagsProvider(project, isDebug, extraFlags); - - BlazeAndroidDeployInfo deployInfo; - try { - deployInfo = buildStep.getDeployInfo(); - } catch (ApkProvisionException e) { - throw new ExecutionException(e); - } - - return BlazeAndroidBinaryApplicationLaunchTaskProvider.getApplicationLaunchTask( - applicationIdProvider, - deployInfo.getMergedManifest(), - configState, - startActivityFlagsProvider); - } - - @Nullable - @Override - public XDebugSession startDebuggerSession( - AndroidDebugger androidDebugger, - AndroidDebuggerState androidDebuggerState, - ExecutionEnvironment env, - IDevice device, - ConsoleView consoleView, - ProgressIndicator indicator, - String packageName) { - try { - return BuildersKt.runBlocking( - EmptyCoroutineContext.INSTANCE, - (scope, continuation) -> - DebugSessionStarter.INSTANCE.attachDebuggerToStartedProcess( - device, - packageName, - env, - androidDebugger, - androidDebuggerState, - /*destroyRunningProcess*/ d -> { - d.forceStop(packageName); - return Unit.INSTANCE; - }, - indicator, - consoleView, - /* timeout= */ 15L, - continuation)); - } catch (InterruptedException e) { - throw new ProcessCanceledException(); - } - } - - @Override - public Executor getExecutor() { - return env.getExecutor(); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java deleted file mode 100644 index 96f3f8be324..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import static com.google.idea.blaze.android.run.runner.BlazeAndroidLaunchTasksProvider.NATIVE_DEBUGGING_ENABLED; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.gradle.util.DynamicAppUtils; -import com.android.tools.idea.run.ApkFileUnit; -import com.android.tools.idea.run.ApkInfo; -import com.android.tools.idea.run.ApkProvider; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.ConsoleProvider; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; -import com.android.tools.idea.run.editor.ProfilerState; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.idea.blaze.android.run.deployinfo.BlazeApkProviderService; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.android.run.runner.BlazeAndroidDeviceSelector; -import com.google.idea.blaze.android.run.runner.BlazeAndroidLaunchTasksProvider; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunContext; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.project.Project; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.annotations.NotNull; - -/** Run context for android_binary. */ -public abstract class BlazeAndroidBinaryNormalBuildRunContextBase - implements BlazeAndroidRunContext { - protected final Project project; - protected final AndroidFacet facet; - protected final RunConfiguration runConfiguration; - protected final ExecutionEnvironment env; - protected final BlazeAndroidBinaryRunConfigurationState configState; - protected final ConsoleProvider consoleProvider; - protected final ApkBuildStep buildStep; - protected final ApkProvider apkProvider; - protected final ApplicationIdProvider applicationIdProvider; - private final String launchId; - - BlazeAndroidBinaryNormalBuildRunContextBase( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - this.project = project; - this.facet = facet; - this.runConfiguration = runConfiguration; - this.env = env; - this.configState = configState; - this.consoleProvider = new BlazeAndroidBinaryConsoleProvider(project); - this.buildStep = buildStep; - this.apkProvider = BlazeApkProviderService.getInstance().getApkProvider(project, buildStep); - this.applicationIdProvider = new BlazeAndroidBinaryApplicationIdProvider(buildStep); - this.launchId = launchId; - } - - @Override - public BlazeAndroidDeviceSelector getDeviceSelector() { - return new BlazeAndroidDeviceSelector.NormalDeviceSelector(); - } - - @Override - public void augmentLaunchOptions(LaunchOptions.Builder options) { - LaunchOptions.Builder unused = - options - .setDeploy(true) - .setOpenLogcatAutomatically(configState.showLogcatAutomatically()) - .addExtraOptions( - ImmutableMap.of( - NATIVE_DEBUGGING_ENABLED, - configState.getCommonState().isNativeDebuggingEnabled())) - .setClearAppStorage(configState.getClearAppStorage()); - } - - @Override - public ConsoleProvider getConsoleProvider() { - return consoleProvider; - } - - @Override - public ApplicationIdProvider getApplicationIdProvider() { - return applicationIdProvider; - } - - @Override - public ApkBuildStep getBuildStep() { - return buildStep; - } - - @Nullable - @Override - public Integer getUserId(IDevice device) throws ExecutionException { - return UserIdHelper.getUserIdFromConfigurationState(project, device, configState); - } - - @Override - public BlazeLaunchTasksProvider getLaunchTasksProvider(LaunchOptions launchOptions) - throws ExecutionException { - return new BlazeAndroidLaunchTasksProvider(project, this, applicationIdProvider, launchOptions); - } - - @Override - public String getAmStartOptions() { - return configState.getAmStartOptions(); - } - - @Nullable - @Override - public ImmutableList getDeployTasks(IDevice device, DeployOptions deployOptions) - throws ExecutionException { - return ImmutableList.of( - new DeploymentTimingReporterTask( - launchId, - project, - getApkInfoToInstall(device, deployOptions, apkProvider), - deployOptions)); - } - - /** Returns a list of APKs excluding any APKs for features that are disabled. */ - public static List getApkInfoToInstall( - IDevice device, DeployOptions deployOptions, ApkProvider apkProvider) - throws ExecutionException { - Collection apks; - try { - apks = apkProvider.getApks(device); - } catch (ApkProvisionException e) { - throw new ExecutionException(e); - } - List disabledFeatures = deployOptions.getDisabledDynamicFeatures(); - return apks.stream() - .map(apk -> getApkInfoToInstall(apk, disabledFeatures)) - .collect(Collectors.toList()); - } - - @NotNull - private static ApkInfo getApkInfoToInstall(ApkInfo apkInfo, List disabledFeatures) { - if (apkInfo.getFiles().size() > 1) { - List filteredApks = - apkInfo.getFiles().stream() - .filter(feature -> DynamicAppUtils.isFeatureEnabled(disabledFeatures, feature)) - .collect(Collectors.toList()); - return new ApkInfo(filteredApks, apkInfo.getApplicationId()); - } else { - return apkInfo; - } - } - - @Override - public Executor getExecutor() { - return env.getExecutor(); - } - - @Override - public ProfilerState getProfileState() { - return configState.getProfilerState(); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextCompat.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextCompat.java deleted file mode 100644 index af20febc771..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextCompat.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.execution.common.debug.DebugSessionStarter; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.xdebugger.XDebugSession; -import javax.annotation.Nullable; -import kotlin.Unit; -import kotlin.coroutines.EmptyCoroutineContext; -import kotlinx.coroutines.BuildersKt; -import org.jetbrains.android.facet.AndroidFacet; - -/** Compat class for {@link BlazeAndroidBinaryNormalBuildRunContext}. */ -public class BlazeAndroidBinaryNormalBuildRunContextCompat - extends BlazeAndroidBinaryNormalBuildRunContext { - - BlazeAndroidBinaryNormalBuildRunContextCompat( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - super(project, facet, runConfiguration, env, configState, buildStep, launchId); - } - - @Nullable - @Override - public XDebugSession startDebuggerSession( - AndroidDebugger androidDebugger, - AndroidDebuggerState androidDebuggerState, - ExecutionEnvironment env, - IDevice device, - ConsoleView consoleView, - ProgressIndicator indicator, - String packageName) { - try { - return BuildersKt.runBlocking( - EmptyCoroutineContext.INSTANCE, - (scope, continuation) -> - DebugSessionStarter.INSTANCE.attachDebuggerToStartedProcess( - device, - packageName, - env, - androidDebugger, - androidDebuggerState, - /*destroyRunningProcess*/ d -> { - d.forceStop(packageName); - return Unit.INSTANCE; - }, - indicator, - consoleView, - 15L, - continuation)); - } catch (InterruptedException e) { - throw new ProcessCanceledException(); - } - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerCompat.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerCompat.java deleted file mode 100644 index 188f6e6b844..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerCompat.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import com.android.tools.idea.execution.common.DeployableToDevice; -import com.google.common.annotations.VisibleForTesting; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.google.idea.blaze.base.settings.Blaze; -import com.intellij.openapi.project.Project; - -/** Compat class for {@link BlazeAndroidBinaryRunConfigurationHandlerCompat}. */ -public class BlazeAndroidBinaryRunConfigurationHandlerCompat { - protected final Project project; - protected final BlazeAndroidBinaryRunConfigurationState configState; - - @VisibleForTesting - protected BlazeAndroidBinaryRunConfigurationHandlerCompat( - BlazeCommandRunConfiguration configuration) { - project = configuration.getProject(); - configState = - new BlazeAndroidBinaryRunConfigurationState( - Blaze.buildSystemName(configuration.getProject())); - configuration.putUserData(DeployableToDevice.getKEY(), true); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java deleted file mode 100644 index bc567e3ff30..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2021 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.run.ApkInfo; -import com.android.tools.idea.run.blaze.BlazeLaunchContext; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.tasks.DeployTasksCompat; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Stopwatch; -import com.google.common.collect.ImmutableList; -import com.google.idea.blaze.android.run.LaunchMetrics; -import com.intellij.execution.ExecutionException; -import com.intellij.openapi.project.Project; -import java.util.Collection; - -/** A wrapper launch task that wraps the given deployment task and logs the deployment latency. */ -public class DeploymentTimingReporterTask implements BlazeLaunchTask { - private final BlazeLaunchTask deployTask; - private final String launchId; - private final ImmutableList packages; - - public DeploymentTimingReporterTask( - String launchId, Project project, Collection packages, DeployOptions deployOptions) { - this.launchId = launchId; - this.deployTask = DeployTasksCompat.createDeployTask(project, packages, deployOptions); - this.packages = ImmutableList.copyOf(packages); - } - - @VisibleForTesting - public ImmutableList getPackages() { - return packages; - } - - @Override - public void run(BlazeLaunchContext launchContext) throws ExecutionException { - Stopwatch s = Stopwatch.createStarted(); - try { - deployTask.run(launchContext); - LaunchMetrics.logDeploymentTime(launchId, s.elapsed(), true); - } catch (ExecutionException e) { - LaunchMetrics.logDeploymentTime(launchId, s.elapsed(), false); - throw e; - } - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java deleted file mode 100644 index b2308bb55a2..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary.mobileinstall; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.execution.common.debug.DebugSessionStarter; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.activity.DefaultStartActivityFlagsProvider; -import com.android.tools.idea.run.activity.StartActivityFlagsProvider; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryApplicationLaunchTaskProvider; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryRunConfigurationState; -import com.google.idea.blaze.android.run.binary.UserIdHelper; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.xdebugger.XDebugSession; -import javax.annotation.Nullable; -import kotlin.Unit; -import kotlin.coroutines.EmptyCoroutineContext; -import kotlinx.coroutines.BuildersKt; -import org.jetbrains.android.facet.AndroidFacet; - -/** Run Context for mobile install launches, #api4.0 compat. */ -public class BlazeAndroidBinaryMobileInstallRunContext - extends BlazeAndroidBinaryMobileInstallRunContextBase { - public BlazeAndroidBinaryMobileInstallRunContext( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - super(project, facet, runConfiguration, env, configState, buildStep, launchId); - } - - @SuppressWarnings("unchecked") // upstream API - @Override - public BlazeLaunchTask getApplicationLaunchTask( - boolean isDebug, @Nullable Integer userId, String contributorsAmStartOptions) - throws ExecutionException { - - String extraFlags = UserIdHelper.getFlagsFromUserId(userId); - if (!contributorsAmStartOptions.isEmpty()) { - extraFlags += (extraFlags.isEmpty() ? "" : " ") + contributorsAmStartOptions; - } - if (isDebug) { - extraFlags += (extraFlags.isEmpty() ? "" : " ") + "-D"; - } - - final StartActivityFlagsProvider startActivityFlagsProvider = - new DefaultStartActivityFlagsProvider(project, isDebug, extraFlags); - BlazeAndroidDeployInfo deployInfo; - try { - deployInfo = buildStep.getDeployInfo(); - } catch (ApkProvisionException e) { - throw new ExecutionException(e); - } - - return BlazeAndroidBinaryApplicationLaunchTaskProvider.getApplicationLaunchTask( - applicationIdProvider, - deployInfo.getMergedManifest(), - configState, - startActivityFlagsProvider); - } - - @Nullable - @Override - public XDebugSession startDebuggerSession( - AndroidDebugger androidDebugger, - AndroidDebuggerState androidDebuggerState, - ExecutionEnvironment env, - IDevice device, - ConsoleView consoleView, - ProgressIndicator indicator, - String packageName) { - try { - return BuildersKt.runBlocking( - EmptyCoroutineContext.INSTANCE, - (scope, continuation) -> - DebugSessionStarter.INSTANCE.attachDebuggerToStartedProcess( - device, - packageName, - env, - androidDebugger, - androidDebuggerState, - /*destroyRunningProcess*/ d -> { - d.forceStop(packageName); - return Unit.INSTANCE; - }, - indicator, - consoleView, - 15L, - continuation)); - } catch (InterruptedException e) { - throw new ProcessCanceledException(e); - } - } - - @Override - public Executor getExecutor() { - return env.getExecutor(); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextBase.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextBase.java deleted file mode 100644 index e0de1841828..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextBase.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary.mobileinstall; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.run.ApkFileUnit; -import com.android.tools.idea.run.ApkInfo; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.ConsoleProvider; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; -import com.android.tools.idea.run.editor.ProfilerState; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryApplicationIdProvider; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryConsoleProvider; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryRunConfigurationState; -import com.google.idea.blaze.android.run.binary.DeploymentTimingReporterTask; -import com.google.idea.blaze.android.run.binary.UserIdHelper; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.android.run.runner.BlazeAndroidDeviceSelector; -import com.google.idea.blaze.android.run.runner.BlazeAndroidLaunchTasksProvider; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunContext; -import com.google.idea.blaze.base.sync.data.BlazeDataStorage; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.project.Project; -import java.util.Collections; -import java.util.stream.Collectors; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; - -/** Run context for android_binary. */ -abstract class BlazeAndroidBinaryMobileInstallRunContextBase implements BlazeAndroidRunContext { - protected final Project project; - protected final AndroidFacet facet; - protected final RunConfiguration runConfiguration; - protected final ExecutionEnvironment env; - protected final BlazeAndroidBinaryRunConfigurationState configState; - protected final ConsoleProvider consoleProvider; - protected final ApplicationIdProvider applicationIdProvider; - protected final ApkBuildStep buildStep; - private final String launchId; - - public BlazeAndroidBinaryMobileInstallRunContextBase( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - this.project = project; - this.facet = facet; - this.runConfiguration = runConfiguration; - this.env = env; - this.configState = configState; - this.consoleProvider = new BlazeAndroidBinaryConsoleProvider(project); - this.buildStep = buildStep; - this.applicationIdProvider = new BlazeAndroidBinaryApplicationIdProvider(buildStep); - this.launchId = launchId; - } - - @Override - public BlazeAndroidDeviceSelector getDeviceSelector() { - return new BlazeAndroidDeviceSelector.NormalDeviceSelector(); - } - - @Override - public void augmentLaunchOptions(LaunchOptions.Builder options) { - options - .setDeploy(buildStep.needsIdeDeploy()) - .setOpenLogcatAutomatically(configState.showLogcatAutomatically()); - // This is needed for compatibility with #api211 - options.addExtraOptions( - ImmutableMap.of("android.profilers.state", configState.getProfilerState())); - } - - @Override - public ConsoleProvider getConsoleProvider() { - return consoleProvider; - } - - @Override - public ApplicationIdProvider getApplicationIdProvider() { - return applicationIdProvider; - } - - @Override - public ApkBuildStep getBuildStep() { - return buildStep; - } - - @Override - public ProfilerState getProfileState() { - return configState.getProfilerState(); - } - - @Override - public ImmutableList getDeployTasks(IDevice device, DeployOptions deployOptions) - throws ExecutionException { - if (!buildStep.needsIdeDeploy()) { - return ImmutableList.of(); - } - - BlazeAndroidDeployInfo deployInfo; - try { - deployInfo = buildStep.getDeployInfo(); - } catch (ApkProvisionException e) { - throw new ExecutionException(e); - } - - String packageName = deployInfo.getMergedManifest().packageName; - if (packageName == null) { - throw new ExecutionException("Could not determine package name from deploy info"); - } - - ApkInfo info = - new ApkInfo( - deployInfo.getApksToDeploy().stream() - .map(file -> new ApkFileUnit(BlazeDataStorage.WORKSPACE_MODULE_NAME, file)) - .collect(Collectors.toList()), - packageName); - return ImmutableList.of( - new DeploymentTimingReporterTask( - launchId, project, Collections.singletonList(info), deployOptions)); - } - - @Nullable - @Override - public Integer getUserId(IDevice device) throws ExecutionException { - return UserIdHelper.getUserIdFromConfigurationState(project, device, configState); - } - - @Override - public BlazeLaunchTasksProvider getLaunchTasksProvider(LaunchOptions launchOptions) - throws ExecutionException { - return new BlazeAndroidLaunchTasksProvider(project, this, applicationIdProvider, launchOptions); - } - - @Override - public String getAmStartOptions() { - return configState.getAmStartOptions(); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextCompat.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextCompat.java deleted file mode 100644 index c69146a143d..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextCompat.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary.mobileinstall; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.execution.common.debug.DebugSessionStarter; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryRunConfigurationState; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.xdebugger.XDebugSession; -import javax.annotation.Nullable; -import kotlin.Unit; -import kotlin.coroutines.EmptyCoroutineContext; -import kotlinx.coroutines.BuildersKt; -import org.jetbrains.android.facet.AndroidFacet; - -/** Compatct class for {@link BlazeAndroidBinaryMobileInstallRunContext}. */ -public class BlazeAndroidBinaryMobileInstallRunContextCompat - extends BlazeAndroidBinaryMobileInstallRunContext { - - public BlazeAndroidBinaryMobileInstallRunContextCompat( - Project project, - AndroidFacet facet, - BlazeCommandRunConfiguration configuration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - super(project, facet, configuration, env, configState, buildStep, launchId); - } - - @Nullable - @Override - public XDebugSession startDebuggerSession( - AndroidDebugger androidDebugger, - AndroidDebuggerState androidDebuggerState, - ExecutionEnvironment env, - IDevice device, - ConsoleView consoleView, - ProgressIndicator indicator, - String packageName) { - try { - return BuildersKt.runBlocking( - EmptyCoroutineContext.INSTANCE, - (scope, continuation) -> - DebugSessionStarter.INSTANCE.attachDebuggerToStartedProcess( - device, - packageName, - env, - androidDebugger, - androidDebuggerState, - /*destroyRunningProcess*/ d -> { - d.forceStop(packageName); - return Unit.INSTANCE; - }, - indicator, - consoleView, - 15L, - continuation)); - } catch (InterruptedException e) { - throw new ProcessCanceledException(e); - } - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java deleted file mode 100644 index a1528a9c4d9..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import static com.android.tools.idea.profilers.AndroidProfilerLaunchTaskContributor.isProfilerLaunch; - -import com.android.ddmlib.IDevice; -import com.android.tools.deployer.ApkVerifierTracker; -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.profilers.AndroidProfilerLaunchTaskContributor; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.idea.blaze.android.run.binary.UserIdHelper; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.xdebugger.XDebugSession; -import java.util.Collections; -import java.util.List; -import org.jetbrains.annotations.NotNull; - -/** Normal launch tasks provider. #api4.1 */ -public class BlazeAndroidLaunchTasksProvider implements BlazeLaunchTasksProvider { - public static final String NATIVE_DEBUGGING_ENABLED = "NATIVE_DEBUGGING_ENABLED"; - private static final Logger LOG = Logger.getInstance(BlazeAndroidLaunchTasksProvider.class); - - private final Project project; - private final BlazeAndroidRunContext runContext; - private final ApplicationIdProvider applicationIdProvider; - private final LaunchOptions launchOptions; - - public BlazeAndroidLaunchTasksProvider( - Project project, - BlazeAndroidRunContext runContext, - ApplicationIdProvider applicationIdProvider, - LaunchOptions launchOptions) { - this.project = project; - this.runContext = runContext; - this.applicationIdProvider = applicationIdProvider; - this.launchOptions = launchOptions; - } - - @NotNull - @Override - public List getTasks(@NotNull IDevice device, boolean isDebug) - throws ExecutionException { - final List launchTasks = Lists.newArrayList(); - - String packageName; - try { - packageName = applicationIdProvider.getPackageName(); - } catch (ApkProvisionException e) { - throw new ExecutionException("Unable to determine application id: " + e); - } - - Integer userId = runContext.getUserId(device); - - // NOTE: Task for opening the profiler tool-window should come before deployment - // to ensure the tool-window opens correctly. This is required because starting - // the profiler session requires the tool-window to be open. - if (isProfilerLaunch(runContext.getExecutor())) { - launchTasks.add(new BlazeAndroidOpenProfilerWindowTask(project)); - } - - if (launchOptions.isDeploy()) { - String userIdFlags = UserIdHelper.getFlagsFromUserId(userId); - String skipVerification = - ApkVerifierTracker.getSkipVerificationInstallationFlag(device, packageName); - String pmInstallOption; - if (skipVerification != null) { - pmInstallOption = userIdFlags + " " + skipVerification; - } else { - pmInstallOption = userIdFlags; - } - DeployOptions deployOptions = - new DeployOptions(Collections.emptyList(), pmInstallOption, false, false); - ImmutableList deployTasks = runContext.getDeployTasks(device, deployOptions); - launchTasks.addAll(deployTasks); - } - - try { - if (isDebug) { - launchTasks.add( - new CheckApkDebuggableTask(project, runContext.getBuildStep().getDeployInfo())); - } - - ImmutableList.Builder amStartOptions = ImmutableList.builder(); - amStartOptions.add(runContext.getAmStartOptions()); - if (isProfilerLaunch(runContext.getExecutor())) { - amStartOptions.add( - AndroidProfilerLaunchTaskContributor.getAmStartOptions( - project, - packageName, - runContext.getProfileState(), - device, - runContext.getExecutor())); - } - BlazeLaunchTask appLaunchTask = - runContext.getApplicationLaunchTask( - isDebug, userId, String.join(" ", amStartOptions.build())); - if (appLaunchTask != null) { - launchTasks.add(appLaunchTask); - // TODO(arvindanekal): the live edit api changed and we cannot get the apk here to create - // live - // edit; the live edit team or Arvind need to fix this - } - } catch (ApkProvisionException e) { - throw new ExecutionException("Unable to determine application id: " + e); - } - - return ImmutableList.copyOf(launchTasks); - } - - @NotNull - @Override - public XDebugSession startDebugSession( - @NotNull ExecutionEnvironment environment, - @NotNull IDevice device, - @NotNull ConsoleView console, - @NotNull ProgressIndicator indicator, - @NotNull String packageName) - throws ExecutionException { - // Do not get debugger state directly from the debugger itself. - // See BlazeAndroidDebuggerService#getDebuggerState for an explanation. - boolean isNativeDebuggingEnabled = isNativeDebuggingEnabled(launchOptions); - BlazeAndroidDebuggerService debuggerService = BlazeAndroidDebuggerService.getInstance(project); - AndroidDebugger debugger = debuggerService.getDebugger(isNativeDebuggingEnabled); - if (debugger == null) { - throw new ExecutionException("Can't find AndroidDebugger for launch"); - } - AndroidDebuggerState debuggerState = debuggerService.getDebuggerState(debugger); - if (debuggerState == null) { - throw new ExecutionException("Can't find AndroidDebuggerState for launch"); - } - if (isNativeDebuggingEnabled) { - BlazeAndroidDeployInfo deployInfo = null; - try { - deployInfo = runContext.getBuildStep().getDeployInfo(); - } catch (ApkProvisionException e) { - LOG.error(e); - } - debuggerService.configureNativeDebugger(debuggerState, deployInfo); - } - - return runContext.startDebuggerSession( - debugger, debuggerState, environment, device, console, indicator, packageName); - } - - private boolean isNativeDebuggingEnabled(LaunchOptions launchOptions) { - Object flag = launchOptions.getExtraOption(NATIVE_DEBUGGING_ENABLED); - return flag instanceof Boolean && (Boolean) flag; - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java deleted file mode 100644 index e0634874fff..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.idea.blaze.android.run.runner; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.editors.literals.LiveEditService; -import com.android.tools.idea.execution.common.AndroidConfigurationExecutor; -import com.android.tools.idea.execution.common.AndroidConfigurationExecutorRunProfileState; -import com.android.tools.idea.execution.common.AppRunSettings; -import com.android.tools.idea.execution.common.ApplicationDeployer; -import com.android.tools.idea.execution.common.ComponentLaunchOptions; -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.execution.common.stats.RunStats; -import com.android.tools.idea.run.ApkProvider; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.DeviceFutures; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeAndroidConfigurationExecutor; -import com.android.tools.idea.run.configuration.execution.AndroidComplicationConfigurationExecutor; -import com.android.tools.idea.run.configuration.execution.AndroidTileConfigurationExecutor; -import com.android.tools.idea.run.configuration.execution.AndroidWatchFaceConfigurationExecutor; -import com.android.tools.idea.run.configuration.execution.ApplicationDeployerImpl; -import com.android.tools.idea.run.configuration.execution.ComplicationLaunchOptions; -import com.android.tools.idea.run.configuration.execution.TileLaunchOptions; -import com.android.tools.idea.run.configuration.execution.WatchFaceLaunchOptions; -import com.android.tools.idea.run.editor.DeployTarget; -import com.android.tools.idea.run.editor.DeployTargetState; -import com.android.tools.idea.run.util.LaunchUtils; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryRunConfigurationState; -import com.google.idea.blaze.android.run.binary.mobileinstall.MobileInstallBuildStep; -import com.google.idea.blaze.android.run.deployinfo.BlazeApkProviderService; -import com.google.idea.blaze.base.async.executor.ProgressiveTaskWithProgressIndicator; -import com.google.idea.blaze.base.command.BlazeInvocationContext.ContextType; -import com.google.idea.blaze.base.experiments.ExperimentScope; -import com.google.idea.blaze.base.issueparser.BlazeIssueParser; -import com.google.idea.blaze.base.model.primitives.WorkspaceRoot; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.google.idea.blaze.base.run.confighandler.BlazeCommandRunConfigurationRunner; -import com.google.idea.blaze.base.run.state.RunConfigurationState; -import com.google.idea.blaze.base.scope.BlazeContext; -import com.google.idea.blaze.base.scope.Scope; -import com.google.idea.blaze.base.scope.ScopedTask; -import com.google.idea.blaze.base.scope.output.IssueOutput; -import com.google.idea.blaze.base.scope.scopes.IdeaLogScope; -import com.google.idea.blaze.base.scope.scopes.ProblemsViewScope; -import com.google.idea.blaze.base.scope.scopes.ToolWindowScope; -import com.google.idea.blaze.base.settings.Blaze; -import com.google.idea.blaze.base.settings.BlazeUserSettings; -import com.google.idea.blaze.base.toolwindow.Task; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.configurations.RunProfileState; -import com.intellij.execution.executors.DefaultDebugExecutor; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Key; -import java.util.Collections; -import java.util.concurrent.CancellationException; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.android.util.AndroidBundle; -import org.jetbrains.annotations.NotNull; - -/** - * Supports the execution. Used by both android_binary and android_test. - * - *

Builds the APK and installs it, launches and debug tasks, etc. - * - *

Any indirection between android_binary/android_test, mobile-install, InstantRun etc. should - * come via the strategy class. - */ -public final class BlazeAndroidRunConfigurationRunner - implements BlazeCommandRunConfigurationRunner { - - private static final Logger LOG = Logger.getInstance(BlazeAndroidRunConfigurationRunner.class); - - private static final Key RUN_CONTEXT_KEY = - Key.create("blaze.run.context"); - public static final Key DEVICE_SESSION_KEY = - Key.create("blaze.device.session"); - - private final Module module; - private final BlazeAndroidRunContext runContext; - private final BlazeCommandRunConfiguration runConfig; - - public BlazeAndroidRunConfigurationRunner( - Module module, BlazeAndroidRunContext runContext, BlazeCommandRunConfiguration runConfig) { - this.module = module; - this.runContext = runContext; - this.runConfig = runConfig; - } - - @Override - @Nullable - public final RunProfileState getRunProfileState(final Executor executor, ExecutionEnvironment env) - throws ExecutionException { - - final AndroidFacet facet = AndroidFacet.getInstance(module); - assert facet != null : "Enforced by fatal validation check in createRunner."; - final Project project = env.getProject(); - - boolean isDebug = executor instanceof DefaultDebugExecutor; - - BlazeAndroidDeviceSelector deviceSelector = runContext.getDeviceSelector(); - BlazeAndroidDeviceSelector.DeviceSession deviceSession = - deviceSelector.getDevice(project, executor, env, isDebug, runConfig.getUniqueID()); - if (deviceSession == null) { - return null; - } - - DeployTarget deployTarget = deviceSession.deployTarget; - if (deployTarget != null && deployTarget.hasCustomRunProfileState(executor)) { - return deployTarget.getRunProfileState(executor, env, DeployTargetState.DEFAULT_STATE); - } - - DeviceFutures deviceFutures = deviceSession.deviceFutures; - if (deviceFutures == null) { - // The user deliberately canceled, or some error was encountered and exposed by the chooser. - // Quietly exit. - return null; - } - - if (deviceFutures.get().isEmpty()) { - throw new ExecutionException(AndroidBundle.message("deployment.target.not.found")); - } - - if (isDebug) { - String error = canDebug(deviceFutures, facet, module.getName()); - if (error != null) { - throw new ExecutionException(error); - } - } - - LaunchOptions.Builder launchOptionsBuilder = getDefaultLaunchOptions(); - runContext.augmentLaunchOptions(launchOptionsBuilder); - - // Store the run context on the execution environment so before-run tasks can access it. - env.putCopyableUserData(RUN_CONTEXT_KEY, runContext); - env.putCopyableUserData(DEVICE_SESSION_KEY, deviceSession); - - RunConfigurationState state = runConfig.getHandler().getState(); - - if (state instanceof BlazeAndroidBinaryRunConfigurationState - && ((BlazeAndroidBinaryRunConfigurationState) state).getCurrentWearLaunchOptions() - != null) { - ComponentLaunchOptions launchOptions = - ((BlazeAndroidBinaryRunConfigurationState) state).getCurrentWearLaunchOptions(); - - return getWearExecutor(launchOptions, env, deployTarget); - } - - ApkProvider apkProvider = - BlazeApkProviderService.getInstance() - .getApkProvider(env.getProject(), runContext.getBuildStep()); - final LaunchOptions launchOptions = launchOptionsBuilder.build(); - BlazeAndroidConfigurationExecutor runner = - new BlazeAndroidConfigurationExecutor( - runContext.getConsoleProvider(), - runContext.getApplicationIdProvider(), - env, - deviceFutures, - runContext.getLaunchTasksProvider(launchOptions), - launchOptions, - apkProvider, - LiveEditService.getInstance(env.getProject())); - return new AndroidConfigurationExecutorRunProfileState(runner); - } - - private RunProfileState getWearExecutor( - ComponentLaunchOptions launchOptions, ExecutionEnvironment env, DeployTarget deployTarget) - throws ExecutionException { - - AppRunSettings settings = - new AppRunSettings() { - @NotNull - @Override - public DeployOptions getDeployOptions() { - return new DeployOptions(Collections.emptyList(), "", true, true); - } - - @NotNull - @Override - public ComponentLaunchOptions getComponentLaunchOptions() { - return launchOptions; - } - - @Override - public Module getModule() { - return runConfig.getModules()[0]; - } - }; - - AndroidConfigurationExecutor configurationExecutor; - ApplicationIdProvider appIdProvider = runContext.getApplicationIdProvider(); - ApkProvider apkProvider = - BlazeApkProviderService.getInstance() - .getApkProvider(env.getProject(), runContext.getBuildStep()); - DeviceFutures deviceFutures = deployTarget.getDevices(env.getProject()); - - ApplicationDeployer deployer = - runContext.getBuildStep() instanceof MobileInstallBuildStep - ? new MobileInstallApplicationDeployer() - : new ApplicationDeployerImpl(env.getProject(), RunStats.from(env)); - - if (launchOptions instanceof TileLaunchOptions) { - configurationExecutor = - new AndroidTileConfigurationExecutor( - env, deviceFutures, settings, appIdProvider, apkProvider, deployer); - } else if (launchOptions instanceof WatchFaceLaunchOptions) { - configurationExecutor = - new AndroidWatchFaceConfigurationExecutor( - env, deviceFutures, settings, appIdProvider, apkProvider, deployer); - } else if (launchOptions instanceof ComplicationLaunchOptions) { - configurationExecutor = - new AndroidComplicationConfigurationExecutor( - env, deviceFutures, settings, appIdProvider, apkProvider, deployer); - } else { - throw new RuntimeException("Unknown launch options " + launchOptions.getClass().getName()); - } - - return new AndroidConfigurationExecutorRunProfileState(configurationExecutor); - } - - private static String canDebug( - DeviceFutures deviceFutures, AndroidFacet facet, String moduleName) { - // If we are debugging on a device, then the app needs to be debuggable - for (ListenableFuture future : deviceFutures.get()) { - if (!future.isDone()) { - // this is an emulator, and we assume that all emulators are debuggable - continue; - } - IDevice device = Futures.getUnchecked(future); - if (!LaunchUtils.canDebugAppOnDevice(facet, device)) { - return AndroidBundle.message( - "android.cannot.debug.noDebugPermissions", moduleName, device.getName()); - } - } - return null; - } - - private static LaunchOptions.Builder getDefaultLaunchOptions() { - return LaunchOptions.builder(); - } - - @Override - public boolean executeBeforeRunTask(ExecutionEnvironment env) { - final Project project = env.getProject(); - BlazeUserSettings settings = BlazeUserSettings.getInstance(); - return Scope.root( - context -> { - context - .push(new ProblemsViewScope(project, settings.getShowProblemsViewOnRun())) - .push(new ExperimentScope()) - .push( - new ToolWindowScope.Builder( - project, new Task(project, "Build apk", Task.Type.BEFORE_LAUNCH)) - .setPopupBehavior(settings.getShowBlazeConsoleOnRun()) - .setIssueParsers( - BlazeIssueParser.defaultIssueParsers( - project, - WorkspaceRoot.fromProject(project), - ContextType.BeforeRunTask)) - .build()) - .push(new IdeaLogScope()); - - BlazeAndroidRunContext runContext = env.getCopyableUserData(RUN_CONTEXT_KEY); - if (runContext == null) { - IssueOutput.error("Could not find run context. Please try again").submit(context); - return false; - } - BlazeAndroidDeviceSelector.DeviceSession deviceSession = - env.getCopyableUserData(DEVICE_SESSION_KEY); - - ApkBuildStep buildStep = runContext.getBuildStep(); - ScopedTask buildTask = - new ScopedTask(context) { - @Override - protected Void execute(BlazeContext context) { - buildStep.build(context, deviceSession); - return null; - } - }; - - try { - ListenableFuture buildFuture = - ProgressiveTaskWithProgressIndicator.builder( - project, - String.format("Executing %s apk build", Blaze.buildSystemName(project))) - .submitTaskWithResult(buildTask); - Futures.getChecked(buildFuture, ExecutionException.class); - } catch (ExecutionException e) { - context.setHasError(); - } catch (CancellationException e) { - context.setCancelled(); - } catch (Exception e) { - LOG.error(e); - return false; - } - return context.shouldContinue(); - }); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidRunContext.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidRunContext.java deleted file mode 100644 index a484e1735a3..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidRunContext.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2023 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.ConsoleProvider; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; -import com.android.tools.idea.run.editor.ProfilerState; -import com.google.common.collect.ImmutableList; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.xdebugger.XDebugSession; -import javax.annotation.Nullable; -import org.jetbrains.annotations.NotNull; - -/** Instantiated when the configuration wants to run. */ -public interface BlazeAndroidRunContext { - - BlazeAndroidDeviceSelector getDeviceSelector(); - - void augmentLaunchOptions(LaunchOptions.Builder options); - - ConsoleProvider getConsoleProvider(); - - ApkBuildStep getBuildStep(); - - ApplicationIdProvider getApplicationIdProvider(); - - BlazeLaunchTasksProvider getLaunchTasksProvider(LaunchOptions launchOptions) - throws ExecutionException; - - /** Returns the tasks to deploy the application. */ - ImmutableList getDeployTasks(IDevice device, DeployOptions deployOptions) - throws ExecutionException; - - /** Returns the task to launch the application. */ - @Nullable - BlazeLaunchTask getApplicationLaunchTask( - boolean isDebug, @Nullable Integer userId, @NotNull String contributorsAmStartOptions) - throws ExecutionException; - - /** Returns the task to connect the debugger. */ - @Nullable - XDebugSession startDebuggerSession( - AndroidDebugger androidDebugger, - AndroidDebuggerState androidDebuggerState, - ExecutionEnvironment env, - IDevice device, - ConsoleView consoleView, - ProgressIndicator indicator, - String packageName); - - @Nullable - Integer getUserId(IDevice device) throws ExecutionException; - - String getAmStartOptions(); - - Executor getExecutor(); - - ProfilerState getProfileState(); -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/LaunchOptionsCompat.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/LaunchOptionsCompat.java deleted file mode 100644 index f31959514c5..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/LaunchOptionsCompat.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import com.android.tools.idea.run.LaunchOptions; - -/** Compat class for LunchOptions.Builder. */ -public class LaunchOptionsCompat { - - private LaunchOptionsCompat() {} - - /** Create default launch options to maintain compatibility with #api211. */ - public static LaunchOptions.Builder getDefaultLaunchOptions() { - return LaunchOptions.builder(); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/MobileInstallApplicationDeployer.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/MobileInstallApplicationDeployer.java deleted file mode 100644 index f637ec7c654..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/MobileInstallApplicationDeployer.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import com.android.ddmlib.IDevice; -import com.android.tools.deployer.ApkParser; -import com.android.tools.deployer.Deployer; -import com.android.tools.deployer.DeployerException; -import com.android.tools.deployer.model.Apk; -import com.android.tools.deployer.model.App; -import com.android.tools.idea.execution.common.ApplicationDeployer; -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.log.LogWrapper; -import com.android.tools.idea.run.ApkFileUnit; -import com.android.tools.idea.run.ApkInfo; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.progress.ProgressIndicator; -import java.nio.file.Path; -import java.util.List; -import java.util.stream.Collectors; -import org.jetbrains.annotations.NotNull; - -/** Deploys mobile install application. */ -public class MobileInstallApplicationDeployer implements ApplicationDeployer { - final Logger log = Logger.getInstance(this.getClass()); - - public MobileInstallApplicationDeployer() {} - - @NotNull - @Override - public Deployer.Result fullDeploy( - @NotNull IDevice device, - @NotNull ApkInfo apkInfo, - @NotNull DeployOptions deployOptions, - ProgressIndicator indicator) - throws DeployerException { - final List apkPaths = - apkInfo.getFiles().stream() - .map(ApkFileUnit::getApkPath) - .map(Path::toString) - .collect(Collectors.toList()); - final List apks = new ApkParser().parsePaths(apkPaths); - App app = new App(apkInfo.getApplicationId(), apks, device, new LogWrapper(log)); - return new Deployer.Result(false, false, false, app); - } - - @NotNull - @Override - public Deployer.Result applyChangesDeploy( - @NotNull IDevice device, - @NotNull ApkInfo app, - @NotNull DeployOptions deployOptions, - ProgressIndicator indicator) - throws DeployerException { - throw new RuntimeException("Apply changes is not supported for mobile-install"); - } - - @NotNull - @Override - public Deployer.Result applyCodeChangesDeploy( - @NotNull IDevice device, - @NotNull ApkInfo app, - @NotNull DeployOptions deployOptions, - ProgressIndicator indicator) - throws DeployerException { - throw new RuntimeException("Apply code changes is not supported for mobile-install"); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java deleted file mode 100644 index 149af277a6b..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.test; - -import static com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryNormalBuildRunContextBase.getApkInfoToInstall; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.execution.common.debug.DebugSessionStarter; -import com.android.tools.idea.run.ApkProvider; -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.ConsoleProvider; -import com.android.tools.idea.run.LaunchOptions; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; -import com.android.tools.idea.run.editor.ProfilerState; -import com.android.tools.idea.run.tasks.DeployTasksCompat; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.google.idea.blaze.android.run.deployinfo.BlazeApkProviderService; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.android.run.runner.BlazeAndroidDeviceSelector; -import com.google.idea.blaze.android.run.runner.BlazeAndroidLaunchTasksProvider; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunContext; -import com.google.idea.blaze.android.run.test.BlazeAndroidTestLaunchMethodsProvider.AndroidTestLaunchMethod; -import com.google.idea.blaze.base.model.primitives.Label; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.google.idea.blaze.base.run.smrunner.BlazeTestUiSession; -import com.google.idea.blaze.base.run.testlogs.BlazeTestResultHolder; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.process.NopProcessHandler; -import com.intellij.execution.process.ProcessHandler; -import com.intellij.execution.process.ProcessOutputTypes; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.xdebugger.XDebugSession; -import java.util.List; -import javax.annotation.Nullable; -import kotlin.Unit; -import kotlin.coroutines.EmptyCoroutineContext; -import kotlinx.coroutines.BuildersKt; -import org.jetbrains.android.facet.AndroidFacet; - -/** Run context for android_test. */ -public class BlazeAndroidTestRunContext implements BlazeAndroidRunContext { - protected final Project project; - protected final AndroidFacet facet; - protected final BlazeCommandRunConfiguration runConfiguration; - protected final ExecutionEnvironment env; - protected final BlazeAndroidTestRunConfigurationState configState; - protected final Label label; - protected final ImmutableList blazeFlags; - protected final List launchTaskCompleteListeners = Lists.newArrayList(); - protected final ConsoleProvider consoleProvider; - protected final ApkBuildStep buildStep; - protected final ApplicationIdProvider applicationIdProvider; - protected final ApkProvider apkProvider; - private final BlazeTestResultHolder testResultsHolder = new BlazeTestResultHolder(); - - public BlazeAndroidTestRunContext( - Project project, - AndroidFacet facet, - BlazeCommandRunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidTestRunConfigurationState configState, - Label label, - ImmutableList blazeFlags, - ApkBuildStep buildStep) { - this.project = project; - this.facet = facet; - this.runConfiguration = runConfiguration; - this.env = env; - this.label = label; - this.configState = configState; - this.buildStep = buildStep; - this.blazeFlags = blazeFlags; - switch (configState.getLaunchMethod()) { - case MOBILE_INSTALL: - case NON_BLAZE: - consoleProvider = new AitIdeTestConsoleProvider(runConfiguration, configState); - break; - case BLAZE_TEST: - BlazeTestUiSession session = - BlazeTestUiSession.create(ImmutableList.of(), testResultsHolder); - this.consoleProvider = new AitBlazeTestConsoleProvider(project, runConfiguration, session); - break; - default: - throw new IllegalStateException( - "Unsupported launch method " + configState.getLaunchMethod()); - } - applicationIdProvider = new BlazeAndroidTestApplicationIdProvider(buildStep); - apkProvider = BlazeApkProviderService.getInstance().getApkProvider(project, buildStep); - } - - @Override - public BlazeAndroidDeviceSelector getDeviceSelector() { - return new BlazeAndroidDeviceSelector.NormalDeviceSelector(); - } - - @Override - public void augmentLaunchOptions(LaunchOptions.Builder options) { - options.setDeploy(!configState.getLaunchMethod().equals(AndroidTestLaunchMethod.BLAZE_TEST)); - } - - @Override - public ConsoleProvider getConsoleProvider() { - return consoleProvider; - } - - @Override - public ApplicationIdProvider getApplicationIdProvider() { - return applicationIdProvider; - } - - @Nullable - @Override - public ApkBuildStep getBuildStep() { - return buildStep; - } - - @Override - public ProfilerState getProfileState() { - return null; - } - - @Override - public BlazeLaunchTasksProvider getLaunchTasksProvider(LaunchOptions launchOptions) - throws ExecutionException { - return new BlazeAndroidLaunchTasksProvider(project, this, applicationIdProvider, launchOptions); - } - - @Override - public ImmutableList getDeployTasks(IDevice device, DeployOptions deployOptions) - throws ExecutionException { - if (configState.getLaunchMethod() != AndroidTestLaunchMethod.NON_BLAZE) { - return ImmutableList.of(); - } - return ImmutableList.of( - DeployTasksCompat.createDeployTask( - project, getApkInfoToInstall(device, deployOptions, apkProvider), deployOptions)); - } - - @Override - @Nullable - public BlazeLaunchTask getApplicationLaunchTask( - boolean isDebug, @Nullable Integer userId, String contributorsAmStartOptions) - throws ExecutionException { - switch (configState.getLaunchMethod()) { - case BLAZE_TEST: - BlazeAndroidTestFilter testFilter = - new BlazeAndroidTestFilter( - configState.getTestingType(), - configState.getClassName(), - configState.getMethodName(), - configState.getPackageName()); - return new BlazeAndroidTestLaunchTask( - project, label, blazeFlags, testFilter, this, isDebug, testResultsHolder); - case NON_BLAZE: - case MOBILE_INSTALL: - BlazeAndroidDeployInfo deployInfo; - try { - deployInfo = buildStep.getDeployInfo(); - } catch (ApkProvisionException e) { - throw new ExecutionException(e); - } - return StockAndroidTestLaunchTask.getStockTestLaunchTask( - configState, applicationIdProvider, isDebug, deployInfo, project); - } - throw new AssertionError(); - } - - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) // Raw type from upstream. - public XDebugSession startDebuggerSession( - AndroidDebugger androidDebugger, - AndroidDebuggerState androidDebuggerState, - ExecutionEnvironment env, - IDevice device, - ConsoleView consoleView, - ProgressIndicator indicator, - String packageName) { - try { - return BuildersKt.runBlocking( - EmptyCoroutineContext.INSTANCE, - (scope, continuation) -> { - switch (configState.getLaunchMethod()) { - case BLAZE_TEST: - - /** - * Wires up listeners to automatically reconnect the debugger for each test method. - * When you `blaze test` an android_test in debug mode, it kills the instrumentation - * process between each test method, disconnecting the debugger. We listen for the - * start of a new method waiting for a debugger, and reconnect. TODO: Support - * stopping Blaze from the UI. This is hard because we have no way to distinguish - * process handler termination/debug session ending initiated by the user. - */ - final ProcessHandler masterProcessHandler = new NopProcessHandler(); - addLaunchTaskCompleteListener( - () -> { - masterProcessHandler.notifyTextAvailable( - "Test run completed.\n", ProcessOutputTypes.STDOUT); - masterProcessHandler.detachProcess(); - }); - return DebugSessionStarter.INSTANCE.attachReattachingDebuggerToStartedProcess( - device, - packageName, - masterProcessHandler, - env, - androidDebugger, - androidDebuggerState, - indicator, - consoleView, - Long.MAX_VALUE, - continuation); - case NON_BLAZE: - case MOBILE_INSTALL: - return DebugSessionStarter.INSTANCE.attachDebuggerToStartedProcess( - device, - packageName, - env, - androidDebugger, - androidDebuggerState, - /*destroyRunningProcess*/ d -> { - d.forceStop(packageName); - return Unit.INSTANCE; - }, - indicator, - consoleView, - Long.MAX_VALUE, - continuation); - } - throw new RuntimeException("Unknown lunch mode"); - }); - } catch (InterruptedException e) { - throw new ProcessCanceledException(); - } - } - - void onLaunchTaskComplete() { - for (Runnable runnable : launchTaskCompleteListeners) { - runnable.run(); - } - } - - void addLaunchTaskCompleteListener(Runnable runnable) { - launchTaskCompleteListeners.add(runnable); - } - - @Override - public Executor getExecutor() { - return env.getExecutor(); - } - - @Nullable - @Override - public Integer getUserId(IDevice device) { - return null; - } - - @Override - public String getAmStartOptions() { - return ""; - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java deleted file mode 100644 index 1a7f9a4f621..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.testrecorder; - -import com.android.annotations.Nullable; -import com.android.ddmlib.IDevice; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunConfigurationRunner; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import java.util.List; - -/** Compat class for implementing TestRecorderBlazeCommandRunConfigurationProxy. */ -public class TestRecorderBlazeCommandRunConfigurationProxy - extends TestRecorderBlazeCommandRunConfigurationProxyBase { - - public TestRecorderBlazeCommandRunConfigurationProxy( - BlazeCommandRunConfiguration baseConfiguration) { - super(baseConfiguration); - } - - @Override - @Nullable - public List> getDeviceFutures(ExecutionEnvironment environment) { - return environment - .getCopyableUserData(BlazeAndroidRunConfigurationRunner.DEVICE_SESSION_KEY) - .deviceFutures - .get(); - } -} diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java b/aswb/sdkcompat/as231/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java deleted file mode 100644 index 3049cdd0eff..00000000000 --- a/aswb/sdkcompat/as231/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2023 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.sync.model.idea; - -import com.android.tools.idea.model.AndroidModel; -import com.android.tools.idea.model.Namespacing; -import com.android.tools.idea.projectsystem.NamedIdeaSourceProvider; -import com.google.common.util.concurrent.ListenableFuture; -import com.intellij.openapi.project.Project; -import java.io.File; - -/** Blaze model for an android project. #api42. */ -public class BlazeAndroidModel extends BlazeAndroidModelBase { - private final NamedIdeaSourceProvider sourceProvider; - - public BlazeAndroidModel( - Project project, - File rootDirPath, - NamedIdeaSourceProvider sourceProvider, - ListenableFuture applicationId, - int minSdkVersion, - boolean desugarJava8Libs) { - super(project, rootDirPath, applicationId, minSdkVersion, desugarJava8Libs); - this.sourceProvider = sourceProvider; - } - - public NamedIdeaSourceProvider getDefaultSourceProvider() { - return sourceProvider; - } - - @Override - public Namespacing getNamespacing() { - return Namespacing.DISABLED; - } - - @Override - protected String uninitializedApplicationId() { - return AndroidModel.UNINITIALIZED_APPLICATION_ID; - } -} diff --git a/aswb/sdkcompat/as232/com/android/tools/configurations/ConfigurationCompat.java b/aswb/sdkcompat/as232/com/android/tools/configurations/ConfigurationCompat.java deleted file mode 100644 index 3d51e831ad7..00000000000 --- a/aswb/sdkcompat/as232/com/android/tools/configurations/ConfigurationCompat.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.configurations; - -import com.android.sdklib.devices.Device; - -/** Compat class for Configuration. */ -public class ConfigurationCompat { - - private Configuration configuration; - - public ConfigurationCompat(Configuration configuration) { - this.configuration = configuration; - } - - public void setDevice(Device device, boolean preserveState) { - configuration.setDevice(device, preserveState); - } -} diff --git a/aswb/sdkcompat/as232/com/android/tools/idea/rendering/RenderErrorContributorCompat.java b/aswb/sdkcompat/as232/com/android/tools/idea/rendering/RenderErrorContributorCompat.java deleted file mode 100644 index bd5059f8cc3..00000000000 --- a/aswb/sdkcompat/as232/com/android/tools/idea/rendering/RenderErrorContributorCompat.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.idea.rendering; - -import com.android.tools.idea.ui.designer.EditorDesignSurface; -import com.android.tools.rendering.RenderResultCompat; -import com.intellij.openapi.actionSystem.DataContext; -import groovyjarjarantlr4.v4.runtime.misc.Nullable; - -/** Contribute blaze specific render errors. */ -public class RenderErrorContributorCompat extends RenderErrorContributorImpl { - public RenderErrorContributorCompat( - EditorDesignSurface surface, RenderResultCompat result, @Nullable DataContext dataContext) { - super(surface, result.get()); - } -} diff --git a/aswb/sdkcompat/as232/com/android/tools/idea/run/tasks/DeployTasksCompat.java b/aswb/sdkcompat/as232/com/android/tools/idea/run/tasks/DeployTasksCompat.java deleted file mode 100644 index ce440ca9d52..00000000000 --- a/aswb/sdkcompat/as232/com/android/tools/idea/run/tasks/DeployTasksCompat.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2020 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.idea.run.tasks; - -import com.android.tools.deployer.DeployerException; -import com.android.tools.idea.execution.common.AndroidExecutionException; -import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.run.ApkInfo; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.google.idea.common.experiments.BoolExperiment; -import com.intellij.openapi.project.Project; -import java.util.Collection; -import java.util.List; - -/** Compat class for {@link DeployTask} */ -public class DeployTasksCompat { - private static final BoolExperiment updateCodeViaJvmti = - new BoolExperiment("android.apply.changes", false); - - private DeployTasksCompat() {} - - public static BlazeLaunchTask createDeployTask( - Project project, Collection packages, DeployOptions deployOptions) { - return launchContext -> { - try { - List unused = - new DeployTask( - project, - packages, - deployOptions.getPmInstallFlags(), - deployOptions.getInstallOnAllUsers(), - deployOptions.getAlwaysInstallWithPm()) - .run(launchContext.getDevice(), launchContext.getProgressIndicator()); - } catch (DeployerException e) { - throw new AndroidExecutionException(e.getId(), e.getMessage()); - } - }; - } -} - diff --git a/aswb/sdkcompat/as232/com/android/tools/rendering/HtmlLinkManagerCompat.java b/aswb/sdkcompat/as232/com/android/tools/rendering/HtmlLinkManagerCompat.java deleted file mode 100644 index 28ca9471258..00000000000 --- a/aswb/sdkcompat/as232/com/android/tools/rendering/HtmlLinkManagerCompat.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.rendering; - -import java.io.File; -import org.jetbrains.annotations.NotNull; - -/** Compat class for {@link HtmlLinkManager} */ -public final class HtmlLinkManagerCompat { - public static String createFilePositionUrl(@NotNull File file, int line, int column) { - return HtmlLinkManager.createFilePositionUrl(file, line, column); - } - - private HtmlLinkManagerCompat() {} -} diff --git a/aswb/sdkcompat/as232/com/android/tools/rendering/RenderLoggerCompat.java b/aswb/sdkcompat/as232/com/android/tools/rendering/RenderLoggerCompat.java deleted file mode 100644 index 96af24f48d3..00000000000 --- a/aswb/sdkcompat/as232/com/android/tools/rendering/RenderLoggerCompat.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.rendering; - -import java.util.Map; -import java.util.Set; - -/** Compat class for RenderLogger. */ -public class RenderLoggerCompat { - private final RenderLogger renderLogger; - - public RenderLoggerCompat(RenderResultCompat result) { - renderLogger = result.getLogger(); - } - - public RenderLogger get() { - return renderLogger; - } - - public boolean hasErrors() { - return renderLogger.hasErrors(); - } - - public Map getBrokenClasses() { - return renderLogger.getBrokenClasses(); - } - - public Set getMissingClasses() { - return renderLogger.getMissingClasses(); - } - - public static void resetFidelityErrorsFilters() { - RenderLogger.resetFidelityErrorsFilters(); - } -} diff --git a/aswb/sdkcompat/as232/com/android/tools/rendering/RenderResultCompat.java b/aswb/sdkcompat/as232/com/android/tools/rendering/RenderResultCompat.java deleted file mode 100644 index 711c6336fcb..00000000000 --- a/aswb/sdkcompat/as232/com/android/tools/rendering/RenderResultCompat.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.tools.rendering; - -import com.android.ide.common.rendering.api.Result; -import com.android.tools.idea.rendering.RenderErrorContributor; -import com.android.tools.idea.rendering.RenderErrorContributorImpl; -import com.android.tools.idea.rendering.RenderErrorModelFactory; -import com.android.tools.idea.rendering.RenderResults; -import com.android.tools.idea.rendering.errors.ui.RenderErrorModel; -import com.android.tools.idea.ui.designer.EditorDesignSurface; -import com.android.tools.rendering.imagepool.ImagePool.Image; -import com.google.idea.blaze.android.rendering.BlazeRenderErrorContributor; -import com.google.idea.blaze.base.settings.Blaze; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiFile; -import org.jetbrains.annotations.Nullable; - -/** Compat class for {@link RenderResult} */ -public final class RenderResultCompat { - private RenderResult result; - - public RenderResultCompat(RenderResult result) { - this.result = result; - } - - public static RenderResultCompat createBlank(PsiFile file) { - return new RenderResultCompat(RenderResults.createBlank(file)); - } - - public RenderErrorModel createErrorModel() { - return RenderErrorModelFactory.createErrorModel(null, result); - } - - public RenderResult get() { - return result; - } - - public RenderLogger getLogger() { - return result.getLogger(); - } - - public Module getModule() { - return result.getModule(); - } - - public Result getRenderResult() { - return result.getRenderResult(); - } - - public Image getRenderedImage() { - return result.getRenderedImage(); - } - - private RenderResultCompat() {} - - /** Extension to provide {@link BlazeRenderErrorContributor}. */ - public static class BlazeProvider extends RenderErrorContributorImpl.Provider { - @Override - public boolean isApplicable(Project project) { - return Blaze.isBlazeProject(project); - } - - @Override - public RenderErrorContributor getContributor( - @Nullable EditorDesignSurface surface, RenderResult result) { - return new BlazeRenderErrorContributor(surface, new RenderResultCompat(result), null); - } - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java deleted file mode 100644 index e92afddc27c..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2018 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.cppimpl.debug; - -/** - * API compat of {@link BlazeNativeAndroidDebuggerBase} with the following additions: - * - *

    - *
  • Creates a run-config setting using {@link BlazeAndroidNativeAttachConfiguration} instead of - * {@link AndroidNativeAttachConfiguration} to override counterproductive validations. - *
- * - * #api4.0 - */ -public class BlazeNativeAndroidDebugger extends BlazeNativeAndroidDebuggerBase {} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/rendering/BlazeRenderSecurityManagerOverrides.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/rendering/BlazeRenderSecurityManagerOverrides.java deleted file mode 100644 index 39d3edd195f..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/rendering/BlazeRenderSecurityManagerOverrides.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2018 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.rendering; - -import com.android.tools.rendering.security.RenderSecurityManagerOverrides; - -/** Overrides some security restrictions used by the render sandbox. */ -public class BlazeRenderSecurityManagerOverrides implements RenderSecurityManagerOverrides { - @Override - public boolean allowsPropertiesAccess() { - // System properties access is needed for SystemPropertyExperimentLoader - return true; - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/rendering/RenderErrorLoggingContributorCompat.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/rendering/RenderErrorLoggingContributorCompat.java deleted file mode 100644 index 268e063c190..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/rendering/RenderErrorLoggingContributorCompat.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.rendering; - -import com.android.tools.idea.rendering.RenderErrorContributor; -import com.android.tools.idea.rendering.RenderErrorContributorImpl; -import com.android.tools.idea.ui.designer.EditorDesignSurface; -import com.android.tools.rendering.RenderResultCompat; -import com.intellij.openapi.actionSystem.DataContext; -import org.jetbrains.annotations.Nullable; - -/** Collects and uploads render errors by hooking into {@link RenderErrorContributor}. */ -abstract class RenderErrorLoggingContributorCompat extends RenderErrorContributorImpl { - public RenderErrorLoggingContributorCompat( - EditorDesignSurface surface, RenderResultCompat result, @Nullable DataContext dataContext) { - super(surface, result.get()); - } - - public RenderErrorLoggingContributorCompat( - EditorDesignSurface surface, RenderResultCompat result) { - super(surface, result.get()); - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/resources/BlazeRClass.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/resources/BlazeRClass.java deleted file mode 100644 index 3c64683d517..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/resources/BlazeRClass.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2018 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.resources; - -import static org.jetbrains.android.AndroidResolveScopeEnlarger.LIGHT_CLASS_KEY; -import static org.jetbrains.android.AndroidResolveScopeEnlarger.MODULE_POINTER_KEY; - -import com.android.ide.common.rendering.api.ResourceNamespace; -import com.android.tools.idea.res.ResourceRepositoryRClass; -import com.android.tools.idea.res.StudioResourceRepositoryManager; -import com.android.tools.res.LocalResourceRepository; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModulePointerManager; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiManager; -import org.jetbrains.android.augment.AndroidLightField; -import org.jetbrains.android.facet.AndroidFacet; - -/** Blaze implementation of an R class based on resource repositories. */ -public class BlazeRClass extends ResourceRepositoryRClass { - - private final AndroidFacet androidFacet; - - public BlazeRClass(PsiManager psiManager, AndroidFacet androidFacet, String packageName) { - super( - psiManager, - new ResourcesSource() { - @Override - public String getPackageName() { - return packageName; - } - - // @Override #api4.1 - public Transitivity getTransitivity() { - return Transitivity.TRANSITIVE; - } - - @Override - public StudioResourceRepositoryManager getResourceRepositoryManager() { - return StudioResourceRepositoryManager.getInstance(androidFacet); - } - - @Override - public LocalResourceRepository getResourceRepository() { - return StudioResourceRepositoryManager.getAppResources(androidFacet); - } - - @Override - public ResourceNamespace getResourceNamespace() { - return ResourceNamespace.RES_AUTO; - } - - @Override - public AndroidLightField.FieldModifier getFieldModifier() { - return AndroidLightField.FieldModifier.NON_FINAL; - } - }); - this.androidFacet = androidFacet; - setModuleInfo(getModule(), false); - VirtualFile virtualFile = myFile.getViewProvider().getVirtualFile(); - virtualFile.putUserData( - MODULE_POINTER_KEY, ModulePointerManager.getInstance(getProject()).create(getModule())); - virtualFile.putUserData(LIGHT_CLASS_KEY, ResourceRepositoryRClass.class); - } - - public Module getModule() { - return androidFacet.getModule(); - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryApplicationLaunchTaskProvider.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryApplicationLaunchTaskProvider.java deleted file mode 100644 index 948dae75f36..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryApplicationLaunchTaskProvider.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import com.android.tools.idea.run.ApkProvisionException; -import com.android.tools.idea.run.ApplicationIdProvider; -import com.android.tools.idea.run.activity.StartActivityFlagsProvider; -import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.google.idea.blaze.android.manifest.ManifestParser; -import com.google.idea.blaze.android.run.binary.tasks.AndroidDeepLinkLaunchTask; -import com.google.idea.blaze.android.run.binary.tasks.BlazeDefaultActivityLaunchTask; -import com.google.idea.blaze.android.run.binary.tasks.SpecificActivityLaunchTask; -import com.intellij.execution.ExecutionException; -import com.intellij.openapi.diagnostic.Logger; - -/** Provides the launch task for android_binary */ -public class BlazeAndroidBinaryApplicationLaunchTaskProvider { - private static final Logger LOG = - Logger.getInstance(BlazeAndroidBinaryApplicationLaunchTaskProvider.class); - - public static BlazeLaunchTask getApplicationLaunchTask( - ApplicationIdProvider applicationIdProvider, - ManifestParser.ParsedManifest mergedManifestParsedManifest, - BlazeAndroidBinaryRunConfigurationState configState, - StartActivityFlagsProvider startActivityFlagsProvider) - throws ExecutionException { - String applicationId; - try { - applicationId = applicationIdProvider.getPackageName(); - } catch (ApkProvisionException e) { - throw new ExecutionException("Unable to identify application id"); - } - - switch (configState.getMode()) { - case BlazeAndroidBinaryRunConfigurationState.LAUNCH_DEFAULT_ACTIVITY: - BlazeDefaultActivityLocator activityLocator = - new BlazeDefaultActivityLocator(mergedManifestParsedManifest); - return new BlazeDefaultActivityLaunchTask( - applicationId, activityLocator, startActivityFlagsProvider); - case BlazeAndroidBinaryRunConfigurationState.LAUNCH_SPECIFIC_ACTIVITY: - return launchContext -> - new SpecificActivityLaunchTask( - applicationId, configState.getActivityClass(), startActivityFlagsProvider) - .run( - launchContext.getDevice(), - launchContext.getProgressIndicator(), - launchContext.getConsoleView()); - case BlazeAndroidBinaryRunConfigurationState.LAUNCH_DEEP_LINK: - return launchContext -> - new AndroidDeepLinkLaunchTask(configState.getDeepLink(), startActivityFlagsProvider) - .run( - launchContext.getDevice(), - launchContext.getProgressIndicator(), - launchContext.getConsoleView()); - default: - return null; - } - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextCompat.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextCompat.java deleted file mode 100644 index d3e7ab1dc65..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextCompat.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.execution.common.debug.DebugSessionStarter; -import com.google.idea.blaze.android.run.BazelApplicationProjectContext; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.xdebugger.XDebugSession; -import javax.annotation.Nullable; -import kotlin.Unit; -import kotlin.coroutines.EmptyCoroutineContext; -import kotlinx.coroutines.BuildersKt; -import org.jetbrains.android.facet.AndroidFacet; - -/** Compat class for {@link BlazeAndroidBinaryNormalBuildRunContext}. */ -public class BlazeAndroidBinaryNormalBuildRunContextCompat - extends BlazeAndroidBinaryNormalBuildRunContext { - - BlazeAndroidBinaryNormalBuildRunContextCompat( - Project project, - AndroidFacet facet, - RunConfiguration runConfiguration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - super(project, facet, runConfiguration, env, configState, buildStep, launchId); - } - - @Nullable - @Override - public XDebugSession startDebuggerSession( - AndroidDebugger androidDebugger, - AndroidDebuggerState androidDebuggerState, - ExecutionEnvironment env, - IDevice device, - ConsoleView consoleView, - ProgressIndicator indicator, - String packageName) { - try { - return BuildersKt.runBlocking( - EmptyCoroutineContext.INSTANCE, - (scope, continuation) -> - DebugSessionStarter.INSTANCE.attachDebuggerToStartedProcess( - device, - new BazelApplicationProjectContext(project, packageName), - env, - androidDebugger, - androidDebuggerState, - /*destroyRunningProcess*/ d -> { - d.forceStop(packageName); - return Unit.INSTANCE; - }, - indicator, - consoleView, - 15L, - continuation)); - } catch (InterruptedException e) { - throw new ProcessCanceledException(); - } - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryProgramRunner.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryProgramRunner.java deleted file mode 100644 index 60bd11debaf..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryProgramRunner.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary; - -import static com.intellij.openapi.application.ModalityState.NON_MODAL; - -import com.android.tools.idea.execution.common.AndroidConfigurationExecutor; -import com.android.tools.idea.profilers.ProfileRunExecutor; -import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationHandler; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.ExecutionResult; -import com.intellij.execution.Executor; -import com.intellij.execution.configurations.RunProfile; -import com.intellij.execution.configurations.RunProfileState; -import com.intellij.execution.configurations.RunnerSettings; -import com.intellij.execution.executors.DefaultDebugExecutor; -import com.intellij.execution.executors.DefaultRunExecutor; -import com.intellij.execution.runners.AsyncProgramRunner; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.runners.RunContentBuilder; -import com.intellij.execution.ui.RunContentDescriptor; -import com.intellij.openapi.application.ActionsKt; -import com.intellij.openapi.fileEditor.FileDocumentManager; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.progress.Task; -import org.jetbrains.concurrency.AsyncPromise; -import org.jetbrains.concurrency.Promise; - -/** Program runner for configurations from {@link BlazeAndroidBinaryRunConfigurationHandler}. */ -public class BlazeAndroidBinaryProgramRunner extends AsyncProgramRunner { - @Override - public boolean canRun(String executorId, RunProfile profile) { - BlazeAndroidRunConfigurationHandler handler = - BlazeAndroidRunConfigurationHandler.getHandlerFrom(profile); - if (!(handler instanceof BlazeAndroidBinaryRunConfigurationHandler)) { - return false; - } - return (DefaultDebugExecutor.EXECUTOR_ID.equals(executorId) - || DefaultRunExecutor.EXECUTOR_ID.equals(executorId) - || ProfileRunExecutor.EXECUTOR_ID.equals(executorId)); - } - - @Override - protected Promise execute( - ExecutionEnvironment environment, RunProfileState state) { - FileDocumentManager.getInstance().saveAllDocuments(); - - AsyncPromise promise = new AsyncPromise<>(); - - ProgressManager.getInstance() - .run( - new Task.Backgroundable(environment.getProject(), "Launching ${runProfile.name}") { - @Override - public void run(ProgressIndicator indicator) { - try { - RunContentDescriptor descriptor; - if (state instanceof AndroidConfigurationExecutor) { - AndroidConfigurationExecutor configurationExecutor = - (AndroidConfigurationExecutor) state; - Executor executor = environment.getExecutor(); - if (executor.getId().equals(DefaultDebugExecutor.EXECUTOR_ID)) { - descriptor = configurationExecutor.debug(indicator); - } else if (executor.getId().equals(DefaultRunExecutor.EXECUTOR_ID) - || executor.getId().equals(ProfileRunExecutor.EXECUTOR_ID)) { - descriptor = configurationExecutor.run(indicator); - } else { - throw new ExecutionException("Unsupported executor"); - } - } else { - descriptor = doExecute(state, environment); - } - promise.setResult(descriptor); - } catch (ExecutionException e) { - boolean unused = promise.setError(e); - } - } - - @Override - public void onCancel() { - super.onCancel(); - promise.setResult(null); - } - }); - - return promise; - } - - private RunContentDescriptor doExecute( - final RunProfileState state, final ExecutionEnvironment env) throws ExecutionException { - ExecutionResult result = state.execute(env.getExecutor(), this); - return ActionsKt.invokeAndWaitIfNeeded( - NON_MODAL, - () -> new RunContentBuilder(result, env).showRunContent(env.getContentToReuse())); - } - - @Override - public String getRunnerId() { - return "AndroidBinaryProgramRunner"; - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextCompat.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextCompat.java deleted file mode 100644 index ca395950614..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextCompat.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.binary.mobileinstall; - -import com.android.ddmlib.IDevice; -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.execution.common.debug.DebugSessionStarter; -import com.google.idea.blaze.android.run.BazelApplicationProjectContext; -import com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryRunConfigurationState; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.ConsoleView; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.xdebugger.XDebugSession; -import javax.annotation.Nullable; -import kotlin.Unit; -import kotlin.coroutines.EmptyCoroutineContext; -import kotlinx.coroutines.BuildersKt; -import org.jetbrains.android.facet.AndroidFacet; - -/** Compatct class for {@link BlazeAndroidBinaryMobileInstallRunContext}. */ -public class BlazeAndroidBinaryMobileInstallRunContextCompat - extends BlazeAndroidBinaryMobileInstallRunContext { - - public BlazeAndroidBinaryMobileInstallRunContextCompat( - Project project, - AndroidFacet facet, - BlazeCommandRunConfiguration configuration, - ExecutionEnvironment env, - BlazeAndroidBinaryRunConfigurationState configState, - ApkBuildStep buildStep, - String launchId) { - super(project, facet, configuration, env, configState, buildStep, launchId); - } - - @Nullable - @Override - public XDebugSession startDebuggerSession( - AndroidDebugger androidDebugger, - AndroidDebuggerState androidDebuggerState, - ExecutionEnvironment env, - IDevice device, - ConsoleView consoleView, - ProgressIndicator indicator, - String packageName) { - try { - return BuildersKt.runBlocking( - EmptyCoroutineContext.INSTANCE, - (scope, continuation) -> - DebugSessionStarter.INSTANCE.attachDebuggerToStartedProcess( - device, - new BazelApplicationProjectContext(project, packageName), - env, - androidDebugger, - androidDebuggerState, - /*destroyRunningProcess*/ d -> { - d.forceStop(packageName); - return Unit.INSTANCE; - }, - indicator, - consoleView, - 15L, - continuation)); - } catch (InterruptedException e) { - throw new ProcessCanceledException(e); - } - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidDebuggerService.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidDebuggerService.java deleted file mode 100644 index 5715392a171..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidDebuggerService.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import com.android.tools.idea.execution.common.debug.AndroidDebugger; -import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; -import com.android.tools.idea.execution.common.debug.impl.java.AndroidJavaDebugger; -import com.android.tools.ndk.run.editor.AutoAndroidDebuggerState; -import com.android.tools.ndk.run.editor.NativeAndroidDebuggerState; -import com.google.common.collect.ImmutableList; -import com.google.idea.blaze.android.cppimpl.debug.BlazeAutoAndroidDebugger; -import com.google.idea.blaze.android.run.deployinfo.BlazeAndroidDeployInfo; -import com.google.idea.blaze.base.model.primitives.WorkspaceRoot; -import com.intellij.ide.plugins.PluginManagerCore; -import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.project.Project; -import javax.annotation.Nullable; - -/** Provides android debuggers and debugger states for blaze projects. */ -public interface BlazeAndroidDebuggerService { - - static BlazeAndroidDebuggerService getInstance(Project project) { - return ServiceManager.getService(project, BlazeAndroidDebuggerService.class); - } - - /** Returns a different debugger depending on whether or not native debugging is required. */ - AndroidDebugger getDebugger(boolean isNativeDebuggingEnabled); - - /** - * Returns fully initialized debugger states. - * - *

Note: Blaze projects should always use this method instead of the debuggers' {@link - * AndroidDebugger#createState()} method. Blaze projects require additional setup such as - * workspace directory flags that cannot be handled by the debuggers themselves. - */ - AndroidDebuggerState getDebuggerState(AndroidDebugger debugger); - - void configureNativeDebugger( - AndroidDebuggerState state, @Nullable BlazeAndroidDeployInfo deployInfo); - - /** Default debugger service. */ - class DefaultDebuggerService implements BlazeAndroidDebuggerService { - private final Project project; - - public DefaultDebuggerService(Project project) { - this.project = project; - } - - @Override - public AndroidDebugger getDebugger(boolean isNativeDebuggingEnabled) { - return isNativeDebuggingEnabled ? new BlazeAutoAndroidDebugger() : new AndroidJavaDebugger(); - } - - @Override - public AndroidDebuggerState getDebuggerState(AndroidDebugger debugger) { - AndroidDebuggerState debuggerState = debugger.createState(); - if (isNdkPluginLoaded() && debuggerState instanceof NativeAndroidDebuggerState) { - NativeAndroidDebuggerState nativeState = (NativeAndroidDebuggerState) debuggerState; - - // Source code is always relative to the workspace root in a blaze project. - String workingDirPath = WorkspaceRoot.fromProject(project).directory().getPath(); - nativeState.setWorkingDir(workingDirPath); - - // Remote built binaries may use /proc/self/cwd to represent the working directory - // so we manually map /proc/self/cwd to the workspace root. We used to use - // `plugin.symbol-file.dwarf.comp-dir-symlink-paths = "/proc/self/cwd"` - // to automatically resolve this but it's no longer supported in newer versions of - // LLDB. - String sourceMapToWorkspaceRootCommand = - "settings append target.source-map /proc/self/cwd/ " + workingDirPath; - ImmutableList startupCommands = - ImmutableList.builder() - .addAll(nativeState.getUserStartupCommands()) - .add(sourceMapToWorkspaceRootCommand) - .build(); - nativeState.setUserStartupCommands(startupCommands); - } - return debuggerState; - } - - @Override - public void configureNativeDebugger( - AndroidDebuggerState rawState, @Nullable BlazeAndroidDeployInfo deployInfo) { - if (!isNdkPluginLoaded() && !(rawState instanceof AutoAndroidDebuggerState)) { - return; - } - AutoAndroidDebuggerState state = (AutoAndroidDebuggerState) rawState; - - // Source code is always relative to the workspace root in a blaze project. - String workingDirPath = WorkspaceRoot.fromProject(project).directory().getPath(); - state.setWorkingDir(workingDirPath); - - // Remote built binaries may use /proc/self/cwd to represent the working directory, - // so we manually map /proc/self/cwd to the workspace root. We used to use - // `plugin.symbol-file.dwarf.comp-dir-symlink-paths = "/proc/self/cwd"` - // to automatically resolve this, but it's no longer supported in newer versions of - // LLDB. - String sourceMapToWorkspaceRootCommand = - "settings append target.source-map /proc/self/cwd/ " + workingDirPath; - - ImmutableList startupCommands = - ImmutableList.builder() - .addAll(state.getUserStartupCommands()) - .add(sourceMapToWorkspaceRootCommand) - .build(); - state.setUserStartupCommands(startupCommands); - - // NDK plugin will pass symbol directories to LLDB as `settings append - // target.exec-search-paths`. - if (deployInfo != null) { - state.setSymbolDirs( - deployInfo.getSymbolFiles().stream() - .map(symbol -> symbol.getParentFile().getAbsolutePath()) - .collect(ImmutableList.toImmutableList())); - } - } - } - - static boolean isNdkPluginLoaded() { - return PluginManagerCore.getLoadedPlugins().stream() - .anyMatch( - d -> d.isEnabled() && d.getPluginId().getIdString().equals("com.android.tools.ndk")); - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/LaunchOptionsCompat.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/LaunchOptionsCompat.java deleted file mode 100644 index f31959514c5..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/LaunchOptionsCompat.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2022 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.runner; - -import com.android.tools.idea.run.LaunchOptions; - -/** Compat class for LunchOptions.Builder. */ -public class LaunchOptionsCompat { - - private LaunchOptionsCompat() {} - - /** Create default launch options to maintain compatibility with #api211. */ - public static LaunchOptions.Builder getDefaultLaunchOptions() { - return LaunchOptions.builder(); - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/test/BlazeAndroidTestProgramRunner.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/test/BlazeAndroidTestProgramRunner.java deleted file mode 100644 index b294b565455..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/test/BlazeAndroidTestProgramRunner.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2018 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.test; - -import com.android.tools.idea.execution.common.AndroidConfigurationExecutor; -import com.android.tools.idea.execution.common.AndroidConfigurationProgramRunner; -import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationHandler; -import com.google.idea.blaze.base.run.BlazeCommandRunConfigurationType; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.configurations.RunProfile; -import com.intellij.execution.executors.DefaultDebugExecutor; -import com.intellij.execution.executors.DefaultRunExecutor; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.execution.ui.RunContentDescriptor; -import com.intellij.openapi.progress.ProgressIndicator; -import java.util.Collections; -import java.util.List; -import org.jetbrains.annotations.NotNull; - -/** Program runner for configurations from {@link BlazeAndroidTestRunConfigurationHandler}. */ -public class BlazeAndroidTestProgramRunner extends AndroidConfigurationProgramRunner { - @Override - public boolean canRun(String executorId, RunProfile profile) { - BlazeAndroidRunConfigurationHandler handler = - BlazeAndroidRunConfigurationHandler.getHandlerFrom(profile); - if (!(handler instanceof BlazeAndroidTestRunConfigurationHandler)) { - return false; - } - return super.canRun(executorId, profile) && DefaultRunExecutor.EXECUTOR_ID.equals(executorId) - || DefaultDebugExecutor.EXECUTOR_ID.equals(executorId); - } - - @Override - public String getRunnerId() { - return "AndroidTestProgramRunner"; - } - - @Override - protected boolean canRunWithMultipleDevices(@NotNull String executorId) { - return true; - } - - @NotNull - @Override - protected List getSupportedConfigurationTypeIds() { - return Collections.singletonList(BlazeCommandRunConfigurationType.getInstance().getId()); - } - - @NotNull - @Override - protected RunContentDescriptor run( - @NotNull ExecutionEnvironment environment, - @NotNull AndroidConfigurationExecutor executor, - @NotNull ProgressIndicator indicator) - throws ExecutionException { - if (DefaultDebugExecutor.EXECUTOR_ID.equals(environment.getExecutor().getId())) { - return executor.debug(indicator); - } - if (DefaultRunExecutor.EXECUTOR_ID.equals(environment.getExecutor().getId())) { - return executor.run(indicator); - } - throw new RuntimeException("Unsupported executor"); - } -} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunConfigurationHandler.java b/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunConfigurationHandler.java deleted file mode 100644 index 67e2ad4dfb7..00000000000 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunConfigurationHandler.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright 2016 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run.test; - -import com.android.tools.idea.execution.common.DeployableToDevice; -import com.android.tools.idea.run.ValidationError; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.idea.blaze.android.run.ApkBuildStepProvider; -import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationCommonState; -import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationHandler; -import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationValidationUtil; -import com.google.idea.blaze.android.run.LaunchMetrics; -import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunConfigurationRunner; -import com.google.idea.blaze.android.run.runner.BlazeAndroidRunContext; -import com.google.idea.blaze.android.run.runner.FullApkBuildStep; -import com.google.idea.blaze.android.run.test.BlazeAndroidTestLaunchMethodsProvider.AndroidTestLaunchMethod; -import com.google.idea.blaze.base.command.BlazeCommandName; -import com.google.idea.blaze.base.command.BlazeInvocationContext; -import com.google.idea.blaze.base.model.primitives.Label; -import com.google.idea.blaze.base.model.primitives.TargetExpression; -import com.google.idea.blaze.base.projectview.ProjectViewManager; -import com.google.idea.blaze.base.projectview.ProjectViewSet; -import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -import com.google.idea.blaze.base.run.BlazeConfigurationNameBuilder; -import com.google.idea.blaze.base.run.ExecutorType; -import com.google.idea.blaze.base.run.confighandler.BlazeCommandRunConfigurationRunner; -import com.google.idea.blaze.base.settings.Blaze; -import com.google.idea.blaze.base.sync.data.BlazeDataStorage; -import com.google.idea.blaze.base.sync.projectstructure.ModuleFinder; -import com.google.idea.blaze.java.AndroidBlazeRules; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.Executor; -import com.intellij.execution.JavaExecutionUtil; -import com.intellij.execution.configurations.RuntimeConfigurationException; -import com.intellij.execution.runners.ExecutionEnvironment; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import java.util.List; -import javax.annotation.Nullable; -import org.jetbrains.android.facet.AndroidFacet; - -/** - * {@link com.google.idea.blaze.base.run.confighandler.BlazeCommandRunConfigurationHandler} for - * android_test targets. - */ -public class BlazeAndroidTestRunConfigurationHandler - implements BlazeAndroidRunConfigurationHandler { - private final Project project; - private final BlazeAndroidTestRunConfigurationState configState; - - BlazeAndroidTestRunConfigurationHandler(BlazeCommandRunConfiguration configuration) { - this.project = configuration.getProject(); - this.configState = - new BlazeAndroidTestRunConfigurationState( - Blaze.buildSystemName(configuration.getProject())); - configuration.putUserData(DeployableToDevice.getKEY(), true); - } - - @Override - public BlazeAndroidTestRunConfigurationState getState() { - return configState; - } - - @Override - public BlazeAndroidRunConfigurationCommonState getCommonState() { - return configState.getCommonState(); - } - - @Override - public BlazeCommandRunConfigurationRunner createRunner( - Executor executor, ExecutionEnvironment env) throws ExecutionException { - Project project = env.getProject(); - BlazeCommandRunConfiguration configuration = - BlazeAndroidRunConfigurationHandler.getCommandConfig(env); - - BlazeAndroidRunConfigurationValidationUtil.validate(project); - Module module = - ModuleFinder.getInstance(env.getProject()) - .findModuleByName(BlazeDataStorage.WORKSPACE_MODULE_NAME); - AndroidFacet facet = module != null ? AndroidFacet.getInstance(module) : null; - ProjectViewSet projectViewSet = ProjectViewManager.getInstance(project).getProjectViewSet(); - - ImmutableList blazeFlags = - configState - .getCommonState() - .getExpandedBuildFlags( - project, - projectViewSet, - BlazeCommandName.TEST, - BlazeInvocationContext.runConfigContext( - ExecutorType.fromExecutor(env.getExecutor()), configuration.getType(), false)); - ImmutableList exeFlags = - ImmutableList.copyOf( - configState.getCommonState().getExeFlagsState().getFlagsForExternalProcesses()); - - // We collect metrics from a few different locations. In order to tie them all - // together, we create a unique launch id. - String launchId = LaunchMetrics.newLaunchId(); - Label label = Label.create(configuration.getSingleTarget().toString()); - - ApkBuildStep buildStep = - getTestBuildStep( - project, configState, configuration, blazeFlags, exeFlags, launchId, label); - - BlazeAndroidRunContext runContext = - new BlazeAndroidTestRunContext( - project, facet, configuration, env, configState, label, blazeFlags, buildStep); - - LaunchMetrics.logTestLaunch( - launchId, configState.getLaunchMethod().name(), env.getExecutor().getId()); - - return new BlazeAndroidRunConfigurationRunner(module, runContext, configuration); - } - - private static ApkBuildStep getTestBuildStep( - Project project, - BlazeAndroidTestRunConfigurationState configState, - BlazeCommandRunConfiguration configuration, - ImmutableList blazeFlags, - ImmutableList exeFlags, - String launchId, - Label label) - throws ExecutionException { - if (configuration.getTargetKind() - == AndroidBlazeRules.RuleTypes.ANDROID_INSTRUMENTATION_TEST.getKind()) { - boolean useMobileInstall = - AndroidTestLaunchMethod.MOBILE_INSTALL.equals(configState.getLaunchMethod()); - return ApkBuildStepProvider.getInstance(Blaze.getBuildSystemName(project)) - .getAitBuildStep( - project, - useMobileInstall, - /* nativeDebuggingEnabled= */ false, - label, - blazeFlags, - exeFlags, - launchId); - } else { - // TODO(b/248317444): This path is only invoked for the deprecated {@code android_test} - // targets, and should eventually be removed. - return new FullApkBuildStep(project, label, blazeFlags, /* nativeDebuggingEnabled= */ false); - } - } - - @Override - public final void checkConfiguration() throws RuntimeConfigurationException { - BlazeAndroidRunConfigurationValidationUtil.throwTopConfigurationError(validate()); - } - - /** - * We collect errors rather than throwing to avoid missing fatal errors by exiting early for a - * warning. We use a separate method for the collection so the compiler prevents us from - * accidentally throwing. - */ - private List validate() { - List errors = Lists.newArrayList(); - errors.addAll(BlazeAndroidRunConfigurationValidationUtil.validateWorkspaceModule(project)); - errors.addAll(configState.validate(project)); - return errors; - } - - @Override - @Nullable - public String suggestedName(BlazeCommandRunConfiguration configuration) { - TargetExpression target = configuration.getSingleTarget(); - if (target == null) { - return null; - } - BlazeConfigurationNameBuilder nameBuilder = new BlazeConfigurationNameBuilder(configuration); - - boolean isClassTest = - configState.getTestingType() == BlazeAndroidTestRunConfigurationState.TEST_CLASS; - boolean isMethodTest = - configState.getTestingType() == BlazeAndroidTestRunConfigurationState.TEST_METHOD; - if ((isClassTest || isMethodTest) && configState.getClassName() != null) { - // Get the class name without the package. - String className = JavaExecutionUtil.getPresentableClassName(configState.getClassName()); - if (className != null) { - String targetString = className; - if (isMethodTest) { - targetString += "#" + configState.getMethodName(); - } - - if (getState().getLaunchMethod().equals(AndroidTestLaunchMethod.NON_BLAZE)) { - return targetString; - } else { - return nameBuilder.setTargetString(targetString).build(); - } - } - } - return nameBuilder.build(); - } - - @Override - @Nullable - public BlazeCommandName getCommandName() { - if (getState().getLaunchMethod().equals(AndroidTestLaunchMethod.BLAZE_TEST)) { - return BlazeCommandName.TEST; - } else if (getState().getLaunchMethod().equals(AndroidTestLaunchMethod.MOBILE_INSTALL)) { - return BlazeCommandName.MOBILE_INSTALL; - } - return null; - } - - @Override - public String getHandlerName() { - return "Android Test Handler"; - } -} diff --git a/aswb/sdkcompat/as233/com/google/idea/blaze/android/run/BazelApplicationProjectContextProvider.java b/aswb/sdkcompat/as233/com/google/idea/blaze/android/run/BazelApplicationProjectContextProvider.java deleted file mode 100644 index bffcc3d238d..00000000000 --- a/aswb/sdkcompat/as233/com/google/idea/blaze/android/run/BazelApplicationProjectContextProvider.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2024 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.run; - -import com.android.ddmlib.Client; -import com.android.ddmlib.ClientData; -import com.android.tools.idea.projectsystem.ApplicationProjectContext; -import com.android.tools.idea.projectsystem.ApplicationProjectContextProvider; -import com.google.idea.blaze.android.projectsystem.BlazeToken; -import com.intellij.openapi.project.Project; -import javax.annotation.Nullable; - -/** An implementation of {@link ApplicationProjectContextProvider} for the Blaze project system. */ -public class BazelApplicationProjectContextProvider - implements ApplicationProjectContextProvider, BlazeToken { - - private final Project project; - - public BazelApplicationProjectContextProvider(Project project) { - this.project = project; - } - - @Nullable - @Override - public ApplicationProjectContext getApplicationProjectContextProvider(Client client) { - ClientData clientData = client.getClientData(); - if (clientData == null) { - return null; - } - String androidPackageName = clientData.getPackageName(); - if (androidPackageName == null) { - return null; - } - return new BazelApplicationProjectContext(project, androidPackageName); - } -} diff --git a/aswb/src/META-INF/aswb.xml b/aswb/src/META-INF/aswb.xml index 63b5e6b5796..d8640eeab5c 100644 --- a/aswb/src/META-INF/aswb.xml +++ b/aswb/src/META-INF/aswb.xml @@ -20,6 +20,7 @@ org.jetbrains.android com.google.gct.test.recorder com.intellij.modules.java + com.android.tools.design @@ -45,7 +46,7 @@ - + @@ -111,7 +112,7 @@ - + @@ -119,6 +120,10 @@ + + + + @@ -127,4 +132,9 @@ + + + + diff --git a/aswb/src/META-INF/ndk_contents.xml b/aswb/src/META-INF/ndk_contents.xml index 6afc76d1025..673b73a74a3 100644 --- a/aswb/src/META-INF/ndk_contents.xml +++ b/aswb/src/META-INF/ndk_contents.xml @@ -21,7 +21,7 @@ - + diff --git a/aswb/src/com/android/tools/idea/rendering/tokens/BUILD b/aswb/src/com/android/tools/idea/rendering/tokens/BUILD new file mode 100644 index 00000000000..d8c8722b5d6 --- /dev/null +++ b/aswb/src/com/android/tools/idea/rendering/tokens/BUILD @@ -0,0 +1,30 @@ +load( + "//:build-visibility.bzl", + "ASWB_SUBPACKAGES_VISIBILITY", + "TEST_ASWB_SUBPACKAGES_VISIBILITY", +) +load( + "//build_defs:build_defs.bzl", + "combine_visibilities", +) + +java_library( + name = "tokens", + srcs = glob(["*.java"]), + visibility = combine_visibilities( + ASWB_SUBPACKAGES_VISIBILITY, + TEST_ASWB_SUBPACKAGES_VISIBILITY, + ), + deps = [ + "//aswb:aswb_lib", + "//base", + "//common/experiments", + "//cpp", + "//java", + "//proto:proto_deps", + "//querysync", + "//shared", + "//shared:artifact", + "//intellij_platform_sdk:plugin_api", + ], +) diff --git a/aswb/src/com/android/tools/idea/rendering/tokens/BazelBuildSystemFilePreviewServices.java b/aswb/src/com/android/tools/idea/rendering/tokens/BazelBuildSystemFilePreviewServices.java new file mode 100644 index 00000000000..d6dfdbc2975 --- /dev/null +++ b/aswb/src/com/android/tools/idea/rendering/tokens/BazelBuildSystemFilePreviewServices.java @@ -0,0 +1,76 @@ +/* + * Copyright 2024 The Bazel Authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.tools.idea.rendering.tokens; + +import com.android.tools.idea.projectsystem.ProjectSystemBuildManager; +import com.android.tools.idea.rendering.BuildTargetReference; +import com.google.idea.blaze.android.projectsystem.BazelProjectSystem; +import com.google.idea.blaze.android.projectsystem.BazelToken; +import com.intellij.openapi.Disposable; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import java.util.Collection; +import org.jetbrains.annotations.NotNull; + + +public class BazelBuildSystemFilePreviewServices + implements BuildSystemFilePreviewServices, BazelToken { + + @Override + public boolean isApplicable(BuildTargetReference buildTargetReference) { + return buildTargetReference instanceof BazelBuildTargetReference; + } + + @Override + public BuildServices getBuildServices() { + return new BuildServices<>() { + @Override + public @NotNull ProjectSystemBuildManager.BuildStatus getLastCompileStatus( + @NotNull BazelBuildTargetReference buildTarget) { + return ProjectSystemBuildManager.BuildStatus.UNKNOWN; + } + + @Override + public void buildArtifacts( + @NotNull Collection buildTargets) { + throw new UnsupportedOperationException(); + } + }; + } + + @Override + public void subscribeBuildListener(Project project, + Disposable parentDisposable, BuildListener listener) { + throw new UnsupportedOperationException(); + } + + @Override + public BuildTargets getBuildTargets() { + return new BuildTargets() { + @Override + public @NotNull BuildTargetReference from(@NotNull Module module, + @NotNull VirtualFile targetFile) { + return fromModuleOnly(module); + } + + @Override + public @NotNull BuildTargetReference fromModuleOnly(@NotNull Module module) { + return new BazelBuildTargetReference(module); + } + }; + } +} \ No newline at end of file diff --git a/aswb/src/com/android/tools/idea/rendering/tokens/BazelBuildTargetReference.java b/aswb/src/com/android/tools/idea/rendering/tokens/BazelBuildTargetReference.java new file mode 100644 index 00000000000..7c957a94da9 --- /dev/null +++ b/aswb/src/com/android/tools/idea/rendering/tokens/BazelBuildTargetReference.java @@ -0,0 +1,55 @@ +/* + * Copyright 2024 The Bazel Authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.tools.idea.rendering.tokens; + +import com.android.tools.idea.rendering.BuildTargetReference; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.project.Project; +import com.intellij.serviceContainer.AlreadyDisposedException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +class BazelBuildTargetReference implements BuildTargetReference { + private final Module module; + + BazelBuildTargetReference(Module module) { + this.module = module; + } + + @NotNull + @Override + public Module getModule() { + if (module.isDisposed()) { + throw new AlreadyDisposedException("Already disposed: " + module); + } + return module; + } + + @NotNull + @Override + public Project getProject() { + return module.getProject(); + } + + @Nullable + @Override + public Module getModuleIfNotDisposed() { + if (module.isDisposed()) { + return null; + } + return module; + } +} diff --git a/aswb/sdkcompat/as231/com/android/tools/idea/run/tasks/DeployTasksCompat.java b/aswb/src/com/android/tools/idea/run/tasks/DeployTasksHelper.java similarity index 82% rename from aswb/sdkcompat/as231/com/android/tools/idea/run/tasks/DeployTasksCompat.java rename to aswb/src/com/android/tools/idea/run/tasks/DeployTasksHelper.java index 8c5bde9785e..1c103aabaeb 100644 --- a/aswb/sdkcompat/as231/com/android/tools/idea/run/tasks/DeployTasksCompat.java +++ b/aswb/src/com/android/tools/idea/run/tasks/DeployTasksHelper.java @@ -20,17 +20,14 @@ import com.android.tools.idea.execution.common.DeployOptions; import com.android.tools.idea.run.ApkInfo; import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.google.idea.common.experiments.BoolExperiment; import com.intellij.openapi.project.Project; import java.util.Collection; import java.util.List; -/** Compat class for {@link DeployTask} */ -public class DeployTasksCompat { - private static final BoolExperiment updateCodeViaJvmti = - new BoolExperiment("android.apply.changes", false); +/** Helper class for {@link DeployTask} */ +public class DeployTasksHelper { - private DeployTasksCompat() {} + private DeployTasksHelper() {} public static BlazeLaunchTask createDeployTask( Project project, Collection packages, DeployOptions deployOptions) { @@ -42,7 +39,8 @@ public static BlazeLaunchTask createDeployTask( packages, deployOptions.getPmInstallFlags(), deployOptions.getInstallOnAllUsers(), - deployOptions.getAlwaysInstallWithPm()) + deployOptions.getAlwaysInstallWithPm(), + deployOptions.getAllowAssumeVerified()) .run(launchContext.getDevice(), launchContext.getProgressIndicator()); } catch (DeployerException e) { throw new AndroidExecutionException(e.getId(), e.getMessage()); diff --git a/aswb/src/com/google/idea/blaze/android/cppimpl/BlazeNdkSupportEnabler.java b/aswb/src/com/google/idea/blaze/android/cppimpl/BlazeNdkSupportEnabler.java index 29cd9527b38..8e987ebf3f0 100644 --- a/aswb/src/com/google/idea/blaze/android/cppimpl/BlazeNdkSupportEnabler.java +++ b/aswb/src/com/google/idea/blaze/android/cppimpl/BlazeNdkSupportEnabler.java @@ -23,16 +23,16 @@ import com.google.idea.blaze.base.model.BlazeProjectData; import com.google.idea.blaze.base.model.primitives.LanguageClass; import com.google.idea.blaze.base.projectview.ProjectViewSet; -import com.google.idea.blaze.base.qsync.BlazeProjectListenerProvider; import com.google.idea.blaze.base.qsync.QuerySyncProject; +import com.google.idea.blaze.base.qsync.QuerySyncProjectListenerProvider; import com.google.idea.blaze.base.scope.BlazeContext; import com.google.idea.blaze.base.settings.BlazeImportSettings; import com.google.idea.blaze.base.sync.SyncListener; import com.google.idea.blaze.base.sync.SyncMode; import com.google.idea.blaze.base.sync.SyncResult; import com.google.idea.blaze.common.Context; -import com.google.idea.blaze.qsync.BlazeProjectListener; -import com.google.idea.blaze.qsync.BlazeProjectSnapshot; +import com.google.idea.blaze.qsync.QuerySyncProjectListener; +import com.google.idea.blaze.qsync.QuerySyncProjectSnapshot; import com.google.idea.blaze.qsync.project.QuerySyncLanguage; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.TransactionGuard; @@ -42,7 +42,7 @@ import com.jetbrains.cidr.lang.workspace.OCWorkspaceModificationTrackersImpl; import java.util.Set; -final class BlazeNdkSupportEnabler implements SyncListener, BlazeProjectListenerProvider { +final class BlazeNdkSupportEnabler implements SyncListener, QuerySyncProjectListenerProvider { @Override public void onSyncComplete( @@ -60,10 +60,10 @@ public void onSyncComplete( } @Override - public BlazeProjectListener createListener(QuerySyncProject project) { - return new BlazeProjectListener() { + public QuerySyncProjectListener createListener(QuerySyncProject project) { + return new QuerySyncProjectListener() { @Override - public void onNewProjectSnapshot(Context context, BlazeProjectSnapshot instance) { + public void onNewProjectSnapshot(Context context, QuerySyncProjectSnapshot instance) { Set allLanguages = Sets.union( diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java b/aswb/src/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java similarity index 89% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java rename to aswb/src/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java index 08f03d50d8f..06fbf1b43b4 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java +++ b/aswb/src/com/google/idea/blaze/android/cppimpl/debug/BlazeAutoAndroidDebugger.java @@ -16,12 +16,10 @@ package com.google.idea.blaze.android.cppimpl.debug; import com.android.ddmlib.Client; -import com.android.ddmlib.ClientData; import com.intellij.openapi.project.Project; import com.intellij.xdebugger.XDebugSession; import org.jetbrains.annotations.NotNull; -/** Shim for #api212 compat. */ public class BlazeAutoAndroidDebugger extends BlazeAutoAndroidDebuggerBase { @Override @@ -35,7 +33,7 @@ public XDebugSession getExistingDebugSession(@NotNull Project project, @NotNull } @Override - protected boolean isNativeDeployment(Project project, ClientData clientData) { + protected boolean isNativeDeployment(Project project, Client clientData) { return isNativeProject(project); } } diff --git a/aswb/sdkcompat/as223/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java b/aswb/src/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java similarity index 70% rename from aswb/sdkcompat/as223/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java rename to aswb/src/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java index e92afddc27c..f125ae025b2 100644 --- a/aswb/sdkcompat/as223/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java +++ b/aswb/src/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebugger.java @@ -15,14 +15,4 @@ */ package com.google.idea.blaze.android.cppimpl.debug; -/** - * API compat of {@link BlazeNativeAndroidDebuggerBase} with the following additions: - * - *

    - *
  • Creates a run-config setting using {@link BlazeAndroidNativeAttachConfiguration} instead of - * {@link AndroidNativeAttachConfiguration} to override counterproductive validations. - *
- * - * #api4.0 - */ public class BlazeNativeAndroidDebugger extends BlazeNativeAndroidDebuggerBase {} diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebuggerBase.java b/aswb/src/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebuggerBase.java similarity index 100% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebuggerBase.java rename to aswb/src/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeAndroidDebuggerBase.java diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeDebuggerStateSourceMapping.java b/aswb/src/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeDebuggerStateSourceMapping.java similarity index 100% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeDebuggerStateSourceMapping.java rename to aswb/src/com/google/idea/blaze/android/cppimpl/debug/BlazeNativeDebuggerStateSourceMapping.java diff --git a/aswb/src/com/google/idea/blaze/android/filecache/ArtifactNotFoundException.java b/aswb/src/com/google/idea/blaze/android/filecache/ArtifactNotFoundException.java index 9161f015b62..139ed5371c1 100644 --- a/aswb/src/com/google/idea/blaze/android/filecache/ArtifactNotFoundException.java +++ b/aswb/src/com/google/idea/blaze/android/filecache/ArtifactNotFoundException.java @@ -21,6 +21,6 @@ /** Signals that a particular artifact cannot be located. */ public class ArtifactNotFoundException extends IOException { public ArtifactNotFoundException(OutputArtifactWithoutDigest artifact) { - super(artifact.getRelativePath() + " not found."); + super(artifact.getBazelOutRelativePath() + " not found."); } } diff --git a/aswb/src/com/google/idea/blaze/android/libraries/UnpackedAarUtils.java b/aswb/src/com/google/idea/blaze/android/libraries/UnpackedAarUtils.java index 60bb636aecd..08192537959 100644 --- a/aswb/src/com/google/idea/blaze/android/libraries/UnpackedAarUtils.java +++ b/aswb/src/com/google/idea/blaze/android/libraries/UnpackedAarUtils.java @@ -37,7 +37,7 @@ public final class UnpackedAarUtils { /* Converts {@link BlazeArtifact} to the key which is used to create aar directory name */ public static String getArtifactKey(BlazeArtifact artifact) { if (artifact instanceof OutputArtifactWithoutDigest) { - return ((OutputArtifactWithoutDigest) artifact).getRelativePath(); + return ((OutputArtifactWithoutDigest) artifact).getBazelOutRelativePath(); } if (artifact instanceof SourceArtifact) { return ((SourceArtifact) artifact).getFile().getPath(); diff --git a/aswb/src/com/google/idea/blaze/android/manifest/ManifestParser.java b/aswb/src/com/google/idea/blaze/android/manifest/ManifestParser.java index 349b16fd2cd..3fb656a7708 100644 --- a/aswb/src/com/google/idea/blaze/android/manifest/ManifestParser.java +++ b/aswb/src/com/google/idea/blaze/android/manifest/ManifestParser.java @@ -86,6 +86,7 @@ public ParsedManifest( *

An invalid manifest is anything that could not be parsed by the parser, such as a malformed * manifest. */ + @Nullable public static ParsedManifest parseManifestFromInputStream(InputStream inputStream) throws IOException { Element manifestRootElement = getManifestRootElementFromInputStream(inputStream); diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeAddDestinationMenuToken.java b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelAddDestinationMenuToken.java similarity index 91% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeAddDestinationMenuToken.java rename to aswb/src/com/google/idea/blaze/android/projectsystem/BazelAddDestinationMenuToken.java index e74aa02a7d2..6d57188b38c 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeAddDestinationMenuToken.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelAddDestinationMenuToken.java @@ -26,11 +26,11 @@ import org.jetbrains.annotations.NotNull; /** Blaze implementation of project system tokens for the navigation editor: Add Destination Menu */ -public class BlazeAddDestinationMenuToken - implements AddDestinationMenuToken, BlazeToken { +public class BazelAddDestinationMenuToken + implements AddDestinationMenuToken, BazelToken { @Override public void modifyProject( - @NotNull BlazeProjectSystem projectSystem, @NotNull AddDestinationMenuToken.Data data) { + @NotNull BazelProjectSystem projectSystem, @NotNull AddDestinationMenuToken.Data data) { NlModel model = data.getSurface().getModel(); if (model == null) { return; diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeModuleDependencies.java b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelModuleDependencies.java similarity index 86% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeModuleDependencies.java rename to aswb/src/com/google/idea/blaze/android/projectsystem/BazelModuleDependencies.java index 72a158468e6..d8fea990a70 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeModuleDependencies.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelModuleDependencies.java @@ -20,12 +20,13 @@ import com.android.ide.common.repository.GoogleMavenArtifactId; import com.android.projectmodel.ExternalAndroidLibrary; import com.android.tools.idea.projectsystem.DependencyScopeType; +import com.android.tools.idea.rendering.PsiClassViewClass; import com.android.tools.module.ModuleDependencies; +import com.android.tools.module.ViewClass; import com.google.common.collect.ImmutableList; import com.google.idea.blaze.android.resources.BlazeLightResourceClassService; import com.intellij.openapi.module.Module; import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiClass; import java.util.List; import java.util.Objects; import java.util.function.Predicate; @@ -33,11 +34,11 @@ import org.jetbrains.annotations.Nullable; /** ASwB specific implementation of [ModuleDependencies]. */ -public class BlazeModuleDependencies implements ModuleDependencies { +public class BazelModuleDependencies implements ModuleDependencies { Module module; - BlazeModuleDependencies(Module module) { + BazelModuleDependencies(Module module) { this.module = module; } @@ -46,13 +47,6 @@ public boolean dependsOn(@NotNull GoogleMavenArtifactId googleMavenArtifactId) { return false; } - @Nullable - @Override - public PsiClass findPsiClassInModuleAndDependencies(@NotNull String fqcn) { - JavaPsiFacade facade = JavaPsiFacade.getInstance(module.getProject()); - return facade.findClass(fqcn, module.getModuleWithDependenciesAndLibrariesScope(false)); - } - /** * Fetches the resource packages within the project and from external dependencies. Input * parameter includeExternalLibraries is ignored as ASwB/Blaze uses a single workspace module to @@ -66,7 +60,7 @@ public List getResourcePackageNames(boolean includeExternalLibraries) { // locations return ImmutableList.builder() .addAll( - BlazeModuleSystem.getInstance(module) + BazelModuleSystem.getInstance(module) .getAndroidLibraryDependencies(DependencyScopeType.MAIN) .stream() .map(ExternalAndroidLibrary::getPackageName) @@ -78,4 +72,12 @@ public List getResourcePackageNames(boolean includeExternalLibraries) { .getWorkspaceResourcePackages()) .build(); } + + @Nullable + @Override + public ViewClass findViewClass(@NotNull String fqcn) { + JavaPsiFacade facade = JavaPsiFacade.getInstance(module.getProject()); + return new PsiClassViewClass( + facade.findClass(fqcn, module.getModuleWithDependenciesAndLibrariesScope(false))); + } } diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeModuleSystem.java b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelModuleSystem.java similarity index 82% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeModuleSystem.java rename to aswb/src/com/google/idea/blaze/android/projectsystem/BazelModuleSystem.java index 2c64e2c2b32..60ea3f85b51 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeModuleSystem.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelModuleSystem.java @@ -28,15 +28,15 @@ import java.nio.file.Path; /** Blaze implementation of {@link AndroidModuleSystem}. */ -public class BlazeModuleSystem extends BlazeModuleSystemBase { +public class BazelModuleSystem extends BlazeModuleSystemBase { - BlazeModuleSystem(Module module) { + BazelModuleSystem(Module module) { super(module); } @Override public ModuleDependencies getModuleDependencies() { - return new BlazeModuleDependencies(getModule()); + return new BazelModuleDependencies(getModule()); } public String blazeTargetNameToKotlinModuleName(String blazeTargetName) { @@ -46,17 +46,6 @@ public String blazeTargetNameToKotlinModuleName(String blazeTargetName) { return blazeTargetName.substring(2).replaceAll("['/',':']", "_"); } - @Override - public String getModuleNameForCompilation(VirtualFile virtualFile) { - String moduleName = - blazeTargetNameToKotlinModuleName( - SourceToTargetMap.getInstance(project) - .getTargetsToBuildForSourceFile(new File(virtualFile.getPath())) - .get(0) // use the first target - .toString()); - return moduleName; - } - /** Check every supporting extension point if they contain desugaring library config files */ @Override public boolean getDesugarLibraryConfigFilesKnown() { diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeNavDesignSurfaceToken.java b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelNavDesignSurfaceToken.java similarity index 92% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeNavDesignSurfaceToken.java rename to aswb/src/com/google/idea/blaze/android/projectsystem/BazelNavDesignSurfaceToken.java index 80e8b353b01..a976873d5ab 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeNavDesignSurfaceToken.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelNavDesignSurfaceToken.java @@ -30,9 +30,9 @@ import org.jetbrains.annotations.NotNull; /** Blaze implementation of project system tokens for the navigation editor: Nav Design Surface */ -class BlazeNavDesignSurfaceToken implements NavDesignSurfaceToken, BlazeToken { +public class BazelNavDesignSurfaceToken implements NavDesignSurfaceToken, BazelToken { @Override - public boolean modifyProject(@NotNull BlazeProjectSystem projectSystem, @NotNull NlModel model) { + public boolean modifyProject(@NotNull BazelProjectSystem projectSystem, @NotNull NlModel model) { AtomicBoolean didAdd = new AtomicBoolean(false); Module module = model.getModule(); List coordinates = diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeProjectSystem.java b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelProjectSystem.java similarity index 88% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeProjectSystem.java rename to aswb/src/com/google/idea/blaze/android/projectsystem/BazelProjectSystem.java index eec76246653..f289c05fcb5 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeProjectSystem.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelProjectSystem.java @@ -24,6 +24,7 @@ import com.android.tools.idea.model.AndroidModel; import com.android.tools.idea.model.ClassJarProvider; import com.android.tools.idea.projectsystem.AndroidProjectSystem; +import com.android.tools.idea.projectsystem.CommonTestType; import com.android.tools.idea.projectsystem.NamedIdeaSourceProvider; import com.android.tools.idea.projectsystem.ProjectSystemBuildManager; import com.android.tools.idea.projectsystem.ProjectSystemSyncManager; @@ -36,6 +37,7 @@ import com.android.tools.idea.res.AndroidResourceClassPsiElementFinder; import com.android.tools.idea.sdk.AndroidSdks; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.idea.blaze.android.resources.BlazeLightResourceClassService; import com.google.idea.blaze.android.sync.model.idea.BlazeAndroidModel; @@ -66,13 +68,13 @@ * Base class to implement common methods in {@link AndroidProjectSystem} for blaze with different * sdk */ -public class BlazeProjectSystem implements AndroidProjectSystem { +public class BazelProjectSystem implements AndroidProjectSystem { protected final Project project; protected final ProjectSystemSyncManager syncManager; protected final List myFinders; private final BlazeProjectSystemBuildManager buildManager; - public BlazeProjectSystem(Project project) { + public BazelProjectSystem(Project project) { this.project = project; syncManager = new BlazeProjectSystemSyncManager(project); buildManager = new BlazeProjectSystemBuildManager(project); @@ -103,7 +105,7 @@ public VirtualFile getDefaultApkFile() { public Path getPathToAapt() { return AaptInvoker.getPathToAapt( AndroidSdks.getInstance().tryToChooseSdkHandler(), - new LogWrapper(BlazeProjectSystem.class)); + new LogWrapper(BazelProjectSystem.class)); } @Override @@ -112,8 +114,8 @@ public ProjectSystemBuildManager getBuildManager() { } @Override - public BlazeModuleSystem getModuleSystem(Module module) { - return BlazeModuleSystem.getInstance(module); + public BazelModuleSystem getModuleSystem(Module module) { + return BazelModuleSystem.getInstance(module); } @Override @@ -150,27 +152,31 @@ private SourceProviders createForModel(BlazeAndroidModel model) { return new SourceProvidersImpl( mainSourceProvider, ImmutableList.of(mainSourceProvider), - ImmutableList.of(), - ImmutableList.of(), + ImmutableMap.of(CommonTestType.UNIT_TEST, ImmutableList.of()), + ImmutableMap.of(CommonTestType.ANDROID_TEST, ImmutableList.of()), ImmutableList.of(), ImmutableList.of(mainSourceProvider), ImmutableList.of(mainSourceProvider), + ImmutableList.of(mainSourceProvider), emptySourceProvider(ScopeType.MAIN), - emptySourceProvider(ScopeType.UNIT_TEST), - emptySourceProvider(ScopeType.ANDROID_TEST), + ImmutableMap.of(CommonTestType.UNIT_TEST, emptySourceProvider(ScopeType.UNIT_TEST)), + ImmutableMap.of( + CommonTestType.ANDROID_TEST, emptySourceProvider(ScopeType.ANDROID_TEST)), emptySourceProvider(ScopeType.TEST_FIXTURES)); } else { return new SourceProvidersImpl( mainSourceProvider, ImmutableList.of(mainSourceProvider), - ImmutableList.of(mainSourceProvider), + ImmutableMap.of(CommonTestType.UNIT_TEST, ImmutableList.of(mainSourceProvider)), + ImmutableMap.of(CommonTestType.ANDROID_TEST, ImmutableList.of(mainSourceProvider)), ImmutableList.of(mainSourceProvider), ImmutableList.of(mainSourceProvider), ImmutableList.of(mainSourceProvider), ImmutableList.of(mainSourceProvider), emptySourceProvider(ScopeType.MAIN), - emptySourceProvider(ScopeType.UNIT_TEST), - emptySourceProvider(ScopeType.ANDROID_TEST), + ImmutableMap.of(CommonTestType.UNIT_TEST, emptySourceProvider(ScopeType.UNIT_TEST)), + ImmutableMap.of( + CommonTestType.ANDROID_TEST, emptySourceProvider(ScopeType.ANDROID_TEST)), emptySourceProvider(ScopeType.TEST_FIXTURES)); } } @@ -183,8 +189,7 @@ public ClassJarProvider getClassJarProvider() { } @Override - public Collection getAndroidFacetsWithPackageName( - Project project, String packageName) { + public Collection getAndroidFacetsWithPackageName(String packageName) { return getAndroidFacetsWithPackageName( project, packageName, GlobalSearchScope.projectScope(project)); } @@ -281,6 +286,11 @@ public Collection getBootClasspath(@NotNull Module module) { return AndroidPlatforms.getInstance(module).getTarget().getBootClasspath(); } + @Override + public boolean isAndroidProject() { + return ProjectFacetManager.getInstance(project).hasFacets(AndroidFacet.ID); + } + private static boolean hasPackageName(AndroidFacet facet, String packageName) { String nameFromFacet = PackageNameUtils.getPackageName(facet.getModule()); if (nameFromFacet == null) { diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeToken.java b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelToken.java similarity index 90% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeToken.java rename to aswb/src/com/google/idea/blaze/android/projectsystem/BazelToken.java index d9a4b21a732..1cb89b26419 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/BlazeToken.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/BazelToken.java @@ -19,9 +19,9 @@ import com.android.tools.idea.projectsystem.Token; /** A mix-in implementation of the {@link Token} interface for the Blaze project system. */ -public interface BlazeToken extends Token { +public interface BazelToken extends Token { @Override default boolean isApplicable(AndroidProjectSystem projectSystem) { - return projectSystem instanceof BlazeProjectSystem; + return projectSystem instanceof BazelProjectSystem; } } diff --git a/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeModuleSystemBase.java b/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeModuleSystemBase.java index 36f5b94a83e..d25d379f47d 100644 --- a/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeModuleSystemBase.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeModuleSystemBase.java @@ -15,10 +15,8 @@ */ package com.google.idea.blaze.android.projectsystem; -import static com.android.SdkConstants.DOT_AAR; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; -import static com.google.idea.blaze.base.qsync.DependencyTracker.DependencyBuildRequest.singleTarget; import static java.util.Arrays.stream; import com.android.ide.common.repository.GradleCoordinate; @@ -52,9 +50,7 @@ import com.google.idea.blaze.android.sync.model.AndroidResourceModule; import com.google.idea.blaze.android.sync.model.AndroidResourceModuleRegistry; import com.google.idea.blaze.android.sync.model.BlazeAndroidSyncData; -import com.google.idea.blaze.android.sync.qsync.AndroidExternalLibraryManager; import com.google.idea.blaze.base.command.buildresult.OutputArtifactResolver; -import com.google.idea.blaze.base.ideinfo.AndroidAarIdeInfo; import com.google.idea.blaze.base.ideinfo.ArtifactLocation; import com.google.idea.blaze.base.ideinfo.Dependency; import com.google.idea.blaze.base.ideinfo.TargetIdeInfo; @@ -65,11 +61,8 @@ import com.google.idea.blaze.base.model.BlazeProjectData; import com.google.idea.blaze.base.model.primitives.WorkspaceRoot; import com.google.idea.blaze.base.projectview.ProjectViewManager; -import com.google.idea.blaze.base.qsync.DependencyTracker; -import com.google.idea.blaze.base.qsync.QuerySync; import com.google.idea.blaze.base.qsync.QuerySyncManager; import com.google.idea.blaze.base.qsync.QuerySyncProject; -import com.google.idea.blaze.base.scope.BlazeContext; import com.google.idea.blaze.base.settings.Blaze; import com.google.idea.blaze.base.settings.BlazeImportSettings.ProjectType; import com.google.idea.blaze.base.settings.BlazeImportSettingsManager; @@ -81,9 +74,8 @@ import com.google.idea.blaze.base.targetmaps.ReverseDependencyMap; import com.google.idea.blaze.base.targetmaps.TransitiveDependencyMap; import com.google.idea.blaze.common.Label; -import com.google.idea.blaze.qsync.BlazeProject; -import com.google.idea.blaze.qsync.BlazeProjectSnapshot; -import com.google.idea.blaze.qsync.deps.ArtifactTracker; +import com.google.idea.blaze.qsync.QuerySyncProjectSnapshot; +import com.google.idea.blaze.qsync.SnapshotHolder; import com.google.idea.blaze.qsync.project.ProjectPath; import com.google.idea.blaze.qsync.project.ProjectProto; import com.google.idea.common.experiments.BoolExperiment; @@ -93,7 +85,6 @@ import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; -import com.intellij.openapi.module.ModuleServiceManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; @@ -101,15 +92,12 @@ import com.intellij.psi.search.ProjectScope; import java.io.File; import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Optional; import java.util.stream.Stream; import kotlin.Triple; import org.jetbrains.annotations.Nullable; @@ -127,14 +115,13 @@ abstract class BlazeModuleSystemBase implements AndroidModuleSystem { public static final BoolExperiment returnSimpleDirectResourceDependents = new BoolExperiment("aswb.return.simple.direct.resource.dependents", true); - protected static final Logger logger = Logger.getInstance(BlazeModuleSystem.class); + protected static final Logger logger = Logger.getInstance(BazelModuleSystem.class); protected Module module; protected final Project project; private final ProjectPath.Resolver pathResolver; SampleDataDirectoryProvider sampleDataDirectoryProvider; RenderJarClassFileFinder classFileFinder; final boolean isWorkspaceModule; - private AndroidExternalLibraryManager androidExternalLibraryManager = null; BlazeModuleSystemBase(Module module) { this.module = module; @@ -149,31 +136,6 @@ abstract class BlazeModuleSystemBase implements AndroidModuleSystem { classFileFinder = new RenderJarClassFileFinder(module); sampleDataDirectoryProvider = new BlazeSampleDataDirectoryProvider(module); isWorkspaceModule = module.getName().equals(BlazeDataStorage.WORKSPACE_MODULE_NAME); - if (Blaze.getProjectType(project) == ProjectType.QUERY_SYNC - && !QuerySync.USE_NEW_BUILD_ARTIFACT_MANAGEMENT) { - androidExternalLibraryManager = - new AndroidExternalLibraryManager( - () -> { - if (!QuerySyncManager.getInstance(project).isProjectLoaded()) { - return ImmutableList.of(); - } - ArtifactTracker artifactTracker = - QuerySyncManager.getInstance(project).getArtifactTracker(); - Path aarDirectory = artifactTracker.getExternalAarDirectory(); - // This can be called by the IDE as the user navigates the project and so might be - // called before a sync has been completed and the project structure has been set - // up. - if (!aarDirectory.toFile().exists()) { - logger.warn("Aar library directory not created yet"); - return ImmutableList.of(); - } - try (Stream stream = Files.list(aarDirectory)) { - return stream.collect(toImmutableList()); - } catch (IOException ioe) { - throw new UncheckedIOException("Could not list aars", ioe); - } - }); - } } @Override @@ -365,84 +327,6 @@ public GradleCoordinate getResolvedDependency( return target != null ? gradleCoordinate : null; } - /** - * Returns first cached aar that build by the label provided. This is used by qsync. Returns null - * if failed to find such aar locally. - * - * @param label the label that aar build from - * @param buildDeps whether run blaze build to build aar before get it. - */ - private Optional getCachedAarForLabel(Label label, boolean buildDeps) { - DependencyTracker dependencyTracker = - QuerySyncManager.getInstance(project).getDependencyTracker(); - if (dependencyTracker == null) { - return Optional.empty(); - } - - if (buildDeps) { - BlazeContext tmpContext = BlazeContext.create(); - try { - boolean unused = - dependencyTracker.buildDependenciesForTargets(tmpContext, singleTarget(label)); - } catch (Exception e) { - tmpContext.handleException("Failed to build dependencies", e); - } - } - - Optional> paths = dependencyTracker.getCachedArtifacts(label); - if (paths.isEmpty()) { - return Optional.empty(); - } - return paths.get().stream().filter(path -> path.toString().endsWith(DOT_AAR)).findFirst(); - } - - /** - * Returns the absolute path of the dependency, if it exists. - * - * @param coordinate external coordinates for the dependency. - * @return the absolute path of the dependency including workspace root and path. - */ - // @Override removed in 232 - @Nullable - public Path getDependencyPath(GradleCoordinate coordinate) { - if (Blaze.getProjectType(project) == ProjectType.QUERY_SYNC) { - Label label = getResolvedLabel(coordinate); - if (label == null) { - return null; - } - Optional result = getCachedAarForLabel(label, false); - if (result.isPresent()) { - return result.get(); - } - // Failed to get cache aar without building the target. It means the target may not be built - // correctly (either not build or its artifact not cached correctly), we need to - // re-build it again as the target cannot not be build except here. This is required for - // compose layout inspector. - return getCachedAarForLabel(label, true).orElse(null); - } - TargetKey target = getResolvedTarget(coordinate); - if (target == null) { - return null; - } - BlazeProjectData projectData = - BlazeProjectDataManager.getInstance(project).getBlazeProjectData(); - Path defaultPath = - WorkspaceRoot.fromProject(project).fileForPath(target.getLabel().blazePackage()).toPath(); - if (projectData == null) { - return defaultPath; - } - - AndroidAarIdeInfo aarIdeInfo = projectData.getTargetMap().get(target).getAndroidAarIdeInfo(); - // Returns its local aar directory path (if exists) instead of google3 one for imported aars. - if (aarIdeInfo == null) { - return defaultPath; - } - File aarDir = - UnpackedAars.getInstance(module.getProject()) - .getAarDir(projectData.getArtifactLocationDecoder(), aarIdeInfo.getAar()); - return aarDir == null || !aarDir.exists() ? defaultPath : aarDir.toPath(); - } - private Stream locateArtifactsFor(GradleCoordinate coordinate) { // External dependencies can be imported into the project via many routes (e.g. maven_jar, // local_repository, custom repo paths, etc). Within the project these dependencies are all @@ -582,30 +466,26 @@ public boolean getUsesCompose() { public Collection getDependentLibraries() { if (Blaze.getProjectType(project) == ProjectType.QUERY_SYNC) { - if (QuerySync.USE_NEW_BUILD_ARTIFACT_MANAGEMENT) { - ProjectProto.Project projectProto = - QuerySyncManager.getInstance(project) - .getLoadedProject() - .map(QuerySyncProject::getSnapshotHolder) - .flatMap(BlazeProject::getCurrent) - .map(BlazeProjectSnapshot::project) - .orElse(null); - if (projectProto == null) { - return ImmutableList.of(); - } - ImmutableList matchingModules = - projectProto.getModulesList().stream() - .filter(m -> m.getName().equals(module.getName())) - .collect(ImmutableList.toImmutableList()); - if (matchingModules.isEmpty()) { - return ImmutableList.of(); - } - return Iterables.getOnlyElement(matchingModules).getAndroidExternalLibrariesList().stream() - .map(this::fromProto) - .collect(toImmutableList()); - } else { - return androidExternalLibraryManager.getExternalLibraries(); + ProjectProto.Project projectProto = + QuerySyncManager.getInstance(project) + .getLoadedProject() + .map(QuerySyncProject::getSnapshotHolder) + .flatMap(SnapshotHolder::getCurrent) + .map(QuerySyncProjectSnapshot::project) + .orElse(null); + if (projectProto == null) { + return ImmutableList.of(); } + ImmutableList matchingModules = + projectProto.getModulesList().stream() + .filter(m -> m.getName().equals(module.getName())) + .collect(ImmutableList.toImmutableList()); + if (matchingModules.isEmpty()) { + return ImmutableList.of(); + } + return Iterables.getOnlyElement(matchingModules).getAndroidExternalLibrariesList().stream() + .map(this::fromProto) + .collect(toImmutableList()); } BlazeProjectData blazeProjectData = BlazeProjectDataManager.getInstance(project).getBlazeProjectData(); @@ -616,7 +496,7 @@ public Collection getDependentLibraries() { if (isWorkspaceModule) { return SyncCache.getInstance(project) - .get(BlazeModuleSystem.class, BlazeModuleSystemBase::getLibrariesForWorkspaceModule); + .get(BazelModuleSystem.class, BlazeModuleSystemBase::getLibrariesForWorkspaceModule); } AndroidResourceModuleRegistry registry = AndroidResourceModuleRegistry.getInstance(project); @@ -650,12 +530,16 @@ public Collection getDependentLibraries() { } private ExternalAndroidLibrary fromProto(ProjectProto.ExternalAndroidLibrary proto) { - return new ExternalLibraryImpl(proto.getName()) - .withLocation(toPathString(proto.getLocation())) - .withManifestFile(toPathString(proto.getManifestFile())) - .withResFolder(new SelectiveResourceFolder(toPathString(proto.getResFolder()), null)) - .withSymbolFile(toPathString(proto.getSymbolFile())) - .withPackageName(proto.getPackageName()); + ExternalLibraryImpl lib = + new ExternalLibraryImpl(proto.getName()) + .withLocation(toPathString(proto.getLocation())) + .withManifestFile(toPathString(proto.getManifestFile())) + .withResFolder(new SelectiveResourceFolder(toPathString(proto.getResFolder()), null)) + .withSymbolFile(toPathString(proto.getSymbolFile())); + if (!proto.getPackageName().isEmpty()) { + lib = lib.withPackageName(proto.getPackageName()); + } + return lib; } private PathString toPathString(ProjectProto.ProjectPath projectPath) { @@ -726,12 +610,12 @@ public Collection getAndroidLibraryDependencies( } @TestOnly - public static BlazeModuleSystem create(Module module) { + public static BazelModuleSystem create(Module module) { Preconditions.checkState(ApplicationManager.getApplication().isUnitTestMode()); - return new BlazeModuleSystem(module); + return new BazelModuleSystem(module); } - public static BlazeModuleSystem getInstance(Module module) { - return ModuleServiceManager.getService(module, BlazeModuleSystem.class); + public static BazelModuleSystem getInstance(Module module) { + return module.getService(BazelModuleSystem.class); } } diff --git a/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeProjectSystemBuildManager.java b/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeProjectSystemBuildManager.java index 97711f1f884..e16aa4081c0 100644 --- a/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeProjectSystemBuildManager.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeProjectSystemBuildManager.java @@ -21,6 +21,8 @@ import com.android.tools.idea.projectsystem.ProjectSystemBuildManager; import com.google.idea.blaze.base.build.BlazeBuildListener; import com.google.idea.blaze.base.build.BlazeBuildService; +import com.google.idea.blaze.base.settings.Blaze; +import com.google.idea.blaze.base.settings.BlazeImportSettings.ProjectType; import com.google.idea.blaze.base.sync.aspects.BlazeBuildOutputs; import com.intellij.openapi.Disposable; import com.intellij.openapi.components.Service; @@ -47,13 +49,6 @@ public void compileProject() { BlazeBuildService.getInstance(project).buildProject(); } - @Override - public void compileFilesAndDependencies(Collection files) { - // TODO(b/191937319): Implement incremental builds for individual files - // Just compile the entire project for now. - compileProject(); - } - @Override public void addBuildListener( Disposable parentDisposable, ProjectSystemBuildManager.BuildListener buildListener) { @@ -109,7 +104,8 @@ public void buildStarting(Project project) { project .getMessageBus() .syncPublisher(PROJECT_SYSTEM_BUILD_TOPIC) - .buildStarted(BuildMode.COMPILE); // Blaze build currently only supports compilation + .buildStarted( + BuildMode.COMPILE_OR_ASSEMBLE); // Blaze build currently only supports compilation } @Override @@ -142,9 +138,7 @@ private static LastBuildResultCache getInstance(Project project) { private BuildResult updateBuildResult( com.google.idea.blaze.base.sync.aspects.BuildResult buildResult) { - lastBuildResult = - new BuildResult( - BuildMode.COMPILE, mapBuildStatus(buildResult), System.currentTimeMillis()); + lastBuildResult = new BuildResult(BuildMode.COMPILE_OR_ASSEMBLE, mapBuildStatus(buildResult)); return lastBuildResult; } @@ -165,3 +159,4 @@ private static BuildStatus mapBuildStatus( } } } + diff --git a/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeProjectSystemProvider.java b/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeProjectSystemProvider.java index 69881940e53..4c0a493da9f 100644 --- a/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeProjectSystemProvider.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/BlazeProjectSystemProvider.java @@ -21,27 +21,22 @@ import com.intellij.openapi.project.Project; /** - * A BlazeProjectSystemProvider determines whether or not a BlazeProjectSystem would be applicable + * A BlazeProjectSystemProvider determines whether or not a BazelProjectSystem would be applicable * for a given project. If so, the provider is responsible for creating the instance of - * BlazeProjectSystem that should be associated with the project. + * BazelProjectSystem that should be associated with the project. * *

We provide this functionality in BlazeProjectSystemProvider instead of having - * BlazeProjectSystem implement AndroidProjectSystemProvider itself because there are times when we + * BazelProjectSystem implement AndroidProjectSystemProvider itself because there are times when we * want to instantiate the provider extension without creating a new instance of the project system. * In particular, the provider extension may be instantiated after the disposal of the project, in * which case we can't create the project system because it interacts with the project during * instantiation. */ public class BlazeProjectSystemProvider implements AndroidProjectSystemProvider { - public static final String ID = "com.google.idea.blaze.BlazeProjectSystem"; - private Project project; - - public BlazeProjectSystemProvider(Project project) { - this.project = project; - } + public static final String ID = "com.google.idea.blaze.BazelProjectSystem"; @Override - public boolean isApplicable() { + public boolean isApplicable(Project project) { return Blaze.isBlazeProject(project); } @@ -51,7 +46,7 @@ public String getId() { } @Override - public AndroidProjectSystem getProjectSystem() { - return new BlazeProjectSystem(project); + public AndroidProjectSystem projectSystemFactory(Project project) { + return new BazelProjectSystem(project); } } diff --git a/aswb/src/com/google/idea/blaze/android/projectsystem/PackageNameUtils.java b/aswb/src/com/google/idea/blaze/android/projectsystem/PackageNameUtils.java index 83a7fcd9b20..f9b1a68db52 100644 --- a/aswb/src/com/google/idea/blaze/android/projectsystem/PackageNameUtils.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/PackageNameUtils.java @@ -17,7 +17,6 @@ import com.android.manifmerger.ManifestSystemProperty; import com.android.tools.idea.model.AndroidManifestIndex; -import com.android.tools.idea.model.AndroidManifestIndexCompat; import com.android.tools.idea.model.AndroidManifestRawText; import com.android.tools.idea.model.MergedManifestModificationTracker; import com.android.tools.idea.projectsystem.ManifestOverrides; @@ -41,8 +40,7 @@ public class PackageNameUtils { /** * Determines whether we use the {@link AndroidManifestIndex} to obtain the raw text package name - * from a module's primary manifest. Note that we still won't use the index if {@link - * AndroidManifestIndex#indexEnabled()} returns false. + * from a module's primary manifest. * * @see PackageNameUtils#getPackageName(Module) * @see PackageNameUtils#doGetPackageName(AndroidFacet, boolean) @@ -58,9 +56,7 @@ public static String getPackageName(Module module) { .getCachedValue( facet, () -> { - boolean useIndex = - AndroidManifestIndexCompat.indexEnabled() - && USE_ANDROID_MANIFEST_INDEX.getValue(); + boolean useIndex = USE_ANDROID_MANIFEST_INDEX.getValue(); String packageName = doGetPackageName(facet, useIndex); return CachedValueProvider.Result.create( StringUtil.nullize(packageName, true), @@ -92,7 +88,7 @@ public static String getPackageName(Module module) { @VisibleForTesting static String doGetPackageName(AndroidFacet facet, boolean useIndex) { ManifestOverrides manifestOverrides = - BlazeModuleSystem.getInstance(facet.getModule()).getManifestOverrides(); + BazelModuleSystem.getInstance(facet.getModule()).getManifestOverrides(); String packageOverride = ManifestValueProcessor.getPackageOverride(manifestOverrides.getDirectOverrides()); if (packageOverride != null) { diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java b/aswb/src/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java similarity index 98% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java rename to aswb/src/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java index 0967d9fc40c..912eba4df65 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java +++ b/aswb/src/com/google/idea/blaze/android/projectsystem/RenderJarClassFileFinder.java @@ -31,7 +31,6 @@ import com.google.idea.blaze.base.ideinfo.TargetIdeInfo; import com.google.idea.blaze.base.ideinfo.TargetKey; import com.google.idea.blaze.base.model.BlazeProjectData; -import com.google.idea.blaze.base.qsync.QuerySync; import com.google.idea.blaze.base.qsync.QuerySyncManager; import com.google.idea.blaze.base.qsync.RenderJarArtifactTracker; import com.google.idea.blaze.base.settings.Blaze; @@ -159,14 +158,17 @@ public ClassContent findClassContent(String fqcn) { } private ClassContent findClassQuerySync(String fqcn) { - if (QuerySync.isComposeEnabled(project)) { + if (Blaze.getProjectType(project) == ProjectType.QUERY_SYNC) { RenderJarArtifactTracker renderJarArtifactTracker = QuerySyncManager.getInstance(project).getRenderJarArtifactTracker(); // TODO(b/283280194): Setup fqcn -> target and target -> Render jar mappings to avoid // iterating over all render jars when trying to locate class for fqcn. // TODO(b/284002836): Collect metrics on time taken to iterate over the jars for (File renderJar : renderJarArtifactTracker.getRenderJars()) { - return findClassInJar(renderJar, fqcn); + ClassContent classContent = findClassInJar(renderJar, fqcn); + if (classContent != null) { + return classContent; + } } return null; } diff --git a/aswb/src/com/google/idea/blaze/android/projectview/AndroidSdkPlatformSection.java b/aswb/src/com/google/idea/blaze/android/projectview/AndroidSdkPlatformSection.java index f165b37f632..b425f101b29 100644 --- a/aswb/src/com/google/idea/blaze/android/projectview/AndroidSdkPlatformSection.java +++ b/aswb/src/com/google/idea/blaze/android/projectview/AndroidSdkPlatformSection.java @@ -15,7 +15,6 @@ */ package com.google.idea.blaze.android.projectview; -import static com.google.idea.blaze.base.projectview.parser.ProjectViewParser.TEMPORARY_LINE_NUMBER; import static java.util.stream.Collectors.toList; import com.google.common.collect.ImmutableList; @@ -78,15 +77,14 @@ public ProjectView addProjectViewDefaultValue( } List sdks = BlazeSdkProvider.getInstance().getAllAndroidSdks(); ProjectView.Builder builder = - ProjectView.builder(topLevelProjectView).add(TextBlockSection.of(TextBlock.newLine(TEMPORARY_LINE_NUMBER))); + ProjectView.builder(topLevelProjectView).add(TextBlockSection.of(TextBlock.newLine())); if (sdks.isEmpty()) { builder - .add(TextBlockSection.of(TextBlock.of(TEMPORARY_LINE_NUMBER, "# Please set to an android SDK platform"))) + .add(TextBlockSection.of(TextBlock.of("# Please set to an android SDK platform"))) .add( TextBlockSection.of( TextBlock.of( - TEMPORARY_LINE_NUMBER, "# You currently have no SDKs. Please use the SDK manager first."))) .add(ScalarSection.builder(KEY).set("(android sdk goes here)")); } else if (sdks.size() == 1) { @@ -96,13 +94,13 @@ public ProjectView addProjectViewDefaultValue( } else { builder.add( TextBlockSection.of( - TextBlock.of(TEMPORARY_LINE_NUMBER, "# Please uncomment an android-SDK platform. Available SDKs are:"))); + TextBlock.of("# Please uncomment an android-SDK platform. Available SDKs are:"))); List sdkOptions = AndroidSdkFromProjectView.getAvailableSdkTargetHashes(sdks) .stream() .map(androidSdk -> "# android_sdk_platform: " + androidSdk) .collect(toList()); - builder.add(TextBlockSection.of(new TextBlock(ImmutableList.copyOf(sdkOptions), TEMPORARY_LINE_NUMBER))); + builder.add(TextBlockSection.of(new TextBlock(ImmutableList.copyOf(sdkOptions)))); } return builder.build(); } diff --git a/aswb/src/com/google/idea/blaze/android/qsync/AndroidProjectProtoTransform.java b/aswb/src/com/google/idea/blaze/android/qsync/AndroidProjectProtoTransform.java index 8521b8bdb3c..e58b89595d2 100644 --- a/aswb/src/com/google/idea/blaze/android/qsync/AndroidProjectProtoTransform.java +++ b/aswb/src/com/google/idea/blaze/android/qsync/AndroidProjectProtoTransform.java @@ -18,16 +18,18 @@ import com.google.common.collect.ImmutableList; import com.google.idea.blaze.android.manifest.ManifestParser; import com.google.idea.blaze.base.qsync.ProjectProtoTransformProvider; -import com.google.idea.blaze.base.qsync.QuerySyncProject; import com.google.idea.blaze.common.Context; import com.google.idea.blaze.exception.BuildException; +import com.google.idea.blaze.qsync.ProjectProtoTransform; +import com.google.idea.blaze.qsync.deps.ArtifactTracker; import com.google.idea.blaze.qsync.deps.ProjectProtoUpdate; import com.google.idea.blaze.qsync.deps.ProjectProtoUpdateOperation; +import com.google.idea.blaze.qsync.java.AarPackageNameExtractor; import com.google.idea.blaze.qsync.java.AddAndroidResPackages; import com.google.idea.blaze.qsync.java.AddDependencyAars; import com.google.idea.blaze.qsync.project.BuildGraphData; +import com.google.idea.blaze.qsync.project.ProjectDefinition; import com.google.idea.blaze.qsync.project.ProjectProto.Project; -import com.google.idea.blaze.qsync.project.ProjectProtoTransform; import java.util.List; /** A {@link ProjectProtoTransform} that adds android specific information to the project proto. */ @@ -38,31 +40,32 @@ public class AndroidProjectProtoTransform implements ProjectProtoTransform { * proto. */ public static class Provider implements ProjectProtoTransformProvider { + @Override - public List createTransforms(QuerySyncProject project) { - return ImmutableList.of(new AndroidProjectProtoTransform(project)); + public List createTransforms(ProjectDefinition projectDef) { + return ImmutableList.of(new AndroidProjectProtoTransform(projectDef)); } } private final ImmutableList updateOperations; - private AndroidProjectProtoTransform(QuerySyncProject project) { + private AndroidProjectProtoTransform(ProjectDefinition projectDefinition) { updateOperations = ImmutableList.of( new AddDependencyAars( - project.getArtifactTracker()::getStateSnapshot, - project.getBuildArtifactCache(), - project.getProjectDefinition(), - in -> ManifestParser.parseManifestFromInputStream(in).packageName), - new AddAndroidResPackages(project.getArtifactTracker()::getStateSnapshot)); + projectDefinition, + new AarPackageNameExtractor( + in -> ManifestParser.parseManifestFromInputStream(in).packageName)), + new AddAndroidResPackages()); } @Override - public Project apply(Project proto, BuildGraphData graph, Context context) + public Project apply( + Project proto, BuildGraphData graph, ArtifactTracker.State artifactState, Context context) throws BuildException { ProjectProtoUpdate update = new ProjectProtoUpdate(proto, graph, context); for (var op : updateOperations) { - op.update(update); + op.update(update, artifactState); } return update.build(); } diff --git a/aswb/src/com/google/idea/blaze/android/qsync/BlazeAndroidQuerySyncPlugin.java b/aswb/src/com/google/idea/blaze/android/qsync/BlazeAndroidQuerySyncPlugin.java index 4c7c47675f3..f5ad13ddc29 100644 --- a/aswb/src/com/google/idea/blaze/android/qsync/BlazeAndroidQuerySyncPlugin.java +++ b/aswb/src/com/google/idea/blaze/android/qsync/BlazeAndroidQuerySyncPlugin.java @@ -53,7 +53,6 @@ import java.io.File; import java.util.Set; import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.android.facet.AndroidFacetProperties; /** ASwB sync plugin. */ public class BlazeAndroidQuerySyncPlugin implements BlazeQuerySyncPlugin { @@ -68,7 +67,7 @@ public void updateProjectSettingsForQuerySync( AndroidSdkFromProjectView.getAndroidSdkPlatform(context, projectViewSet); Sdk sdk = BlazeSdkProvider.getInstance().findSdk(androidSdkPlatform.androidSdk); LanguageLevel javaLanguageLevel = - JavaLanguageLevelSection.getLanguageLevel(projectViewSet, LanguageLevel.JDK_11); + JavaLanguageLevelSection.getLanguageLevel(projectViewSet, LanguageLevel.JDK_21); ProjectRootManagerEx rootManager = ProjectRootManagerEx.getInstanceEx(project); rootManager.setProjectSdk(sdk); LanguageLevelProjectExtension ext = LanguageLevelProjectExtension.getInstance(project); @@ -123,8 +122,6 @@ public void updateProjectStructureForQuerySync( // Set AndroidModel for this AndroidFacet ProjectViewSet projectViewSet = ProjectViewManager.getInstance(project).getProjectViewSet(); - boolean desugarJava8Libs = - projectViewSet.listItems(BuildFlagsSection.KEY).contains("--config=android_java8_libs"); AndroidSdkPlatform androidSdkPlatform = AndroidSdkFromProjectView.getAndroidSdkPlatform(context, projectViewSet); @@ -134,13 +131,8 @@ public void updateProjectStructureForQuerySync( workspaceRoot.directory(), sourceProvider, Futures.immediateFuture(":workspace"), - androidSdkPlatform != null ? androidSdkPlatform.androidMinSdkLevel : 1, - desugarJava8Libs); + androidSdkPlatform != null ? androidSdkPlatform.androidMinSdkLevel : 1); AndroidModel.set(workspaceFacet, androidModel); - workspaceFacet.getProperties().RES_FOLDERS_RELATIVE_PATH = - androidResourceDirectoryFiles.stream() - .map(VfsUtilCore::fileToUrl) - .collect(joining(AndroidFacetProperties.PATH_LIST_SEPARATOR_IN_FACET_CONFIGURATION)); // Register all source java packages as workspace packages BlazeLightResourceClassService.Builder rClassBuilder = diff --git a/aswb/src/com/google/idea/blaze/android/qsync/projectstructure/AndroidFacetModuleCustomizer.java b/aswb/src/com/google/idea/blaze/android/qsync/projectstructure/AndroidFacetModuleCustomizer.java index a8db85e8119..50266af470b 100755 --- a/aswb/src/com/google/idea/blaze/android/qsync/projectstructure/AndroidFacetModuleCustomizer.java +++ b/aswb/src/com/google/idea/blaze/android/qsync/projectstructure/AndroidFacetModuleCustomizer.java @@ -23,7 +23,6 @@ import com.intellij.openapi.module.Module; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.android.facet.AndroidFacetProperties; -import org.jetbrains.android.facet.AndroidFacetPropertiesCompat; /** Adds the Android facet to modules imported from {@link AndroidProject}s. */ public class AndroidFacetModuleCustomizer { @@ -56,6 +55,5 @@ private static void configureFacet(AndroidFacet facet, boolean isApp) { facetState.MANIFEST_FILE_RELATIVE_PATH = ""; facetState.RES_FOLDER_RELATIVE_PATH = ""; facetState.ASSETS_FOLDER_RELATIVE_PATH = ""; - AndroidFacetPropertiesCompat.enableSourcesAutogeneration(facetState, false); } } diff --git a/aswb/src/com/google/idea/blaze/android/rendering/BlazeRenderErrorContributor.java b/aswb/src/com/google/idea/blaze/android/rendering/BlazeRenderErrorContributor.java index 827e5975a35..4fd90645f03 100644 --- a/aswb/src/com/google/idea/blaze/android/rendering/BlazeRenderErrorContributor.java +++ b/aswb/src/com/google/idea/blaze/android/rendering/BlazeRenderErrorContributor.java @@ -18,12 +18,13 @@ import static com.android.SdkConstants.ANDROID_MANIFEST_XML; import static com.google.common.collect.ImmutableMap.toImmutableMap; -import com.android.tools.idea.rendering.RenderErrorContributorCompat; +import com.android.tools.idea.rendering.RenderErrorContributor; +import com.android.tools.idea.rendering.RenderUtils; import com.android.tools.idea.rendering.errors.ui.RenderErrorModel; import com.android.tools.idea.ui.designer.EditorDesignSurface; -import com.android.tools.rendering.HtmlLinkManagerCompat; -import com.android.tools.rendering.RenderLoggerCompat; -import com.android.tools.rendering.RenderResultCompat; +import com.android.tools.rendering.HtmlLinkManager; +import com.android.tools.rendering.RenderLogger; +import com.android.tools.rendering.RenderResult; import com.android.utils.HtmlBuilder; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableCollection; @@ -43,12 +44,12 @@ import com.google.idea.blaze.base.model.BlazeProjectData; import com.google.idea.blaze.base.settings.Blaze; import com.google.idea.blaze.base.settings.BlazeImportSettings.ProjectType; +import com.google.idea.blaze.base.settings.BuildSystemName; import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager; import com.google.idea.blaze.base.sync.workspace.ArtifactLocationDecoder; import com.google.idea.blaze.base.targetmaps.SourceToTargetMap; import com.google.idea.blaze.base.targetmaps.TransitiveDependencyMap; import com.intellij.lang.annotation.HighlightSeverity; -import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.IndexNotReadyException; @@ -62,26 +63,118 @@ import com.intellij.psi.PsiFile; import com.intellij.psi.search.GlobalSearchScope; import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.function.Function; +import javax.swing.JEditorPane; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; +import javax.swing.text.html.HTMLDocument; +import javax.swing.text.html.HTMLFrameHyperlinkEvent; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** Contribute blaze specific render errors. */ -public class BlazeRenderErrorContributor extends RenderErrorContributorCompat { - private final RenderLoggerCompat logger; +public class BlazeRenderErrorContributor implements RenderErrorContributor { + private final EditorDesignSurface designSurface; + private final RenderLogger logger; private final Module module; + private final PsiFile sourceFile; private final Project project; + private final HtmlLinkManager linkManager; + private final HyperlinkListener linkHandler; + private final Set issues = new LinkedHashSet<>(); - public BlazeRenderErrorContributor( - EditorDesignSurface surface, RenderResultCompat result, @Nullable DataContext dataContext) { - super(surface, result, dataContext); - logger = new RenderLoggerCompat(result); + public BlazeRenderErrorContributor(EditorDesignSurface surface, RenderResult result) { + designSurface = surface; + logger = result.getLogger(); module = result.getModule(); + sourceFile = result.getSourceFile(); project = module.getProject(); + linkManager = logger.getLinkManager(); + linkHandler = + e -> { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + JEditorPane pane = (JEditorPane) e.getSource(); + if (e instanceof HTMLFrameHyperlinkEvent) { + HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e; + HTMLDocument doc = (HTMLDocument) pane.getDocument(); + doc.processHTMLFrameHyperlinkEvent(evt); + return; + } + + performClick(e.getDescription()); + } + }; + } + + private HtmlLinkManager getLinkManager() { + return linkManager; + } + + private Collection getIssues() { + return Collections.unmodifiableCollection(issues); + } + + private RenderErrorModel.Issue.Builder addIssue() { + return new RenderErrorModel.Issue.Builder() { + @Override + public RenderErrorModel.Issue build() { + RenderErrorModel.Issue built = super.build(); + issues.add(built); + return built; + } + }.setLinkHandler(linkHandler); + } + + private void performClick(String url) { + linkManager.handleUrl( + url, + module, + sourceFile, + true, + new HtmlLinkManager.RefreshableSurface() { + @Override + public void handleRefreshRenderUrl() { + if (designSurface != null) { + // TODO(b/321801969): Remove and replace with direct call when in repo. + // Use reflection to getConfigurations() from designSurface. Can't call directly + // because it returns an incompatible version of ImmutableCollection. + // RenderUtils.clearCache(designSurface.getConfigurations()); would fail at runtime. + try { + Method getConfigurationsMethod = + EditorDesignSurface.class.getMethod("getConfigurations", null); + Object configurations = getConfigurationsMethod.invoke(designSurface); + Method clearCacheMethod = + RenderUtils.class.getMethod( + "clearCache", getConfigurationsMethod.getReturnType()); + clearCacheMethod.invoke(null, configurations); + } catch (NoSuchMethodException ex) { + throw new RuntimeException( + "Error using reflection to get getConfigurations() instance method: " + ex); + } catch (IllegalAccessException ex) { + throw new RuntimeException( + "Error accessing getConfigurations() instance method" + ex); + } catch (InvocationTargetException ex) { + throw new RuntimeException("Error invoking target getConfigurations(): " + ex); + } + designSurface.forceUserRequestedRefresh(); + } + } + + @Override + public void requestRender() { + if (designSurface != null) { + designSurface.forceUserRequestedRefresh(); + } + } + }); } @Override @@ -203,7 +296,7 @@ private void reportNonStandardAndroidManifestName( HtmlBuilder builder = new HtmlBuilder(); addTargetLink(builder, target, decoder) .add(" uses a non-standard name for the Android manifest: "); - String linkToManifest = HtmlLinkManagerCompat.createFilePositionUrl(manifest, -1, 0); + String linkToManifest = HtmlLinkManager.createFilePositionUrl(manifest, -1, 0); if (linkToManifest != null) { builder.addLink(manifest.getName(), linkToManifest); } else { @@ -342,10 +435,22 @@ private HtmlBuilder addTargetLink( return StringUtil.offsetToLineNumber( psiFile.getText(), buildTargetPsi.getTextOffset()); }); - String url = HtmlLinkManagerCompat.createFilePositionUrl(buildFile, line, 0); + String url = HtmlLinkManager.createFilePositionUrl(buildFile, line, 0); if (url != null) { return builder.addLink(target.toString(), url); } return builder.add(target.toString()); } + + public static class Provider implements RenderErrorContributor.Provider { + + public boolean isApplicable(Project project) { + return Blaze.getProjectType(project) != ProjectType.UNKNOWN + && Blaze.getBuildSystemName(project) == BuildSystemName.Blaze; + } + + public RenderErrorContributor getContributor(@Nullable EditorDesignSurface surface, @NotNull RenderResult result) { + return new BlazeRenderErrorContributor(surface, result); + } + } } diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/rendering/BlazeRenderSecurityManagerOverrides.java b/aswb/src/com/google/idea/blaze/android/rendering/BlazeRenderSecurityManagerOverrides.java similarity index 100% rename from aswb/sdkcompat/as231/com/google/idea/blaze/android/rendering/BlazeRenderSecurityManagerOverrides.java rename to aswb/src/com/google/idea/blaze/android/rendering/BlazeRenderSecurityManagerOverrides.java diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/resources/BlazeLightResourceClassServiceBase.java b/aswb/src/com/google/idea/blaze/android/resources/BlazeLightResourceClassServiceBase.java similarity index 100% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/resources/BlazeLightResourceClassServiceBase.java rename to aswb/src/com/google/idea/blaze/android/resources/BlazeLightResourceClassServiceBase.java diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/resources/BlazeRClass.java b/aswb/src/com/google/idea/blaze/android/resources/BlazeRClass.java similarity index 100% rename from aswb/sdkcompat/as231/com/google/idea/blaze/android/resources/BlazeRClass.java rename to aswb/src/com/google/idea/blaze/android/resources/BlazeRClass.java diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/BazelApplicationProjectContext.java b/aswb/src/com/google/idea/blaze/android/run/BazelApplicationProjectContext.java similarity index 100% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/BazelApplicationProjectContext.java rename to aswb/src/com/google/idea/blaze/android/run/BazelApplicationProjectContext.java diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/BazelApplicationProjectContextProvider.java b/aswb/src/com/google/idea/blaze/android/run/BazelApplicationProjectContextProvider.java similarity index 58% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/BazelApplicationProjectContextProvider.java rename to aswb/src/com/google/idea/blaze/android/run/BazelApplicationProjectContextProvider.java index bffcc3d238d..da3d9de897f 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/BazelApplicationProjectContextProvider.java +++ b/aswb/src/com/google/idea/blaze/android/run/BazelApplicationProjectContextProvider.java @@ -15,35 +15,26 @@ */ package com.google.idea.blaze.android.run; -import com.android.ddmlib.Client; -import com.android.ddmlib.ClientData; import com.android.tools.idea.projectsystem.ApplicationProjectContext; import com.android.tools.idea.projectsystem.ApplicationProjectContextProvider; -import com.google.idea.blaze.android.projectsystem.BlazeToken; -import com.intellij.openapi.project.Project; +import com.google.idea.blaze.android.projectsystem.BazelProjectSystem; +import com.google.idea.blaze.android.projectsystem.BazelToken; import javax.annotation.Nullable; /** An implementation of {@link ApplicationProjectContextProvider} for the Blaze project system. */ public class BazelApplicationProjectContextProvider - implements ApplicationProjectContextProvider, BlazeToken { - - private final Project project; - - public BazelApplicationProjectContextProvider(Project project) { - this.project = project; - } + implements ApplicationProjectContextProvider, BazelToken { @Nullable @Override - public ApplicationProjectContext getApplicationProjectContextProvider(Client client) { - ClientData clientData = client.getClientData(); - if (clientData == null) { - return null; - } - String androidPackageName = clientData.getPackageName(); - if (androidPackageName == null) { + public ApplicationProjectContext computeApplicationProjectContext( + BazelProjectSystem projectSystem, + ApplicationProjectContextProvider.RunningApplicationIdentity identity + ) { + String applicationId = identity.getHeuristicApplicationId(); + if (applicationId == null) { return null; } - return new BazelApplicationProjectContext(project, androidPackageName); + return new BazelApplicationProjectContext(projectSystem.getProject(), applicationId); } } diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/BlazeNativeDebuggerAppContextProvider.java b/aswb/src/com/google/idea/blaze/android/run/BazelNativeDebuggerAppContextProvider.java similarity index 93% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/BlazeNativeDebuggerAppContextProvider.java rename to aswb/src/com/google/idea/blaze/android/run/BazelNativeDebuggerAppContextProvider.java index df4cd15d3cf..ee2817f48d0 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/BlazeNativeDebuggerAppContextProvider.java +++ b/aswb/src/com/google/idea/blaze/android/run/BazelNativeDebuggerAppContextProvider.java @@ -20,7 +20,7 @@ import com.android.tools.ndk.run.NativeDebuggerAppContext; import com.android.tools.ndk.run.NativeDebuggerAppContextProvider; import com.android.tools.ndk.run.SymbolDir; -import com.google.idea.blaze.android.projectsystem.BlazeToken; +import com.google.idea.blaze.android.projectsystem.BazelToken; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import java.io.File; @@ -30,8 +30,8 @@ import java.util.Map; /** An implementation of {@link NativeDebuggerAppContextProvider} for the Blaze project system. */ -public class BlazeNativeDebuggerAppContextProvider - implements NativeDebuggerAppContextProvider, BlazeToken { +public class BazelNativeDebuggerAppContextProvider + implements NativeDebuggerAppContextProvider, BazelToken { @Override public NativeDebuggerAppContext getNativeDebuggerAppContext( diff --git a/aswb/src/com/google/idea/blaze/android/run/BlazeAndroidRunConfigurationCommonState.java b/aswb/src/com/google/idea/blaze/android/run/BlazeAndroidRunConfigurationCommonState.java index 756ea45a61c..020c43f6ee4 100644 --- a/aswb/src/com/google/idea/blaze/android/run/BlazeAndroidRunConfigurationCommonState.java +++ b/aswb/src/com/google/idea/blaze/android/run/BlazeAndroidRunConfigurationCommonState.java @@ -27,10 +27,13 @@ import com.google.idea.blaze.base.model.BlazeProjectData; import com.google.idea.blaze.base.model.primitives.LanguageClass; import com.google.idea.blaze.base.projectview.ProjectViewSet; +import com.google.idea.blaze.base.qsync.QuerySync; import com.google.idea.blaze.base.run.state.RunConfigurationFlagsState; import com.google.idea.blaze.base.run.state.RunConfigurationState; import com.google.idea.blaze.base.run.state.RunConfigurationStateEditor; import com.google.idea.blaze.base.scope.BlazeContext; +import com.google.idea.blaze.base.settings.Blaze; +import com.google.idea.blaze.base.settings.BlazeImportSettings.ProjectType; import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager; import com.google.idea.blaze.base.ui.UiUtil; import com.intellij.openapi.project.Project; @@ -105,6 +108,9 @@ private ImmutableList getNativeDebuggerFlags() { * warning. */ public List validate(Project project) { + if (Blaze.getProjectType(project) == ProjectType.QUERY_SYNC) { + return ImmutableList.of(); + } List errors = Lists.newArrayList(); BlazeProjectData blazeProjectData = BlazeProjectDataManager.getInstance(project).getBlazeProjectData(); diff --git a/aswb/src/com/google/idea/blaze/android/run/BlazeAndroidRunConfigurationValidationUtil.java b/aswb/src/com/google/idea/blaze/android/run/BlazeAndroidRunConfigurationValidationUtil.java index c717407a075..f06e9fff494 100644 --- a/aswb/src/com/google/idea/blaze/android/run/BlazeAndroidRunConfigurationValidationUtil.java +++ b/aswb/src/com/google/idea/blaze/android/run/BlazeAndroidRunConfigurationValidationUtil.java @@ -33,7 +33,7 @@ import com.intellij.openapi.project.Project; import java.util.List; import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.android.sdk.AndroidPlatformsCompat; +import org.jetbrains.android.sdk.AndroidPlatforms; import org.jetbrains.android.util.AndroidBundle; /** @@ -80,7 +80,7 @@ public static List validateWorkspaceModule(Project project) { "Android model missing from workspace module. Please resync project.", () -> resync(project))); } - if (AndroidPlatformsCompat.getInstance(workspaceModule) == null) { + if (AndroidPlatforms.getInstance(workspaceModule) == null) { errors.add(ValidationError.fatal(AndroidBundle.message("select.platform.error"))); } return errors; diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryApplicationLaunchTaskProvider.java b/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryApplicationLaunchTaskProvider.java similarity index 100% rename from aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryApplicationLaunchTaskProvider.java rename to aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryApplicationLaunchTaskProvider.java diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java b/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java similarity index 98% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java rename to aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java index 01af2003452..1d134314d6e 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java +++ b/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContext.java @@ -15,6 +15,7 @@ */ package com.google.idea.blaze.android.run.binary; +import com.android.ddmlib.ClientData; import com.android.ddmlib.IDevice; import com.android.tools.idea.execution.common.debug.AndroidDebugger; import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; @@ -42,7 +43,6 @@ import kotlinx.coroutines.BuildersKt; import org.jetbrains.android.facet.AndroidFacet; -/** Compat for #api212 */ public class BlazeAndroidBinaryNormalBuildRunContext extends BlazeAndroidBinaryNormalBuildRunContextBase { BlazeAndroidBinaryNormalBuildRunContext( @@ -117,6 +117,7 @@ public XDebugSession startDebuggerSession( indicator, consoleView, 15L, + ClientData.DebuggerStatus.WAITING, continuation)); } catch (InterruptedException e) { throw new ProcessCanceledException(); diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java b/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java similarity index 99% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java rename to aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java index 96f3f8be324..79e00886994 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java +++ b/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryNormalBuildRunContextBase.java @@ -19,7 +19,6 @@ import com.android.ddmlib.IDevice; import com.android.tools.idea.execution.common.DeployOptions; -import com.android.tools.idea.gradle.util.DynamicAppUtils; import com.android.tools.idea.run.ApkFileUnit; import com.android.tools.idea.run.ApkInfo; import com.android.tools.idea.run.ApkProvider; @@ -30,6 +29,7 @@ import com.android.tools.idea.run.blaze.BlazeLaunchTask; import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; import com.android.tools.idea.run.editor.ProfilerState; +import com.android.tools.idea.util.DynamicAppUtils; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.idea.blaze.android.run.deployinfo.BlazeApkProviderService; diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryProgramRunner.java b/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryProgramRunner.java similarity index 100% rename from aswb/sdkcompat/as231/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryProgramRunner.java rename to aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryProgramRunner.java diff --git a/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandler.java b/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandler.java index 1e62fed2087..c31ad4cbad5 100644 --- a/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandler.java +++ b/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandler.java @@ -28,7 +28,7 @@ import com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationValidationUtil; import com.google.idea.blaze.android.run.LaunchMetrics; import com.google.idea.blaze.android.run.binary.AndroidBinaryLaunchMethodsUtils.AndroidBinaryLaunchMethod; -import com.google.idea.blaze.android.run.binary.mobileinstall.BlazeAndroidBinaryMobileInstallRunContextCompat; +import com.google.idea.blaze.android.run.binary.mobileinstall.BlazeAndroidBinaryMobileInstallRunContext; import com.google.idea.blaze.android.run.runner.ApkBuildStep; import com.google.idea.blaze.android.run.runner.BlazeAndroidRunConfigurationRunner; import com.google.idea.blaze.android.run.runner.BlazeAndroidRunContext; @@ -68,7 +68,7 @@ * android_binary targets. */ public class BlazeAndroidBinaryRunConfigurationHandler - extends BlazeAndroidBinaryRunConfigurationHandlerCompat + extends BlazeAndroidBinaryRunConfigurationHandlerTestHelper implements BlazeAndroidRunConfigurationHandler { @VisibleForTesting @@ -147,7 +147,7 @@ public BlazeCommandRunConfigurationRunner createRunner( switch (configState.getLaunchMethod()) { case NON_BLAZE: runContext = - new BlazeAndroidBinaryNormalBuildRunContextCompat( + new BlazeAndroidBinaryNormalBuildRunContext( project, facet, configuration, env, configState, buildStep, launchId); break; case MOBILE_INSTALL_V2: @@ -156,7 +156,7 @@ public BlazeCommandRunConfigurationRunner createRunner( // fall through case MOBILE_INSTALL: runContext = - new BlazeAndroidBinaryMobileInstallRunContextCompat( + new BlazeAndroidBinaryMobileInstallRunContext( project, facet, configuration, env, configState, buildStep, launchId); break; default: diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerCompat.java b/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerTestHelper.java similarity index 86% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerCompat.java rename to aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerTestHelper.java index 188f6e6b844..eab92c983a6 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerCompat.java +++ b/aswb/src/com/google/idea/blaze/android/run/binary/BlazeAndroidBinaryRunConfigurationHandlerTestHelper.java @@ -21,13 +21,13 @@ import com.google.idea.blaze.base.settings.Blaze; import com.intellij.openapi.project.Project; -/** Compat class for {@link BlazeAndroidBinaryRunConfigurationHandlerCompat}. */ -public class BlazeAndroidBinaryRunConfigurationHandlerCompat { +/** Test Helper class for {@link BlazeAndroidBinaryRunConfigurationHandlerTestHelper}. */ +public class BlazeAndroidBinaryRunConfigurationHandlerTestHelper { protected final Project project; protected final BlazeAndroidBinaryRunConfigurationState configState; @VisibleForTesting - protected BlazeAndroidBinaryRunConfigurationHandlerCompat( + protected BlazeAndroidBinaryRunConfigurationHandlerTestHelper( BlazeCommandRunConfiguration configuration) { project = configuration.getProject(); configState = diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java b/aswb/src/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java similarity index 94% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java rename to aswb/src/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java index bc567e3ff30..a9986ad85f0 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java +++ b/aswb/src/com/google/idea/blaze/android/run/binary/DeploymentTimingReporterTask.java @@ -19,7 +19,7 @@ import com.android.tools.idea.run.ApkInfo; import com.android.tools.idea.run.blaze.BlazeLaunchContext; import com.android.tools.idea.run.blaze.BlazeLaunchTask; -import com.android.tools.idea.run.tasks.DeployTasksCompat; +import com.android.tools.idea.run.tasks.DeployTasksHelper; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; @@ -37,7 +37,7 @@ public class DeploymentTimingReporterTask implements BlazeLaunchTask { public DeploymentTimingReporterTask( String launchId, Project project, Collection packages, DeployOptions deployOptions) { this.launchId = launchId; - this.deployTask = DeployTasksCompat.createDeployTask(project, packages, deployOptions); + this.deployTask = DeployTasksHelper.createDeployTask(project, packages, deployOptions); this.packages = ImmutableList.copyOf(packages); } diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java b/aswb/src/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java similarity index 98% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java rename to aswb/src/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java index 1d04c7b4e95..771363e7250 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java +++ b/aswb/src/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContext.java @@ -15,6 +15,7 @@ */ package com.google.idea.blaze.android.run.binary.mobileinstall; +import com.android.ddmlib.ClientData; import com.android.ddmlib.IDevice; import com.android.tools.idea.execution.common.debug.AndroidDebugger; import com.android.tools.idea.execution.common.debug.AndroidDebuggerState; @@ -121,6 +122,7 @@ public XDebugSession startDebuggerSession( indicator, consoleView, 15L, + ClientData.DebuggerStatus.WAITING, continuation)); } catch (InterruptedException e) { throw new ProcessCanceledException(e); diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextBase.java b/aswb/src/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextBase.java similarity index 100% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextBase.java rename to aswb/src/com/google/idea/blaze/android/run/binary/mobileinstall/BlazeAndroidBinaryMobileInstallRunContextBase.java diff --git a/aswb/src/com/google/idea/blaze/android/run/binary/mobileinstall/MobileInstallBuildStep.java b/aswb/src/com/google/idea/blaze/android/run/binary/mobileinstall/MobileInstallBuildStep.java index 9f2d5cec421..33c61d697f2 100644 --- a/aswb/src/com/google/idea/blaze/android/run/binary/mobileinstall/MobileInstallBuildStep.java +++ b/aswb/src/com/google/idea/blaze/android/run/binary/mobileinstall/MobileInstallBuildStep.java @@ -65,6 +65,7 @@ import com.intellij.openapi.project.Project; import java.io.File; import java.net.InetSocketAddress; +import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.CancellationException; import javax.annotation.Nullable; @@ -155,7 +156,7 @@ public void build(BlazeContext context, BlazeAndroidDeviceSelector.DeviceSession Blaze.getBuildSystemProvider(project) .getBuildSystem() .getBuildInvoker(project, context, BlazeCommandName.MOBILE_INSTALL); - BlazeCommand.Builder command = BlazeCommand.builder(invoker, BlazeCommandName.MOBILE_INSTALL, project); + BlazeCommand.Builder command = BlazeCommand.builder(invoker, BlazeCommandName.MOBILE_INSTALL); if (passAdbArgWithSerialToMi.getValue()) { // Redundant, but we need this to get around bug in bazel. @@ -279,17 +280,18 @@ public BlazeAndroidDeployInfo getDeployInfo() throws ApkProvisionException { } private static AdbTunnelConfigurator getTunnelConfigurator(BlazeContext context) { - try { - AdbTunnelConfigurator configurator = - Iterables.getOnlyElement(AdbTunnelConfiguratorProvider.EP_NAME.getExtensionList()) - .createConfigurator(context); + List extensions = + AdbTunnelConfiguratorProvider.EP_NAME.getExtensionList(); + if (extensions.size() > 1) { + // This is fine in tests. + log.warn("More than one provider registered; Using the first one!\n" + extensions); + } + // Fail quietly when there's no configurable registered. + if (!extensions.isEmpty()) { + AdbTunnelConfigurator configurator = extensions.get(0).createConfigurator(context); if (configurator != null) { return configurator; } - } catch (NoSuchElementException ex) { - // Fail quietly when there's no configurable registered. - } catch (IllegalArgumentException ex) { - log.warn("More than one provider registered; there should only be one!"); } return new AdbTunnelConfigurator() { @Override diff --git a/aswb/src/com/google/idea/blaze/android/run/deployinfo/BlazeApkDeployInfoProtoHelper.java b/aswb/src/com/google/idea/blaze/android/run/deployinfo/BlazeApkDeployInfoProtoHelper.java index f4bbf2162f2..aa369a0861b 100644 --- a/aswb/src/com/google/idea/blaze/android/run/deployinfo/BlazeApkDeployInfoProtoHelper.java +++ b/aswb/src/com/google/idea/blaze/android/run/deployinfo/BlazeApkDeployInfoProtoHelper.java @@ -17,7 +17,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.rules.android.deployinfo.AndroidDeployInfoOuterClass.AndroidDeployInfo; import com.google.devtools.build.lib.rules.android.deployinfo.AndroidDeployInfoOuterClass.Artifact; import com.google.idea.blaze.android.manifest.ManifestParser.ParsedManifest; @@ -30,7 +29,6 @@ import com.google.idea.blaze.common.artifact.OutputArtifact; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; -import com.intellij.util.containers.ContainerUtil; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -47,7 +45,7 @@ public class BlazeApkDeployInfoProtoHelper { public AndroidDeployInfo readDeployInfoProtoForTarget( Label target, BuildResultHelper buildResultHelper, Predicate pathFilter) throws GetDeployInfoException { - ImmutableSet outputArtifacts; + ImmutableList outputArtifacts; try { outputArtifacts = buildResultHelper.getBuildArtifactsForTarget(target, pathFilter); } catch (GetArtifactsException e) { @@ -61,10 +59,10 @@ public AndroidDeployInfo readDeployInfoProtoForTarget( log.warn("Local execroot: " + bepOutput.getLocalExecRoot()); log.warn("All output artifacts:"); for (OutputArtifact outputArtifact : bepOutput.getAllOutputArtifacts(path -> true)) { - log.warn(outputArtifact.getRelativePath() + " -> " + outputArtifact.getRelativePath()); + log.warn(outputArtifact.getBazelOutRelativePath() + " -> " + outputArtifact.getBazelOutRelativePath()); } log.warn("All local artifacts for " + target + ":"); - ImmutableSet allBuildArtifacts = + List allBuildArtifacts = buildResultHelper.getBuildArtifactsForTarget(target, path -> true); List allLocalFiles = LocalFileArtifact.getLocalFiles(allBuildArtifacts); for (File file : allLocalFiles) { @@ -85,11 +83,11 @@ public AndroidDeployInfo readDeployInfoProtoForTarget( throw new GetDeployInfoException( "More than one deploy info proto artifact found: " + outputArtifacts.stream() - .map(OutputArtifact::getRelativePath) + .map(OutputArtifact::getBazelOutRelativePath) .collect(Collectors.joining(", ", "[", "]"))); } - try (InputStream inputStream = ContainerUtil.getFirstItem(outputArtifacts).getInputStream()) { + try (InputStream inputStream = outputArtifacts.get(0).getInputStream()) { return AndroidDeployInfo.parseFrom(inputStream); } catch (IOException e) { throw new GetDeployInfoException(e.getMessage()); diff --git a/aswb/src/com/google/idea/blaze/android/run/deployinfo/BlazeApkProviderService.java b/aswb/src/com/google/idea/blaze/android/run/deployinfo/BlazeApkProviderService.java index 1683c989eef..e89caf6c251 100644 --- a/aswb/src/com/google/idea/blaze/android/run/deployinfo/BlazeApkProviderService.java +++ b/aswb/src/com/google/idea/blaze/android/run/deployinfo/BlazeApkProviderService.java @@ -17,13 +17,13 @@ import com.android.tools.idea.run.ApkProvider; import com.google.idea.blaze.android.run.runner.ApkBuildStep; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; /** Service to provide ApkProviders that source APKs from {@link ApkBuildStep}. */ public interface BlazeApkProviderService { static BlazeApkProviderService getInstance() { - return ServiceManager.getService(BlazeApkProviderService.class); + return ApplicationManager.getApplication().getService(BlazeApkProviderService.class); } /** Returns an APK provider that sources APKs from the given {@link ApkBuildStep}. */ diff --git a/aswb/src/com/google/idea/blaze/android/run/runner/AaptUtil.java b/aswb/src/com/google/idea/blaze/android/run/runner/AaptUtil.java index 6a9f2f3f96f..9f3db2b35c4 100644 --- a/aswb/src/com/google/idea/blaze/android/run/runner/AaptUtil.java +++ b/aswb/src/com/google/idea/blaze/android/run/runner/AaptUtil.java @@ -17,6 +17,7 @@ import com.android.sdklib.BuildToolInfo; import com.android.sdklib.BuildToolInfo.PathId; +import com.android.tools.sdk.AndroidPlatform; import com.google.idea.blaze.android.sync.sdk.SdkUtil; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; @@ -30,7 +31,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; -import org.jetbrains.android.sdk.AndroidPlatformCompat; /** A collection of utilities for extracting information from APKs using aapt. */ public final class AaptUtil { @@ -69,12 +69,12 @@ private static MatchResult getAaptBadging(Project project, File apk, Pattern pat if (!apk.exists()) { throw new AaptUtilException("apk file does not exist: " + apk); } - AndroidPlatformCompat androidPlatform = SdkUtil.getAndroidPlatform(project); + AndroidPlatform androidPlatform = SdkUtil.getAndroidPlatform(project); if (androidPlatform == null) { throw new AaptUtilException( "Could not find Android platform sdk for project " + project.getName()); } - BuildToolInfo toolInfo = androidPlatform.getLatestBuildTool(true); + BuildToolInfo toolInfo = androidPlatform.getSdkData().getLatestBuildTool(true); if (toolInfo == null) { throw new AaptUtilException( "Could not find Android sdk build-tools for project " + project.getName()); diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidDebuggerService.java b/aswb/src/com/google/idea/blaze/android/run/runner/BlazeAndroidDebuggerService.java similarity index 100% rename from aswb/sdkcompat/as231/com/google/idea/blaze/android/run/runner/BlazeAndroidDebuggerService.java rename to aswb/src/com/google/idea/blaze/android/run/runner/BlazeAndroidDebuggerService.java diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java b/aswb/src/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java similarity index 99% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java rename to aswb/src/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java index a1528a9c4d9..bd9c151ac78 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java +++ b/aswb/src/com/google/idea/blaze/android/run/runner/BlazeAndroidLaunchTasksProvider.java @@ -97,7 +97,7 @@ public List getTasks(@NotNull IDevice device, boolean isDebug) pmInstallOption = userIdFlags; } DeployOptions deployOptions = - new DeployOptions(Collections.emptyList(), pmInstallOption, false, false); + new DeployOptions(Collections.emptyList(), pmInstallOption, false, false, false); ImmutableList deployTasks = runContext.getDeployTasks(device, deployOptions); launchTasks.addAll(deployTasks); } diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java b/aswb/src/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java similarity index 96% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java rename to aswb/src/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java index 364a7f9a1ca..0a1215b5b82 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java +++ b/aswb/src/com/google/idea/blaze/android/run/runner/BlazeAndroidRunConfigurationRunner.java @@ -27,7 +27,6 @@ import com.android.tools.idea.execution.common.stats.RunStats; import com.android.tools.idea.projectsystem.ApplicationProjectContext; import com.android.tools.idea.run.ApkProvider; -import com.android.tools.idea.run.ApplicationIdProvider; import com.android.tools.idea.run.DeviceFutures; import com.android.tools.idea.run.LaunchOptions; import com.android.tools.idea.run.blaze.BlazeAndroidConfigurationExecutor; @@ -174,14 +173,14 @@ public final RunProfileState getRunProfileState(final Executor executor, Executi final LaunchOptions launchOptions = launchOptionsBuilder.build(); BlazeAndroidConfigurationExecutor runner = new BlazeAndroidConfigurationExecutor( - runContext.getConsoleProvider(), - runContext.getApplicationIdProvider(), - env, - deviceFutures, - runContext.getLaunchTasksProvider(launchOptions), - launchOptions, - apkProvider, - LiveEditService.getInstance(env.getProject())); + runContext.getConsoleProvider(), + runContext.getApplicationProjectContext(), + env, + deviceFutures, + runContext.getLaunchTasksProvider(launchOptions), + launchOptions, + apkProvider, + LiveEditService.getInstance(env.getProject())); return new AndroidConfigurationExecutorRunProfileState(runner); } @@ -194,7 +193,7 @@ private RunProfileState getWearExecutor( @NotNull @Override public DeployOptions getDeployOptions() { - return new DeployOptions(Collections.emptyList(), "", true, true); + return new DeployOptions(Collections.emptyList(), "", true, true, false); } @NotNull @@ -210,7 +209,6 @@ public Module getModule() { }; AndroidConfigurationExecutor configurationExecutor; - ApplicationIdProvider appIdProvider = runContext.getApplicationIdProvider(); ApplicationProjectContext applicationProjectContext = runContext.getApplicationProjectContext(); ApkProvider apkProvider = BlazeApkProviderService.getInstance() @@ -228,7 +226,6 @@ public Module getModule() { env, deviceFutures, settings, - appIdProvider, apkProvider, applicationProjectContext, deployer); @@ -238,7 +235,6 @@ public Module getModule() { env, deviceFutures, settings, - appIdProvider, apkProvider, applicationProjectContext, deployer); @@ -248,7 +244,6 @@ public Module getModule() { env, deviceFutures, settings, - appIdProvider, apkProvider, applicationProjectContext, deployer); diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidRunContext.java b/aswb/src/com/google/idea/blaze/android/run/runner/BlazeAndroidRunContext.java similarity index 100% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/BlazeAndroidRunContext.java rename to aswb/src/com/google/idea/blaze/android/run/runner/BlazeAndroidRunContext.java diff --git a/aswb/src/com/google/idea/blaze/android/run/runner/BlazeInstrumentationTestApkBuildStep.java b/aswb/src/com/google/idea/blaze/android/run/runner/BlazeInstrumentationTestApkBuildStep.java index f43cae9cb57..1537feac26f 100644 --- a/aswb/src/com/google/idea/blaze/android/run/runner/BlazeInstrumentationTestApkBuildStep.java +++ b/aswb/src/com/google/idea/blaze/android/run/runner/BlazeInstrumentationTestApkBuildStep.java @@ -88,7 +88,7 @@ public void build(BlazeContext context, BlazeAndroidDeviceSelector.DeviceSession BuildInvoker invoker = Blaze.getBuildSystemProvider(project).getBuildSystem().getBuildInvoker(project, context); - BlazeCommand.Builder command = BlazeCommand.builder(invoker, BlazeCommandName.BUILD, project); + BlazeCommand.Builder command = BlazeCommand.builder(invoker, BlazeCommandName.BUILD); WorkspaceRoot workspaceRoot = WorkspaceRoot.fromProject(project); // TODO(mathewi) we implicitly rely here on the fact that the getBuildInvoker() call above diff --git a/aswb/src/com/google/idea/blaze/android/run/runner/FullApkBuildStep.java b/aswb/src/com/google/idea/blaze/android/run/runner/FullApkBuildStep.java index bd9d96850e0..72e4cbad18a 100644 --- a/aswb/src/com/google/idea/blaze/android/run/runner/FullApkBuildStep.java +++ b/aswb/src/com/google/idea/blaze/android/run/runner/FullApkBuildStep.java @@ -17,6 +17,7 @@ import static java.util.stream.Collectors.joining; +import com.android.annotations.Nullable; import com.android.tools.idea.run.ApkProvisionException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; @@ -72,6 +73,7 @@ public class FullApkBuildStep implements ApkBuildStep { private final BlazeApkDeployInfoProtoHelper deployInfoHelper; private final boolean nativeDebuggingEnabled; private BlazeAndroidDeployInfo deployInfo = null; + @Nullable private final List defaultNativeSymbolFinderList; @VisibleForTesting public FullApkBuildStep( @@ -79,12 +81,14 @@ public FullApkBuildStep( Label label, ImmutableList buildFlags, boolean nativeDebuggingEnabled, - BlazeApkDeployInfoProtoHelper deployInfoHelper) { + BlazeApkDeployInfoProtoHelper deployInfoHelper, + List defaultNativeSymbolFinderList) { this.project = project; this.label = label; this.buildFlags = buildFlags; this.deployInfoHelper = deployInfoHelper; this.nativeDebuggingEnabled = nativeDebuggingEnabled; + this.defaultNativeSymbolFinderList = defaultNativeSymbolFinderList; } public FullApkBuildStep( @@ -92,7 +96,13 @@ public FullApkBuildStep( Label label, ImmutableList buildFlags, boolean nativeDebuggingEnabled) { - this(project, label, buildFlags, nativeDebuggingEnabled, new BlazeApkDeployInfoProtoHelper()); + this( + project, + label, + buildFlags, + nativeDebuggingEnabled, + new BlazeApkDeployInfoProtoHelper(), + null); } private static boolean apksRequireDownload(BlazeAndroidDeployInfo deployInfo) { @@ -146,6 +156,13 @@ private static File downloadLibIfRemote(File lib, BlazeContext context) { return lib; } + private List getNativeSymbolFinderList() { + if (defaultNativeSymbolFinderList != null) { + return defaultNativeSymbolFinderList; + } + return NativeSymbolFinder.EP_NAME.getExtensionList(); + } + @Override public void build(BlazeContext context, BlazeAndroidDeviceSelector.DeviceSession deviceSession) { BlazeProjectData projectData = @@ -158,12 +175,11 @@ public void build(BlazeContext context, BlazeAndroidDeviceSelector.DeviceSession BuildInvoker invoker = Blaze.getBuildSystemProvider(project).getBuildSystem().getBuildInvoker(project, context); - BlazeCommand.Builder command = BlazeCommand.builder(invoker, BlazeCommandName.BUILD, project); + BlazeCommand.Builder command = BlazeCommand.builder(invoker, BlazeCommandName.BUILD); WorkspaceRoot workspaceRoot = WorkspaceRoot.fromProject(project); try (BuildResultHelper buildResultHelper = invoker.createBuildResultHelper()) { - List nativeSymbolFinderList = - NativeSymbolFinder.EP_NAME.getExtensionList(); + List nativeSymbolFinderList = getNativeSymbolFinderList(); command.addTargets(label).addBlazeFlags("--output_groups=+android_deploy_info"); if (!nativeSymbolFinderList.isEmpty()) { diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/MobileInstallApplicationDeployer.java b/aswb/src/com/google/idea/blaze/android/run/runner/MobileInstallApplicationDeployer.java similarity index 100% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/runner/MobileInstallApplicationDeployer.java rename to aswb/src/com/google/idea/blaze/android/run/runner/MobileInstallApplicationDeployer.java diff --git a/aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestLaunchTask.java b/aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestLaunchTask.java index f505e849402..dc7dd974c06 100644 --- a/aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestLaunchTask.java +++ b/aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestLaunchTask.java @@ -26,6 +26,8 @@ import com.google.idea.blaze.base.command.BlazeCommandName; import com.google.idea.blaze.base.command.BlazeFlags; import com.google.idea.blaze.base.command.buildresult.BuildResultHelper; +import com.google.idea.blaze.base.command.buildresult.BuildResultHelper.GetArtifactsException; +import com.google.idea.blaze.base.command.buildresult.BuildResultHelperBep; import com.google.idea.blaze.base.filecache.FileCaches; import com.google.idea.blaze.base.ideinfo.AndroidInstrumentationInfo; import com.google.idea.blaze.base.ideinfo.TargetIdeInfo; @@ -155,8 +157,7 @@ public void run(@NotNull BlazeLaunchContext launchContext) Blaze.getBuildSystemProvider(project) .getBuildSystem() .getBuildInvoker(project, context), - BlazeCommandName.TEST, - project) + BlazeCommandName.TEST) .addTargets(target); // Build flags must match BlazeBeforeRunTask. commandBuilder.addBlazeFlags(buildFlags); @@ -193,7 +194,7 @@ public void run(@NotNull BlazeLaunchContext launchContext) String.format("Starting %s test...\n", Blaze.buildSystemName(project))); int retVal; - try (final var buildResultHelper = new BuildResultHelper()) { + try (BuildResultHelper buildResultHelper = new BuildResultHelperBep()) { commandBuilder.addBlazeFlags(buildResultHelper.getBuildFlags()); BlazeCommand command = commandBuilder.build(); ExecutionUtils.println(console, command + "\n"); @@ -210,13 +211,16 @@ public void run(@NotNull BlazeLaunchContext launchContext) if (retVal != 0) { context.setHasError(); } else { - testResultsHolder.setTestResults(buildResultHelper.getTestResults()); + testResultsHolder.setTestResults( + buildResultHelper.getTestResults(Optional.empty())); } ListenableFuture unusedFuture = FileCaches.refresh( project, context, BlazeBuildOutputs.noOutputs(BuildResult.fromExitCode(retVal))); + } catch (GetArtifactsException e) { + LOG.error(e.getMessage()); } return !context.hasErrors(); })); diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/test/BlazeAndroidTestProgramRunner.java b/aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestProgramRunner.java similarity index 100% rename from aswb/sdkcompat/as231/com/google/idea/blaze/android/run/test/BlazeAndroidTestProgramRunner.java rename to aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestProgramRunner.java diff --git a/aswb/sdkcompat/as231/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunConfigurationHandler.java b/aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunConfigurationHandler.java similarity index 100% rename from aswb/sdkcompat/as231/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunConfigurationHandler.java rename to aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunConfigurationHandler.java diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java b/aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java similarity index 98% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java rename to aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java index 8f5df7f82fd..f54c5ff92f4 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java +++ b/aswb/src/com/google/idea/blaze/android/run/test/BlazeAndroidTestRunContext.java @@ -17,6 +17,7 @@ import static com.google.idea.blaze.android.run.binary.BlazeAndroidBinaryNormalBuildRunContextBase.getApkInfoToInstall; +import com.android.ddmlib.ClientData; import com.android.ddmlib.IDevice; import com.android.tools.idea.execution.common.DeployOptions; import com.android.tools.idea.execution.common.debug.AndroidDebugger; @@ -31,7 +32,7 @@ import com.android.tools.idea.run.blaze.BlazeLaunchTask; import com.android.tools.idea.run.blaze.BlazeLaunchTasksProvider; import com.android.tools.idea.run.editor.ProfilerState; -import com.android.tools.idea.run.tasks.DeployTasksCompat; +import com.android.tools.idea.run.tasks.DeployTasksHelper; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.idea.blaze.android.run.BazelApplicationProjectContext; @@ -164,7 +165,7 @@ public ImmutableList getDeployTasks(IDevice device, DeployOptio return ImmutableList.of(); } return ImmutableList.of( - DeployTasksCompat.createDeployTask( + DeployTasksHelper.createDeployTask( project, getApkInfoToInstall(device, deployOptions, apkProvider), deployOptions)); } @@ -255,6 +256,7 @@ public XDebugSession startDebuggerSession( indicator, consoleView, Long.MAX_VALUE, + ClientData.DebuggerStatus.WAITING, continuation); } throw new RuntimeException("Unknown lunch mode"); diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java b/aswb/src/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java similarity index 93% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java rename to aswb/src/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java index fa96a5dc6e1..599f2c90061 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java +++ b/aswb/src/com/google/idea/blaze/android/run/testrecorder/TestRecorderBlazeCommandRunConfigurationProxy.java @@ -18,7 +18,7 @@ import com.google.idea.blaze.android.cppimpl.debug.BlazeAutoAndroidDebuggerBase; import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration; -/** Compat class for implementing TestRecorderBlazeCommandRunConfigurationProxy. */ +/** Implementation of TestRecorderBlazeCommandRunConfigurationProxy. */ public class TestRecorderBlazeCommandRunConfigurationProxy extends TestRecorderBlazeCommandRunConfigurationProxyBase { diff --git a/aswb/src/com/google/idea/blaze/android/sdk/BlazeSdkProvider.java b/aswb/src/com/google/idea/blaze/android/sdk/BlazeSdkProvider.java index 866351d88ee..2a5e43fe22e 100644 --- a/aswb/src/com/google/idea/blaze/android/sdk/BlazeSdkProvider.java +++ b/aswb/src/com/google/idea/blaze/android/sdk/BlazeSdkProvider.java @@ -15,7 +15,7 @@ */ package com.google.idea.blaze.android.sdk; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.projectRoots.Sdk; import java.util.List; import javax.annotation.Nullable; @@ -23,7 +23,7 @@ /** Indirection to Sdks for testing purposes. */ public interface BlazeSdkProvider { static BlazeSdkProvider getInstance() { - return ServiceManager.getService(BlazeSdkProvider.class); + return ApplicationManager.getApplication().getService(BlazeSdkProvider.class); } List getAllAndroidSdks(); diff --git a/aswb/src/com/google/idea/blaze/android/sdk/BlazeSdkProviderImpl.java b/aswb/src/com/google/idea/blaze/android/sdk/BlazeSdkProviderImpl.java index b4481f9ab32..c45d330e9b9 100644 --- a/aswb/src/com/google/idea/blaze/android/sdk/BlazeSdkProviderImpl.java +++ b/aswb/src/com/google/idea/blaze/android/sdk/BlazeSdkProviderImpl.java @@ -16,7 +16,7 @@ package com.google.idea.blaze.android.sdk; import com.android.repository.api.ProgressIndicator; -import com.android.tools.idea.progress.StudioLoggerProgressIndicatorCompat; +import com.android.tools.idea.progress.StudioLoggerProgressIndicator; import com.android.tools.idea.sdk.AndroidSdks; import com.android.tools.idea.sdk.IdeSdks; import com.google.idea.blaze.android.sync.sdk.SdkUtil; @@ -25,7 +25,6 @@ import java.util.List; import javax.annotation.Nullable; import org.jetbrains.android.sdk.AndroidSdkAdditionalData; -import org.jetbrains.android.sdk.AndroidSdkAdditionalDataCompat; /** Indirection to Sdks for testing purposes. */ public class BlazeSdkProviderImpl implements BlazeSdkProvider { @@ -45,7 +44,7 @@ public Sdk findSdk(String targetHash) { // We may have an android platform downloaded, but not created an IntelliJ SDK out of it. // If so, trigger the construction of an SDK ProgressIndicator progress = - new StudioLoggerProgressIndicatorCompat(BlazeSdkProviderImpl.class); + new StudioLoggerProgressIndicator(BlazeSdkProviderImpl.class); androidSdks.tryToChooseSdkHandler().getSdkManager(progress).reloadLocalIfNeeded(progress); return UIUtil.invokeAndWaitIfNeeded( @@ -55,7 +54,7 @@ public Sdk findSdk(String targetHash) { @Override @Nullable public String getSdkTargetHash(Sdk sdk) { - AndroidSdkAdditionalData additionalData = AndroidSdkAdditionalDataCompat.from(sdk); + AndroidSdkAdditionalData additionalData = AndroidSdkAdditionalData.from(sdk); if (additionalData == null) { return null; } diff --git a/aswb/src/com/google/idea/blaze/android/settings/BlazeAndroidUserSettings.java b/aswb/src/com/google/idea/blaze/android/settings/BlazeAndroidUserSettings.java index 81176577075..919c169c9c9 100644 --- a/aswb/src/com/google/idea/blaze/android/settings/BlazeAndroidUserSettings.java +++ b/aswb/src/com/google/idea/blaze/android/settings/BlazeAndroidUserSettings.java @@ -15,8 +15,8 @@ */ package com.google.idea.blaze.android.settings; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; -import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.util.xmlb.XmlSerializerUtil; @@ -30,7 +30,7 @@ public class BlazeAndroidUserSettings private boolean useLayoutEditor = false; public static BlazeAndroidUserSettings getInstance() { - return ServiceManager.getService(BlazeAndroidUserSettings.class); + return ApplicationManager.getApplication().getService(BlazeAndroidUserSettings.class); } @Override diff --git a/aswb/src/com/google/idea/blaze/android/sync/BlazeNdkDependencySyncPlugin.java b/aswb/src/com/google/idea/blaze/android/sync/BlazeNdkDependencySyncPlugin.java index 8e323a36657..e945650f37d 100644 --- a/aswb/src/com/google/idea/blaze/android/sync/BlazeNdkDependencySyncPlugin.java +++ b/aswb/src/com/google/idea/blaze/android/sync/BlazeNdkDependencySyncPlugin.java @@ -80,7 +80,7 @@ private static void notifyMissingPlugin(BlazeContext context, PluginNameAndId pl + "Click here to install/enable it, then restart the IDE", plugin.name); IssueOutput.error(msg) - .withNavigatable(PluginUtils.installOrEnablePluginNavigable(plugin.id)) + .navigatable(PluginUtils.installOrEnablePluginNavigable(plugin.id)) .submit(context); } } diff --git a/aswb/src/com/google/idea/blaze/android/sync/importer/BlazeAndroidWorkspaceImporter.java b/aswb/src/com/google/idea/blaze/android/sync/importer/BlazeAndroidWorkspaceImporter.java index 999a810506e..62a41bf8ba5 100644 --- a/aswb/src/com/google/idea/blaze/android/sync/importer/BlazeAndroidWorkspaceImporter.java +++ b/aswb/src/com/google/idea/blaze/android/sync/importer/BlazeAndroidWorkspaceImporter.java @@ -41,10 +41,10 @@ import com.google.idea.blaze.base.model.primitives.Label; import com.google.idea.blaze.base.scope.BlazeContext; import com.google.idea.blaze.base.scope.output.IssueOutput; +import com.google.idea.blaze.base.scope.output.IssueOutput.Category; import com.google.idea.blaze.base.scope.output.PerformanceWarning; import com.google.idea.blaze.common.Output; import com.google.idea.common.experiments.BoolExperiment; -import com.intellij.build.events.MessageEvent.Kind; import com.intellij.openapi.project.Project; import java.util.Collection; import java.util.Collections; @@ -327,7 +327,7 @@ private ImmutableList buildAndroidResourceModules( if (mergeResourcesEnabled.getValue()) { messageBuilder.append(" ").append("Merging Resources...").append("\n"); String message = messageBuilder.toString(); - context.accept(IssueOutput.issue(Kind.INFO, message).build()); + context.accept(IssueOutput.issue(Category.INFORMATION, message).build()); result.add(mergeAndroidResourceModules(androidResourceModulesWithJavaPackage)); } else { diff --git a/aswb/src/com/google/idea/blaze/android/sync/importer/BlazeImportUtil.java b/aswb/src/com/google/idea/blaze/android/sync/importer/BlazeImportUtil.java index 8e806f54bd2..1b2ab3540f9 100644 --- a/aswb/src/com/google/idea/blaze/android/sync/importer/BlazeImportUtil.java +++ b/aswb/src/com/google/idea/blaze/android/sync/importer/BlazeImportUtil.java @@ -39,7 +39,6 @@ import com.google.idea.blaze.base.sync.projectview.ProjectViewTargetImportFilter; import com.google.idea.blaze.common.Output; import com.google.idea.blaze.java.sync.model.BlazeJarLibrary; -import com.intellij.build.events.MessageEvent.Kind; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import java.util.Collection; @@ -111,7 +110,8 @@ static Consumer asConsumer(BlazeContext context) { context.output(issue); if (issue instanceof IssueOutput) { IssueOutput issueOutput = (IssueOutput) issue; - if (issueOutput.getKind() == Kind.ERROR) { + if (issueOutput.getCategory() + == com.google.idea.blaze.base.scope.output.IssueOutput.Category.ERROR) { context.setHasError(); } } diff --git a/aswb/src/com/google/idea/blaze/android/sync/importer/problems/GeneratedResourceWarnings.java b/aswb/src/com/google/idea/blaze/android/sync/importer/problems/GeneratedResourceWarnings.java index 7edd9de643c..81641227959 100644 --- a/aswb/src/com/google/idea/blaze/android/sync/importer/problems/GeneratedResourceWarnings.java +++ b/aswb/src/com/google/idea/blaze/android/sync/importer/problems/GeneratedResourceWarnings.java @@ -71,7 +71,9 @@ public static void submit( + "Double-click to add to project view if needed to resolve" + " references.", interestingDirectories.size())) - .withFile(projectViewFile) + .inFile(projectViewFile) + .onLine(1) + .inColumn(1) .build()); for (Map.Entry entry : interestingDirectories.entrySet()) { context.accept( @@ -79,7 +81,10 @@ public static void submit( String.format( "Dropping generated resource directory '%s' w/ %d subdirs", entry.getKey(), entry.getValue())) - .withFile(projectViewFile) + .inFile(projectViewFile) + .navigatable( + new AddGeneratedResourceDirectoryNavigatable( + project, projectViewFile, entry.getKey())) .build()); } } @@ -93,7 +98,7 @@ public static void submit( unusedAllowlistEntries.size(), GeneratedAndroidResourcesSection.KEY.getName(), String.join("\n ", unusedAllowlistEntries))) - .withFile(projectViewFile) + .inFile(projectViewFile) .build()); } } diff --git a/aswb/src/com/google/idea/blaze/android/sync/model/AarLibrary.java b/aswb/src/com/google/idea/blaze/android/sync/model/AarLibrary.java index 4e8509bdb53..cdc3b5d008b 100644 --- a/aswb/src/com/google/idea/blaze/android/sync/model/AarLibrary.java +++ b/aswb/src/com/google/idea/blaze/android/sync/model/AarLibrary.java @@ -59,7 +59,7 @@ public final class AarLibrary extends BlazeLibrary { public final ArtifactLocation aarArtifact; // resourcePackage is used to set the resource package of the corresponding ExternalLibrary - // generated by BlazeModuleSystem. Setting resourcePackage to null will create an ExternalLibrary + // generated by BazelModuleSystem. Setting resourcePackage to null will create an ExternalLibrary // that doesn't have its resource package set. // // resourcePackage is null when we don't want to export a resource package for the Aar. This would diff --git a/aswb/sdkcompat/as232/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java b/aswb/src/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java similarity index 89% rename from aswb/sdkcompat/as232/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java rename to aswb/src/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java index 00a9e4a94c9..e1344d6a976 100644 --- a/aswb/sdkcompat/as232/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java +++ b/aswb/src/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModel.java @@ -22,7 +22,7 @@ import com.intellij.openapi.project.Project; import java.io.File; -/** Blaze model for an android project. #api42. */ +/** Blaze model for an android project */ public class BlazeAndroidModel extends BlazeAndroidModelBase { private final NamedIdeaSourceProvider sourceProvider; @@ -31,9 +31,8 @@ public BlazeAndroidModel( File rootDirPath, NamedIdeaSourceProvider sourceProvider, ListenableFuture applicationId, - int minSdkVersion, - boolean desugarJava8Libs) { - super(project, rootDirPath, applicationId, minSdkVersion, desugarJava8Libs); + int minSdkVersion) { + super(project, rootDirPath, applicationId, minSdkVersion); this.sourceProvider = sourceProvider; } diff --git a/aswb/src/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModelBase.java b/aswb/src/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModelBase.java index 3e996c8c12f..8650347a439 100644 --- a/aswb/src/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModelBase.java +++ b/aswb/src/com/google/idea/blaze/android/sync/model/idea/BlazeAndroidModelBase.java @@ -45,18 +45,15 @@ abstract class BlazeAndroidModelBase implements AndroidModel { protected final Project project; private final ListenableFuture applicationId; private final int minSdkVersion; - private final boolean desugarJava8Libs; protected BlazeAndroidModelBase( Project project, File rootDirPath, ListenableFuture applicationId, - int minSdkVersion, - boolean desugarJava8Libs) { + int minSdkVersion) { this.project = project; this.applicationId = applicationId; this.minSdkVersion = minSdkVersion; - this.desugarJava8Libs = desugarJava8Libs; } @Override @@ -113,7 +110,7 @@ public ClassJarProvider getClassJarProvider() { @Override public Set getDesugaring() { - return desugarJava8Libs ? Desugaring.FULL : Desugaring.DEFAULT; + return Desugaring.FULL; } @Override diff --git a/aswb/src/com/google/idea/blaze/android/sync/projectstructure/AndroidFacetModuleCustomizer.java b/aswb/src/com/google/idea/blaze/android/sync/projectstructure/AndroidFacetModuleCustomizer.java index 7da6e1939a8..4023dca033b 100755 --- a/aswb/src/com/google/idea/blaze/android/sync/projectstructure/AndroidFacetModuleCustomizer.java +++ b/aswb/src/com/google/idea/blaze/android/sync/projectstructure/AndroidFacetModuleCustomizer.java @@ -22,7 +22,6 @@ import com.intellij.openapi.module.Module; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.android.facet.AndroidFacetProperties; -import org.jetbrains.android.facet.AndroidFacetPropertiesCompat; /** Adds the Android facet to modules imported from {@link AndroidProject}s. */ public class AndroidFacetModuleCustomizer { @@ -62,6 +61,5 @@ private static void configureFacet(AndroidFacet facet, boolean isApp) { facetState.MANIFEST_FILE_RELATIVE_PATH = ""; facetState.RES_FOLDER_RELATIVE_PATH = ""; facetState.ASSETS_FOLDER_RELATIVE_PATH = ""; - AndroidFacetPropertiesCompat.enableSourcesAutogeneration(facetState, false); } } diff --git a/aswb/src/com/google/idea/blaze/android/sync/projectstructure/BlazeAndroidProjectStructureSyncer.java b/aswb/src/com/google/idea/blaze/android/sync/projectstructure/BlazeAndroidProjectStructureSyncer.java index 2382d6b168e..3fc28c91042 100644 --- a/aswb/src/com/google/idea/blaze/android/sync/projectstructure/BlazeAndroidProjectStructureSyncer.java +++ b/aswb/src/com/google/idea/blaze/android/sync/projectstructure/BlazeAndroidProjectStructureSyncer.java @@ -81,7 +81,6 @@ import java.util.stream.Collectors; import javax.annotation.Nullable; import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.android.facet.AndroidFacetProperties; /** Updates the IDE's project structure. */ public class BlazeAndroidProjectStructureSyncer { @@ -112,7 +111,7 @@ public static void updateProjectStructure( if (!isAndroidWorkspace) { AndroidFacetModuleCustomizer.removeAndroidFacet(workspaceModule); // Workspace type should always be ANDROID as long as the blaze android plugin is present. - log.error( + log.warn( "No android workspace found for project \"" + project.getName() + "\". Removing AndroidFacet from workspace module."); @@ -274,15 +273,13 @@ private static void updateInMemoryState( if (androidSdkPlatform == null) { return; } - boolean configAndroidJava8Libs = hasConfigAndroidJava8Libs(projectViewSet); - updateWorkspaceModuleFacetInMemoryState( project, context, workspaceRoot, workspaceModule, - androidSdkPlatform, - configAndroidJava8Libs); + androidSdkPlatform + ); ArtifactLocationDecoder artifactLocationDecoder = blazeProjectData.getArtifactLocationDecoder(); ModuleFinder moduleFinder = ModuleFinder.getInstance(project); @@ -354,8 +351,8 @@ private static void updateInMemoryState( moduleDirectory, manifestFile, modulePackage, - resources, - configAndroidJava8Libs); + resources + ); rClassBuilder.addRClass(modulePackage, module); sourcePackages.remove(modulePackage); } @@ -363,12 +360,6 @@ private static void updateInMemoryState( rClassBuilder.addWorkspacePackages(sourcePackages); } - @VisibleForTesting - static boolean hasConfigAndroidJava8Libs(ProjectViewSet projectViewSet) { - return projectViewSet.listItems(BuildFlagsSection.KEY).stream() - .anyMatch(f -> "--config=android_java8_libs".equals(f)); - } - private static File moduleDirectoryForAndroidTarget( WorkspaceRoot workspaceRoot, TargetIdeInfo target) { return workspaceRoot.fileForPath(target.getKey().getLabel().blazePackage()); @@ -436,8 +427,7 @@ private static void updateWorkspaceModuleFacetInMemoryState( BlazeContext context, WorkspaceRoot workspaceRoot, Module workspaceModule, - AndroidSdkPlatform androidSdkPlatform, - boolean configAndroidJava8Libs) { + AndroidSdkPlatform androidSdkPlatform) { File moduleDirectory = workspaceRoot.directory(); String resourceJavaPackage = ":workspace"; updateModuleFacetInMemoryState( @@ -448,8 +438,8 @@ private static void updateWorkspaceModuleFacetInMemoryState( moduleDirectory, null, resourceJavaPackage, - ImmutableList.of(), - configAndroidJava8Libs); + ImmutableList.of() + ); } private static void updateModuleFacetInMemoryState( @@ -460,8 +450,7 @@ private static void updateModuleFacetInMemoryState( File moduleDirectory, @Nullable File manifestFile, String resourceJavaPackage, - Collection resources, - boolean configAndroidJava8Libs) { + Collection resources) { String name = module.getName(); File manifest = manifestFile != null ? manifestFile : new File("MissingManifest.xml"); NamedIdeaSourceProvider sourceProvider = @@ -487,8 +476,7 @@ private static void updateModuleFacetInMemoryState( moduleDirectory, sourceProvider, applicationId, - androidSdkPlatform.androidMinSdkLevel, - configAndroidJava8Libs); + androidSdkPlatform.androidMinSdkLevel); AndroidFacet facet = AndroidFacet.getInstance(module); if (facet != null) { updateAndroidFacetWithSourceAndModel(facet, sourceProvider, androidModel); @@ -497,11 +485,6 @@ private static void updateModuleFacetInMemoryState( private static void updateAndroidFacetWithSourceAndModel( AndroidFacet facet, NamedIdeaSourceProvider sourceProvider, BlazeAndroidModel androidModel) { - facet.getProperties().RES_FOLDERS_RELATIVE_PATH = - String.join( - AndroidFacetProperties.PATH_LIST_SEPARATOR_IN_FACET_CONFIGURATION, - sourceProvider.getResDirectoryUrls()); - facet.getProperties().TEST_RES_FOLDERS_RELATIVE_PATH = ""; AndroidModel.set(facet, androidModel); } } diff --git a/aswb/src/com/google/idea/blaze/android/sync/qsync/AndroidExternalLibraryManager.java b/aswb/src/com/google/idea/blaze/android/sync/qsync/AndroidExternalLibraryManager.java deleted file mode 100644 index 2a5c0e551e9..00000000000 --- a/aswb/src/com/google/idea/blaze/android/sync/qsync/AndroidExternalLibraryManager.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.idea.blaze.android.sync.qsync; - -import com.android.ide.common.util.PathString; -import com.android.projectmodel.ExternalAndroidLibrary; -import com.android.projectmodel.ExternalLibraryImpl; -import com.android.projectmodel.SelectiveResourceFolder; -import com.google.idea.blaze.android.manifest.ManifestParser; -import com.google.idea.blaze.android.manifest.ManifestParser.ParsedManifest; -import com.intellij.openapi.diagnostic.Logger; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Path; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Supplier; -import javax.annotation.Nullable; - -/** Retrieves {@link ExternalAndroidLibrary} for external aars */ -public final class AndroidExternalLibraryManager { - private static final Logger logger = Logger.getInstance(AndroidExternalLibraryManager.class); - - private final Supplier> pathSupplier; - private final Map librariesByPath; - - public AndroidExternalLibraryManager(Supplier> pathSupplier) { - this.pathSupplier = pathSupplier; - this.librariesByPath = new HashMap<>(); - } - - public synchronized Collection getExternalLibraries() { - Collection currentPaths = pathSupplier.get(); - librariesByPath.keySet().retainAll(currentPaths); - - for (Path path : currentPaths) { - // TODO: This assumes that a given dependency will never change over the lifetime of a - // project, which may not always be true. - if (librariesByPath.containsKey(path)) { - continue; - } else { - ExternalAndroidLibrary externalAndroidLibrary = toExternalLibrary(path); - if (externalAndroidLibrary != null) { - librariesByPath.put(path, externalAndroidLibrary); - } - } - } - return librariesByPath.values(); - } - - @Nullable - private static ExternalAndroidLibrary toExternalLibrary(Path libraryPath) { - File aarFile = libraryPath.toFile(); - File manifest = new File(aarFile, "AndroidManifest.xml"); - if (!manifest.exists()) { - logger.warn(String.format("No manifest for library %s", aarFile.getName())); - return null; - } - - String javaPackage; - try (InputStream is = new FileInputStream(manifest)) { - ParsedManifest parsedManifest = ManifestParser.parseManifestFromInputStream(is); - javaPackage = parsedManifest.packageName; - } catch (IOException ioe) { - logger.warn( - String.format("Could not parse package from manifest in library %s", aarFile.getName())); - return null; - } - - PathString resFolderPathString = new PathString(new File(aarFile, "res")); - return new ExternalLibraryImpl(aarFile.getName()) - .withLocation(new PathString(aarFile)) - .withManifestFile(new PathString(manifest)) - .withResFolder(new SelectiveResourceFolder(resFolderPathString, null)) - .withSymbolFile(resFolderPathString.getParentOrRoot().resolve("R.txt")) - .withPackageName(javaPackage); - } -} diff --git a/aswb/src/com/google/idea/blaze/android/sync/sdk/AndroidSdkFromProjectView.java b/aswb/src/com/google/idea/blaze/android/sync/sdk/AndroidSdkFromProjectView.java index 9445ccc47c1..fecc301f3b3 100644 --- a/aswb/src/com/google/idea/blaze/android/sync/sdk/AndroidSdkFromProjectView.java +++ b/aswb/src/com/google/idea/blaze/android/sync/sdk/AndroidSdkFromProjectView.java @@ -15,6 +15,7 @@ */ package com.google.idea.blaze.android.sync.sdk; +import com.android.tools.sdk.AndroidPlatform; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @@ -33,10 +34,11 @@ import java.util.List; import java.util.Set; import javax.annotation.Nullable; -import org.jetbrains.android.sdk.AndroidPlatformCompat; +import org.jetbrains.android.sdk.AndroidSdkAdditionalData; /** Calculates AndroidSdkPlatform. */ public final class AndroidSdkFromProjectView { + private static final int DEFAULT_ANDROID_SDK_API_LEVEL = 1; private static final Joiner COMMA_JOINER = Joiner.on(", "); public static final String NO_SDK_ERROR_TEMPLATE = "No such android_sdk_platform: '%s'. " @@ -87,7 +89,7 @@ public boolean canNavigateToSource() { + getAvailableTargetHashesAsList(sdks) + ". To install more android SDKs, use the SDK manager."; IssueOutput.error(msg) - .withFile(projectViewFile != null ? projectViewFile.projectViewFile : null) + .inFile(projectViewFile != null ? projectViewFile.projectViewFile : null) .submit(context); BlazeSyncManager.printAndLogError(msg, context); return null; @@ -98,7 +100,7 @@ public boolean canNavigateToSource() { ProjectViewFile projectViewFile = projectViewSet.getTopLevelProjectViewFile(); String msg = String.format(NO_SDK_ERROR_TEMPLATE, androidSdk, getAllAvailableTargetHashes()); IssueOutput.error(msg) - .withFile(projectViewFile != null ? projectViewFile.projectViewFile : null) + .inFile(projectViewFile != null ? projectViewFile.projectViewFile : null) .submit(context); BlazeSyncManager.printAndLogError(msg, context); return null; @@ -133,7 +135,14 @@ private static String getAllAvailableTargetHashes() { } private static int getAndroidSdkApiLevel(Sdk sdk) { - return AndroidPlatformCompat.getApiLevel(sdk); + AndroidSdkAdditionalData additionalData = (AndroidSdkAdditionalData) sdk.getSdkAdditionalData(); + if (additionalData != null) { + AndroidPlatform androidPlatform = additionalData.getAndroidPlatform(); + if (androidPlatform != null) { + return androidPlatform.getApiLevel(); + } + } + return DEFAULT_ANDROID_SDK_API_LEVEL; } private AndroidSdkFromProjectView() {} diff --git a/aswb/src/com/google/idea/blaze/android/sync/sdk/SdkUtil.java b/aswb/src/com/google/idea/blaze/android/sync/sdk/SdkUtil.java index b58f80f78c0..a4f24dc8fa4 100644 --- a/aswb/src/com/google/idea/blaze/android/sync/sdk/SdkUtil.java +++ b/aswb/src/com/google/idea/blaze/android/sync/sdk/SdkUtil.java @@ -19,6 +19,7 @@ import static com.android.SdkConstants.RES_FOLDER; import com.android.tools.idea.updater.configure.SdkUpdaterConfigurableProvider; +import com.android.tools.sdk.AndroidPlatform; import com.google.idea.blaze.android.projectview.AndroidSdkPlatformSection; import com.google.idea.blaze.android.sdk.BlazeSdkProvider; import com.google.idea.blaze.android.sync.model.BlazeAndroidSyncData; @@ -43,8 +44,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ui.UIUtil; import java.util.Optional; -import org.jetbrains.android.sdk.AndroidPlatformCompat; -import org.jetbrains.android.sdk.AndroidPlatformsCompat; +import org.jetbrains.android.sdk.AndroidPlatforms; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -71,7 +71,7 @@ private static String getAndroidSdkPlatform(Project project, BlazeProjectData bl } @Nullable - public static AndroidPlatformCompat getAndroidPlatform(@NotNull Project project) { + public static AndroidPlatform getAndroidPlatform(@NotNull Project project) { BlazeProjectData blazeProjectData = BlazeProjectDataManager.getInstance(project).getBlazeProjectData(); if (blazeProjectData == null) { @@ -85,7 +85,7 @@ public static AndroidPlatformCompat getAndroidPlatform(@NotNull Project project) if (sdk == null) { return null; } - return AndroidPlatformsCompat.getInstance(sdk); + return AndroidPlatforms.getInstance(sdk); } /** Opens the SDK manager settings page */ diff --git a/aswb/src/icons/BlazeAndroidIcons.java b/aswb/src/icons/BlazeAndroidIcons.java index cd986d31632..4b1abc4f374 100644 --- a/aswb/src/icons/BlazeAndroidIcons.java +++ b/aswb/src/icons/BlazeAndroidIcons.java @@ -32,6 +32,6 @@ public class BlazeAndroidIcons { load("aswb/resources/icons/crowToolWindow.png"); // 13x13 private static Icon load(String path) { - return IconLoader.getIcon(BASE + path, BlazeAndroidIcons.class); + return IconLoader.findIcon(BASE + path, BlazeAndroidIcons.class); } } diff --git a/aswb/src/org/jetbrains/android/sdk/AndroidPlatformCompat.java b/aswb/src/org/jetbrains/android/sdk/AndroidPlatformCompat.java deleted file mode 100644 index f745ba55516..00000000000 --- a/aswb/src/org/jetbrains/android/sdk/AndroidPlatformCompat.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.android.sdk; - -import com.android.sdklib.BuildToolInfo; -import com.android.tools.sdk.AndroidPlatform; -import com.intellij.openapi.projectRoots.Sdk; - -/** Compat class for {@link com.android.tools.sdk.AndroidPlatform} */ -public class AndroidPlatformCompat { - AndroidPlatform androidPlatform; - - public AndroidPlatformCompat(AndroidPlatform androidPlatform) { - this.androidPlatform = androidPlatform; - } - - public BuildToolInfo getLatestBuildTool(boolean allowBuildTool) { - return androidPlatform.getSdkData().getLatestBuildTool(allowBuildTool); - } - - public int getApiLevel() { - return androidPlatform.getApiLevel(); - } - - public static int getApiLevel(Sdk sdk) { - int androidSdkApiLevel = 1; - AndroidSdkAdditionalData additionalData = (AndroidSdkAdditionalData) sdk.getSdkAdditionalData(); - if (additionalData != null) { - AndroidPlatform androidPlatform = additionalData.getAndroidPlatform(); - if (androidPlatform != null) { - androidSdkApiLevel = androidPlatform.getApiLevel(); - } - } - return androidSdkApiLevel; - } -} diff --git a/aswb/src/org/jetbrains/android/sdk/AndroidPlatformsCompat.java b/aswb/src/org/jetbrains/android/sdk/AndroidPlatformsCompat.java deleted file mode 100644 index d016d7ce236..00000000000 --- a/aswb/src/org/jetbrains/android/sdk/AndroidPlatformsCompat.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.android.sdk; - -import com.intellij.openapi.module.Module; -import com.intellij.openapi.projectRoots.Sdk; - -/** Compat shim class for {@link AndroidPlatforms} */ -public class AndroidPlatformsCompat { - private AndroidPlatformsCompat() {} - - public static AndroidPlatformCompat getInstance(Sdk sdk) { - return new AndroidPlatformCompat(AndroidPlatforms.getInstance(sdk)); - } - - public static AndroidPlatformCompat getInstance(Module module) { - return new AndroidPlatformCompat(AndroidPlatforms.getInstance(module)); - } -} diff --git a/aswb/src/org/jetbrains/android/sdk/AndroidSdkDataCompat.java b/aswb/src/org/jetbrains/android/sdk/AndroidSdkDataCompat.java deleted file mode 100644 index 4aea6d6e832..00000000000 --- a/aswb/src/org/jetbrains/android/sdk/AndroidSdkDataCompat.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2023 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.android.sdk; - -import com.android.sdklib.IAndroidTarget; -import com.android.tools.sdk.AndroidSdkData; -import com.google.errorprone.annotations.CanIgnoreReturnValue; -import java.io.File; - -/** Compat class for {@link com.android.tools.sdk.AndroidSdkData} */ -public class AndroidSdkDataCompat { - AndroidSdkData androidSdkData; - - private AndroidSdkDataCompat(File sdkLocation, boolean forceReparse) { - androidSdkData = AndroidSdkData.getSdkData(sdkLocation, forceReparse); - } - - public static AndroidSdkDataCompat getSdkData(String sdkHomepath) { - return new AndroidSdkDataCompat(new File(sdkHomepath), false); - } - - @CanIgnoreReturnValue - public static AndroidSdkDataCompat getSdkData(File sdkLocation, boolean forceReparse) { - return new AndroidSdkDataCompat(sdkLocation, forceReparse); - } - - public IAndroidTarget[] getTargets() { - return androidSdkData.getTargets(); - } -} diff --git a/aswb/testdata/projects/BUILD b/aswb/testdata/projects/BUILD new file mode 100644 index 00000000000..2e2588069a0 --- /dev/null +++ b/aswb/testdata/projects/BUILD @@ -0,0 +1,26 @@ +load("@bazel_skylib//rules:build_test.bzl", "build_test") +load("//:build-visibility.bzl", "DEFAULT_TEST_VISIBILITY") + +package( + default_visibility = DEFAULT_TEST_VISIBILITY, +) + +build_test( + name = "test_projects_test", + targets = [ + # TODO: b/335388630 + # "//aswb/testdata/projects/android1/project:test_data_build", + "//aswb/testdata/projects/autovalue:test_data_build", + "//aswb/testdata/projects/cc1:test_data_build", + "//aswb/testdata/projects/cc_genhdr:test_data_build", + "//aswb/testdata/projects/generated1:test_data_build", + "//aswb/testdata/projects/generated2:test_data_build", + "//aswb/testdata/projects/generated3:test_data_build", + "//aswb/testdata/projects/generated_tests:test_data_build", + "//aswb/testdata/projects/javabinaries:test_data_build", + "//aswb/testdata/projects/kotlin1:test_data_build", + "//aswb/testdata/projects/sample1:test_data_build", + "//aswb/testdata/projects/proto1/project:test_data_build", + "//aswb/testdata/projects/src_transform:test_data_build", + ], +) diff --git a/aswb/testdata/projects/android1/external/BUILD b/aswb/testdata/projects/android1/external/BUILD new file mode 100644 index 00000000000..a67d8cdb8e8 --- /dev/null +++ b/aswb/testdata/projects/android1/external/BUILD @@ -0,0 +1,12 @@ +package( + default_visibility = [ + "//aswb/testdata/projects/android1:__subpackages__", + ], +) + +android_library( + name = "lib", + srcs = glob(["lib/java/**/*.java"]), + manifest = "lib/AndroidManifest.xml", + resource_files = glob(["lib/res/**"]), +) diff --git a/aswb/testdata/projects/android1/external/lib/AndroidManifest.xml b/aswb/testdata/projects/android1/external/lib/AndroidManifest.xml new file mode 100644 index 00000000000..d3967f0a1a8 --- /dev/null +++ b/aswb/testdata/projects/android1/external/lib/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + diff --git a/aswb/testdata/projects/android1/external/lib/java/com/example/external/lib/ExternalGreeter.java b/aswb/testdata/projects/android1/external/lib/java/com/example/external/lib/ExternalGreeter.java new file mode 100644 index 00000000000..79f34616a27 --- /dev/null +++ b/aswb/testdata/projects/android1/external/lib/java/com/example/external/lib/ExternalGreeter.java @@ -0,0 +1,23 @@ +/* + * Copyright 2023 The Bazel Authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.external.lib; + +/** A tiny Greeter library for the Bazel Android "Hello, World" app. */ +public class ExternalGreeter { + public String sayHello() { + return "Hello Bazel! \uD83D\uDC4B\uD83C\uDF31"; // Unicode for 👋🌱 + } +} diff --git a/aswb/testdata/projects/android1/external/lib/res/font/just_font.ttf b/aswb/testdata/projects/android1/external/lib/res/font/just_font.ttf new file mode 100644 index 00000000000..59f351b5d2c --- /dev/null +++ b/aswb/testdata/projects/android1/external/lib/res/font/just_font.ttf @@ -0,0 +1 @@ +# just a file \ No newline at end of file diff --git a/aswb/testdata/projects/android1/external/lib/res/values/colors.xml b/aswb/testdata/projects/android1/external/lib/res/values/colors.xml new file mode 100644 index 00000000000..f098c3e1685 --- /dev/null +++ b/aswb/testdata/projects/android1/external/lib/res/values/colors.xml @@ -0,0 +1,5 @@ + + + #FFFFFF + #43A047 + diff --git a/aswb/testdata/projects/android1/external/lib/res/values/strings.xml b/aswb/testdata/projects/android1/external/lib/res/values/strings.xml new file mode 100644 index 00000000000..5621ad60f1c --- /dev/null +++ b/aswb/testdata/projects/android1/external/lib/res/values/strings.xml @@ -0,0 +1,5 @@ + + + Say hello, External! + 🤔 + diff --git a/aswb/testdata/projects/android1/external/lib/res/values/typography.xml b/aswb/testdata/projects/android1/external/lib/res/values/typography.xml new file mode 100644 index 00000000000..85ffa5c73f1 --- /dev/null +++ b/aswb/testdata/projects/android1/external/lib/res/values/typography.xml @@ -0,0 +1,4 @@ + + + @font/just_font + \ No newline at end of file diff --git a/aswb/testdata/projects/android1/project/.bazelproject b/aswb/testdata/projects/android1/project/.bazelproject new file mode 100644 index 00000000000..85d9ae89f04 --- /dev/null +++ b/aswb/testdata/projects/android1/project/.bazelproject @@ -0,0 +1,7 @@ + +directories: + aswb/testdata/projects/android1/project +derive_targets_from_directories: true +android_sdk_platform: android-34 + + diff --git a/aswb/testdata/projects/android1/project/BUILD b/aswb/testdata/projects/android1/project/BUILD new file mode 100644 index 00000000000..151e9439d84 --- /dev/null +++ b/aswb/testdata/projects/android1/project/BUILD @@ -0,0 +1,86 @@ +load( + "//aswb/testdata/projects:test_projects.bzl", + "test_project_package", +) + +package( + default_visibility = ["//src:__subpackages__"], +) + +test_project_package( + name = "test_data", + all_targets = [ + ":app", + ":app_srcs", + #":app_test", + #":app_test_bin", + ":lib", + ":resources", + ], + visibility = [ + "//aswb/testdata/projects:__pkg__", + "//javatests/com/google/devtools/intellij/blaze/plugin/aswb:__pkg__", + ], +) + +android_library( + name = "app_srcs", + srcs = glob(["app/java/**/*.java"]), + exports_manifest = 1, + javacopts = [ + "-source", + "8", + "-target", + "8", + ], + manifest = "app/AndroidManifest.xml", + resource_files = glob(["app/res/**"]), + deps = [ + ":lib", + ":resources", + "//aswb/testdata/projects/android1/external:lib", + ], +) + +android_binary( + name = "app", + manifest = "app/AndroidManifest.xml", + deps = [ + ":app_srcs", + ], +) + +android_library( + name = "lib", + srcs = glob(["lib/java/**/*.java"]), + custom_package = "com.example.bazel", + manifest = "lib/AndroidManifest.xml", + resource_files = glob(["lib/res/**"]), +) + +android_library( + name = "resources", + srcs = [], + manifest = "resources/AndroidManifest.xml", + resource_files = glob(["resources/res/**"]), +) + +# TODO(b/331378322) Re-enable this. +#android_application_test( +# name = "app_test", +# srcs = ["test/javatests/com/example/bazel/AppTest.java"], +# instruments = ":app", +# manifest = "test/AndroidManifest.xml", +# target_devices = [ +# "//tools/android/emulated_devices/generic_phone:android_21_x86", +# ], +# test_class = "com.example.bazel.AppTest", +# deps = [ +# ":app_srcs", +# "//third_party/android/androidx_test/espresso/core", +# "//third_party/android/androidx_test/ext/junit", +# "//third_party/java/android/android_sdk_linux/extras/android/compatibility/v4", +# "//third_party/java/androidx/appcompat", +# "//third_party/java/junit:junit-android", +# ], +#) diff --git a/aswb/testdata/projects/android1/project/app/AndroidManifest.xml b/aswb/testdata/projects/android1/project/app/AndroidManifest.xml new file mode 100644 index 00000000000..36274edab33 --- /dev/null +++ b/aswb/testdata/projects/android1/project/app/AndroidManifest.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + diff --git a/aswb/testdata/projects/android1/project/app/java/com/example/bazel/MainActivity.java b/aswb/testdata/projects/android1/project/app/java/com/example/bazel/MainActivity.java new file mode 100644 index 00000000000..ae1c0ac0caa --- /dev/null +++ b/aswb/testdata/projects/android1/project/app/java/com/example/bazel/MainActivity.java @@ -0,0 +1,45 @@ +/* + * Copyright 2023 The Bazel Authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.bazel; + +import android.app.Activity; +import android.os.Bundle; +import android.util.Log; +import android.widget.Button; +import android.widget.TextView; +import com.example.external.lib.ExternalGreeter; +import com.example.lib.Greeter; + +/** Main class for the Bazel Android "Hello, World" app. */ +public class MainActivity extends Activity { + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Log.v("Bazel", "Hello, Android"); + + setContentView(R.layout.activity_main); + + Button clickMeButton = findViewById(R.id.clickMeButton); + Button clickMeButtonExternal = findViewById(R.id.clickMeButtonExternal); + TextView helloBazelTextView = findViewById(R.id.helloBazelTextView); + + Greeter greeter = new Greeter(); + ExternalGreeter externalGreeter = new ExternalGreeter(); + + // Bazel supports Java 8 language features like lambdas! + clickMeButton.setOnClickListener(v -> helloBazelTextView.setText(greeter.sayHello())); + } +} diff --git a/aswb/sdkcompat/as231/com/android/tools/configurations/ConfigurationCompat.java b/aswb/testdata/projects/android1/project/app/java/com/example/bazel/pkg1/ScopedResourceActivity.java similarity index 58% rename from aswb/sdkcompat/as231/com/android/tools/configurations/ConfigurationCompat.java rename to aswb/testdata/projects/android1/project/app/java/com/example/bazel/pkg1/ScopedResourceActivity.java index 3d51e831ad7..4d34faf9ab1 100644 --- a/aswb/sdkcompat/as231/com/android/tools/configurations/ConfigurationCompat.java +++ b/aswb/testdata/projects/android1/project/app/java/com/example/bazel/pkg1/ScopedResourceActivity.java @@ -13,20 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.android.tools.configurations; +package com.example.bazel.pkg1; -import com.android.sdklib.devices.Device; +import android.app.Activity; +import android.os.Bundle; +import android.util.Log; +import com.example.bazel.resources.R; -/** Compat class for Configuration. */ -public class ConfigurationCompat { - - private Configuration configuration; - - public ConfigurationCompat(Configuration configuration) { - this.configuration = configuration; - } - - public void setDevice(Device device, boolean preserveState) { - configuration.setDevice(device, preserveState); +/** Class consuming resources from a specific library. */ +public class ScopedResourceActivity extends Activity { + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Log.v("Bazel", getResources().getString(R.string.resource_lib_string)); } } diff --git a/aswb/testdata/projects/android1/project/app/res/layout/activity_main.xml b/aswb/testdata/projects/android1/project/app/res/layout/activity_main.xml new file mode 100644 index 00000000000..f208f3be11f --- /dev/null +++ b/aswb/testdata/projects/android1/project/app/res/layout/activity_main.xml @@ -0,0 +1,37 @@ + + + + + +