aboutsummaryrefslogtreecommitdiffhomepage
path: root/experimental/FileReaderApp/ReaderView.cpp
blob: d0792d26c57c568cd1968f477ea076ef0b498099 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "ReaderView.h"
#include "SkGPipe.h"
#include "SkCanvas.h"

#include <stdio.h>

#define FILE_PATH   "/Users/yangsu/Code/test/test.a"
ReaderView::ReaderView() {
    fBGColor = 0xFFDDDDDD;
    fFilePos = 0;
    fBufferBitmaps[0].setConfig(SkBitmap::kARGB_8888_Config, 640, 480);
    fBufferBitmaps[0].allocPixels(NULL);
    fBufferBitmaps[1].setConfig(SkBitmap::kARGB_8888_Config, 640, 480);
    fBufferBitmaps[1].allocPixels(NULL);
    fFront  = 0;
    fBack   = 1;
}

void ReaderView::draw(SkCanvas* canvas) {
    canvas->drawColor(fBGColor);

    SkAutoCanvasRestore acr(canvas, true);

    //Create a temporary canvas and reader object that draws into the back
    //bitmap so that the incremental changes or incomplete reads are not shown
    //on screen
    SkCanvas bufferCanvas(fBufferBitmaps[fBack]);
    SkGPipeReader reader(&bufferCanvas);

    //The file specified by FILE_PATH MUST exist
    FILE* f = fopen(FILE_PATH, "rb");
    SkASSERT(f != NULL);

    fseek(f, 0, SEEK_END);
    int size = ftell(f) * sizeof(char);
    if (size <= fFilePos) {
        fFilePos = 0;
    }

    //Resume from the last read location
    fseek(f, fFilePos, SEEK_SET);
    int toBeRead = size - fFilePos;
    if (size > 0 && toBeRead > 0) {
        void* block = sk_malloc_throw(toBeRead);
        fread(block, 1, toBeRead, f);

        size_t bytesRead;
        SkGPipeReader::Status fStatus = reader.playback(block, toBeRead, &bytesRead);
        SkASSERT(SkGPipeReader::kError_Status != fStatus);
        SkASSERT(toBeRead >= bytesRead);

        //if the reader reaches a done verb, a frame is complete.
        //Update the file location and swap the front and back bitmaps to show
        //the new frame
        if (SkGPipeReader::kDone_Status == fStatus) {
            fFilePos += bytesRead;
            fFront = fFront ^ 0x1;
            fBack = fBack ^ 0x1;
        }
        sk_free(block);
    }

    fclose(f);

    //the front bitmap is always drawn
    canvas->drawBitmap(fBufferBitmaps[fFront], 0, 0, NULL);
    this->inval(NULL);
}