1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef _ANDROID_GRAPHICS_UTILS_H_
18 #define _ANDROID_GRAPHICS_UTILS_H_
19 
20 #include "SkRefCnt.h"
21 #include "SkStream.h"
22 
23 class SkData;
24 
25 #include <jni.h>
26 #include <androidfw/Asset.h>
27 
28 namespace android {
29 
30 class AssetStreamAdaptor : public SkStreamRewindable {
31 public:
32     explicit AssetStreamAdaptor(Asset*);
33 
34     virtual bool rewind();
35     virtual size_t read(void* buffer, size_t size);
hasLength()36     virtual bool hasLength() const { return true; }
37     virtual size_t getLength() const;
38     virtual bool hasPosition() const;
39     virtual size_t getPosition() const;
40     virtual bool seek(size_t position);
41     virtual bool move(long offset);
42     virtual bool isAtEnd() const;
43 
44 protected:
45     SkStreamRewindable* onDuplicate() const override;
46 
47 private:
48     Asset* fAsset;
49 };
50 
51 /**
52  *  Make a deep copy of the asset, and return it as an SkData, or NULL if there
53  *  was an error.
54  */
55 
56 sk_sp<SkData> CopyAssetToData(Asset*);
57 
58 /** Restore the file descriptor's offset in our destructor
59  */
60 class AutoFDSeek {
61 public:
AutoFDSeek(int fd)62     explicit AutoFDSeek(int fd) : fFD(fd) {
63         fCurr = ::lseek(fd, 0, SEEK_CUR);
64     }
~AutoFDSeek()65     ~AutoFDSeek() {
66         if (fCurr >= 0) {
67             ::lseek(fFD, fCurr, SEEK_SET);
68         }
69     }
70 private:
71     int     fFD;
72     off64_t   fCurr;
73 };
74 
75 jobject nullObjectReturn(const char msg[]);
76 
77 /** Check if the file descriptor is seekable.
78  */
79 bool isSeekable(int descriptor);
80 
81 JNIEnv* get_env_or_die(JavaVM* jvm);
82 
83 /**
84  * Helper method for accessing the JNI interface pointer.
85  *
86  * Image decoding (which this supports) is started on a thread that is already
87  * attached to the Java VM. But an AnimatedImageDrawable continues decoding on
88  * the AnimatedImageThread, which is not attached. This will attach if
89  * necessary.
90  */
91 JNIEnv* requireEnv(JavaVM* jvm);
92 
93 }; // namespace android
94 
95 #endif  // _ANDROID_GRAPHICS_UTILS_H_
96