diff options
| author | 2023-11-30 04:21:19 +0000 | |
|---|---|---|
| committer | 2023-11-30 04:21:19 +0000 | |
| commit | d067918b8705c65438f92279cd5a8e8fdbccd6b7 (patch) | |
| tree | c4fa2b05024bb6b03fae82747e9552467c062de4 | |
| parent | 2f16184f65f5d9739645f33001f297b9eddf06ec (diff) | |
| parent | 917043bc2586743afda5a21386893fa8c787800b (diff) | |
Merge "Revert "Move some image/9patch code to androidfw"" into main
55 files changed, 690 insertions, 603 deletions
diff --git a/libs/androidfw/Android.bp b/libs/androidfw/Android.bp index 2f28363aedc7..47a7f3579764 100644 --- a/libs/androidfw/Android.bp +++ b/libs/androidfw/Android.bp @@ -63,21 +63,15 @@ cc_library { "AssetsProvider.cpp", "AttributeResolution.cpp", "BigBuffer.cpp", - "BigBufferStream.cpp", "ChunkIterator.cpp", "ConfigDescription.cpp", - "FileStream.cpp", "Idmap.cpp", "LoadedArsc.cpp", "Locale.cpp", "LocaleData.cpp", "misc.cpp", - "NinePatch.cpp", "ObbFile.cpp", "PosixUtils.cpp", - "Png.cpp", - "PngChunkFilter.cpp", - "PngCrunch.cpp", "ResourceTimer.cpp", "ResourceTypes.cpp", "ResourceUtils.cpp", @@ -90,10 +84,7 @@ cc_library { ], export_include_dirs: ["include"], export_shared_lib_headers: ["libz"], - static_libs: [ - "libincfs-utils", - "libpng", - ], + static_libs: ["libincfs-utils"], whole_static_libs: [ "libandroidfw_pathutils", "libincfs-utils", @@ -207,11 +198,9 @@ cc_test { "tests/ConfigDescription_test.cpp", "tests/ConfigLocale_test.cpp", "tests/DynamicRefTable_test.cpp", - "tests/FileStream_test.cpp", "tests/Idmap_test.cpp", "tests/LoadedArsc_test.cpp", "tests/Locale_test.cpp", - "tests/NinePatch_test.cpp", "tests/ResourceTimer_test.cpp", "tests/ResourceUtils_test.cpp", "tests/ResTable_test.cpp", diff --git a/tools/aapt2/Android.bp b/tools/aapt2/Android.bp index 275a0e21fedd..412aa9bf88ab 100644 --- a/tools/aapt2/Android.bp +++ b/tools/aapt2/Android.bp @@ -92,6 +92,10 @@ cc_library_host_static { srcs: [ "compile/IdAssigner.cpp", "compile/InlineXmlFormatParser.cpp", + "compile/NinePatch.cpp", + "compile/Png.cpp", + "compile/PngChunkFilter.cpp", + "compile/PngCrunch.cpp", "compile/PseudolocaleGenerator.cpp", "compile/Pseudolocalizer.cpp", "compile/XmlIdCollector.cpp", @@ -108,7 +112,9 @@ cc_library_host_static { "format/binary/XmlFlattener.cpp", "format/proto/ProtoDeserialize.cpp", "format/proto/ProtoSerialize.cpp", + "io/BigBufferStream.cpp", "io/File.cpp", + "io/FileStream.cpp", "io/FileSystem.cpp", "io/StringStream.cpp", "io/Util.cpp", diff --git a/tools/aapt2/LoadedApk.cpp b/tools/aapt2/LoadedApk.cpp index d6502d82848f..6b1fd9ff11eb 100644 --- a/tools/aapt2/LoadedApk.cpp +++ b/tools/aapt2/LoadedApk.cpp @@ -18,12 +18,12 @@ #include "ResourceValues.h" #include "ValueVisitor.h" -#include "androidfw/BigBufferStream.h" #include "format/Archive.h" #include "format/binary/TableFlattener.h" #include "format/binary/XmlFlattener.h" #include "format/proto/ProtoDeserialize.h" #include "format/proto/ProtoSerialize.h" +#include "io/BigBufferStream.h" #include "io/Util.h" #include "xml/XmlDom.h" @@ -48,7 +48,7 @@ static ApkFormat DetermineApkFormat(io::IFileCollection* apk) { } // First try in proto format. - std::unique_ptr<android::InputStream> manifest_in = manifest_file->OpenInputStream(); + std::unique_ptr<io::InputStream> manifest_in = manifest_file->OpenInputStream(); if (manifest_in != nullptr) { pb::XmlNode pb_node; io::ProtoInputStreamReader proto_reader(manifest_in.get()); @@ -102,7 +102,7 @@ std::unique_ptr<LoadedApk> LoadedApk::LoadProtoApkFromFileCollection( io::IFile* table_file = collection->FindFile(kProtoResourceTablePath); if (table_file != nullptr) { pb::ResourceTable pb_table; - std::unique_ptr<android::InputStream> in = table_file->OpenInputStream(); + std::unique_ptr<io::InputStream> in = table_file->OpenInputStream(); if (in == nullptr) { diag->Error(android::DiagMessage(source) << "failed to open " << kProtoResourceTablePath); return {}; @@ -129,7 +129,7 @@ std::unique_ptr<LoadedApk> LoadedApk::LoadProtoApkFromFileCollection( return {}; } - std::unique_ptr<android::InputStream> manifest_in = manifest_file->OpenInputStream(); + std::unique_ptr<io::InputStream> manifest_in = manifest_file->OpenInputStream(); if (manifest_in == nullptr) { diag->Error(android::DiagMessage(source) << "failed to open " << kAndroidManifestPath); return {}; @@ -262,7 +262,7 @@ bool LoadedApk::WriteToArchive(IAaptContext* context, ResourceTable* split_table return false; } - android::BigBufferInputStream input_stream(&buffer); + io::BigBufferInputStream input_stream(&buffer); if (!io::CopyInputStreamToArchive(context, &input_stream, path, @@ -296,7 +296,7 @@ bool LoadedApk::WriteToArchive(IAaptContext* context, ResourceTable* split_table } uint32_t compression_flags = file->WasCompressed() ? ArchiveEntry::kCompress : 0u; - android::BigBufferInputStream manifest_buffer_in(&buffer); + io::BigBufferInputStream manifest_buffer_in(&buffer); if (!io::CopyInputStreamToArchive(context, &manifest_buffer_in, path, compression_flags, writer)) { return false; @@ -321,7 +321,7 @@ std::unique_ptr<xml::XmlResource> LoadedApk::LoadXml(const std::string& file_pat std::unique_ptr<xml::XmlResource> doc; if (format_ == ApkFormat::kProto) { - std::unique_ptr<android::InputStream> in = file->OpenInputStream(); + std::unique_ptr<io::InputStream> in = file->OpenInputStream(); if (!in) { diag->Error(android::DiagMessage() << "failed to open file"); return nullptr; diff --git a/tools/aapt2/Main.cpp b/tools/aapt2/Main.cpp index b351d6ee4f33..a0b4dab9b8e5 100644 --- a/tools/aapt2/Main.cpp +++ b/tools/aapt2/Main.cpp @@ -27,7 +27,6 @@ #include "Diagnostics.h" #include "android-base/stringprintf.h" #include "android-base/utf8.h" -#include "androidfw/FileStream.h" #include "androidfw/IDiagnostics.h" #include "androidfw/StringPiece.h" #include "cmd/ApkInfo.h" @@ -38,6 +37,7 @@ #include "cmd/Dump.h" #include "cmd/Link.h" #include "cmd/Optimize.h" +#include "io/FileStream.h" #include "trace/TraceBuffer.h" #include "util/Files.h" #include "util/Util.h" @@ -99,7 +99,7 @@ class MainCommand : public Command { */ class DaemonCommand : public Command { public: - explicit DaemonCommand(android::FileOutputStream* out, android::IDiagnostics* diagnostics) + explicit DaemonCommand(io::FileOutputStream* out, android::IDiagnostics* diagnostics) : Command("daemon", "m"), out_(out), diagnostics_(diagnostics) { SetDescription("Runs aapt in daemon mode. Each subsequent line is a single parameter to the\n" "command. The end of an invocation is signaled by providing an empty line."); @@ -147,7 +147,7 @@ class DaemonCommand : public Command { } private: - android::FileOutputStream* out_; + io::FileOutputStream* out_; android::IDiagnostics* diagnostics_; std::optional<std::string> trace_folder_; }; @@ -167,7 +167,7 @@ int MainImpl(int argc, char** argv) { // Use a smaller buffer so that there is less latency for printing to stdout. constexpr size_t kStdOutBufferSize = 1024u; - android::FileOutputStream fout(STDOUT_FILENO, kStdOutBufferSize); + aapt::io::FileOutputStream fout(STDOUT_FILENO, kStdOutBufferSize); aapt::text::Printer printer(&fout); aapt::StdErrDiagnostics diagnostics; diff --git a/tools/aapt2/cmd/Compile.cpp b/tools/aapt2/cmd/Compile.cpp index 031dd5bb139c..728ba8aa4fdd 100644 --- a/tools/aapt2/cmd/Compile.cpp +++ b/tools/aapt2/cmd/Compile.cpp @@ -25,16 +25,13 @@ #include "android-base/errors.h" #include "android-base/file.h" #include "android-base/utf8.h" -#include "androidfw/BigBufferStream.h" #include "androidfw/ConfigDescription.h" -#include "androidfw/FileStream.h" #include "androidfw/IDiagnostics.h" -#include "androidfw/Image.h" -#include "androidfw/Png.h" #include "androidfw/StringPiece.h" #include "cmd/Util.h" #include "compile/IdAssigner.h" #include "compile/InlineXmlFormatParser.h" +#include "compile/Png.h" #include "compile/PseudolocaleGenerator.h" #include "compile/XmlIdCollector.h" #include "format/Archive.h" @@ -42,6 +39,8 @@ #include "format/proto/ProtoSerialize.h" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/zero_copy_stream_impl_lite.h" +#include "io/BigBufferStream.h" +#include "io/FileStream.h" #include "io/FileSystem.h" #include "io/StringStream.h" #include "io/Util.h" @@ -53,9 +52,9 @@ #include "xml/XmlDom.h" #include "xml/XmlPullParser.h" +using ::aapt::io::FileInputStream; using ::aapt::text::Printer; using ::android::ConfigDescription; -using ::android::FileInputStream; using ::android::StringPiece; using ::android::base::SystemErrorCodeToString; using ::google::protobuf::io::CopyingOutputStreamAdaptor; @@ -242,7 +241,7 @@ static bool CompileTable(IAaptContext* context, const CompileOptions& options, } if (options.generate_text_symbols_path) { - android::FileOutputStream fout_text(options.generate_text_symbols_path.value()); + io::FileOutputStream fout_text(options.generate_text_symbols_path.value()); if (fout_text.HadError()) { context->GetDiagnostics()->Error(android::DiagMessage() @@ -308,7 +307,7 @@ static bool CompileTable(IAaptContext* context, const CompileOptions& options, } static bool WriteHeaderAndDataToWriter(StringPiece output_path, const ResourceFile& file, - android::KnownSizeInputStream* in, IArchiveWriter* writer, + io::KnownSizeInputStream* in, IArchiveWriter* writer, android::IDiagnostics* diag) { TRACE_CALL(); // Start the entry so we can write the header. @@ -449,7 +448,7 @@ static bool CompileXml(IAaptContext* context, const CompileOptions& options, } if (options.generate_text_symbols_path) { - android::FileOutputStream fout_text(options.generate_text_symbols_path.value()); + io::FileOutputStream fout_text(options.generate_text_symbols_path.value()); if (fout_text.HadError()) { context->GetDiagnostics()->Error(android::DiagMessage() @@ -499,22 +498,21 @@ static bool CompilePng(IAaptContext* context, const CompileOptions& options, } android::BigBuffer crunched_png_buffer(4096); - android::BigBufferOutputStream crunched_png_buffer_out(&crunched_png_buffer); + io::BigBufferOutputStream crunched_png_buffer_out(&crunched_png_buffer); // Ensure that we only keep the chunks we care about if we end up // using the original PNG instead of the crunched one. const StringPiece content(reinterpret_cast<const char*>(data->data()), data->size()); - android::PngChunkFilter png_chunk_filter(content); - android::SourcePathDiagnostics source_diag(path_data.source, context->GetDiagnostics()); - auto image = android::ReadPng(&png_chunk_filter, &source_diag); + PngChunkFilter png_chunk_filter(content); + std::unique_ptr<Image> image = ReadPng(context, path_data.source, &png_chunk_filter); if (!image) { return false; } - std::unique_ptr<android::NinePatch> nine_patch; + std::unique_ptr<NinePatch> nine_patch; if (path_data.extension == "9.png") { std::string err; - nine_patch = android::NinePatch::Create(image->rows.get(), image->width, image->height, &err); + nine_patch = NinePatch::Create(image->rows.get(), image->width, image->height, &err); if (!nine_patch) { context->GetDiagnostics()->Error(android::DiagMessage() << err); return false; @@ -539,8 +537,7 @@ static bool CompilePng(IAaptContext* context, const CompileOptions& options, } // Write the crunched PNG. - if (!android::WritePng(image.get(), nine_patch.get(), &crunched_png_buffer_out, {}, - &source_diag, context->IsVerbose())) { + if (!WritePng(context, image.get(), nine_patch.get(), &crunched_png_buffer_out, {})) { return false; } @@ -560,7 +557,7 @@ static bool CompilePng(IAaptContext* context, const CompileOptions& options, png_chunk_filter.Rewind(); android::BigBuffer filtered_png_buffer(4096); - android::BigBufferOutputStream filtered_png_buffer_out(&filtered_png_buffer); + io::BigBufferOutputStream filtered_png_buffer_out(&filtered_png_buffer); io::Copy(&filtered_png_buffer_out, &png_chunk_filter); buffer.AppendBuffer(std::move(filtered_png_buffer)); } @@ -570,7 +567,7 @@ static bool CompilePng(IAaptContext* context, const CompileOptions& options, // This will help catch exotic cases where the new code may generate larger PNGs. std::stringstream legacy_stream{std::string(content)}; android::BigBuffer legacy_buffer(4096); - android::Png png(context->GetDiagnostics()); + Png png(context->GetDiagnostics()); if (!png.process(path_data.source, &legacy_stream, &legacy_buffer, {})) { return false; } @@ -581,7 +578,7 @@ static bool CompilePng(IAaptContext* context, const CompileOptions& options, } } - android::BigBufferInputStream buffer_in(&buffer); + io::BigBufferInputStream buffer_in(&buffer); return WriteHeaderAndDataToWriter(output_path, res_file, &buffer_in, writer, context->GetDiagnostics()); } diff --git a/tools/aapt2/cmd/Compile_test.cpp b/tools/aapt2/cmd/Compile_test.cpp index 9337cb913a0b..8880089d0e20 100644 --- a/tools/aapt2/cmd/Compile_test.cpp +++ b/tools/aapt2/cmd/Compile_test.cpp @@ -341,7 +341,7 @@ TEST_F(CompilerTest, RelativePathTest) { // Check resources.pb contains relative sources. io::IFile* proto_file = apk.get()->GetFileCollection()->FindFile("resources.pb"); - std::unique_ptr<android::InputStream> proto_stream = proto_file->OpenInputStream(); + std::unique_ptr<io::InputStream> proto_stream = proto_file->OpenInputStream(); io::ProtoInputStreamReader proto_reader(proto_stream.get()); pb::ResourceTable pb_table; proto_reader.ReadMessage(&pb_table); diff --git a/tools/aapt2/cmd/Convert.cpp b/tools/aapt2/cmd/Convert.cpp index c132792d374b..387dcfe2ddf3 100644 --- a/tools/aapt2/cmd/Convert.cpp +++ b/tools/aapt2/cmd/Convert.cpp @@ -24,13 +24,13 @@ #include "android-base/file.h" #include "android-base/macros.h" #include "android-base/stringprintf.h" -#include "androidfw/BigBufferStream.h" #include "androidfw/StringPiece.h" #include "cmd/Util.h" #include "format/binary/TableFlattener.h" #include "format/binary/XmlFlattener.h" #include "format/proto/ProtoDeserialize.h" #include "format/proto/ProtoSerialize.h" +#include "io/BigBufferStream.h" #include "io/Util.h" #include "process/IResourceTableConsumer.h" #include "process/SymbolTable.h" @@ -80,7 +80,7 @@ class BinaryApkSerializer : public IApkSerializer { return false; } - android::BigBufferInputStream input_stream(&buffer); + io::BigBufferInputStream input_stream(&buffer); return io::CopyInputStreamToArchive(context_, &input_stream, path, compression_flags, writer); } @@ -91,14 +91,14 @@ class BinaryApkSerializer : public IApkSerializer { return false; } - android::BigBufferInputStream input_stream(&buffer); + io::BigBufferInputStream input_stream(&buffer); return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath, ArchiveEntry::kAlign, writer); } bool SerializeFile(FileReference* file, IArchiveWriter* writer) override { if (file->type == ResourceFile::Type::kProtoXml) { - unique_ptr<android::InputStream> in = file->file->OpenInputStream(); + unique_ptr<io::InputStream> in = file->file->OpenInputStream(); if (in == nullptr) { context_->GetDiagnostics()->Error(android::DiagMessage(source_) << "failed to open file " << *file->path); diff --git a/tools/aapt2/cmd/Dump.cpp b/tools/aapt2/cmd/Dump.cpp index 6fa9ecbfa544..864af06f187e 100644 --- a/tools/aapt2/cmd/Dump.cpp +++ b/tools/aapt2/cmd/Dump.cpp @@ -19,18 +19,19 @@ #include <cinttypes> #include <vector> +#include "android-base/stringprintf.h" +#include "androidfw/ConfigDescription.h" +#include "androidfw/StringPiece.h" + #include "Debug.h" #include "Diagnostics.h" #include "LoadedApk.h" #include "Util.h" -#include "android-base/stringprintf.h" -#include "androidfw/ConfigDescription.h" -#include "androidfw/FileStream.h" -#include "androidfw/StringPiece.h" #include "format/Container.h" #include "format/binary/BinaryResourceParser.h" #include "format/binary/XmlFlattener.h" #include "format/proto/ProtoDeserialize.h" +#include "io/FileStream.h" #include "io/ZipArchive.h" #include "process/IResourceTableConsumer.h" #include "text/Printer.h" @@ -144,7 +145,7 @@ int DumpAPCCommand::Action(const std::vector<std::string>& args) { bool error = false; for (auto container : args) { - android::FileInputStream input(container); + io::FileInputStream input(container); if (input.HadError()) { context.GetDiagnostics()->Error(android::DiagMessage(container) << "failed to open file: " << input.GetError()); diff --git a/tools/aapt2/cmd/Dump.h b/tools/aapt2/cmd/Dump.h index 119a59b28317..76d33d7aa3b2 100644 --- a/tools/aapt2/cmd/Dump.h +++ b/tools/aapt2/cmd/Dump.h @@ -17,7 +17,7 @@ #ifndef AAPT2_DUMP_H #define AAPT2_DUMP_H -#include <androidfw/FileStream.h> +#include <io/FileStream.h> #include <io/ZipArchive.h> #include "Command.h" diff --git a/tools/aapt2/cmd/Link.cpp b/tools/aapt2/cmd/Link.cpp index 9ca546fc8d89..c638873873dc 100644 --- a/tools/aapt2/cmd/Link.cpp +++ b/tools/aapt2/cmd/Link.cpp @@ -35,8 +35,6 @@ #include "android-base/expected.h" #include "android-base/file.h" #include "android-base/stringprintf.h" -#include "androidfw/BigBufferStream.h" -#include "androidfw/FileStream.h" #include "androidfw/IDiagnostics.h" #include "androidfw/Locale.h" #include "androidfw/StringPiece.h" @@ -50,6 +48,8 @@ #include "format/binary/XmlFlattener.h" #include "format/proto/ProtoDeserialize.h" #include "format/proto/ProtoSerialize.h" +#include "io/BigBufferStream.h" +#include "io/FileStream.h" #include "io/FileSystem.h" #include "io/Util.h" #include "io/ZipArchive.h" @@ -73,8 +73,8 @@ #include "util/Files.h" #include "xml/XmlDom.h" +using ::aapt::io::FileInputStream; using ::android::ConfigDescription; -using ::android::FileInputStream; using ::android::StringPiece; using ::android::base::expected; using ::android::base::StringPrintf; @@ -263,7 +263,7 @@ static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, S return false; } - android::BigBufferInputStream input_stream(&buffer); + io::BigBufferInputStream input_stream(&buffer); return io::CopyInputStreamToArchive(context, &input_stream, path, ArchiveEntry::kCompress, writer); } break; @@ -284,7 +284,7 @@ static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, S static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, android::IDiagnostics* diag) { TRACE_CALL(); - android::FileInputStream fin(path); + FileInputStream fin(path); if (fin.HadError()) { diag->Error(android::DiagMessage(path) << "failed to load XML file: " << fin.GetError()); return {}; @@ -687,7 +687,7 @@ bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archiv static bool WriteStableIdMapToPath(android::IDiagnostics* diag, const std::unordered_map<ResourceName, ResourceId>& id_map, const std::string& id_map_path) { - android::FileOutputStream fout(id_map_path); + io::FileOutputStream fout(id_map_path); if (fout.HadError()) { diag->Error(android::DiagMessage(id_map_path) << "failed to open: " << fout.GetError()); return false; @@ -1197,7 +1197,7 @@ class Linker { return false; } - android::BigBufferInputStream input_stream(&buffer); + io::BigBufferInputStream input_stream(&buffer); return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath, ArchiveEntry::kAlign, writer); } break; @@ -1221,7 +1221,7 @@ class Linker { } std::string out_path; - std::unique_ptr<android::FileOutputStream> fout; + std::unique_ptr<io::FileOutputStream> fout; if (options_.generate_java_class_path) { out_path = options_.generate_java_class_path.value(); file::AppendPath(&out_path, file::PackageToPath(out_package)); @@ -1233,7 +1233,7 @@ class Linker { file::AppendPath(&out_path, "R.java"); - fout = util::make_unique<android::FileOutputStream>(out_path); + fout = util::make_unique<io::FileOutputStream>(out_path); if (fout->HadError()) { context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path @@ -1242,9 +1242,9 @@ class Linker { } } - std::unique_ptr<android::FileOutputStream> fout_text; + std::unique_ptr<io::FileOutputStream> fout_text; if (out_text_symbols_path) { - fout_text = util::make_unique<android::FileOutputStream>(out_text_symbols_path.value()); + fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value()); if (fout_text->HadError()) { context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_text_symbols_path.value() @@ -1386,7 +1386,7 @@ class Linker { file::AppendPath(&out_path, "Manifest.java"); - android::FileOutputStream fout(out_path); + io::FileOutputStream fout(out_path); if (fout.HadError()) { context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path << "': " << fout.GetError()); @@ -1412,7 +1412,7 @@ class Linker { } const std::string& out_path = out.value(); - android::FileOutputStream fout(out_path); + io::FileOutputStream fout(out_path); if (fout.HadError()) { context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path << "': " << fout.GetError()); @@ -1601,7 +1601,7 @@ class Linker { } } - std::unique_ptr<android::InputStream> input_stream = file->OpenInputStream(); + std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream(); if (input_stream == nullptr) { context_->GetDiagnostics()->Error(android::DiagMessage(src) << "failed to open file"); return false; diff --git a/tools/aapt2/cmd/Optimize.cpp b/tools/aapt2/cmd/Optimize.cpp index 762441ee1872..f045dad6d11a 100644 --- a/tools/aapt2/cmd/Optimize.cpp +++ b/tools/aapt2/cmd/Optimize.cpp @@ -30,7 +30,6 @@ #include "ValueVisitor.h" #include "android-base/file.h" #include "android-base/stringprintf.h" -#include "androidfw/BigBufferStream.h" #include "androidfw/ConfigDescription.h" #include "androidfw/IDiagnostics.h" #include "androidfw/ResourceTypes.h" @@ -40,6 +39,7 @@ #include "filter/AbiFilter.h" #include "format/binary/TableFlattener.h" #include "format/binary/XmlFlattener.h" +#include "io/BigBufferStream.h" #include "io/Util.h" #include "optimize/MultiApkGenerator.h" #include "optimize/Obfuscator.h" @@ -249,7 +249,7 @@ class Optimizer { return false; } - android::BigBufferInputStream manifest_buffer_in(&manifest_buffer); + io::BigBufferInputStream manifest_buffer_in(&manifest_buffer); if (!io::CopyInputStreamToArchive(context_, &manifest_buffer_in, "AndroidManifest.xml", ArchiveEntry::kCompress, writer)) { return false; @@ -297,7 +297,7 @@ class Optimizer { return false; } - android::BigBufferInputStream table_buffer_in(&table_buffer); + io::BigBufferInputStream table_buffer_in(&table_buffer); return io::CopyInputStreamToArchive(context_, &table_buffer_in, "resources.arsc", ArchiveEntry::kAlign, writer); } diff --git a/libs/androidfw/include/androidfw/Image.h b/tools/aapt2/compile/Image.h index c18c34c25bf9..db0b945e1f18 100644 --- a/libs/androidfw/include/androidfw/Image.h +++ b/tools/aapt2/compile/Image.h @@ -14,7 +14,8 @@ * limitations under the License. */ -#pragma once +#ifndef AAPT_COMPILE_IMAGE_H +#define AAPT_COMPILE_IMAGE_H #include <cstdint> #include <memory> @@ -23,7 +24,7 @@ #include "android-base/macros.h" -namespace android { +namespace aapt { /** * An in-memory image, loaded from disk, with pixels in RGBA_8888 format. @@ -36,7 +37,7 @@ class Image { * A `height` sized array of pointers, where each element points to a * `width` sized row of RGBA_8888 pixels. */ - std::unique_ptr<uint8_t*[]> rows; + std::unique_ptr<uint8_t* []> rows; /** * The width of the image in RGBA_8888 pixels. This is int32_t because of @@ -71,8 +72,7 @@ struct Range { int32_t end = 0; explicit Range() = default; - inline explicit Range(int32_t s, int32_t e) : start(s), end(e) { - } + inline explicit Range(int32_t s, int32_t e) : start(s), end(e) {} }; inline bool operator==(const Range& left, const Range& right) { @@ -93,8 +93,7 @@ struct Bounds { explicit Bounds() = default; inline explicit Bounds(int32_t l, int32_t t, int32_t r, int32_t b) - : left(l), top(t), right(r), bottom(b) { - } + : left(l), top(t), right(r), bottom(b) {} bool nonZero() const; }; @@ -104,8 +103,8 @@ inline bool Bounds::nonZero() const { } inline bool operator==(const Bounds& left, const Bounds& right) { - return left.left == right.left && left.top == right.top && left.right == right.right && - left.bottom == right.bottom; + return left.left == right.left && left.top == right.top && + left.right == right.right && left.bottom == right.bottom; } /** @@ -116,7 +115,8 @@ inline bool operator==(const Bounds& left, const Bounds& right) { class NinePatch { public: static std::unique_ptr<NinePatch> Create(uint8_t** rows, const int32_t width, - const int32_t height, std::string* err_out); + const int32_t height, + std::string* err_out); /** * Packs the RGBA_8888 data pointed to by pixel into a uint32_t @@ -204,4 +204,6 @@ class NinePatch { ::std::ostream& operator<<(::std::ostream& out, const Bounds& bounds); ::std::ostream& operator<<(::std::ostream& out, const NinePatch& nine_patch); -} // namespace android
\ No newline at end of file +} // namespace aapt + +#endif /* AAPT_COMPILE_IMAGE_H */ diff --git a/libs/androidfw/NinePatch.cpp b/tools/aapt2/compile/NinePatch.cpp index 1fdbebfb6daa..4538ecc56e4c 100644 --- a/libs/androidfw/NinePatch.cpp +++ b/tools/aapt2/compile/NinePatch.cpp @@ -14,17 +14,20 @@ * limitations under the License. */ +#include "compile/Image.h" + #include <sstream> #include <string> #include <vector> -#include "androidfw/Image.h" #include "androidfw/ResourceTypes.h" #include "androidfw/StringPiece.h" +#include "util/Util.h" + using android::StringPiece; -namespace android { +namespace aapt { // Colors in the format 0xAARRGGBB (the way 9-patch expects it). constexpr static const uint32_t kColorOpaqueWhite = 0xffffffffu; @@ -87,8 +90,10 @@ class ColorValidator { // }; // template <typename ImageLine> -static bool FillRanges(const ImageLine* image_line, const ColorValidator* color_validator, - std::vector<Range>* primary_ranges, std::vector<Range>* secondary_ranges, +static bool FillRanges(const ImageLine* image_line, + const ColorValidator* color_validator, + std::vector<Range>* primary_ranges, + std::vector<Range>* secondary_ranges, std::string* out_err) { const int32_t length = image_line->GetLength(); @@ -128,13 +133,11 @@ static bool FillRanges(const ImageLine* image_line, const ColorValidator* color_ */ class HorizontalImageLine { public: - explicit HorizontalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset, int32_t length) - : rows_(rows), xoffset_(xoffset), yoffset_(yoffset), length_(length) { - } + explicit HorizontalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset, + int32_t length) + : rows_(rows), xoffset_(xoffset), yoffset_(yoffset), length_(length) {} - inline int32_t GetLength() const { - return length_; - } + inline int32_t GetLength() const { return length_; } inline uint32_t GetColor(int32_t idx) const { return NinePatch::PackRGBA(rows_[yoffset_] + (idx + xoffset_) * 4); @@ -153,13 +156,11 @@ class HorizontalImageLine { */ class VerticalImageLine { public: - explicit VerticalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset, int32_t length) - : rows_(rows), xoffset_(xoffset), yoffset_(yoffset), length_(length) { - } + explicit VerticalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset, + int32_t length) + : rows_(rows), xoffset_(xoffset), yoffset_(yoffset), length_(length) {} - inline int32_t GetLength() const { - return length_; - } + inline int32_t GetLength() const { return length_; } inline uint32_t GetColor(int32_t idx) const { return NinePatch::PackRGBA(rows_[yoffset_ + idx] + (xoffset_ * 4)); @@ -174,22 +175,20 @@ class VerticalImageLine { class DiagonalImageLine { public: - explicit DiagonalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset, int32_t xstep, - int32_t ystep, int32_t length) + explicit DiagonalImageLine(uint8_t** rows, int32_t xoffset, int32_t yoffset, + int32_t xstep, int32_t ystep, int32_t length) : rows_(rows), xoffset_(xoffset), yoffset_(yoffset), xstep_(xstep), ystep_(ystep), - length_(length) { - } + length_(length) {} - inline int32_t GetLength() const { - return length_; - } + inline int32_t GetLength() const { return length_; } inline uint32_t GetColor(int32_t idx) const { - return NinePatch::PackRGBA(rows_[yoffset_ + (idx * ystep_)] + ((idx + xoffset_) * xstep_) * 4); + return NinePatch::PackRGBA(rows_[yoffset_ + (idx * ystep_)] + + ((idx + xoffset_) * xstep_) * 4); } private: @@ -244,7 +243,8 @@ static bool PopulateBounds(const std::vector<Range>& padding, if (layout_bounds.size() > 2) { std::stringstream err_stream; - err_stream << "too many layout bounds sections on " << edge_name << " border"; + err_stream << "too many layout bounds sections on " << edge_name + << " border"; *out_err = err_stream.str(); return false; } @@ -258,7 +258,8 @@ static bool PopulateBounds(const std::vector<Range>& padding, // end at length. if (range.start != 0 && range.end != length) { std::stringstream err_stream; - err_stream << "layout bounds on " << edge_name << " border must start at edge"; + err_stream << "layout bounds on " << edge_name + << " border must start at edge"; *out_err = err_stream.str(); return false; } @@ -268,7 +269,8 @@ static bool PopulateBounds(const std::vector<Range>& padding, const Range& range = layout_bounds.back(); if (range.end != length) { std::stringstream err_stream; - err_stream << "layout bounds on " << edge_name << " border must start at edge"; + err_stream << "layout bounds on " << edge_name + << " border must start at edge"; *out_err = err_stream.str(); return false; } @@ -278,7 +280,8 @@ static bool PopulateBounds(const std::vector<Range>& padding, return true; } -static int32_t CalculateSegmentCount(const std::vector<Range>& stretch_regions, int32_t length) { +static int32_t CalculateSegmentCount(const std::vector<Range>& stretch_regions, + int32_t length) { if (stretch_regions.size() == 0) { return 0; } @@ -296,7 +299,8 @@ static int32_t CalculateSegmentCount(const std::vector<Range>& stretch_regions, static uint32_t GetRegionColor(uint8_t** rows, const Bounds& region) { // Sample the first pixel to compare against. - const uint32_t expected_color = NinePatch::PackRGBA(rows[region.top] + region.left * 4); + const uint32_t expected_color = + NinePatch::PackRGBA(rows[region.top] + region.left * 4); for (int32_t y = region.top; y < region.bottom; y++) { const uint8_t* row = rows[y]; for (int32_t x = region.left; x < region.right; x++) { @@ -332,11 +336,10 @@ static uint32_t GetRegionColor(uint8_t** rows, const Bounds& region) { // the indices must be offset by 1. // // width and height also include the 9-patch 1px border. -static void CalculateRegionColors(uint8_t** rows, - const std::vector<Range>& horizontal_stretch_regions, - const std::vector<Range>& vertical_stretch_regions, - const int32_t width, const int32_t height, - std::vector<uint32_t>* out_colors) { +static void CalculateRegionColors( + uint8_t** rows, const std::vector<Range>& horizontal_stretch_regions, + const std::vector<Range>& vertical_stretch_regions, const int32_t width, + const int32_t height, std::vector<uint32_t>* out_colors) { int32_t next_top = 0; Bounds bounds; auto row_iter = vertical_stretch_regions.begin(); @@ -398,7 +401,8 @@ static void CalculateRegionColors(uint8_t** rows, // alpha value begins // (on both sides). template <typename ImageLine> -static void FindOutlineInsets(const ImageLine* image_line, int32_t* out_start, int32_t* out_end) { +static void FindOutlineInsets(const ImageLine* image_line, int32_t* out_start, + int32_t* out_end) { *out_start = 0; *out_end = 0; @@ -451,8 +455,10 @@ uint32_t NinePatch::PackRGBA(const uint8_t* pixel) { return (pixel[3] << 24) | (pixel[0] << 16) | (pixel[1] << 8) | pixel[2]; } -std::unique_ptr<NinePatch> NinePatch::Create(uint8_t** rows, const int32_t width, - const int32_t height, std::string* out_err) { +std::unique_ptr<NinePatch> NinePatch::Create(uint8_t** rows, + const int32_t width, + const int32_t height, + std::string* out_err) { if (width < 3 || height < 3) { *out_err = "image must be at least 3x3 (1x1 image with 1 pixel border)"; return {}; @@ -466,11 +472,12 @@ std::unique_ptr<NinePatch> NinePatch::Create(uint8_t** rows, const int32_t width std::unique_ptr<ColorValidator> color_validator; if (rows[0][3] == 0) { - color_validator = std::make_unique<TransparentNeutralColorValidator>(); + color_validator = util::make_unique<TransparentNeutralColorValidator>(); } else if (PackRGBA(rows[0]) == kColorOpaqueWhite) { - color_validator = std::make_unique<WhiteNeutralColorValidator>(); + color_validator = util::make_unique<WhiteNeutralColorValidator>(); } else { - *out_err = "top-left corner pixel must be either opaque white or transparent"; + *out_err = + "top-left corner pixel must be either opaque white or transparent"; return {}; } @@ -478,8 +485,9 @@ std::unique_ptr<NinePatch> NinePatch::Create(uint8_t** rows, const int32_t width auto nine_patch = std::unique_ptr<NinePatch>(new NinePatch()); HorizontalImageLine top_row(rows, 0, 0, width); - if (!FillRanges(&top_row, color_validator.get(), &nine_patch->horizontal_stretch_regions, - &unexpected_ranges, out_err)) { + if (!FillRanges(&top_row, color_validator.get(), + &nine_patch->horizontal_stretch_regions, &unexpected_ranges, + out_err)) { return {}; } @@ -493,8 +501,9 @@ std::unique_ptr<NinePatch> NinePatch::Create(uint8_t** rows, const int32_t width } VerticalImageLine left_col(rows, 0, 0, height); - if (!FillRanges(&left_col, color_validator.get(), &nine_patch->vertical_stretch_regions, - &unexpected_ranges, out_err)) { + if (!FillRanges(&left_col, color_validator.get(), + &nine_patch->vertical_stretch_regions, &unexpected_ranges, + out_err)) { return {}; } @@ -513,28 +522,32 @@ std::unique_ptr<NinePatch> NinePatch::Create(uint8_t** rows, const int32_t width } if (!PopulateBounds(horizontal_padding, horizontal_layout_bounds, - nine_patch->horizontal_stretch_regions, width - 2, &nine_patch->padding.left, - &nine_patch->padding.right, &nine_patch->layout_bounds.left, + nine_patch->horizontal_stretch_regions, width - 2, + &nine_patch->padding.left, &nine_patch->padding.right, + &nine_patch->layout_bounds.left, &nine_patch->layout_bounds.right, "bottom", out_err)) { return {}; } VerticalImageLine right_col(rows, width - 1, 0, height); - if (!FillRanges(&right_col, color_validator.get(), &vertical_padding, &vertical_layout_bounds, - out_err)) { + if (!FillRanges(&right_col, color_validator.get(), &vertical_padding, + &vertical_layout_bounds, out_err)) { return {}; } if (!PopulateBounds(vertical_padding, vertical_layout_bounds, - nine_patch->vertical_stretch_regions, height - 2, &nine_patch->padding.top, - &nine_patch->padding.bottom, &nine_patch->layout_bounds.top, + nine_patch->vertical_stretch_regions, height - 2, + &nine_patch->padding.top, &nine_patch->padding.bottom, + &nine_patch->layout_bounds.top, &nine_patch->layout_bounds.bottom, "right", out_err)) { return {}; } // Fill the region colors of the 9-patch. - const int32_t num_rows = CalculateSegmentCount(nine_patch->horizontal_stretch_regions, width - 2); - const int32_t num_cols = CalculateSegmentCount(nine_patch->vertical_stretch_regions, height - 2); + const int32_t num_rows = + CalculateSegmentCount(nine_patch->horizontal_stretch_regions, width - 2); + const int32_t num_cols = + CalculateSegmentCount(nine_patch->vertical_stretch_regions, height - 2); if ((int64_t)num_rows * (int64_t)num_cols > 0x7f) { *out_err = "too many regions in 9-patch"; return {}; @@ -542,35 +555,40 @@ std::unique_ptr<NinePatch> NinePatch::Create(uint8_t** rows, const int32_t width nine_patch->region_colors.reserve(num_rows * num_cols); CalculateRegionColors(rows, nine_patch->horizontal_stretch_regions, - nine_patch->vertical_stretch_regions, width - 2, height - 2, - &nine_patch->region_colors); + nine_patch->vertical_stretch_regions, width - 2, + height - 2, &nine_patch->region_colors); // Compute the outline based on opacity. // Find left and right extent of 9-patch content on center row. HorizontalImageLine mid_row(rows, 1, height / 2, width - 2); - FindOutlineInsets(&mid_row, &nine_patch->outline.left, &nine_patch->outline.right); + FindOutlineInsets(&mid_row, &nine_patch->outline.left, + &nine_patch->outline.right); // Find top and bottom extent of 9-patch content on center column. VerticalImageLine mid_col(rows, width / 2, 1, height - 2); - FindOutlineInsets(&mid_col, &nine_patch->outline.top, &nine_patch->outline.bottom); + FindOutlineInsets(&mid_col, &nine_patch->outline.top, + &nine_patch->outline.bottom); - const int32_t outline_width = (width - 2) - nine_patch->outline.left - nine_patch->outline.right; + const int32_t outline_width = + (width - 2) - nine_patch->outline.left - nine_patch->outline.right; const int32_t outline_height = (height - 2) - nine_patch->outline.top - nine_patch->outline.bottom; // Find the largest alpha value within the outline area. - HorizontalImageLine outline_mid_row(rows, 1 + nine_patch->outline.left, - 1 + nine_patch->outline.top + (outline_height / 2), - outline_width); - VerticalImageLine outline_mid_col(rows, 1 + nine_patch->outline.left + (outline_width / 2), - 1 + nine_patch->outline.top, outline_height); + HorizontalImageLine outline_mid_row( + rows, 1 + nine_patch->outline.left, + 1 + nine_patch->outline.top + (outline_height / 2), outline_width); + VerticalImageLine outline_mid_col( + rows, 1 + nine_patch->outline.left + (outline_width / 2), + 1 + nine_patch->outline.top, outline_height); nine_patch->outline_alpha = std::max(FindMaxAlpha(&outline_mid_row), FindMaxAlpha(&outline_mid_col)); // Assuming the image is a round rect, compute the radius by marching // diagonally from the top left corner towards the center. - DiagonalImageLine diagonal(rows, 1 + nine_patch->outline.left, 1 + nine_patch->outline.top, 1, 1, + DiagonalImageLine diagonal(rows, 1 + nine_patch->outline.left, + 1 + nine_patch->outline.top, 1, 1, std::min(outline_width, outline_height)); int32_t top_left, bottom_right; FindOutlineInsets(&diagonal, &top_left, &bottom_right); @@ -596,9 +614,10 @@ std::unique_ptr<uint8_t[]> NinePatch::SerializeBase(size_t* outLen) const { data.paddingBottom = padding.bottom; auto buffer = std::unique_ptr<uint8_t[]>(new uint8_t[data.serializedSize()]); - android::Res_png_9patch::serialize(data, (const int32_t*)horizontal_stretch_regions.data(), - (const int32_t*)vertical_stretch_regions.data(), - region_colors.data(), buffer.get()); + android::Res_png_9patch::serialize( + data, (const int32_t*)horizontal_stretch_regions.data(), + (const int32_t*)vertical_stretch_regions.data(), region_colors.data(), + buffer.get()); // Convert to file endianness. reinterpret_cast<android::Res_png_9patch*>(buffer.get())->deviceToFile(); @@ -606,7 +625,8 @@ std::unique_ptr<uint8_t[]> NinePatch::SerializeBase(size_t* outLen) const { return buffer; } -std::unique_ptr<uint8_t[]> NinePatch::SerializeLayoutBounds(size_t* out_len) const { +std::unique_ptr<uint8_t[]> NinePatch::SerializeLayoutBounds( + size_t* out_len) const { size_t chunk_len = sizeof(uint32_t) * 4; auto buffer = std::unique_ptr<uint8_t[]>(new uint8_t[chunk_len]); uint8_t* cursor = buffer.get(); @@ -627,7 +647,8 @@ std::unique_ptr<uint8_t[]> NinePatch::SerializeLayoutBounds(size_t* out_len) con return buffer; } -std::unique_ptr<uint8_t[]> NinePatch::SerializeRoundedRectOutline(size_t* out_len) const { +std::unique_ptr<uint8_t[]> NinePatch::SerializeRoundedRectOutline( + size_t* out_len) const { size_t chunk_len = sizeof(uint32_t) * 6; auto buffer = std::unique_ptr<uint8_t[]>(new uint8_t[chunk_len]); uint8_t* cursor = buffer.get(); @@ -658,25 +679,20 @@ std::unique_ptr<uint8_t[]> NinePatch::SerializeRoundedRectOutline(size_t* out_le } ::std::ostream& operator<<(::std::ostream& out, const Bounds& bounds) { - return out << "l=" << bounds.left << " t=" << bounds.top << " r=" << bounds.right - << " b=" << bounds.bottom; -} - -template <typename T> -std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { - for (int i = 0; i < v.size(); ++i) { - os << v[i]; - if (i != v.size() - 1) os << " "; - } - return os; + return out << "l=" << bounds.left << " t=" << bounds.top + << " r=" << bounds.right << " b=" << bounds.bottom; } ::std::ostream& operator<<(::std::ostream& out, const NinePatch& nine_patch) { - return out << "horizontalStretch:" << nine_patch.horizontal_stretch_regions - << " verticalStretch:" << nine_patch.vertical_stretch_regions - << " padding: " << nine_patch.padding << ", bounds: " << nine_patch.layout_bounds - << ", outline: " << nine_patch.outline << " rad=" << nine_patch.outline_radius + return out << "horizontalStretch:" + << util::Joiner(nine_patch.horizontal_stretch_regions, " ") + << " verticalStretch:" + << util::Joiner(nine_patch.vertical_stretch_regions, " ") + << " padding: " << nine_patch.padding + << ", bounds: " << nine_patch.layout_bounds + << ", outline: " << nine_patch.outline + << " rad=" << nine_patch.outline_radius << " alpha=" << nine_patch.outline_alpha; } -} // namespace android +} // namespace aapt diff --git a/libs/androidfw/tests/NinePatch_test.cpp b/tools/aapt2/compile/NinePatch_test.cpp index 7ee8e9ebd624..f54bb2e62842 100644 --- a/libs/androidfw/tests/NinePatch_test.cpp +++ b/tools/aapt2/compile/NinePatch_test.cpp @@ -14,11 +14,11 @@ * limitations under the License. */ -#include "androidfw/Image.h" -#include "androidfw/ResourceTypes.h" -#include "gtest/gtest.h" +#include "compile/Image.h" -namespace android { +#include "test/Test.h" + +namespace aapt { // Pixels are in RGBA_8888 packing. @@ -33,19 +33,16 @@ namespace android { #define TRANS "\x00\x00\x00\x00" static uint8_t* k2x2[] = { - (uint8_t*)WHITE WHITE, - (uint8_t*)WHITE WHITE, + (uint8_t*)WHITE WHITE, (uint8_t*)WHITE WHITE, }; static uint8_t* kMixedNeutralColor3x3[] = { - (uint8_t*)WHITE BLACK TRANS, - (uint8_t*)TRANS RED TRANS, + (uint8_t*)WHITE BLACK TRANS, (uint8_t*)TRANS RED TRANS, (uint8_t*)WHITE WHITE WHITE, }; static uint8_t* kTransparentNeutralColor3x3[] = { - (uint8_t*)TRANS BLACK TRANS, - (uint8_t*)BLACK RED BLACK, + (uint8_t*)TRANS BLACK TRANS, (uint8_t*)BLACK RED BLACK, (uint8_t*)TRANS BLACK TRANS, }; @@ -69,44 +66,55 @@ static uint8_t* kMultipleStretch10x7[] = { }; static uint8_t* kPadding6x5[] = { - (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE, - (uint8_t*)WHITE WHITE WHITE WHITE WHITE BLACK, (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE BLACK, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE BLACK BLACK WHITE WHITE, }; static uint8_t* kLayoutBoundsWrongEdge3x3[] = { - (uint8_t*)WHITE RED WHITE, - (uint8_t*)RED WHITE WHITE, + (uint8_t*)WHITE RED WHITE, (uint8_t*)RED WHITE WHITE, (uint8_t*)WHITE WHITE WHITE, }; static uint8_t* kLayoutBoundsNotEdgeAligned5x5[] = { - (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE WHITE, - (uint8_t*)WHITE WHITE WHITE WHITE RED, (uint8_t*)WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE RED, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE RED WHITE WHITE, }; static uint8_t* kLayoutBounds5x5[] = { - (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE RED, - (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE RED, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE RED, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE RED, (uint8_t*)WHITE RED WHITE RED WHITE, }; static uint8_t* kAsymmetricLayoutBounds5x5[] = { - (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE RED, - (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE RED, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE RED WHITE WHITE WHITE, }; static uint8_t* kPaddingAndLayoutBounds5x5[] = { - (uint8_t*)WHITE WHITE WHITE WHITE WHITE, (uint8_t*)WHITE WHITE WHITE WHITE RED, - (uint8_t*)WHITE WHITE WHITE WHITE BLACK, (uint8_t*)WHITE WHITE WHITE WHITE RED, + (uint8_t*)WHITE WHITE WHITE WHITE WHITE, + (uint8_t*)WHITE WHITE WHITE WHITE RED, + (uint8_t*)WHITE WHITE WHITE WHITE BLACK, + (uint8_t*)WHITE WHITE WHITE WHITE RED, (uint8_t*)WHITE RED BLACK RED WHITE, }; static uint8_t* kColorfulImage5x5[] = { - (uint8_t*)WHITE BLACK WHITE BLACK WHITE, (uint8_t*)BLACK RED BLUE GREEN WHITE, - (uint8_t*)BLACK RED GREEN GREEN WHITE, (uint8_t*)WHITE TRANS BLUE GREEN WHITE, + (uint8_t*)WHITE BLACK WHITE BLACK WHITE, + (uint8_t*)BLACK RED BLUE GREEN WHITE, + (uint8_t*)BLACK RED GREEN GREEN WHITE, + (uint8_t*)WHITE TRANS BLUE GREEN WHITE, (uint8_t*)WHITE WHITE WHITE WHITE WHITE, }; @@ -137,21 +145,33 @@ static uint8_t* kOutlineTranslucent10x10[] = { }; static uint8_t* kOutlineOffsetTranslucent12x10[] = { - (uint8_t*)WHITE WHITE WHITE BLACK BLACK BLACK BLACK BLACK BLACK BLACK BLACK WHITE, - (uint8_t*)WHITE TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS WHITE, - (uint8_t*)WHITE TRANS TRANS TRANS TRANS GR_20 GR_20 GR_20 GR_20 TRANS TRANS WHITE, - (uint8_t*)WHITE TRANS TRANS TRANS TRANS GR_50 GR_50 GR_50 GR_50 TRANS TRANS WHITE, - (uint8_t*)WHITE TRANS TRANS TRANS GR_20 GR_50 GR_70 GR_70 GR_50 GR_20 TRANS WHITE, - (uint8_t*)WHITE TRANS TRANS TRANS GR_20 GR_50 GR_70 GR_70 GR_50 GR_20 TRANS WHITE, - (uint8_t*)WHITE TRANS TRANS TRANS TRANS GR_50 GR_50 GR_50 GR_50 TRANS TRANS WHITE, - (uint8_t*)WHITE TRANS TRANS TRANS TRANS GR_20 GR_20 GR_20 GR_20 TRANS TRANS WHITE, - (uint8_t*)WHITE TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS WHITE, - (uint8_t*)WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE, + (uint8_t*) + WHITE WHITE WHITE BLACK BLACK BLACK BLACK BLACK BLACK BLACK BLACK WHITE, + (uint8_t*) + WHITE TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS WHITE, + (uint8_t*) + WHITE TRANS TRANS TRANS TRANS GR_20 GR_20 GR_20 GR_20 TRANS TRANS WHITE, + (uint8_t*) + WHITE TRANS TRANS TRANS TRANS GR_50 GR_50 GR_50 GR_50 TRANS TRANS WHITE, + (uint8_t*) + WHITE TRANS TRANS TRANS GR_20 GR_50 GR_70 GR_70 GR_50 GR_20 TRANS WHITE, + (uint8_t*) + WHITE TRANS TRANS TRANS GR_20 GR_50 GR_70 GR_70 GR_50 GR_20 TRANS WHITE, + (uint8_t*) + WHITE TRANS TRANS TRANS TRANS GR_50 GR_50 GR_50 GR_50 TRANS TRANS WHITE, + (uint8_t*) + WHITE TRANS TRANS TRANS TRANS GR_20 GR_20 GR_20 GR_20 TRANS TRANS WHITE, + (uint8_t*) + WHITE TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS TRANS WHITE, + (uint8_t*) + WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE WHITE, }; static uint8_t* kOutlineRadius5x5[] = { - (uint8_t*)WHITE BLACK BLACK BLACK WHITE, (uint8_t*)BLACK TRANS GREEN TRANS WHITE, - (uint8_t*)BLACK GREEN GREEN GREEN WHITE, (uint8_t*)BLACK TRANS GREEN TRANS WHITE, + (uint8_t*)WHITE BLACK BLACK BLACK WHITE, + (uint8_t*)BLACK TRANS GREEN TRANS WHITE, + (uint8_t*)BLACK GREEN GREEN GREEN WHITE, + (uint8_t*)BLACK TRANS GREEN TRANS WHITE, (uint8_t*)WHITE WHITE WHITE WHITE WHITE, }; @@ -175,12 +195,14 @@ TEST(NinePatchTest, MixedNeutralColors) { TEST(NinePatchTest, TransparentNeutralColor) { std::string err; - EXPECT_NE(nullptr, NinePatch::Create(kTransparentNeutralColor3x3, 3, 3, &err)); + EXPECT_NE(nullptr, + NinePatch::Create(kTransparentNeutralColor3x3, 3, 3, &err)); } TEST(NinePatchTest, SingleStretchRegion) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kSingleStretch7x6, 7, 6, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kSingleStretch7x6, 7, 6, &err); ASSERT_NE(nullptr, nine_patch); ASSERT_EQ(1u, nine_patch->horizontal_stretch_regions.size()); @@ -192,7 +214,8 @@ TEST(NinePatchTest, SingleStretchRegion) { TEST(NinePatchTest, MultipleStretchRegions) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kMultipleStretch10x7, 10, 7, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kMultipleStretch10x7, 10, 7, &err); ASSERT_NE(nullptr, nine_patch); ASSERT_EQ(3u, nine_patch->horizontal_stretch_regions.size()); @@ -208,14 +231,16 @@ TEST(NinePatchTest, MultipleStretchRegions) { TEST(NinePatchTest, InferPaddingFromStretchRegions) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kMultipleStretch10x7, 10, 7, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kMultipleStretch10x7, 10, 7, &err); ASSERT_NE(nullptr, nine_patch); EXPECT_EQ(Bounds(1, 0, 1, 0), nine_patch->padding); } TEST(NinePatchTest, Padding) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kPadding6x5, 6, 5, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kPadding6x5, 6, 5, &err); ASSERT_NE(nullptr, nine_patch); EXPECT_EQ(Bounds(1, 1, 1, 1), nine_patch->padding); } @@ -228,13 +253,15 @@ TEST(NinePatchTest, LayoutBoundsAreOnWrongEdge) { TEST(NinePatchTest, LayoutBoundsMustTouchEdges) { std::string err; - EXPECT_EQ(nullptr, NinePatch::Create(kLayoutBoundsNotEdgeAligned5x5, 5, 5, &err)); + EXPECT_EQ(nullptr, + NinePatch::Create(kLayoutBoundsNotEdgeAligned5x5, 5, 5, &err)); EXPECT_FALSE(err.empty()); } TEST(NinePatchTest, LayoutBounds) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kLayoutBounds5x5, 5, 5, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kLayoutBounds5x5, 5, 5, &err); ASSERT_NE(nullptr, nine_patch); EXPECT_EQ(Bounds(1, 1, 1, 1), nine_patch->layout_bounds); @@ -245,7 +272,8 @@ TEST(NinePatchTest, LayoutBounds) { TEST(NinePatchTest, PaddingAndLayoutBounds) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kPaddingAndLayoutBounds5x5, 5, 5, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kPaddingAndLayoutBounds5x5, 5, 5, &err); ASSERT_NE(nullptr, nine_patch); EXPECT_EQ(Bounds(1, 1, 1, 1), nine_patch->padding); EXPECT_EQ(Bounds(1, 1, 1, 1), nine_patch->layout_bounds); @@ -253,20 +281,25 @@ TEST(NinePatchTest, PaddingAndLayoutBounds) { TEST(NinePatchTest, RegionColorsAreCorrect) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kColorfulImage5x5, 5, 5, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kColorfulImage5x5, 5, 5, &err); ASSERT_NE(nullptr, nine_patch); std::vector<uint32_t> expected_colors = { - NinePatch::PackRGBA((uint8_t*)RED), (uint32_t)android::Res_png_9patch::NO_COLOR, - NinePatch::PackRGBA((uint8_t*)GREEN), (uint32_t)android::Res_png_9patch::TRANSPARENT_COLOR, - NinePatch::PackRGBA((uint8_t*)BLUE), NinePatch::PackRGBA((uint8_t*)GREEN), + NinePatch::PackRGBA((uint8_t*)RED), + (uint32_t)android::Res_png_9patch::NO_COLOR, + NinePatch::PackRGBA((uint8_t*)GREEN), + (uint32_t)android::Res_png_9patch::TRANSPARENT_COLOR, + NinePatch::PackRGBA((uint8_t*)BLUE), + NinePatch::PackRGBA((uint8_t*)GREEN), }; EXPECT_EQ(expected_colors, nine_patch->region_colors); } TEST(NinePatchTest, OutlineFromOpaqueImage) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kOutlineOpaque10x10, 10, 10, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kOutlineOpaque10x10, 10, 10, &err); ASSERT_NE(nullptr, nine_patch); EXPECT_EQ(Bounds(2, 2, 2, 2), nine_patch->outline); EXPECT_EQ(0x000000ffu, nine_patch->outline_alpha); @@ -275,7 +308,8 @@ TEST(NinePatchTest, OutlineFromOpaqueImage) { TEST(NinePatchTest, OutlineFromTranslucentImage) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kOutlineTranslucent10x10, 10, 10, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kOutlineTranslucent10x10, 10, 10, &err); ASSERT_NE(nullptr, nine_patch); EXPECT_EQ(Bounds(3, 3, 3, 3), nine_patch->outline); EXPECT_EQ(0x000000b3u, nine_patch->outline_alpha); @@ -303,7 +337,8 @@ TEST(NinePatchTest, OutlineFromOffCenterImage) { TEST(NinePatchTest, OutlineRadius) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kOutlineRadius5x5, 5, 5, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kOutlineRadius5x5, 5, 5, &err); ASSERT_NE(nullptr, nine_patch); EXPECT_EQ(Bounds(0, 0, 0, 0), nine_patch->outline); EXPECT_EQ(3.4142f, nine_patch->outline_radius); @@ -318,7 +353,8 @@ TEST(NinePatchTest, OutlineRadius) { TEST(NinePatchTest, SerializePngEndianness) { std::string err; - std::unique_ptr<NinePatch> nine_patch = NinePatch::Create(kStretchAndPadding5x5, 5, 5, &err); + std::unique_ptr<NinePatch> nine_patch = + NinePatch::Create(kStretchAndPadding5x5, 5, 5, &err); ASSERT_NE(nullptr, nine_patch); size_t len; @@ -338,4 +374,4 @@ TEST(NinePatchTest, SerializePngEndianness) { EXPECT_TRUE(BigEndianOne(cursor + 12)); } -} // namespace android +} // namespace aapt diff --git a/libs/androidfw/Png.cpp b/tools/aapt2/compile/Png.cpp index fb45cd9b49d0..76db815129dd 100644 --- a/libs/androidfw/Png.cpp +++ b/tools/aapt2/compile/Png.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "androidfw/Png.h" +#include "Png.h" #include <png.h> #include <zlib.h> @@ -24,12 +24,13 @@ #include <string> #include <vector> -#include "android-base/strings.h" #include "androidfw/BigBuffer.h" #include "androidfw/ResourceTypes.h" #include "androidfw/Source.h" +#include "trace/TraceBuffer.h" +#include "util/Util.h" -namespace android { +namespace aapt { constexpr bool kDebug = false; @@ -46,8 +47,9 @@ struct PngInfo { } void* serialize9Patch() { - void* serialized = Res_png_9patch::serialize(info9Patch, xDivs, yDivs, colors.data()); - reinterpret_cast<Res_png_9patch*>(serialized)->deviceToFile(); + void* serialized = android::Res_png_9patch::serialize(info9Patch, xDivs, + yDivs, colors.data()); + reinterpret_cast<android::Res_png_9patch*>(serialized)->deviceToFile(); return serialized; } @@ -56,7 +58,7 @@ struct PngInfo { std::vector<png_bytep> rows; bool is9Patch = false; - Res_png_9patch info9Patch; + android::Res_png_9patch info9Patch; int32_t* xDivs = nullptr; int32_t* yDivs = nullptr; std::vector<uint32_t> colors; @@ -77,30 +79,34 @@ struct PngInfo { uint8_t outlineAlpha; }; -static void readDataFromStream(png_structp readPtr, png_bytep data, png_size_t length) { - std::istream* input = reinterpret_cast<std::istream*>(png_get_io_ptr(readPtr)); +static void readDataFromStream(png_structp readPtr, png_bytep data, + png_size_t length) { + std::istream* input = + reinterpret_cast<std::istream*>(png_get_io_ptr(readPtr)); if (!input->read(reinterpret_cast<char*>(data), length)) { png_error(readPtr, strerror(errno)); } } -static void writeDataToStream(png_structp writePtr, png_bytep data, png_size_t length) { - BigBuffer* outBuffer = reinterpret_cast<BigBuffer*>(png_get_io_ptr(writePtr)); +static void writeDataToStream(png_structp writePtr, png_bytep data, + png_size_t length) { + android::BigBuffer* outBuffer = reinterpret_cast<android::BigBuffer*>(png_get_io_ptr(writePtr)); png_bytep buf = outBuffer->NextBlock<png_byte>(length); memcpy(buf, data, length); } -static void flushDataToStream(png_structp /*writePtr*/) { -} +static void flushDataToStream(png_structp /*writePtr*/) {} static void logWarning(png_structp readPtr, png_const_charp warningMessage) { - IDiagnostics* diag = reinterpret_cast<IDiagnostics*>(png_get_error_ptr(readPtr)); - diag->Warn(DiagMessage() << warningMessage); + android::IDiagnostics* diag = + reinterpret_cast<android::IDiagnostics*>(png_get_error_ptr(readPtr)); + diag->Warn(android::DiagMessage() << warningMessage); } -static bool readPng(IDiagnostics* diag, png_structp readPtr, png_infop infoPtr, PngInfo* outInfo) { +static bool readPng(android::IDiagnostics* diag, png_structp readPtr, png_infop infoPtr, + PngInfo* outInfo) { if (setjmp(png_jmpbuf(readPtr))) { - diag->Error(DiagMessage() << "failed reading png"); + diag->Error(android::DiagMessage() << "failed reading png"); return false; } @@ -108,8 +114,8 @@ static bool readPng(IDiagnostics* diag, png_structp readPtr, png_infop infoPtr, png_read_info(readPtr, infoPtr); int colorType, bitDepth, interlaceType, compressionType; - png_get_IHDR(readPtr, infoPtr, &outInfo->width, &outInfo->height, &bitDepth, &colorType, - &interlaceType, &compressionType, nullptr); + png_get_IHDR(readPtr, infoPtr, &outInfo->width, &outInfo->height, &bitDepth, + &colorType, &interlaceType, &compressionType, nullptr); if (colorType == PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(readPtr); @@ -131,7 +137,8 @@ static bool readPng(IDiagnostics* diag, png_structp readPtr, png_infop infoPtr, png_set_add_alpha(readPtr, 0xFF, PNG_FILLER_AFTER); } - if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA) { + if (colorType == PNG_COLOR_TYPE_GRAY || + colorType == PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(readPtr); } @@ -149,11 +156,12 @@ static bool readPng(IDiagnostics* diag, png_structp readPtr, png_infop infoPtr, return true; } -static void checkNinePatchSerialization(Res_png_9patch* inPatch, void* data) { +static void checkNinePatchSerialization(android::Res_png_9patch* inPatch, + void* data) { size_t patchSize = inPatch->serializedSize(); void* newData = malloc(patchSize); memcpy(newData, data, patchSize); - Res_png_9patch* outPatch = inPatch->deserialize(newData); + android::Res_png_9patch* outPatch = inPatch->deserialize(newData); outPatch->fileToDevice(); // deserialization is done in place, so outPatch == newData assert(outPatch == newData); @@ -236,9 +244,10 @@ PNG_COLOR_TYPE_RGB_ALPHA) { #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define ABS(a) ((a) < 0 ? -(a) : (a)) -static void analyze_image(IDiagnostics* diag, const PngInfo& imageInfo, int grayscaleTolerance, - png_colorp rgbPalette, png_bytep alphaPalette, int* paletteEntries, - bool* hasTransparency, int* colorType, png_bytepp outRows) { +static void analyze_image(android::IDiagnostics* diag, const PngInfo& imageInfo, + int grayscaleTolerance, png_colorp rgbPalette, png_bytep alphaPalette, + int* paletteEntries, bool* hasTransparency, int* colorType, + png_bytepp outRows) { int w = imageInfo.width; int h = imageInfo.height; int i, j, rr, gg, bb, aa, idx; @@ -275,8 +284,8 @@ static void analyze_image(IDiagnostics* diag, const PngInfo& imageInfo, int gray maxGrayDeviation = MAX(ABS(bb - rr), maxGrayDeviation); if (maxGrayDeviation > odev) { if (kDebug) { - printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n", maxGrayDeviation, i, j, - rr, gg, bb, aa); + printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n", + maxGrayDeviation, i, j, rr, gg, bb, aa); } } @@ -284,7 +293,8 @@ static void analyze_image(IDiagnostics* diag, const PngInfo& imageInfo, int gray if (isGrayscale) { if (rr != gg || rr != bb) { if (kDebug) { - printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n", i, j, rr, gg, bb, aa); + printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n", i, j, + rr, gg, bb, aa); } isGrayscale = false; } @@ -294,7 +304,8 @@ static void analyze_image(IDiagnostics* diag, const PngInfo& imageInfo, int gray if (isOpaque) { if (aa != 0xff) { if (kDebug) { - printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n", i, j, rr, gg, bb, aa); + printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n", i, j, + rr, gg, bb, aa); } isOpaque = false; } @@ -338,9 +349,10 @@ static void analyze_image(IDiagnostics* diag, const PngInfo& imageInfo, int gray printf("isGrayscale = %s\n", isGrayscale ? "true" : "false"); printf("isOpaque = %s\n", isOpaque ? "true" : "false"); printf("isPalette = %s\n", isPalette ? "true" : "false"); - printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n", paletteSize, 2 * w * h, - bpp * w * h); - printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance); + printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n", paletteSize, + 2 * w * h, bpp * w * h); + printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, + grayscaleTolerance); } // Choose the best color type for the image. @@ -369,8 +381,8 @@ static void analyze_image(IDiagnostics* diag, const PngInfo& imageInfo, int gray *colorType = PNG_COLOR_TYPE_PALETTE; } else { if (maxGrayDeviation <= grayscaleTolerance) { - diag->Note(DiagMessage() << "forcing image to gray (max deviation = " << maxGrayDeviation - << ")"); + diag->Note(android::DiagMessage() + << "forcing image to gray (max deviation = " << maxGrayDeviation << ")"); *colorType = isOpaque ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_GRAY_ALPHA; } else { *colorType = isOpaque ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA; @@ -392,7 +404,8 @@ static void analyze_image(IDiagnostics* diag, const PngInfo& imageInfo, int gray rgbPalette[idx].blue = (png_byte)((col >> 8) & 0xff); alphaPalette[idx] = (png_byte)(col & 0xff); } - } else if (*colorType == PNG_COLOR_TYPE_GRAY || *colorType == PNG_COLOR_TYPE_GRAY_ALPHA) { + } else if (*colorType == PNG_COLOR_TYPE_GRAY || + *colorType == PNG_COLOR_TYPE_GRAY_ALPHA) { // If the image is gray or gray + alpha, compact the pixels into outRows for (j = 0; j < h; j++) { const png_byte* row = imageInfo.rows[j]; @@ -416,10 +429,10 @@ static void analyze_image(IDiagnostics* diag, const PngInfo& imageInfo, int gray } } -static bool writePng(IDiagnostics* diag, png_structp writePtr, png_infop infoPtr, PngInfo* info, - int grayScaleTolerance) { +static bool writePng(android::IDiagnostics* diag, png_structp writePtr, png_infop infoPtr, + PngInfo* info, int grayScaleTolerance) { if (setjmp(png_jmpbuf(writePtr))) { - diag->Error(DiagMessage() << "failed to write png"); + diag->Error(android::DiagMessage() << "failed to write png"); return false; } @@ -431,7 +444,8 @@ static bool writePng(IDiagnostics* diag, png_structp writePtr, png_infop infoPtr unknowns[1].data = nullptr; unknowns[2].data = nullptr; - png_bytepp outRows = (png_bytepp)malloc((int)info->height * sizeof(png_bytep)); + png_bytepp outRows = + (png_bytepp)malloc((int)info->height * sizeof(png_bytep)); if (outRows == (png_bytepp)0) { printf("Can't allocate output buffer!\n"); exit(1); @@ -447,7 +461,8 @@ static bool writePng(IDiagnostics* diag, png_structp writePtr, png_infop infoPtr png_set_compression_level(writePtr, Z_BEST_COMPRESSION); if (kDebug) { - diag->Note(DiagMessage() << "writing image: w = " << info->width << ", h = " << info->height); + diag->Note(android::DiagMessage() + << "writing image: w = " << info->width << ", h = " << info->height); } png_color rgbPalette[256]; @@ -455,45 +470,48 @@ static bool writePng(IDiagnostics* diag, png_structp writePtr, png_infop infoPtr bool hasTransparency; int paletteEntries; - analyze_image(diag, *info, grayScaleTolerance, rgbPalette, alphaPalette, &paletteEntries, - &hasTransparency, &colorType, outRows); + analyze_image(diag, *info, grayScaleTolerance, rgbPalette, alphaPalette, + &paletteEntries, &hasTransparency, &colorType, outRows); // If the image is a 9-patch, we need to preserve it as a ARGB file to make // sure the pixels will not be pre-dithered/clamped until we decide they are - if (info->is9Patch && (colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_GRAY || - colorType == PNG_COLOR_TYPE_PALETTE)) { + if (info->is9Patch && + (colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_GRAY || + colorType == PNG_COLOR_TYPE_PALETTE)) { colorType = PNG_COLOR_TYPE_RGB_ALPHA; } if (kDebug) { switch (colorType) { case PNG_COLOR_TYPE_PALETTE: - diag->Note(DiagMessage() << "has " << paletteEntries << " colors" - << (hasTransparency ? " (with alpha)" : "") - << ", using PNG_COLOR_TYPE_PALLETTE"); + diag->Note(android::DiagMessage() << "has " << paletteEntries << " colors" + << (hasTransparency ? " (with alpha)" : "") + << ", using PNG_COLOR_TYPE_PALLETTE"); break; case PNG_COLOR_TYPE_GRAY: - diag->Note(DiagMessage() << "is opaque gray, using PNG_COLOR_TYPE_GRAY"); + diag->Note(android::DiagMessage() << "is opaque gray, using PNG_COLOR_TYPE_GRAY"); break; case PNG_COLOR_TYPE_GRAY_ALPHA: - diag->Note(DiagMessage() << "is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA"); + diag->Note(android::DiagMessage() << "is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA"); break; case PNG_COLOR_TYPE_RGB: - diag->Note(DiagMessage() << "is opaque RGB, using PNG_COLOR_TYPE_RGB"); + diag->Note(android::DiagMessage() << "is opaque RGB, using PNG_COLOR_TYPE_RGB"); break; case PNG_COLOR_TYPE_RGB_ALPHA: - diag->Note(DiagMessage() << "is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA"); + diag->Note(android::DiagMessage() << "is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA"); break; } } - png_set_IHDR(writePtr, infoPtr, info->width, info->height, 8, colorType, PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); + png_set_IHDR(writePtr, infoPtr, info->width, info->height, 8, colorType, + PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, + PNG_FILTER_TYPE_DEFAULT); if (colorType == PNG_COLOR_TYPE_PALETTE) { png_set_PLTE(writePtr, infoPtr, rgbPalette, paletteEntries); if (hasTransparency) { - png_set_tRNS(writePtr, infoPtr, alphaPalette, paletteEntries, (png_color_16p)0); + png_set_tRNS(writePtr, infoPtr, alphaPalette, paletteEntries, + (png_color_16p)0); } png_set_filter(writePtr, 0, PNG_NO_FILTERS); } else { @@ -508,12 +526,13 @@ static bool writePng(IDiagnostics* diag, png_structp writePtr, png_infop infoPtr // Chunks ordered thusly because older platforms depend on the base 9 patch // data being last - png_bytep chunkNames = - info->haveLayoutBounds ? (png_bytep) "npOl\0npLb\0npTc\0" : (png_bytep) "npOl\0npTc"; + png_bytep chunkNames = info->haveLayoutBounds + ? (png_bytep) "npOl\0npLb\0npTc\0" + : (png_bytep) "npOl\0npTc"; // base 9 patch data if (kDebug) { - diag->Note(DiagMessage() << "adding 9-patch info.."); + diag->Note(android::DiagMessage() << "adding 9-patch info.."); } memcpy((char*)unknowns[pIndex].name, "npTc", 5); unknowns[pIndex].data = (png_byte*)info->serialize9Patch(); @@ -544,7 +563,8 @@ static bool writePng(IDiagnostics* diag, png_structp writePtr, png_infop infoPtr for (int i = 0; i < chunkCount; i++) { unknowns[i].location = PNG_HAVE_PLTE; } - png_set_keep_unknown_chunks(writePtr, PNG_HANDLE_CHUNK_ALWAYS, chunkNames, chunkCount); + png_set_keep_unknown_chunks(writePtr, PNG_HANDLE_CHUNK_ALWAYS, chunkNames, + chunkCount); png_set_unknown_chunks(writePtr, infoPtr, unknowns, chunkCount); #if PNG_LIBPNG_VER < 10600 @@ -559,7 +579,8 @@ static bool writePng(IDiagnostics* diag, png_structp writePtr, png_infop infoPtr png_write_info(writePtr, infoPtr); png_bytepp rows; - if (colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_RGB_ALPHA) { + if (colorType == PNG_COLOR_TYPE_RGB || + colorType == PNG_COLOR_TYPE_RGB_ALPHA) { if (colorType == PNG_COLOR_TYPE_RGB) { png_set_filler(writePtr, 0, PNG_FILLER_AFTER); } @@ -584,13 +605,14 @@ static bool writePng(IDiagnostics* diag, png_structp writePtr, png_infop infoPtr free(unknowns[1].data); free(unknowns[2].data); - png_get_IHDR(writePtr, infoPtr, &width, &height, &bitDepth, &colorType, &interlaceType, - &compressionType, nullptr); + png_get_IHDR(writePtr, infoPtr, &width, &height, &bitDepth, &colorType, + &interlaceType, &compressionType, nullptr); if (kDebug) { - diag->Note(DiagMessage() << "image written: w = " << width << ", h = " << height - << ", d = " << bitDepth << ", colors = " << colorType - << ", inter = " << interlaceType << ", comp = " << compressionType); + diag->Note(android::DiagMessage() + << "image written: w = " << width << ", h = " << height << ", d = " << bitDepth + << ", colors = " << colorType << ", inter = " << interlaceType + << ", comp = " << compressionType); } return true; } @@ -651,8 +673,9 @@ static TickType tickType(png_bytep p, bool transparent, const char** outError) { enum class TickState { kStart, kInside1, kOutside1 }; -static bool getHorizontalTicks(png_bytep row, int width, bool transparent, bool required, - int32_t* outLeft, int32_t* outRight, const char** outError, +static bool getHorizontalTicks(png_bytep row, int width, bool transparent, + bool required, int32_t* outLeft, + int32_t* outRight, const char** outError, uint8_t* outDivs, bool multipleAllowed) { *outLeft = *outRight = -1; TickState state = TickState::kStart; @@ -660,7 +683,8 @@ static bool getHorizontalTicks(png_bytep row, int width, bool transparent, bool for (int i = 1; i < width - 1; i++) { if (tickType(row + i * 4, transparent, outError) == TickType::kTick) { - if (state == TickState::kStart || (state == TickState::kOutside1 && multipleAllowed)) { + if (state == TickState::kStart || + (state == TickState::kOutside1 && multipleAllowed)) { *outLeft = i - 1; *outRight = width - 2; found = true; @@ -695,16 +719,18 @@ static bool getHorizontalTicks(png_bytep row, int width, bool transparent, bool return true; } -static bool getVerticalTicks(png_bytepp rows, int offset, int height, bool transparent, - bool required, int32_t* outTop, int32_t* outBottom, - const char** outError, uint8_t* outDivs, bool multipleAllowed) { +static bool getVerticalTicks(png_bytepp rows, int offset, int height, + bool transparent, bool required, int32_t* outTop, + int32_t* outBottom, const char** outError, + uint8_t* outDivs, bool multipleAllowed) { *outTop = *outBottom = -1; TickState state = TickState::kStart; bool found = false; for (int i = 1; i < height - 1; i++) { if (tickType(rows[i] + offset, transparent, outError) == TickType::kTick) { - if (state == TickState::kStart || (state == TickState::kOutside1 && multipleAllowed)) { + if (state == TickState::kStart || + (state == TickState::kOutside1 && multipleAllowed)) { *outTop = i - 1; *outBottom = height - 2; found = true; @@ -739,8 +765,10 @@ static bool getVerticalTicks(png_bytepp rows, int offset, int height, bool trans return true; } -static bool getHorizontalLayoutBoundsTicks(png_bytep row, int width, bool transparent, - bool /* required */, int32_t* outLeft, int32_t* outRight, +static bool getHorizontalLayoutBoundsTicks(png_bytep row, int width, + bool transparent, + bool /* required */, + int32_t* outLeft, int32_t* outRight, const char** outError) { *outLeft = *outRight = 0; @@ -751,20 +779,23 @@ static bool getHorizontalLayoutBoundsTicks(png_bytep row, int width, bool transp while (i < width - 1) { (*outLeft)++; i++; - if (tickType(row + i * 4, transparent, outError) != TickType::kLayoutBounds) { + if (tickType(row + i * 4, transparent, outError) != + TickType::kLayoutBounds) { break; } } } // Look for right tick - if (tickType(row + (width - 2) * 4, transparent, outError) == TickType::kLayoutBounds) { + if (tickType(row + (width - 2) * 4, transparent, outError) == + TickType::kLayoutBounds) { // Ending with a layout padding tick int i = width - 2; while (i > 1) { (*outRight)++; i--; - if (tickType(row + i * 4, transparent, outError) != TickType::kLayoutBounds) { + if (tickType(row + i * 4, transparent, outError) != + TickType::kLayoutBounds) { break; } } @@ -772,32 +803,38 @@ static bool getHorizontalLayoutBoundsTicks(png_bytep row, int width, bool transp return true; } -static bool getVerticalLayoutBoundsTicks(png_bytepp rows, int offset, int height, bool transparent, - bool /* required */, int32_t* outTop, int32_t* outBottom, +static bool getVerticalLayoutBoundsTicks(png_bytepp rows, int offset, + int height, bool transparent, + bool /* required */, int32_t* outTop, + int32_t* outBottom, const char** outError) { *outTop = *outBottom = 0; // Look for top tick - if (tickType(rows[1] + offset, transparent, outError) == TickType::kLayoutBounds) { + if (tickType(rows[1] + offset, transparent, outError) == + TickType::kLayoutBounds) { // Starting with a layout padding tick int i = 1; while (i < height - 1) { (*outTop)++; i++; - if (tickType(rows[i] + offset, transparent, outError) != TickType::kLayoutBounds) { + if (tickType(rows[i] + offset, transparent, outError) != + TickType::kLayoutBounds) { break; } } } // Look for bottom tick - if (tickType(rows[height - 2] + offset, transparent, outError) == TickType::kLayoutBounds) { + if (tickType(rows[height - 2] + offset, transparent, outError) == + TickType::kLayoutBounds) { // Ending with a layout padding tick int i = height - 2; while (i > 1) { (*outBottom)++; i--; - if (tickType(rows[i] + offset, transparent, outError) != TickType::kLayoutBounds) { + if (tickType(rows[i] + offset, transparent, outError) != + TickType::kLayoutBounds) { break; } } @@ -805,12 +842,13 @@ static bool getVerticalLayoutBoundsTicks(png_bytepp rows, int offset, int height return true; } -static void findMaxOpacity(png_bytepp rows, int startX, int startY, int endX, int endY, int dX, - int dY, int* outInset) { +static void findMaxOpacity(png_bytepp rows, int startX, int startY, int endX, + int endY, int dX, int dY, int* outInset) { uint8_t maxOpacity = 0; int inset = 0; *outInset = 0; - for (int x = startX, y = startY; x != endX && y != endY; x += dX, y += dY, inset++) { + for (int x = startX, y = startY; x != endX && y != endY; + x += dX, y += dY, inset++) { png_byte* color = rows[y] + x * 4; uint8_t opacity = color[3]; if (opacity > maxOpacity) { @@ -830,7 +868,8 @@ static uint8_t maxAlphaOverRow(png_bytep row, int startX, int endX) { return maxAlpha; } -static uint8_t maxAlphaOverCol(png_bytepp rows, int offsetX, int startY, int endY) { +static uint8_t maxAlphaOverCol(png_bytepp rows, int offsetX, int startY, + int endY) { uint8_t maxAlpha = 0; for (int y = startY; y < endY; y++) { uint8_t alpha = (rows[y] + offsetX * 4)[3]; @@ -847,8 +886,10 @@ static void getOutline(PngInfo* image) { // find left and right extent of nine patch content on center row if (image->width > 4) { - findMaxOpacity(image->rows.data(), 1, midY, midX, -1, 1, 0, &image->outlineInsetsLeft); - findMaxOpacity(image->rows.data(), endX, midY, midX, -1, -1, 0, &image->outlineInsetsRight); + findMaxOpacity(image->rows.data(), 1, midY, midX, -1, 1, 0, + &image->outlineInsetsLeft); + findMaxOpacity(image->rows.data(), endX, midY, midX, -1, -1, 0, + &image->outlineInsetsRight); } else { image->outlineInsetsLeft = 0; image->outlineInsetsRight = 0; @@ -856,8 +897,10 @@ static void getOutline(PngInfo* image) { // find top and bottom extent of nine patch content on center column if (image->height > 4) { - findMaxOpacity(image->rows.data(), midX, 1, -1, midY, 0, 1, &image->outlineInsetsTop); - findMaxOpacity(image->rows.data(), midX, endY, -1, midY, 0, -1, &image->outlineInsetsBottom); + findMaxOpacity(image->rows.data(), midX, 1, -1, midY, 0, 1, + &image->outlineInsetsTop); + findMaxOpacity(image->rows.data(), midX, endY, -1, midY, 0, -1, + &image->outlineInsetsBottom); } else { image->outlineInsetsTop = 0; image->outlineInsetsBottom = 0; @@ -872,13 +915,13 @@ static void getOutline(PngInfo* image) { // assuming the image is a round rect, compute the radius by marching // diagonally from the top left corner towards the center - image->outlineAlpha = - std::max(maxAlphaOverRow(image->rows[innerMidY], innerStartX, innerEndX), - maxAlphaOverCol(image->rows.data(), innerMidX, innerStartY, innerStartY)); + image->outlineAlpha = std::max( + maxAlphaOverRow(image->rows[innerMidY], innerStartX, innerEndX), + maxAlphaOverCol(image->rows.data(), innerMidX, innerStartY, innerStartY)); int diagonalInset = 0; - findMaxOpacity(image->rows.data(), innerStartX, innerStartY, innerMidX, innerMidY, 1, 1, - &diagonalInset); + findMaxOpacity(image->rows.data(), innerStartX, innerStartY, innerMidX, + innerMidY, 1, 1, &diagonalInset); /* Determine source radius based upon inset: * sqrt(r^2 + r^2) = sqrt(i^2 + i^2) + r @@ -889,17 +932,19 @@ static void getOutline(PngInfo* image) { image->outlineRadius = 3.4142f * diagonalInset; if (kDebug) { - printf("outline insets %d %d %d %d, rad %f, alpha %x\n", image->outlineInsetsLeft, - image->outlineInsetsTop, image->outlineInsetsRight, image->outlineInsetsBottom, + printf("outline insets %d %d %d %d, rad %f, alpha %x\n", + image->outlineInsetsLeft, image->outlineInsetsTop, + image->outlineInsetsRight, image->outlineInsetsBottom, image->outlineRadius, image->outlineAlpha); } } -static uint32_t getColor(png_bytepp rows, int left, int top, int right, int bottom) { +static uint32_t getColor(png_bytepp rows, int left, int top, int right, + int bottom) { png_bytep color = rows[top] + left * 4; if (left > right || top > bottom) { - return Res_png_9patch::TRANSPARENT_COLOR; + return android::Res_png_9patch::TRANSPARENT_COLOR; } while (top <= bottom) { @@ -907,17 +952,18 @@ static uint32_t getColor(png_bytepp rows, int left, int top, int right, int bott png_bytep p = rows[top] + i * 4; if (color[3] == 0) { if (p[3] != 0) { - return Res_png_9patch::NO_COLOR; + return android::Res_png_9patch::NO_COLOR; } - } else if (p[0] != color[0] || p[1] != color[1] || p[2] != color[2] || p[3] != color[3]) { - return Res_png_9patch::NO_COLOR; + } else if (p[0] != color[0] || p[1] != color[1] || p[2] != color[2] || + p[3] != color[3]) { + return android::Res_png_9patch::NO_COLOR; } } top++; } if (color[3] == 0) { - return Res_png_9patch::TRANSPARENT_COLOR; + return android::Res_png_9patch::TRANSPARENT_COLOR; } return (color[3] << 24) | (color[0] << 16) | (color[1] << 8) | color[2]; } @@ -968,22 +1014,23 @@ static bool do9Patch(PngInfo* image, std::string* outError) { } // Validate frame... - if (!transparent && (p[0] != 0xFF || p[1] != 0xFF || p[2] != 0xFF || p[3] != 0xFF)) { + if (!transparent && + (p[0] != 0xFF || p[1] != 0xFF || p[2] != 0xFF || p[3] != 0xFF)) { errorMsg = "Must have one-pixel frame that is either transparent or white"; goto getout; } // Find left and right of sizing areas... - if (!getHorizontalTicks(p, W, transparent, true, &xDivs[0], &xDivs[1], &errorMsg, &numXDivs, - true)) { + if (!getHorizontalTicks(p, W, transparent, true, &xDivs[0], &xDivs[1], + &errorMsg, &numXDivs, true)) { errorPixel = xDivs[0]; errorEdge = "top"; goto getout; } // Find top and bottom of sizing areas... - if (!getVerticalTicks(image->rows.data(), 0, H, transparent, true, &yDivs[0], &yDivs[1], - &errorMsg, &numYDivs, true)) { + if (!getVerticalTicks(image->rows.data(), 0, H, transparent, true, &yDivs[0], + &yDivs[1], &errorMsg, &numYDivs, true)) { errorPixel = yDivs[0]; errorEdge = "left"; goto getout; @@ -994,8 +1041,10 @@ static bool do9Patch(PngInfo* image, std::string* outError) { image->info9Patch.numYDivs = numYDivs; // Find left and right of padding area... - if (!getHorizontalTicks(image->rows[H - 1], W, transparent, false, &image->info9Patch.paddingLeft, - &image->info9Patch.paddingRight, &errorMsg, nullptr, false)) { + if (!getHorizontalTicks(image->rows[H - 1], W, transparent, false, + &image->info9Patch.paddingLeft, + &image->info9Patch.paddingRight, &errorMsg, nullptr, + false)) { errorPixel = image->info9Patch.paddingLeft; errorEdge = "bottom"; goto getout; @@ -1003,8 +1052,9 @@ static bool do9Patch(PngInfo* image, std::string* outError) { // Find top and bottom of padding area... if (!getVerticalTicks(image->rows.data(), (W - 1) * 4, H, transparent, false, - &image->info9Patch.paddingTop, &image->info9Patch.paddingBottom, &errorMsg, - nullptr, false)) { + &image->info9Patch.paddingTop, + &image->info9Patch.paddingBottom, &errorMsg, nullptr, + false)) { errorPixel = image->info9Patch.paddingTop; errorEdge = "right"; goto getout; @@ -1012,18 +1062,22 @@ static bool do9Patch(PngInfo* image, std::string* outError) { // Find left and right of layout padding... getHorizontalLayoutBoundsTicks(image->rows[H - 1], W, transparent, false, - &image->layoutBoundsLeft, &image->layoutBoundsRight, &errorMsg); + &image->layoutBoundsLeft, + &image->layoutBoundsRight, &errorMsg); - getVerticalLayoutBoundsTicks(image->rows.data(), (W - 1) * 4, H, transparent, false, - &image->layoutBoundsTop, &image->layoutBoundsBottom, &errorMsg); + getVerticalLayoutBoundsTicks(image->rows.data(), (W - 1) * 4, H, transparent, + false, &image->layoutBoundsTop, + &image->layoutBoundsBottom, &errorMsg); - image->haveLayoutBounds = image->layoutBoundsLeft != 0 || image->layoutBoundsRight != 0 || - image->layoutBoundsTop != 0 || image->layoutBoundsBottom != 0; + image->haveLayoutBounds = + image->layoutBoundsLeft != 0 || image->layoutBoundsRight != 0 || + image->layoutBoundsTop != 0 || image->layoutBoundsBottom != 0; if (image->haveLayoutBounds) { if (kDebug) { - printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop, - image->layoutBoundsRight, image->layoutBoundsBottom); + printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, + image->layoutBoundsTop, image->layoutBoundsRight, + image->layoutBoundsBottom); } } @@ -1135,7 +1189,7 @@ static bool do9Patch(PngInfo* image, std::string* outError) { c = getColor(image->rows.data(), left, top, right - 1, bottom - 1); image->colors[colorIndex++] = c; if (kDebug) { - if (c != Res_png_9patch::NO_COLOR) { + if (c != android::Res_png_9patch::NO_COLOR) { hasColor = true; } } @@ -1160,7 +1214,8 @@ getout: if (errorEdge) { err << "." << std::endl; if (errorPixel >= 0) { - err << "Found at pixel #" << errorPixel << " along " << errorEdge << " edge"; + err << "Found at pixel #" << errorPixel << " along " << errorEdge + << " edge"; } else { err << "Found along " << errorEdge << " edge"; } @@ -1171,19 +1226,20 @@ getout: return true; } -bool Png::process(const Source& source, std::istream* input, BigBuffer* outBuffer, +bool Png::process(const android::Source& source, std::istream* input, android::BigBuffer* outBuffer, const PngOptions& options) { + TRACE_CALL(); png_byte signature[kPngSignatureSize]; // Read the PNG signature first. if (!input->read(reinterpret_cast<char*>(signature), kPngSignatureSize)) { - mDiag->Error(DiagMessage() << strerror(errno)); + mDiag->Error(android::DiagMessage() << strerror(errno)); return false; } // If the PNG signature doesn't match, bail early. if (png_sig_cmp(signature, 0, kPngSignatureSize) != 0) { - mDiag->Error(DiagMessage() << "not a valid png file"); + mDiag->Error(android::DiagMessage() << "not a valid png file"); return false; } @@ -1196,17 +1252,18 @@ bool Png::process(const Source& source, std::istream* input, BigBuffer* outBuffe readPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, nullptr, nullptr); if (!readPtr) { - mDiag->Error(DiagMessage() << "failed to allocate read ptr"); + mDiag->Error(android::DiagMessage() << "failed to allocate read ptr"); goto bail; } infoPtr = png_create_info_struct(readPtr); if (!infoPtr) { - mDiag->Error(DiagMessage() << "failed to allocate info ptr"); + mDiag->Error(android::DiagMessage() << "failed to allocate info ptr"); goto bail; } - png_set_error_fn(readPtr, reinterpret_cast<png_voidp>(mDiag), nullptr, logWarning); + png_set_error_fn(readPtr, reinterpret_cast<png_voidp>(mDiag), nullptr, + logWarning); // Set the read function to read from std::istream. png_set_read_fn(readPtr, (png_voidp)input, readDataFromStream); @@ -1215,32 +1272,35 @@ bool Png::process(const Source& source, std::istream* input, BigBuffer* outBuffe goto bail; } - if (android::base::EndsWith(source.path, ".9.png")) { + if (util::EndsWith(source.path, ".9.png")) { std::string errorMsg; if (!do9Patch(&pngInfo, &errorMsg)) { - mDiag->Error(DiagMessage() << errorMsg); + mDiag->Error(android::DiagMessage() << errorMsg); goto bail; } } - writePtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, nullptr, nullptr); + writePtr = + png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, nullptr, nullptr); if (!writePtr) { - mDiag->Error(DiagMessage() << "failed to allocate write ptr"); + mDiag->Error(android::DiagMessage() << "failed to allocate write ptr"); goto bail; } writeInfoPtr = png_create_info_struct(writePtr); if (!writeInfoPtr) { - mDiag->Error(DiagMessage() << "failed to allocate write info ptr"); + mDiag->Error(android::DiagMessage() << "failed to allocate write info ptr"); goto bail; } png_set_error_fn(writePtr, nullptr, nullptr, logWarning); // Set the write function to write to std::ostream. - png_set_write_fn(writePtr, (png_voidp)outBuffer, writeDataToStream, flushDataToStream); + png_set_write_fn(writePtr, (png_voidp)outBuffer, writeDataToStream, + flushDataToStream); - if (!writePng(mDiag, writePtr, writeInfoPtr, &pngInfo, options.grayscale_tolerance)) { + if (!writePng(mDiag, writePtr, writeInfoPtr, &pngInfo, + options.grayscale_tolerance)) { goto bail; } @@ -1256,4 +1316,4 @@ bail: return result; } -} // namespace android +} // namespace aapt diff --git a/libs/androidfw/include/androidfw/Png.h b/tools/aapt2/compile/Png.h index 2ece43e08110..a8b7dd18f12f 100644 --- a/libs/androidfw/include/androidfw/Png.h +++ b/tools/aapt2/compile/Png.h @@ -14,18 +14,22 @@ * limitations under the License. */ -#pragma once +#ifndef AAPT_PNG_H +#define AAPT_PNG_H +#include <iostream> #include <string> -#include "BigBuffer.h" -#include "IDiagnostics.h" -#include "Image.h" -#include "Source.h" -#include "Streams.h" #include "android-base/macros.h" +#include "androidfw/BigBuffer.h" +#include "androidfw/IDiagnostics.h" +#include "androidfw/Source.h" +#include "compile/Image.h" +#include "io/Io.h" +#include "process/IResourceTableConsumer.h" + +namespace aapt { -namespace android { // Size in bytes of the PNG signature. constexpr size_t kPngSignatureSize = 8u; @@ -38,36 +42,32 @@ struct PngOptions { */ class Png { public: - explicit Png(IDiagnostics* diag) : mDiag(diag) { + explicit Png(android::IDiagnostics* diag) : mDiag(diag) { } - bool process(const Source& source, std::istream* input, BigBuffer* outBuffer, + bool process(const android::Source& source, std::istream* input, android::BigBuffer* outBuffer, const PngOptions& options); private: DISALLOW_COPY_AND_ASSIGN(Png); - IDiagnostics* mDiag; + android::IDiagnostics* mDiag; }; /** * An InputStream that filters out unimportant PNG chunks. */ -class PngChunkFilter : public InputStream { +class PngChunkFilter : public io::InputStream { public: - explicit PngChunkFilter(StringPiece data); + explicit PngChunkFilter(android::StringPiece data); virtual ~PngChunkFilter() = default; bool Next(const void** buffer, size_t* len) override; void BackUp(size_t count) override; - bool CanRewind() const override { - return true; - } + bool CanRewind() const override { return true; } bool Rewind() override; - size_t ByteCount() const override { - return window_start_; - } + size_t ByteCount() const override { return window_start_; } bool HadError() const override { return !error_msg_.empty(); @@ -81,20 +81,26 @@ class PngChunkFilter : public InputStream { bool ConsumeWindow(const void** buffer, size_t* len); - StringPiece data_; + android::StringPiece data_; size_t window_start_ = 0; size_t window_end_ = 0; std::string error_msg_; }; + /** * Reads a PNG from the InputStream into memory as an RGBA Image. */ -std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag); +std::unique_ptr<Image> ReadPng(IAaptContext* context, const android::Source& source, + io::InputStream* in); /** * Writes the RGBA Image, with optional 9-patch meta-data, into the OutputStream * as a PNG. */ -bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out, - const PngOptions& options, IDiagnostics* diag, bool verbose); -} // namespace android
\ No newline at end of file +bool WritePng(IAaptContext* context, const Image* image, + const NinePatch* nine_patch, io::OutputStream* out, + const PngOptions& options); + +} // namespace aapt + +#endif // AAPT_PNG_H diff --git a/libs/androidfw/PngChunkFilter.cpp b/tools/aapt2/compile/PngChunkFilter.cpp index 331b94803e93..2e55d0c82b7b 100644 --- a/libs/androidfw/PngChunkFilter.cpp +++ b/tools/aapt2/compile/PngChunkFilter.cpp @@ -14,22 +14,25 @@ * limitations under the License. */ +#include "compile/Png.h" + #include "android-base/stringprintf.h" -#include "android-base/strings.h" -#include "androidfw/Png.h" -#include "androidfw/Streams.h" #include "androidfw/StringPiece.h" +#include "io/Io.h" + +using ::android::StringPiece; using ::android::base::StringPrintf; -namespace android { +namespace aapt { static constexpr const char* kPngSignature = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"; // Useful helper function that encodes individual bytes into a uint32 // at compile time. constexpr uint32_t u32(uint8_t a, uint8_t b, uint8_t c, uint8_t d) { - return (((uint32_t)a) << 24) | (((uint32_t)b) << 16) | (((uint32_t)c) << 8) | ((uint32_t)d); + return (((uint32_t)a) << 24) | (((uint32_t)b) << 16) | (((uint32_t)c) << 8) | + ((uint32_t)d); } // Allow list of PNG chunk types that we want to keep in the resulting PNG. @@ -68,7 +71,7 @@ static bool IsPngChunkAllowed(uint32_t type) { } PngChunkFilter::PngChunkFilter(StringPiece data) : data_(data) { - if (android::base::StartsWith(data_, kPngSignature)) { + if (util::StartsWith(data_, kPngSignature)) { window_start_ = 0; window_end_ = kPngSignatureSize; } else { @@ -173,4 +176,5 @@ bool PngChunkFilter::Rewind() { window_end_ = kPngSignatureSize; return true; } -} // namespace android + +} // namespace aapt diff --git a/libs/androidfw/PngCrunch.cpp b/tools/aapt2/compile/PngCrunch.cpp index cf3c0eeff402..4ef87ba3671b 100644 --- a/libs/androidfw/PngCrunch.cpp +++ b/tools/aapt2/compile/PngCrunch.cpp @@ -14,6 +14,8 @@ * limitations under the License. */ +#include "compile/Png.h" + #include <png.h> #include <zlib.h> @@ -24,16 +26,16 @@ #include "android-base/errors.h" #include "android-base/logging.h" #include "android-base/macros.h" -#include "androidfw/Png.h" -namespace android { +#include "trace/TraceBuffer.h" + +namespace aapt { // Custom deleter that destroys libpng read and info structs. class PngReadStructDeleter { public: PngReadStructDeleter(png_structp read_ptr, png_infop info_ptr) - : read_ptr_(read_ptr), info_ptr_(info_ptr) { - } + : read_ptr_(read_ptr), info_ptr_(info_ptr) {} ~PngReadStructDeleter() { png_destroy_read_struct(&read_ptr_, &info_ptr_, nullptr); @@ -50,8 +52,7 @@ class PngReadStructDeleter { class PngWriteStructDeleter { public: PngWriteStructDeleter(png_structp write_ptr, png_infop info_ptr) - : write_ptr_(write_ptr), info_ptr_(info_ptr) { - } + : write_ptr_(write_ptr), info_ptr_(info_ptr) {} ~PngWriteStructDeleter() { png_destroy_write_struct(&write_ptr_, &info_ptr_); @@ -82,7 +83,7 @@ static void LogError(png_structp png_ptr, png_const_charp error_msg) { } static void ReadDataFromStream(png_structp png_ptr, png_bytep buffer, png_size_t len) { - InputStream* in = (InputStream*)png_get_io_ptr(png_ptr); + io::InputStream* in = (io::InputStream*)png_get_io_ptr(png_ptr); const void* in_buffer; size_t in_len; @@ -107,7 +108,7 @@ static void ReadDataFromStream(png_structp png_ptr, png_bytep buffer, png_size_t } static void WriteDataToStream(png_structp png_ptr, png_bytep buffer, png_size_t len) { - OutputStream* out = (OutputStream*)png_get_io_ptr(png_ptr); + io::OutputStream* out = (io::OutputStream*)png_get_io_ptr(png_ptr); void* out_buffer; size_t out_len; @@ -142,22 +143,28 @@ static void WriteDataToStream(png_structp png_ptr, png_bytep buffer, png_size_t } } -std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag) { +std::unique_ptr<Image> ReadPng(IAaptContext* context, const android::Source& source, + io::InputStream* in) { + TRACE_CALL(); + // Create a diagnostics that has the source information encoded. + android::SourcePathDiagnostics source_diag(source, context->GetDiagnostics()); + // Read the first 8 bytes of the file looking for the PNG signature. // Bail early if it does not match. const png_byte* signature; size_t buffer_size; if (!in->Next((const void**)&signature, &buffer_size)) { if (in->HadError()) { - diag->Error(android::DiagMessage() << "failed to read PNG signature: " << in->GetError()); + source_diag.Error(android::DiagMessage() + << "failed to read PNG signature: " << in->GetError()); } else { - diag->Error(android::DiagMessage() << "not enough data for PNG signature"); + source_diag.Error(android::DiagMessage() << "not enough data for PNG signature"); } return {}; } if (buffer_size < kPngSignatureSize || png_sig_cmp(signature, 0, kPngSignatureSize) != 0) { - diag->Error(android::DiagMessage() << "file signature does not match PNG signature"); + source_diag.Error(android::DiagMessage() << "file signature does not match PNG signature"); return {}; } @@ -169,14 +176,14 @@ std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag) { // version of libpng. png_structp read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (read_ptr == nullptr) { - diag->Error(android::DiagMessage() << "failed to create libpng read png_struct"); + source_diag.Error(android::DiagMessage() << "failed to create libpng read png_struct"); return {}; } // Create and initialize the memory for image header and data. png_infop info_ptr = png_create_info_struct(read_ptr); if (info_ptr == nullptr) { - diag->Error(android::DiagMessage() << "failed to create libpng read png_info"); + source_diag.Error(android::DiagMessage() << "failed to create libpng read png_info"); png_destroy_read_struct(&read_ptr, nullptr, nullptr); return {}; } @@ -192,7 +199,7 @@ std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag) { } // Handle warnings ourselves via IDiagnostics. - png_set_error_fn(read_ptr, (png_voidp)&diag, LogError, LogWarning); + png_set_error_fn(read_ptr, (png_voidp)&source_diag, LogError, LogWarning); // Set up the read functions which read from our custom data sources. png_set_read_fn(read_ptr, (png_voidp)in, ReadDataFromStream); @@ -206,8 +213,8 @@ std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag) { // Extract image meta-data from the various chunk headers. uint32_t width, height; int bit_depth, color_type, interlace_method, compression_method, filter_method; - png_get_IHDR(read_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_method, - &compression_method, &filter_method); + png_get_IHDR(read_ptr, info_ptr, &width, &height, &bit_depth, &color_type, + &interlace_method, &compression_method, &filter_method); // When the image is read, expand it so that it is in RGBA 8888 format // so that image handling is uniform. @@ -232,7 +239,8 @@ std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag) { png_set_add_alpha(read_ptr, 0xFF, PNG_FILLER_AFTER); } - if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { + if (color_type == PNG_COLOR_TYPE_GRAY || + color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(read_ptr); } @@ -248,12 +256,12 @@ std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag) { // something // that can always be represented by 9-patch. if (width > std::numeric_limits<int32_t>::max() || height > std::numeric_limits<int32_t>::max()) { - diag->Error(android::DiagMessage() - << "PNG image dimensions are too large: " << width << "x" << height); + source_diag.Error(android::DiagMessage() + << "PNG image dimensions are too large: " << width << "x" << height); return {}; } - std::unique_ptr<Image> output_image = std::make_unique<Image>(); + std::unique_ptr<Image> output_image = util::make_unique<Image>(); output_image->width = static_cast<int32_t>(width); output_image->height = static_cast<int32_t>(height); @@ -264,7 +272,7 @@ std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag) { output_image->data = std::unique_ptr<uint8_t[]>(new uint8_t[height * row_bytes]); // Create an array of rows that index into the data block. - output_image->rows = std::unique_ptr<uint8_t*[]>(new uint8_t*[height]); + output_image->rows = std::unique_ptr<uint8_t* []>(new uint8_t*[height]); for (uint32_t h = 0; h < height; h++) { output_image->rows[h] = output_image->data.get() + (h * row_bytes); } @@ -324,7 +332,8 @@ static int PickColorType(int32_t width, int32_t height, bool grayscale, // This grayscale has alpha and can fit within a palette. // See if it is worth fitting into a palette. const size_t palette_threshold = palette_chunk_size + alpha_chunk_size + - palette_data_chunk_size + kPaletteOverheadConstant; + palette_data_chunk_size + + kPaletteOverheadConstant; if (grayscale_alpha_data_chunk_size > palette_threshold) { return PNG_COLOR_TYPE_PALETTE; } @@ -334,14 +343,16 @@ static int PickColorType(int32_t width, int32_t height, bool grayscale, if (color_palette_size <= 256 && !has_nine_patch) { // This image can fit inside a palette. Let's see if it is worth it. - size_t total_size_with_palette = palette_data_chunk_size + palette_chunk_size; + size_t total_size_with_palette = + palette_data_chunk_size + palette_chunk_size; size_t total_size_without_palette = color_data_chunk_size; if (alpha_palette_size > 0) { total_size_with_palette += alpha_palette_size; total_size_without_palette = color_alpha_data_chunk_size; } - if (total_size_without_palette > total_size_with_palette + kPaletteOverheadConstant) { + if (total_size_without_palette > + total_size_with_palette + kPaletteOverheadConstant) { return PNG_COLOR_TYPE_PALETTE; } } @@ -471,22 +482,26 @@ static void WriteNinePatch(png_structp write_ptr, png_infop write_info_ptr, png_set_unknown_chunks(write_ptr, write_info_ptr, unknown_chunks, index); } -bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out, - const PngOptions& options, IDiagnostics* diag, bool verbose) { +bool WritePng(IAaptContext* context, const Image* image, + const NinePatch* nine_patch, io::OutputStream* out, + const PngOptions& options) { + TRACE_CALL(); // Create and initialize the write png_struct with the default error and // warning handlers. // The header version is also passed in to ensure that this was built against the same // version of libpng. png_structp write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (write_ptr == nullptr) { - diag->Error(android::DiagMessage() << "failed to create libpng write png_struct"); + context->GetDiagnostics()->Error(android::DiagMessage() + << "failed to create libpng write png_struct"); return false; } // Allocate memory to store image header data. png_infop write_info_ptr = png_create_info_struct(write_ptr); if (write_info_ptr == nullptr) { - diag->Error(android::DiagMessage() << "failed to create libpng write png_info"); + context->GetDiagnostics()->Error(android::DiagMessage() + << "failed to create libpng write png_info"); png_destroy_write_struct(&write_ptr, nullptr); return false; } @@ -501,7 +516,7 @@ bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out } // Handle warnings with our IDiagnostics. - png_set_error_fn(write_ptr, (png_voidp)&diag, LogError, LogWarning); + png_set_error_fn(write_ptr, (png_voidp)context->GetDiagnostics(), LogError, LogWarning); // Set up the write functions which write to our custom data sources. png_set_write_fn(write_ptr, (png_voidp)out, WriteDataToStream, nullptr); @@ -563,21 +578,22 @@ bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out } } - if (verbose) { + if (context->IsVerbose()) { android::DiagMessage msg; - msg << " paletteSize=" << color_palette.size() << " alphaPaletteSize=" << alpha_palette.size() + msg << " paletteSize=" << color_palette.size() + << " alphaPaletteSize=" << alpha_palette.size() << " maxGrayDeviation=" << max_gray_deviation << " grayScale=" << (grayscale ? "true" : "false"); - diag->Note(msg); + context->GetDiagnostics()->Note(msg); } const bool convertible_to_grayscale = max_gray_deviation <= options.grayscale_tolerance; - const int new_color_type = - PickColorType(image->width, image->height, grayscale, convertible_to_grayscale, - nine_patch != nullptr, color_palette.size(), alpha_palette.size()); + const int new_color_type = PickColorType( + image->width, image->height, grayscale, convertible_to_grayscale, + nine_patch != nullptr, color_palette.size(), alpha_palette.size()); - if (verbose) { + if (context->IsVerbose()) { android::DiagMessage msg; msg << "encoding PNG "; if (nine_patch) { @@ -603,11 +619,12 @@ bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out msg << "unknown type " << new_color_type; break; } - diag->Note(msg); + context->GetDiagnostics()->Note(msg); } - png_set_IHDR(write_ptr, write_info_ptr, image->width, image->height, 8, new_color_type, - PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); + png_set_IHDR(write_ptr, write_info_ptr, image->width, image->height, 8, + new_color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, + PNG_FILTER_TYPE_DEFAULT); if (new_color_type & PNG_COLOR_MASK_PALETTE) { // Assigns indices to the palette, and writes the encoded palette to the @@ -649,9 +666,11 @@ bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out } png_write_row(write_ptr, out_row.get()); } - } else if (new_color_type == PNG_COLOR_TYPE_GRAY || new_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { + } else if (new_color_type == PNG_COLOR_TYPE_GRAY || + new_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { const size_t bpp = new_color_type == PNG_COLOR_TYPE_GRAY ? 1 : 2; - auto out_row = std::unique_ptr<png_byte[]>(new png_byte[image->width * bpp]); + auto out_row = + std::unique_ptr<png_byte[]>(new png_byte[image->width * bpp]); for (int32_t y = 0; y < image->height; y++) { png_const_bytep in_row = image->rows[y]; @@ -672,7 +691,8 @@ bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out // The image is convertible to grayscale, use linear-luminance of // sRGB colorspace: // https://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-preserving.29_conversion_to_grayscale - out_row[x * bpp] = (png_byte)(rr * 0.2126f + gg * 0.7152f + bb * 0.0722f); + out_row[x * bpp] = + (png_byte)(rr * 0.2126f + gg * 0.7152f + bb * 0.0722f); } if (bpp == 2) { @@ -727,4 +747,4 @@ bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out return true; } -} // namespace android +} // namespace aapt diff --git a/tools/aapt2/dump/DumpManifest.cpp b/tools/aapt2/dump/DumpManifest.cpp index a5962292b5b0..a2b48187c24f 100644 --- a/tools/aapt2/dump/DumpManifest.cpp +++ b/tools/aapt2/dump/DumpManifest.cpp @@ -29,8 +29,8 @@ #include "SdkConstants.h" #include "ValueVisitor.h" #include "androidfw/ConfigDescription.h" -#include "androidfw/FileStream.h" #include "io/File.h" +#include "io/FileStream.h" #include "process/IResourceTableConsumer.h" #include "xml/XmlDom.h" diff --git a/tools/aapt2/format/Archive.cpp b/tools/aapt2/format/Archive.cpp index 91768a09ea59..e9a93d8b12ad 100644 --- a/tools/aapt2/format/Archive.cpp +++ b/tools/aapt2/format/Archive.cpp @@ -91,7 +91,7 @@ class DirectoryWriter : public IArchiveWriter { return true; } - bool WriteFile(StringPiece path, uint32_t flags, android::InputStream* in) override { + bool WriteFile(StringPiece path, uint32_t flags, io::InputStream* in) override { if (!StartEntry(path, flags)) { return false; } @@ -182,7 +182,7 @@ class ZipFileWriter : public IArchiveWriter { return true; } - bool WriteFile(StringPiece path, uint32_t flags, android::InputStream* in) override { + bool WriteFile(StringPiece path, uint32_t flags, io::InputStream* in) override { while (true) { if (!StartEntry(path, flags)) { return false; diff --git a/tools/aapt2/format/Archive.h b/tools/aapt2/format/Archive.h index 3c3d0ab74c52..6cde753a255d 100644 --- a/tools/aapt2/format/Archive.h +++ b/tools/aapt2/format/Archive.h @@ -24,9 +24,9 @@ #include "androidfw/BigBuffer.h" #include "androidfw/IDiagnostics.h" -#include "androidfw/Streams.h" #include "androidfw/StringPiece.h" #include "google/protobuf/io/zero_copy_stream_impl_lite.h" +#include "io/Io.h" #include "util/Files.h" namespace aapt { @@ -46,7 +46,7 @@ class IArchiveWriter : public ::google::protobuf::io::CopyingOutputStream { public: virtual ~IArchiveWriter() = default; - virtual bool WriteFile(android::StringPiece path, uint32_t flags, android::InputStream* in) = 0; + virtual bool WriteFile(android::StringPiece path, uint32_t flags, io::InputStream* in) = 0; // Starts a new entry and allows caller to write bytes to it sequentially. // Only use StartEntry if code you do not control needs to write to a CopyingOutputStream. diff --git a/tools/aapt2/format/Archive_test.cpp b/tools/aapt2/format/Archive_test.cpp index df105f8a83e5..fd50af92ceee 100644 --- a/tools/aapt2/format/Archive_test.cpp +++ b/tools/aapt2/format/Archive_test.cpp @@ -95,7 +95,7 @@ void VerifyDirectory(const std::string& path, const std::string& file, const uin void VerifyZipFile(const std::string& output_path, const std::string& file, const uint8_t array[]) { std::unique_ptr<io::ZipFileCollection> zip = io::ZipFileCollection::Create(output_path, nullptr); - std::unique_ptr<android::InputStream> stream = zip->FindFile(file)->OpenInputStream(); + std::unique_ptr<io::InputStream> stream = zip->FindFile(file)->OpenInputStream(); std::vector<uint8_t> buffer; const void* data; diff --git a/tools/aapt2/format/Container.cpp b/tools/aapt2/format/Container.cpp index cb4a225c73e7..1ff6c4996b91 100644 --- a/tools/aapt2/format/Container.cpp +++ b/tools/aapt2/format/Container.cpp @@ -94,7 +94,7 @@ bool ContainerWriter::AddResTableEntry(const pb::ResourceTable& table) { } bool ContainerWriter::AddResFileEntry(const pb::internal::CompiledFile& file, - android::KnownSizeInputStream* in) { + io::KnownSizeInputStream* in) { if (current_entry_count_ >= total_entry_count_) { error_ = "too many entries being serialized"; return false; @@ -264,7 +264,7 @@ std::string ContainerReaderEntry::GetError() const { return reader_->GetError(); } -ContainerReader::ContainerReader(android::InputStream* in) +ContainerReader::ContainerReader(io::InputStream* in) : in_(in), adaptor_(in), coded_in_(&adaptor_), diff --git a/tools/aapt2/format/Container.h b/tools/aapt2/format/Container.h index c5d567697a5a..121c592537bf 100644 --- a/tools/aapt2/format/Container.h +++ b/tools/aapt2/format/Container.h @@ -22,9 +22,9 @@ #include "Resources.pb.h" #include "ResourcesInternal.pb.h" #include "androidfw/BigBuffer.h" -#include "androidfw/Streams.h" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/zero_copy_stream.h" +#include "io/Io.h" #include "io/Util.h" namespace aapt { @@ -39,7 +39,7 @@ class ContainerWriter { explicit ContainerWriter(::google::protobuf::io::ZeroCopyOutputStream* out, size_t entry_count); bool AddResTableEntry(const pb::ResourceTable& table); - bool AddResFileEntry(const pb::internal::CompiledFile& file, android::KnownSizeInputStream* in); + bool AddResFileEntry(const pb::internal::CompiledFile& file, io::KnownSizeInputStream* in); bool HadError() const; std::string GetError() const; @@ -79,7 +79,7 @@ class ContainerReaderEntry { class ContainerReader { public: - explicit ContainerReader(android::InputStream* in); + explicit ContainerReader(io::InputStream* in); ContainerReaderEntry* Next(); @@ -91,7 +91,7 @@ class ContainerReader { friend class ContainerReaderEntry; - android::InputStream* in_; + io::InputStream* in_; io::ZeroCopyInputAdaptor adaptor_; ::google::protobuf::io::CodedInputStream coded_in_; size_t total_entry_count_; diff --git a/libs/androidfw/BigBufferStream.cpp b/tools/aapt2/io/BigBufferStream.cpp index f18199cfa52b..9704caae4719 100644 --- a/libs/androidfw/BigBufferStream.cpp +++ b/tools/aapt2/io/BigBufferStream.cpp @@ -14,11 +14,10 @@ * limitations under the License. */ -#include "androidfw/BigBufferStream.h" +#include "io/BigBufferStream.h" -#include <algorithm> - -namespace android { +namespace aapt { +namespace io { // // BigBufferInputStream @@ -77,34 +76,6 @@ size_t BigBufferInputStream::TotalSize() const { return buffer_->size(); } -bool BigBufferInputStream::ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) { - if (byte_count == 0) { - return true; - } - if (offset < 0) { - return false; - } - if (offset > std::numeric_limits<off64_t>::max() - byte_count) { - return false; - } - if (offset + byte_count > buffer_->size()) { - return false; - } - auto p = reinterpret_cast<uint8_t*>(data); - for (auto iter = buffer_->begin(); iter != buffer_->end() && byte_count > 0; ++iter) { - if (offset < iter->size) { - size_t to_read = std::min(byte_count, (size_t)(iter->size - offset)); - memcpy(p, iter->buffer.get() + offset, to_read); - byte_count -= to_read; - p += to_read; - offset = 0; - } else { - offset -= iter->size; - } - } - return byte_count == 0; -} - // // BigBufferOutputStream // @@ -126,4 +97,5 @@ bool BigBufferOutputStream::HadError() const { return false; } -} // namespace android +} // namespace io +} // namespace aapt diff --git a/libs/androidfw/include/androidfw/BigBufferStream.h b/tools/aapt2/io/BigBufferStream.h index e55fe0d653cc..63a5e5756ed4 100644 --- a/libs/androidfw/include/androidfw/BigBufferStream.h +++ b/tools/aapt2/io/BigBufferStream.h @@ -14,16 +14,18 @@ * limitations under the License. */ -#pragma once +#ifndef AAPT_IO_BIGBUFFERSTREAM_H +#define AAPT_IO_BIGBUFFERSTREAM_H -#include "BigBuffer.h" -#include "Streams.h" +#include "androidfw/BigBuffer.h" +#include "io/Io.h" -namespace android { +namespace aapt { +namespace io { class BigBufferInputStream : public KnownSizeInputStream { public: - inline explicit BigBufferInputStream(const BigBuffer* buffer) + inline explicit BigBufferInputStream(const android::BigBuffer* buffer) : buffer_(buffer), iter_(buffer->begin()) { } virtual ~BigBufferInputStream() = default; @@ -42,20 +44,18 @@ class BigBufferInputStream : public KnownSizeInputStream { size_t TotalSize() const override; - bool ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) override; - private: DISALLOW_COPY_AND_ASSIGN(BigBufferInputStream); - const BigBuffer* buffer_; - BigBuffer::const_iterator iter_; + const android::BigBuffer* buffer_; + android::BigBuffer::const_iterator iter_; size_t offset_ = 0; size_t bytes_read_ = 0; }; class BigBufferOutputStream : public OutputStream { public: - inline explicit BigBufferOutputStream(BigBuffer* buffer) : buffer_(buffer) { + inline explicit BigBufferOutputStream(android::BigBuffer* buffer) : buffer_(buffer) { } virtual ~BigBufferOutputStream() = default; @@ -70,7 +70,10 @@ class BigBufferOutputStream : public OutputStream { private: DISALLOW_COPY_AND_ASSIGN(BigBufferOutputStream); - BigBuffer* buffer_; + android::BigBuffer* buffer_; }; -} // namespace android
\ No newline at end of file +} // namespace io +} // namespace aapt + +#endif // AAPT_IO_BIGBUFFERSTREAM_H diff --git a/tools/aapt2/io/Data.h b/tools/aapt2/io/Data.h index 29f523aeff1b..db91a77a5ae6 100644 --- a/tools/aapt2/io/Data.h +++ b/tools/aapt2/io/Data.h @@ -20,14 +20,15 @@ #include <memory> #include "android-base/macros.h" -#include "androidfw/Streams.h" #include "utils/FileMap.h" +#include "io/Io.h" + namespace aapt { namespace io { // Interface for a block of contiguous memory. An instance of this interface owns the data. -class IData : public android::KnownSizeInputStream { +class IData : public KnownSizeInputStream { public: virtual ~IData() = default; diff --git a/tools/aapt2/io/File.cpp b/tools/aapt2/io/File.cpp index 4dfdb5bb8ad9..b4f1ff3a5b49 100644 --- a/tools/aapt2/io/File.cpp +++ b/tools/aapt2/io/File.cpp @@ -39,7 +39,7 @@ std::unique_ptr<IData> FileSegment::OpenAsData() { return {}; } -std::unique_ptr<android::InputStream> FileSegment::OpenInputStream() { +std::unique_ptr<io::InputStream> FileSegment::OpenInputStream() { return OpenAsData(); } diff --git a/tools/aapt2/io/File.h b/tools/aapt2/io/File.h index 248756b51f2e..673d1b75e660 100644 --- a/tools/aapt2/io/File.h +++ b/tools/aapt2/io/File.h @@ -43,7 +43,7 @@ class IFile { // Returns nullptr on failure. virtual std::unique_ptr<IData> OpenAsData() = 0; - virtual std::unique_ptr<android::InputStream> OpenInputStream() = 0; + virtual std::unique_ptr<io::InputStream> OpenInputStream() = 0; // Returns the source of this file. This is for presentation to the user and // may not be a valid file system path (for example, it may contain a '@' sign to separate @@ -78,7 +78,7 @@ class FileSegment : public IFile { : file_(file), offset_(offset), len_(len) {} std::unique_ptr<IData> OpenAsData() override; - std::unique_ptr<android::InputStream> OpenInputStream() override; + std::unique_ptr<io::InputStream> OpenInputStream() override; const android::Source& GetSource() const override { return file_->GetSource(); diff --git a/libs/androidfw/FileStream.cpp b/tools/aapt2/io/FileStream.cpp index b86c9cb729d4..27529bc08a16 100644 --- a/libs/androidfw/FileStream.cpp +++ b/tools/aapt2/io/FileStream.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "androidfw/FileStream.h" +#include "io/FileStream.h" #include <errno.h> // for errno #include <fcntl.h> // for O_RDONLY @@ -34,7 +34,8 @@ using ::android::base::SystemErrorCodeToString; using ::android::base::unique_fd; -namespace android { +namespace aapt { +namespace io { FileInputStream::FileInputStream(const std::string& path, size_t buffer_capacity) : buffer_capacity_(buffer_capacity) { @@ -107,10 +108,6 @@ std::string FileInputStream::GetError() const { return error_; } -bool FileInputStream::ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) { - return base::ReadFullyAtOffset(fd_, data, byte_count, offset); -} - FileOutputStream::FileOutputStream(const std::string& path, size_t buffer_capacity) : buffer_capacity_(buffer_capacity) { int mode = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY; @@ -202,4 +199,5 @@ std::string FileOutputStream::GetError() const { return error_; } -} // namespace android +} // namespace io +} // namespace aapt diff --git a/libs/androidfw/include/androidfw/FileStream.h b/tools/aapt2/io/FileStream.h index fb84a91a00de..62d910f0b06a 100644 --- a/libs/androidfw/include/androidfw/FileStream.h +++ b/tools/aapt2/io/FileStream.h @@ -14,16 +14,19 @@ * limitations under the License. */ -#pragma once +#ifndef AAPT_IO_FILESTREAM_H +#define AAPT_IO_FILESTREAM_H + +#include "io/Io.h" #include <memory> #include <string> -#include "Streams.h" #include "android-base/macros.h" #include "android-base/unique_fd.h" -namespace android { +namespace aapt { +namespace io { constexpr size_t kDefaultBufferCapacity = 4096u; @@ -45,8 +48,6 @@ class FileInputStream : public InputStream { std::string GetError() const override; - bool ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) override; - private: DISALLOW_COPY_AND_ASSIGN(FileInputStream); @@ -100,4 +101,7 @@ class FileOutputStream : public OutputStream { size_t total_byte_count_ = 0u; }; -} // namespace android
\ No newline at end of file +} // namespace io +} // namespace aapt + +#endif // AAPT_IO_FILESTREAM_H diff --git a/libs/androidfw/tests/FileStream_test.cpp b/tools/aapt2/io/FileStream_test.cpp index 978597507a6d..cc9cd2808a0c 100644 --- a/libs/androidfw/tests/FileStream_test.cpp +++ b/tools/aapt2/io/FileStream_test.cpp @@ -14,21 +14,20 @@ * limitations under the License. */ -#include "androidfw/FileStream.h" -#include "androidfw/StringPiece.h" +#include "io/FileStream.h" #include "android-base/file.h" #include "android-base/macros.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" +#include "test/Test.h" using ::android::StringPiece; using ::testing::Eq; using ::testing::NotNull; using ::testing::StrEq; -namespace android { +namespace aapt { +namespace io { TEST(FileInputStreamTest, NextAndBackup) { std::string input = "this is a cool string"; @@ -124,4 +123,5 @@ TEST(FileOutputStreamTest, NextAndBackup) { EXPECT_THAT(actual, StrEq(input)); } -} // namespace android +} // namespace io +} // namespace aapt diff --git a/tools/aapt2/io/FileSystem.cpp b/tools/aapt2/io/FileSystem.cpp index 03fabcc4dcce..6a692e497816 100644 --- a/tools/aapt2/io/FileSystem.cpp +++ b/tools/aapt2/io/FileSystem.cpp @@ -22,9 +22,9 @@ #include <sys/stat.h> #include "android-base/errors.h" -#include "androidfw/FileStream.h" #include "androidfw/Source.h" #include "androidfw/StringPiece.h" +#include "io/FileStream.h" #include "util/Files.h" #include "util/Util.h" #include "utils/FileMap.h" @@ -49,8 +49,8 @@ std::unique_ptr<IData> RegularFile::OpenAsData() { return {}; } -std::unique_ptr<android::InputStream> RegularFile::OpenInputStream() { - return util::make_unique<android::FileInputStream>(source_.path); +std::unique_ptr<io::InputStream> RegularFile::OpenInputStream() { + return util::make_unique<FileInputStream>(source_.path); } const android::Source& RegularFile::GetSource() const { diff --git a/tools/aapt2/io/FileSystem.h b/tools/aapt2/io/FileSystem.h index d6ecfebab67d..f975196b9cfa 100644 --- a/tools/aapt2/io/FileSystem.h +++ b/tools/aapt2/io/FileSystem.h @@ -30,7 +30,7 @@ class RegularFile : public IFile { explicit RegularFile(const android::Source& source); std::unique_ptr<IData> OpenAsData() override; - std::unique_ptr<android::InputStream> OpenInputStream() override; + std::unique_ptr<io::InputStream> OpenInputStream() override; const android::Source& GetSource() const override; bool GetModificationTime(struct tm* buf) const override; diff --git a/libs/androidfw/include/androidfw/Streams.h b/tools/aapt2/io/Io.h index 89f16205162a..e1df23a698f5 100644 --- a/libs/androidfw/include/androidfw/Streams.h +++ b/tools/aapt2/io/Io.h @@ -14,11 +14,13 @@ * limitations under the License. */ -#pragma once +#ifndef AAPT_IO_IO_H +#define AAPT_IO_IO_H #include <string> -namespace android { +namespace aapt { +namespace io { // InputStream interface that mimics protobuf's ZeroCopyInputStream, // with added error handling methods to better report issues. @@ -39,34 +41,21 @@ class InputStream { virtual void BackUp(size_t count) = 0; // Returns true if this InputStream can rewind. If so, Rewind() can be called. - virtual bool CanRewind() const { - return false; - }; + virtual bool CanRewind() const { return false; }; // Rewinds the stream to the beginning so it can be read again. // Returns true if the rewind succeeded. // This does nothing if CanRewind() returns false. - virtual bool Rewind() { - return false; - } + virtual bool Rewind() { return false; } // Returns the number of bytes that have been read from the stream. virtual size_t ByteCount() const = 0; // Returns an error message if HadError() returned true. - virtual std::string GetError() const { - return {}; - } + virtual std::string GetError() const { return {}; } // Returns true if an error occurred. Errors are permanent. virtual bool HadError() const = 0; - - virtual bool ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) { - (void)data; - (void)byte_count; - (void)offset; - return false; - } }; // A sub-InputStream interface that knows the total size of its stream. @@ -98,12 +87,13 @@ class OutputStream { virtual size_t ByteCount() const = 0; // Returns an error message if HadError() returned true. - virtual std::string GetError() const { - return {}; - } + virtual std::string GetError() const { return {}; } // Returns true if an error occurred. Errors are permanent. virtual bool HadError() const = 0; }; -} // namespace android
\ No newline at end of file +} // namespace io +} // namespace aapt + +#endif /* AAPT_IO_IO_H */ diff --git a/tools/aapt2/io/StringStream.cpp b/tools/aapt2/io/StringStream.cpp index bb3911b20175..9c497882b99b 100644 --- a/tools/aapt2/io/StringStream.cpp +++ b/tools/aapt2/io/StringStream.cpp @@ -51,23 +51,6 @@ size_t StringInputStream::TotalSize() const { return str_.size(); } -bool StringInputStream::ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) { - if (byte_count == 0) { - return true; - } - if (offset < 0) { - return false; - } - if (offset > std::numeric_limits<off64_t>::max() - byte_count) { - return false; - } - if (offset + byte_count > str_.size()) { - return false; - } - memcpy(data, str_.data() + offset, byte_count); - return true; -} - StringOutputStream::StringOutputStream(std::string* str, size_t buffer_capacity) : str_(str), buffer_capacity_(buffer_capacity), diff --git a/tools/aapt2/io/StringStream.h b/tools/aapt2/io/StringStream.h index 7e1abe583170..f7bdecca0dee 100644 --- a/tools/aapt2/io/StringStream.h +++ b/tools/aapt2/io/StringStream.h @@ -17,16 +17,17 @@ #ifndef AAPT_IO_STRINGSTREAM_H #define AAPT_IO_STRINGSTREAM_H +#include "io/Io.h" + #include <memory> #include "android-base/macros.h" -#include "androidfw/Streams.h" #include "androidfw/StringPiece.h" namespace aapt { namespace io { -class StringInputStream : public android::KnownSizeInputStream { +class StringInputStream : public KnownSizeInputStream { public: explicit StringInputStream(android::StringPiece str); @@ -46,8 +47,6 @@ class StringInputStream : public android::KnownSizeInputStream { size_t TotalSize() const override; - bool ReadFullyAtOffset(void* data, size_t byte_count, off64_t offset) override; - private: DISALLOW_COPY_AND_ASSIGN(StringInputStream); @@ -55,7 +54,7 @@ class StringInputStream : public android::KnownSizeInputStream { size_t offset_; }; -class StringOutputStream : public android::OutputStream { +class StringOutputStream : public OutputStream { public: explicit StringOutputStream(std::string* str, size_t buffer_capacity = 4096u); diff --git a/tools/aapt2/io/Util.cpp b/tools/aapt2/io/Util.cpp index 9616e479eda0..79d8d527fe8b 100644 --- a/tools/aapt2/io/Util.cpp +++ b/tools/aapt2/io/Util.cpp @@ -26,9 +26,8 @@ using ::google::protobuf::io::ZeroCopyOutputStream; namespace aapt { namespace io { -bool CopyInputStreamToArchive(IAaptContext* context, android::InputStream* in, - std::string_view out_path, uint32_t compression_flags, - IArchiveWriter* writer) { +bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, std::string_view out_path, + uint32_t compression_flags, IArchiveWriter* writer) { TRACE_CALL(); if (context->IsVerbose()) { context->GetDiagnostics()->Note(android::DiagMessage() @@ -92,7 +91,7 @@ bool CopyProtoToArchive(IAaptContext* context, ::google::protobuf::Message* prot return false; } -bool Copy(android::OutputStream* out, android::InputStream* in) { +bool Copy(OutputStream* out, InputStream* in) { TRACE_CALL(); const void* in_buffer; size_t in_len; @@ -111,7 +110,7 @@ bool Copy(android::OutputStream* out, android::InputStream* in) { return !in->HadError(); } -bool Copy(android::OutputStream* out, StringPiece in) { +bool Copy(OutputStream* out, StringPiece in) { const char* in_buffer = in.data(); size_t in_len = in.size(); while (in_len != 0) { @@ -130,7 +129,7 @@ bool Copy(android::OutputStream* out, StringPiece in) { return true; } -bool Copy(ZeroCopyOutputStream* out, android::InputStream* in) { +bool Copy(ZeroCopyOutputStream* out, InputStream* in) { OutputStreamAdaptor adaptor(out); return Copy(&adaptor, in); } diff --git a/tools/aapt2/io/Util.h b/tools/aapt2/io/Util.h index 25aa8f8d1916..685f522a2e71 100644 --- a/tools/aapt2/io/Util.h +++ b/tools/aapt2/io/Util.h @@ -19,19 +19,18 @@ #include <string_view> -#include "androidfw/Streams.h" #include "format/Archive.h" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/message.h" #include "io/File.h" +#include "io/Io.h" #include "process/IResourceTableConsumer.h" namespace aapt { namespace io { -bool CopyInputStreamToArchive(IAaptContext* context, android::InputStream* in, - std::string_view out_path, uint32_t compression_flags, - IArchiveWriter* writer); +bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, std::string_view out_path, + uint32_t compression_flags, IArchiveWriter* writer); bool CopyFileToArchive(IAaptContext* context, IFile* file, std::string_view out_path, uint32_t compression_flags, IArchiveWriter* writer); @@ -45,11 +44,11 @@ bool CopyProtoToArchive(IAaptContext* context, ::google::protobuf::Message* prot // Copies the data from in to out. Returns false if there was an error. // If there was an error, check the individual streams' HadError/GetError methods. -bool Copy(android::OutputStream* out, android::InputStream* in); -bool Copy(android::OutputStream* out, android::StringPiece in); -bool Copy(::google::protobuf::io::ZeroCopyOutputStream* out, android::InputStream* in); +bool Copy(OutputStream* out, InputStream* in); +bool Copy(OutputStream* out, android::StringPiece in); +bool Copy(::google::protobuf::io::ZeroCopyOutputStream* out, InputStream* in); -class OutputStreamAdaptor : public android::OutputStream { +class OutputStreamAdaptor : public io::OutputStream { public: explicit OutputStreamAdaptor(::google::protobuf::io::ZeroCopyOutputStream* out) : out_(out) { } @@ -85,7 +84,7 @@ class OutputStreamAdaptor : public android::OutputStream { class ZeroCopyInputAdaptor : public ::google::protobuf::io::ZeroCopyInputStream { public: - explicit ZeroCopyInputAdaptor(android::InputStream* in) : in_(in) { + explicit ZeroCopyInputAdaptor(io::InputStream* in) : in_(in) { } bool Next(const void** data, int* size) override { @@ -120,13 +119,12 @@ class ZeroCopyInputAdaptor : public ::google::protobuf::io::ZeroCopyInputStream private: DISALLOW_COPY_AND_ASSIGN(ZeroCopyInputAdaptor); - android::InputStream* in_; + io::InputStream* in_; }; class ProtoInputStreamReader { public: - explicit ProtoInputStreamReader(android::InputStream* in) : in_(in) { - } + explicit ProtoInputStreamReader(io::InputStream* in) : in_(in) { } /** Deserializes a Message proto from the current position in the input stream.*/ template <typename T> bool ReadMessage(T *message) { @@ -137,7 +135,7 @@ class ProtoInputStreamReader { } private: - android::InputStream* in_; + io::InputStream* in_; }; } // namespace io diff --git a/tools/aapt2/io/ZipArchive.cpp b/tools/aapt2/io/ZipArchive.cpp index e44d61e08899..cb5bbe96b8b7 100644 --- a/tools/aapt2/io/ZipArchive.cpp +++ b/tools/aapt2/io/ZipArchive.cpp @@ -63,7 +63,7 @@ std::unique_ptr<IData> ZipFile::OpenAsData() { } } -std::unique_ptr<android::InputStream> ZipFile::OpenInputStream() { +std::unique_ptr<io::InputStream> ZipFile::OpenInputStream() { return OpenAsData(); } diff --git a/tools/aapt2/io/ZipArchive.h b/tools/aapt2/io/ZipArchive.h index a53c4a2e39f8..ac125d097983 100644 --- a/tools/aapt2/io/ZipArchive.h +++ b/tools/aapt2/io/ZipArchive.h @@ -35,7 +35,7 @@ class ZipFile : public IFile { ZipFile(::ZipArchiveHandle handle, const ::ZipEntry& entry, const android::Source& source); std::unique_ptr<IData> OpenAsData() override; - std::unique_ptr<android::InputStream> OpenInputStream() override; + std::unique_ptr<io::InputStream> OpenInputStream() override; const android::Source& GetSource() const override; bool WasCompressed() override; bool GetModificationTime(struct tm* buf) const override; diff --git a/tools/aapt2/java/ClassDefinition.cpp b/tools/aapt2/java/ClassDefinition.cpp index db7aa35d5ad4..98f3bd2018b0 100644 --- a/tools/aapt2/java/ClassDefinition.cpp +++ b/tools/aapt2/java/ClassDefinition.cpp @@ -111,7 +111,7 @@ constexpr static const char* sWarningHeader = " */\n\n"; void ClassDefinition::WriteJavaFile(const ClassDefinition* def, StringPiece package, bool final, - bool strip_api_annotations, android::OutputStream* out) { + bool strip_api_annotations, io::OutputStream* out) { Printer printer(out); printer.Print(sWarningHeader).Print("package ").Print(package).Println(";"); printer.Println(); diff --git a/tools/aapt2/java/ClassDefinition.h b/tools/aapt2/java/ClassDefinition.h index 84e3f33db941..63c99821a836 100644 --- a/tools/aapt2/java/ClassDefinition.h +++ b/tools/aapt2/java/ClassDefinition.h @@ -241,7 +241,7 @@ enum class ClassQualifier { kNone, kStatic }; class ClassDefinition : public ClassMember { public: static void WriteJavaFile(const ClassDefinition* def, android::StringPiece package, bool final, - bool strip_api_annotations, android::OutputStream* out); + bool strip_api_annotations, io::OutputStream* out); ClassDefinition(android::StringPiece name, ClassQualifier qualifier, bool createIfEmpty) : name_(name), qualifier_(qualifier), create_if_empty_(createIfEmpty) { diff --git a/tools/aapt2/java/JavaClassGenerator.cpp b/tools/aapt2/java/JavaClassGenerator.cpp index 58f656458177..7665d0e8d9cb 100644 --- a/tools/aapt2/java/JavaClassGenerator.cpp +++ b/tools/aapt2/java/JavaClassGenerator.cpp @@ -37,8 +37,8 @@ #include "java/ClassDefinition.h" #include "process/SymbolTable.h" +using ::aapt::io::OutputStream; using ::aapt::text::Printer; -using ::android::OutputStream; using ::android::StringPiece; using ::android::base::StringPrintf; diff --git a/tools/aapt2/java/JavaClassGenerator.h b/tools/aapt2/java/JavaClassGenerator.h index 9909eeccb6ac..234df04472ce 100644 --- a/tools/aapt2/java/JavaClassGenerator.h +++ b/tools/aapt2/java/JavaClassGenerator.h @@ -19,10 +19,11 @@ #include <string> +#include "androidfw/StringPiece.h" + #include "ResourceTable.h" #include "ResourceValues.h" -#include "androidfw/Streams.h" -#include "androidfw/StringPiece.h" +#include "io/Io.h" #include "process/IResourceTableConsumer.h" #include "process/SymbolTable.h" #include "text/Printer.h" @@ -69,12 +70,12 @@ class JavaClassGenerator { // All symbols technically belong to a single package, but linked libraries will // have their names mangled, denoting that they came from a different package. // We need to generate these symbols in a separate file. Returns true on success. - bool Generate(android::StringPiece package_name_to_generate, android::OutputStream* out, - android::OutputStream* out_r_txt = nullptr); + bool Generate(android::StringPiece package_name_to_generate, io::OutputStream* out, + io::OutputStream* out_r_txt = nullptr); bool Generate(android::StringPiece package_name_to_generate, - android::StringPiece output_package_name, android::OutputStream* out, - android::OutputStream* out_r_txt = nullptr); + android::StringPiece output_package_name, io::OutputStream* out, + io::OutputStream* out_r_txt = nullptr); const std::string& GetError() const; diff --git a/tools/aapt2/java/ProguardRules.cpp b/tools/aapt2/java/ProguardRules.cpp index aef48fc102d7..80a46d553960 100644 --- a/tools/aapt2/java/ProguardRules.cpp +++ b/tools/aapt2/java/ProguardRules.cpp @@ -29,8 +29,8 @@ #include "util/Util.h" #include "xml/XmlDom.h" +using ::aapt::io::OutputStream; using ::aapt::text::Printer; -using ::android::OutputStream; namespace aapt { namespace proguard { diff --git a/tools/aapt2/java/ProguardRules.h b/tools/aapt2/java/ProguardRules.h index 876ef48042f5..267f7ede274a 100644 --- a/tools/aapt2/java/ProguardRules.h +++ b/tools/aapt2/java/ProguardRules.h @@ -26,8 +26,8 @@ #include "ResourceTable.h" #include "ValueVisitor.h" #include "androidfw/Source.h" -#include "androidfw/Streams.h" #include "androidfw/StringPiece.h" +#include "io/Io.h" #include "process/IResourceTableConsumer.h" #include "xml/XmlDom.h" @@ -69,7 +69,7 @@ class KeepSet { } private: - friend void WriteKeepSet(const KeepSet& keep_set, android::OutputStream* out, bool minimal_keep, + friend void WriteKeepSet(const KeepSet& keep_set, io::OutputStream* out, bool minimal_keep, bool no_location_reference); friend bool CollectLocations(const UsageLocation& location, const KeepSet& keep_set, @@ -89,7 +89,7 @@ bool CollectProguardRules(IAaptContext* context, xml::XmlResource* res, KeepSet* bool CollectResourceReferences(IAaptContext* context, ResourceTable* table, KeepSet* keep_set); -void WriteKeepSet(const KeepSet& keep_set, android::OutputStream* out, bool minimal_keep, +void WriteKeepSet(const KeepSet& keep_set, io::OutputStream* out, bool minimal_keep, bool no_location_reference); bool CollectLocations(const UsageLocation& location, const KeepSet& keep_set, diff --git a/tools/aapt2/test/Common.h b/tools/aapt2/test/Common.h index 04379804d8ee..e48668cf96a3 100644 --- a/tools/aapt2/test/Common.h +++ b/tools/aapt2/test/Common.h @@ -90,7 +90,7 @@ class TestFile : public io::IFile { return {}; } - std::unique_ptr<android::InputStream> OpenInputStream() override { + std::unique_ptr<io::InputStream> OpenInputStream() override { return OpenAsData(); } diff --git a/tools/aapt2/test/Fixture.cpp b/tools/aapt2/test/Fixture.cpp index b91abe572306..428372f31d0d 100644 --- a/tools/aapt2/test/Fixture.cpp +++ b/tools/aapt2/test/Fixture.cpp @@ -20,7 +20,6 @@ #include <android-base/file.h> #include <android-base/stringprintf.h> #include <android-base/utf8.h> -#include <androidfw/FileStream.h> #include <androidfw/StringPiece.h> #include <dirent.h> #include <gmock/gmock.h> @@ -29,6 +28,7 @@ #include "Diagnostics.h" #include "cmd/Compile.h" #include "cmd/Link.h" +#include "io/FileStream.h" #include "util/Files.h" using testing::Eq; diff --git a/tools/aapt2/text/Printer.cpp b/tools/aapt2/text/Printer.cpp index c2fa8cccd536..8e491aca794d 100644 --- a/tools/aapt2/text/Printer.cpp +++ b/tools/aapt2/text/Printer.cpp @@ -20,7 +20,7 @@ #include "io/Util.h" -using ::android::OutputStream; +using ::aapt::io::OutputStream; using ::android::StringPiece; namespace aapt { diff --git a/tools/aapt2/text/Printer.h b/tools/aapt2/text/Printer.h index 44f0fc546c7c..f7ad98bfd981 100644 --- a/tools/aapt2/text/Printer.h +++ b/tools/aapt2/text/Printer.h @@ -18,16 +18,17 @@ #define AAPT_TEXT_PRINTER_H #include "android-base/macros.h" -#include "androidfw/Streams.h" #include "androidfw/StringPiece.h" +#include "io/Io.h" + namespace aapt { namespace text { // An indenting Printer that helps write formatted text to the OutputStream. class Printer { public: - explicit Printer(android::OutputStream* out) : out_(out) { + explicit Printer(::aapt::io::OutputStream* out) : out_(out) { } Printer& Print(android::StringPiece str); @@ -40,7 +41,7 @@ class Printer { private: DISALLOW_COPY_AND_ASSIGN(Printer); - android::OutputStream* out_; + ::aapt::io::OutputStream* out_; int indent_level_ = 0; bool needs_indent_ = false; bool error_ = false; diff --git a/tools/aapt2/xml/XmlDom.cpp b/tools/aapt2/xml/XmlDom.cpp index 49807db26bb7..8dea8ea52f92 100644 --- a/tools/aapt2/xml/XmlDom.cpp +++ b/tools/aapt2/xml/XmlDom.cpp @@ -30,7 +30,7 @@ #include "XmlPullParser.h" #include "util/Util.h" -using ::android::InputStream; +using ::aapt::io::InputStream; using ::android::StringPiece; using ::android::StringPiece16; diff --git a/tools/aapt2/xml/XmlDom.h b/tools/aapt2/xml/XmlDom.h index 9668b6a6e8ef..c253b0a1f4a9 100644 --- a/tools/aapt2/xml/XmlDom.h +++ b/tools/aapt2/xml/XmlDom.h @@ -24,8 +24,8 @@ #include "Resource.h" #include "ResourceValues.h" #include "androidfw/IDiagnostics.h" -#include "androidfw/Streams.h" #include "androidfw/StringPiece.h" +#include "io/Io.h" #include "util/Util.h" #include "xml/XmlUtil.h" @@ -152,7 +152,7 @@ class XmlResource { }; // Inflates an XML DOM from an InputStream, logging errors to the logger. -std::unique_ptr<XmlResource> Inflate(android::InputStream* in, android::IDiagnostics* diag, +std::unique_ptr<XmlResource> Inflate(io::InputStream* in, android::IDiagnostics* diag, const android::Source& source); // Inflates an XML DOM from a binary ResXMLTree. diff --git a/tools/aapt2/xml/XmlPullParser.cpp b/tools/aapt2/xml/XmlPullParser.cpp index 203832d2dbe8..d79446bfae6f 100644 --- a/tools/aapt2/xml/XmlPullParser.cpp +++ b/tools/aapt2/xml/XmlPullParser.cpp @@ -21,7 +21,7 @@ #include "xml/XmlPullParser.h" #include "xml/XmlUtil.h" -using ::android::InputStream; +using ::aapt::io::InputStream; using ::android::StringPiece; namespace aapt { diff --git a/tools/aapt2/xml/XmlPullParser.h b/tools/aapt2/xml/XmlPullParser.h index 655e6dc93e75..fe4cd018d808 100644 --- a/tools/aapt2/xml/XmlPullParser.h +++ b/tools/aapt2/xml/XmlPullParser.h @@ -27,10 +27,11 @@ #include <string> #include <vector> -#include "Resource.h" #include "android-base/macros.h" -#include "androidfw/Streams.h" #include "androidfw/StringPiece.h" + +#include "Resource.h" +#include "io/Io.h" #include "process/IResourceTableConsumer.h" #include "xml/XmlUtil.h" @@ -65,7 +66,7 @@ class XmlPullParser : public IPackageDeclStack { static bool SkipCurrentElement(XmlPullParser* parser); static bool IsGoodEvent(Event event); - explicit XmlPullParser(android::InputStream* in); + explicit XmlPullParser(io::InputStream* in); ~XmlPullParser(); /** @@ -178,7 +179,7 @@ class XmlPullParser : public IPackageDeclStack { std::vector<Attribute> attributes; }; - android::InputStream* in_; + io::InputStream* in_; XML_Parser parser_; std::queue<EventData> event_queue_; std::string error_; |