SampleApp.cpp revision 5fb2ce38b3dcb8e60e9e112df23c9d42456d7069
1/*
2 * Copyright 2011 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7#include "SampleApp.h"
8
9#include "SkData.h"
10#include "SkCanvas.h"
11#include "SkDevice.h"
12#include "SkGraphics.h"
13#include "SkImageDecoder.h"
14#include "SkImageEncoder.h"
15#include "SkPaint.h"
16#include "SkPicture.h"
17#include "SkStream.h"
18#include "SkTSort.h"
19#include "SkTime.h"
20#include "SkWindow.h"
21
22#include "SampleCode.h"
23#include "SkTypeface.h"
24
25#if SK_SUPPORT_GPU
26#include "gl/GrGLInterface.h"
27#include "gl/GrGLUtil.h"
28#include "GrRenderTarget.h"
29#include "GrContext.h"
30#include "SkGpuDevice.h"
31#else
32class GrContext;
33#endif
34
35#include "SkOSFile.h"
36#include "SkPDFDevice.h"
37#include "SkPDFDocument.h"
38#include "SkStream.h"
39
40#include "SkGPipe.h"
41#include "SamplePipeControllers.h"
42#include "OverView.h"
43#include "TransitionView.h"
44
45extern SampleView* CreateSamplePictFileView(const char filename[]);
46
47class PictFileFactory : public SkViewFactory {
48    SkString fFilename;
49public:
50    PictFileFactory(const SkString& filename) : fFilename(filename) {}
51    virtual SkView* operator() () const SK_OVERRIDE {
52        return CreateSamplePictFileView(fFilename.c_str());
53    }
54};
55
56#ifdef SAMPLE_PDF_FILE_VIEWER
57extern SampleView* CreateSamplePdfFileViewer(const char filename[]);
58
59class PdfFileViewerFactory : public SkViewFactory {
60    SkString fFilename;
61public:
62    PdfFileViewerFactory(const SkString& filename) : fFilename(filename) {}
63    virtual SkView* operator() () const SK_OVERRIDE {
64        return CreateSamplePdfFileViewer(fFilename.c_str());
65    }
66};
67#endif  // SAMPLE_PDF_FILE_VIEWER
68
69#define PIPE_FILEx
70#ifdef  PIPE_FILE
71#define FILE_PATH "/path/to/drawing.data"
72#endif
73
74#define PIPE_NETx
75#ifdef  PIPE_NET
76#include "SkSockets.h"
77SkTCPServer gServer;
78#endif
79
80#define USE_ARROWS_FOR_ZOOM true
81
82#if SK_ANGLE
83//#define DEFAULT_TO_ANGLE 1
84#else
85#define DEFAULT_TO_GPU 0 // if 1 default rendering is on GPU
86#endif
87
88#define ANIMATING_EVENTTYPE "nextSample"
89#define ANIMATING_DELAY     250
90
91#ifdef SK_DEBUG
92    #define FPS_REPEAT_MULTIPLIER   1
93#else
94    #define FPS_REPEAT_MULTIPLIER   10
95#endif
96#define FPS_REPEAT_COUNT    (10 * FPS_REPEAT_MULTIPLIER)
97
98static SampleWindow* gSampleWindow;
99
100static bool gShowGMBounds;
101
102static void post_event_to_sink(SkEvent* evt, SkEventSink* sink) {
103    evt->setTargetID(sink->getSinkID())->post();
104}
105
106///////////////////////////////////////////////////////////////////////////////
107
108static const char* skip_until(const char* str, const char* skip) {
109    if (!str) {
110        return NULL;
111    }
112    return strstr(str, skip);
113}
114
115static const char* skip_past(const char* str, const char* skip) {
116    const char* found = skip_until(str, skip);
117    if (!found) {
118        return NULL;
119    }
120    return found + strlen(skip);
121}
122
123static const char* gPrefFileName = "sampleapp_prefs.txt";
124
125static bool readTitleFromPrefs(SkString* title) {
126    SkFILEStream stream(gPrefFileName);
127    if (!stream.isValid()) {
128        return false;
129    }
130
131    size_t len = stream.getLength();
132    SkString data(len);
133    stream.read(data.writable_str(), len);
134    const char* s = data.c_str();
135
136    s = skip_past(s, "curr-slide-title");
137    s = skip_past(s, "=");
138    s = skip_past(s, "\"");
139    const char* stop = skip_until(s, "\"");
140    if (stop > s) {
141        title->set(s, stop - s);
142        return true;
143    }
144    return false;
145}
146
147static void writeTitleToPrefs(const char* title) {
148    SkFILEWStream stream(gPrefFileName);
149    SkString data;
150    data.printf("curr-slide-title = \"%s\"\n", title);
151    stream.write(data.c_str(), data.size());
152}
153
154///////////////////////////////////////////////////////////////////////////////
155
156class SampleWindow::DefaultDeviceManager : public SampleWindow::DeviceManager {
157public:
158
159    DefaultDeviceManager() {
160#if SK_SUPPORT_GPU
161        fCurContext = NULL;
162        fCurIntf = NULL;
163        fCurRenderTarget = NULL;
164        fMSAASampleCount = 0;
165#endif
166        fBackend = kNone_BackEndType;
167    }
168
169    virtual ~DefaultDeviceManager() {
170#if SK_SUPPORT_GPU
171        SkSafeUnref(fCurContext);
172        SkSafeUnref(fCurIntf);
173        SkSafeUnref(fCurRenderTarget);
174#endif
175    }
176
177    virtual void setUpBackend(SampleWindow* win, int msaaSampleCount) {
178        SkASSERT(kNone_BackEndType == fBackend);
179
180        fBackend = kNone_BackEndType;
181
182#if SK_SUPPORT_GPU
183        switch (win->getDeviceType()) {
184            case kRaster_DeviceType:
185                // fallthrough
186            case kPicture_DeviceType:
187                // fallthrough
188            case kGPU_DeviceType:
189                // fallthrough
190            case kNullGPU_DeviceType:
191                // all these guys use the native backend
192                fBackend = kNativeGL_BackEndType;
193                break;
194#if SK_ANGLE
195            case kANGLE_DeviceType:
196                // ANGLE is really the only odd man out
197                fBackend = kANGLE_BackEndType;
198                break;
199#endif // SK_ANGLE
200            default:
201                SkASSERT(false);
202                break;
203        }
204        AttachmentInfo attachmentInfo;
205        bool result = win->attach(fBackend, msaaSampleCount, &attachmentInfo);
206        if (!result) {
207            SkDebugf("Failed to initialize GL");
208            return;
209        }
210        fMSAASampleCount = msaaSampleCount;
211
212        SkASSERT(NULL == fCurIntf);
213        SkAutoTUnref<const GrGLInterface> glInterface;
214        switch (win->getDeviceType()) {
215            case kRaster_DeviceType:
216                // fallthrough
217            case kPicture_DeviceType:
218                // fallthrough
219            case kGPU_DeviceType:
220                // all these guys use the native interface
221                glInterface.reset(GrGLCreateNativeInterface());
222                break;
223#if SK_ANGLE
224            case kANGLE_DeviceType:
225                glInterface.reset(GrGLCreateANGLEInterface());
226                break;
227#endif // SK_ANGLE
228            case kNullGPU_DeviceType:
229                glInterface.reset(GrGLCreateNullInterface());
230                break;
231            default:
232                SkASSERT(false);
233                break;
234        }
235
236        // Currently SampleApp does not use NVPR. TODO: Provide an NVPR device type that is skipped
237        // when the driver doesn't support NVPR.
238        fCurIntf = GrGLInterfaceRemoveNVPR(glInterface.get());
239
240        SkASSERT(NULL == fCurContext);
241        fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf);
242
243        if (NULL == fCurContext || NULL == fCurIntf) {
244            // We need some context and interface to see results
245            SkSafeUnref(fCurContext);
246            SkSafeUnref(fCurIntf);
247            fCurContext = NULL;
248            fCurIntf = NULL;
249            SkDebugf("Failed to setup 3D");
250
251            win->detach();
252        }
253#endif // SK_SUPPORT_GPU
254        // call windowSizeChanged to create the render target
255        this->windowSizeChanged(win);
256    }
257
258    virtual void tearDownBackend(SampleWindow *win) {
259#if SK_SUPPORT_GPU
260        SkSafeUnref(fCurContext);
261        fCurContext = NULL;
262
263        SkSafeUnref(fCurIntf);
264        fCurIntf = NULL;
265
266        SkSafeUnref(fCurRenderTarget);
267        fCurRenderTarget = NULL;
268#endif
269        win->detach();
270        fBackend = kNone_BackEndType;
271    }
272
273    virtual SkCanvas* createCanvas(SampleWindow::DeviceType dType,
274                                   SampleWindow* win) {
275#if SK_SUPPORT_GPU
276        if (IsGpuDeviceType(dType) && NULL != fCurContext) {
277            SkAutoTUnref<SkBaseDevice> device(new SkGpuDevice(fCurContext, fCurRenderTarget));
278            return new SkCanvas(device);
279        } else
280#endif
281        {
282            return NULL;
283        }
284    }
285
286    virtual void publishCanvas(SampleWindow::DeviceType dType,
287                               SkCanvas* canvas,
288                               SampleWindow* win) {
289#if SK_SUPPORT_GPU
290        if (fCurContext) {
291            // in case we have queued drawing calls
292            fCurContext->flush();
293
294            if (!IsGpuDeviceType(dType)) {
295                // need to send the raster bits to the (gpu) window
296                fCurContext->setRenderTarget(fCurRenderTarget);
297                const SkBitmap& bm = win->getBitmap();
298                fCurRenderTarget->writePixels(0, 0, bm.width(), bm.height(),
299                                             kSkia8888_GrPixelConfig,
300                                             bm.getPixels(),
301                                             bm.rowBytes());
302            }
303        }
304#endif
305
306        win->present();
307    }
308
309    virtual void windowSizeChanged(SampleWindow* win) {
310#if SK_SUPPORT_GPU
311        if (fCurContext) {
312            AttachmentInfo attachmentInfo;
313            win->attach(fBackend, fMSAASampleCount, &attachmentInfo);
314
315            GrBackendRenderTargetDesc desc;
316            desc.fWidth = SkScalarRoundToInt(win->width());
317            desc.fHeight = SkScalarRoundToInt(win->height());
318            desc.fConfig = kSkia8888_GrPixelConfig;
319            desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
320            desc.fSampleCnt = attachmentInfo.fSampleCount;
321            desc.fStencilBits = attachmentInfo.fStencilBits;
322            GrGLint buffer;
323            GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
324            desc.fRenderTargetHandle = buffer;
325
326            SkSafeUnref(fCurRenderTarget);
327            fCurRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
328        }
329#endif
330    }
331
332    virtual GrContext* getGrContext() {
333#if SK_SUPPORT_GPU
334        return fCurContext;
335#else
336        return NULL;
337#endif
338    }
339
340    virtual GrRenderTarget* getGrRenderTarget() SK_OVERRIDE {
341#if SK_SUPPORT_GPU
342        return fCurRenderTarget;
343#else
344        return NULL;
345#endif
346    }
347
348private:
349
350#if SK_SUPPORT_GPU
351    GrContext*              fCurContext;
352    const GrGLInterface*    fCurIntf;
353    GrRenderTarget*         fCurRenderTarget;
354    int fMSAASampleCount;
355#endif
356
357    SkOSWindow::SkBackEndTypes fBackend;
358
359    typedef SampleWindow::DeviceManager INHERITED;
360};
361
362///////////////
363static const char view_inval_msg[] = "view-inval-msg";
364
365void SampleWindow::postInvalDelay() {
366    (new SkEvent(view_inval_msg, this->getSinkID()))->postDelay(1);
367}
368
369static bool isInvalEvent(const SkEvent& evt) {
370    return evt.isType(view_inval_msg);
371}
372//////////////////
373
374SkFuncViewFactory::SkFuncViewFactory(SkViewCreateFunc func)
375    : fCreateFunc(func) {
376}
377
378SkView* SkFuncViewFactory::operator() () const {
379    return (*fCreateFunc)();
380}
381
382#include "GMSampleView.h"
383
384SkGMSampleViewFactory::SkGMSampleViewFactory(GMFactoryFunc func)
385    : fFunc(func) {
386}
387
388SkView* SkGMSampleViewFactory::operator() () const {
389    skiagm::GM* gm = fFunc(NULL);
390    gm->setMode(skiagm::GM::kSample_Mode);
391    return new GMSampleView(gm);
392}
393
394SkViewRegister* SkViewRegister::gHead;
395SkViewRegister::SkViewRegister(SkViewFactory* fact) : fFact(fact) {
396    fFact->ref();
397    fChain = gHead;
398    gHead = this;
399}
400
401SkViewRegister::SkViewRegister(SkViewCreateFunc func) {
402    fFact = new SkFuncViewFactory(func);
403    fChain = gHead;
404    gHead = this;
405}
406
407SkViewRegister::SkViewRegister(GMFactoryFunc func) {
408    fFact = new SkGMSampleViewFactory(func);
409    fChain = gHead;
410    gHead = this;
411}
412
413class AutoUnrefArray {
414public:
415    AutoUnrefArray() {}
416    ~AutoUnrefArray() {
417        int count = fObjs.count();
418        for (int i = 0; i < count; ++i) {
419            fObjs[i]->unref();
420        }
421    }
422    SkRefCnt*& push_back() { return *fObjs.append(); }
423
424private:
425    SkTDArray<SkRefCnt*> fObjs;
426};
427
428// registers GMs as Samples
429// This can't be performed during static initialization because it could be
430// run before GMRegistry has been fully built.
431static void SkGMRegistyToSampleRegistry() {
432    static bool gOnce;
433    static AutoUnrefArray fRegisters;
434
435    if (!gOnce) {
436        const skiagm::GMRegistry* gmreg = skiagm::GMRegistry::Head();
437        while (gmreg) {
438            fRegisters.push_back() = new SkViewRegister(gmreg->factory());
439            gmreg = gmreg->next();
440        }
441        gOnce = true;
442    }
443}
444
445//////////////////////////////////////////////////////////////////////////////
446
447enum FlipAxisEnum {
448    kFlipAxis_X = (1 << 0),
449    kFlipAxis_Y = (1 << 1)
450};
451
452#include "SkDrawFilter.h"
453
454struct HintingState {
455    SkPaint::Hinting hinting;
456    const char* name;
457    const char* label;
458};
459static HintingState gHintingStates[] = {
460    {SkPaint::kNo_Hinting, "Mixed", NULL },
461    {SkPaint::kNo_Hinting, "None", "H0 " },
462    {SkPaint::kSlight_Hinting, "Slight", "Hs " },
463    {SkPaint::kNormal_Hinting, "Normal", "Hn " },
464    {SkPaint::kFull_Hinting, "Full", "Hf " },
465};
466
467struct FilterLevelState {
468    SkPaint::FilterLevel    fLevel;
469    const char*             fName;
470    const char*             fLabel;
471};
472static FilterLevelState gFilterLevelStates[] = {
473    { SkPaint::kNone_FilterLevel,   "Mixed",    NULL    },
474    { SkPaint::kNone_FilterLevel,   "None",     "F0 "   },
475    { SkPaint::kLow_FilterLevel,    "Low",      "F1 "   },
476    { SkPaint::kMedium_FilterLevel, "Medium",   "F2 "   },
477    { SkPaint::kHigh_FilterLevel,   "High",     "F3 "   },
478};
479
480class FlagsDrawFilter : public SkDrawFilter {
481public:
482    FlagsDrawFilter(SkOSMenu::TriState lcd, SkOSMenu::TriState aa,
483                    SkOSMenu::TriState subpixel, int hinting, int filterlevel)
484        : fLCDState(lcd)
485        , fAAState(aa)
486        , fSubpixelState(subpixel)
487        , fHintingState(hinting)
488        , fFilterLevelIndex(filterlevel)
489    {
490        SkASSERT((unsigned)filterlevel < SK_ARRAY_COUNT(gFilterLevelStates));
491    }
492
493    virtual bool filter(SkPaint* paint, Type t) {
494        if (kText_Type == t && SkOSMenu::kMixedState != fLCDState) {
495            paint->setLCDRenderText(SkOSMenu::kOnState == fLCDState);
496        }
497        if (SkOSMenu::kMixedState != fAAState) {
498            paint->setAntiAlias(SkOSMenu::kOnState == fAAState);
499        }
500        if (0 != fFilterLevelIndex) {
501            paint->setFilterLevel(gFilterLevelStates[fFilterLevelIndex].fLevel);
502        }
503        if (SkOSMenu::kMixedState != fSubpixelState) {
504            paint->setSubpixelText(SkOSMenu::kOnState == fSubpixelState);
505        }
506        if (0 != fHintingState && fHintingState < (int)SK_ARRAY_COUNT(gHintingStates)) {
507            paint->setHinting(gHintingStates[fHintingState].hinting);
508        }
509        return true;
510    }
511
512private:
513    SkOSMenu::TriState  fLCDState;
514    SkOSMenu::TriState  fAAState;
515    SkOSMenu::TriState  fSubpixelState;
516    int fHintingState;
517    int fFilterLevelIndex;
518};
519
520//////////////////////////////////////////////////////////////////////////////
521
522#define MAX_ZOOM_LEVEL  8
523#define MIN_ZOOM_LEVEL  -8
524
525static const char gCharEvtName[] = "SampleCode_Char_Event";
526static const char gKeyEvtName[] = "SampleCode_Key_Event";
527static const char gTitleEvtName[] = "SampleCode_Title_Event";
528static const char gPrefSizeEvtName[] = "SampleCode_PrefSize_Event";
529static const char gFastTextEvtName[] = "SampleCode_FastText_Event";
530static const char gUpdateWindowTitleEvtName[] = "SampleCode_UpdateWindowTitle";
531
532bool SampleCode::CharQ(const SkEvent& evt, SkUnichar* outUni) {
533    if (evt.isType(gCharEvtName, sizeof(gCharEvtName) - 1)) {
534        if (outUni) {
535            *outUni = evt.getFast32();
536        }
537        return true;
538    }
539    return false;
540}
541
542bool SampleCode::KeyQ(const SkEvent& evt, SkKey* outKey) {
543    if (evt.isType(gKeyEvtName, sizeof(gKeyEvtName) - 1)) {
544        if (outKey) {
545            *outKey = (SkKey)evt.getFast32();
546        }
547        return true;
548    }
549    return false;
550}
551
552bool SampleCode::TitleQ(const SkEvent& evt) {
553    return evt.isType(gTitleEvtName, sizeof(gTitleEvtName) - 1);
554}
555
556void SampleCode::TitleR(SkEvent* evt, const char title[]) {
557    SkASSERT(evt && TitleQ(*evt));
558    evt->setString(gTitleEvtName, title);
559}
560
561bool SampleCode::RequestTitle(SkView* view, SkString* title) {
562    SkEvent evt(gTitleEvtName);
563    if (view->doQuery(&evt)) {
564        title->set(evt.findString(gTitleEvtName));
565        return true;
566    }
567    return false;
568}
569
570bool SampleCode::PrefSizeQ(const SkEvent& evt) {
571    return evt.isType(gPrefSizeEvtName, sizeof(gPrefSizeEvtName) - 1);
572}
573
574void SampleCode::PrefSizeR(SkEvent* evt, SkScalar width, SkScalar height) {
575    SkASSERT(evt && PrefSizeQ(*evt));
576    SkScalar size[2];
577    size[0] = width;
578    size[1] = height;
579    evt->setScalars(gPrefSizeEvtName, 2, size);
580}
581
582bool SampleCode::FastTextQ(const SkEvent& evt) {
583    return evt.isType(gFastTextEvtName, sizeof(gFastTextEvtName) - 1);
584}
585
586///////////////////////////////////////////////////////////////////////////////
587
588static SkMSec gAnimTime;
589static SkMSec gAnimTimePrev;
590
591SkMSec SampleCode::GetAnimTime() { return gAnimTime; }
592SkMSec SampleCode::GetAnimTimeDelta() { return gAnimTime - gAnimTimePrev; }
593SkScalar SampleCode::GetAnimSecondsDelta() {
594    return SkDoubleToScalar(GetAnimTimeDelta() / 1000.0);
595}
596
597SkScalar SampleCode::GetAnimScalar(SkScalar speed, SkScalar period) {
598    // since gAnimTime can be up to 32 bits, we can't convert it to a float
599    // or we'll lose the low bits. Hence we use doubles for the intermediate
600    // calculations
601    double seconds = (double)gAnimTime / 1000.0;
602    double value = SkScalarToDouble(speed) * seconds;
603    if (period) {
604        value = ::fmod(value, SkScalarToDouble(period));
605    }
606    return SkDoubleToScalar(value);
607}
608
609SkScalar SampleCode::GetAnimSinScalar(SkScalar amplitude,
610                                      SkScalar periodInSec,
611                                      SkScalar phaseInSec) {
612    if (!periodInSec) {
613        return 0;
614    }
615    double t = (double)gAnimTime / 1000.0 + phaseInSec;
616    t *= SkScalarToFloat(2 * SK_ScalarPI) / periodInSec;
617    amplitude = SK_ScalarHalf * amplitude;
618    return SkScalarMul(amplitude, SkDoubleToScalar(sin(t))) + amplitude;
619}
620
621enum TilingMode {
622    kNo_Tiling,
623    kAbs_128x128_Tiling,
624    kAbs_256x256_Tiling,
625    kRel_4x4_Tiling,
626    kRel_1x16_Tiling,
627    kRel_16x1_Tiling,
628
629    kLast_TilingMode_Enum
630};
631
632struct TilingInfo {
633    const char* label;
634    SkScalar    w, h;
635};
636
637static const struct TilingInfo gTilingInfo[] = {
638    { "No tiling", SK_Scalar1        , SK_Scalar1         }, // kNo_Tiling
639    { "128x128"  , SkIntToScalar(128), SkIntToScalar(128) }, // kAbs_128x128_Tiling
640    { "256x256"  , SkIntToScalar(256), SkIntToScalar(256) }, // kAbs_256x256_Tiling
641    { "1/4x1/4"  , SK_Scalar1 / 4    , SK_Scalar1 / 4     }, // kRel_4x4_Tiling
642    { "1/1x1/16" , SK_Scalar1        , SK_Scalar1 / 16    }, // kRel_1x16_Tiling
643    { "1/16x1/1" , SK_Scalar1 / 16   , SK_Scalar1         }, // kRel_16x1_Tiling
644};
645SK_COMPILE_ASSERT((SK_ARRAY_COUNT(gTilingInfo) == kLast_TilingMode_Enum),
646                  Incomplete_tiling_labels);
647
648SkSize SampleWindow::tileSize() const {
649    SkASSERT((TilingMode)fTilingMode < kLast_TilingMode_Enum);
650    const struct TilingInfo* info = gTilingInfo + fTilingMode;
651    return SkSize::Make(info->w > SK_Scalar1 ? info->w : this->width() * info->w,
652                        info->h > SK_Scalar1 ? info->h : this->height() * info->h);
653}
654//////////////////////////////////////////////////////////////////////////////
655
656static SkView* curr_view(SkWindow* wind) {
657    SkView::F2BIter iter(wind);
658    return iter.next();
659}
660
661static bool curr_title(SkWindow* wind, SkString* title) {
662    SkView* view = curr_view(wind);
663    if (view) {
664        SkEvent evt(gTitleEvtName);
665        if (view->doQuery(&evt)) {
666            title->set(evt.findString(gTitleEvtName));
667            return true;
668        }
669    }
670    return false;
671}
672
673void SampleWindow::setZoomCenter(float x, float y)
674{
675    fZoomCenterX = x;
676    fZoomCenterY = y;
677}
678
679bool SampleWindow::zoomIn()
680{
681    // Arbitrarily decided
682    if (fFatBitsScale == 25) return false;
683    fFatBitsScale++;
684    this->inval(NULL);
685    return true;
686}
687
688bool SampleWindow::zoomOut()
689{
690    if (fFatBitsScale == 1) return false;
691    fFatBitsScale--;
692    this->inval(NULL);
693    return true;
694}
695
696void SampleWindow::updatePointer(int x, int y)
697{
698    fMouseX = x;
699    fMouseY = y;
700    if (fShowZoomer) {
701        this->inval(NULL);
702    }
703}
704
705static inline SampleWindow::DeviceType cycle_devicetype(SampleWindow::DeviceType ct) {
706    static const SampleWindow::DeviceType gCT[] = {
707        SampleWindow::kPicture_DeviceType,
708#if SK_SUPPORT_GPU
709        SampleWindow::kGPU_DeviceType,
710#if SK_ANGLE
711        SampleWindow::kANGLE_DeviceType,
712#endif // SK_ANGLE
713        SampleWindow::kRaster_DeviceType, // skip the null gpu device in normal cycling
714#endif // SK_SUPPORT_GPU
715        SampleWindow::kRaster_DeviceType
716    };
717    SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gCT) == SampleWindow::kDeviceTypeCnt, array_size_mismatch);
718    return gCT[ct];
719}
720
721static void usage(const char * argv0) {
722    SkDebugf("%s [--slide sampleName] [-i resourcePath] [--msaa sampleCount] [--pictureDir dirPath] [--picture path] [--sort]\n", argv0);
723#ifdef SAMPLE_PDF_FILE_VIEWER
724    SkDebugf("                [--pdfDir pdfPath]\n");
725    SkDebugf("    pdfPath: path to directory pdf files are read from\n");
726#endif  // SAMPLE_PDF_FILE_VIEWER
727    SkDebugf("    sampleName: sample at which to start.\n");
728    SkDebugf("    resourcePath: directory that stores image resources.\n");
729    SkDebugf("    msaa: request multisampling with the given sample count.\n");
730    SkDebugf("    dirPath: path to directory skia pictures are read from\n");
731    SkDebugf("    path: path to skia picture\n");
732    SkDebugf("    --sort: sort samples by title, this would help to compare pdf rendering (P:foo.pdf) with skp rendering (P:foo.pdf)\n");
733}
734
735static SkString getSampleTitle(const SkViewFactory* sampleFactory) {
736    SkView* view = (*sampleFactory)();
737    SkString title;
738    SampleCode::RequestTitle(view, &title);
739    view->unref();
740    return title;
741}
742
743static bool compareSampleTitle(const SkViewFactory* first, const SkViewFactory* second) {
744    return strcmp(getSampleTitle(first).c_str(), getSampleTitle(second).c_str()) < 0;
745}
746
747SampleWindow::SampleWindow(void* hwnd, int argc, char** argv, DeviceManager* devManager)
748    : INHERITED(hwnd)
749    , fDevManager(NULL) {
750
751    fCurrIndex = -1;
752
753    this->registerPictFileSamples(argv, argc);
754    this->registerPictFileSample(argv, argc);
755#ifdef SAMPLE_PDF_FILE_VIEWER
756    this->registerPdfFileViewerSamples(argv, argc);
757#endif  // SAMPLE_PDF_FILE_VIEWER
758    SkGMRegistyToSampleRegistry();
759    {
760        const SkViewRegister* reg = SkViewRegister::Head();
761        while (reg) {
762            *fSamples.append() = reg->factory();
763            reg = reg->next();
764        }
765    }
766
767    bool sort = false;
768    for (int i = 0; i < argc; ++i) {
769        if (!strcmp(argv[i], "--sort")) {
770            sort = true;
771            break;
772        }
773    }
774
775    if (sort) {
776        // Sort samples, so foo.skp and foo.pdf are consecutive and we can quickly spot where
777        // skp -> pdf -> png fails.
778        SkTQSort(fSamples.begin(), fSamples.end() ? fSamples.end() - 1 : NULL, compareSampleTitle);
779    }
780
781    const char* resourcePath = "resources";  // same default as tests
782    fMSAASampleCount = 0;
783
784    const char* const commandName = argv[0];
785    char* const* stop = argv + argc;
786    for (++argv; argv < stop; ++argv) {
787        if (!strcmp(*argv, "-i") || !strcmp(*argv, "--resourcePath")) {
788            argv++;
789            if (argv < stop && **argv) {
790                resourcePath = *argv;
791            }
792        } else if (strcmp(*argv, "--slide") == 0) {
793            argv++;
794            if (argv < stop && **argv) {
795                fCurrIndex = findByTitle(*argv);
796                if (fCurrIndex < 0) {
797                    fprintf(stderr, "Unknown sample \"%s\"\n", *argv);
798                    listTitles();
799                }
800            }
801        } else if (strcmp(*argv, "--msaa") == 0) {
802            ++argv;
803            if (argv < stop && **argv) {
804                fMSAASampleCount = atoi(*argv);
805            }
806        } else if (strcmp(*argv, "--list") == 0) {
807            listTitles();
808        } else if (strcmp(*argv, "--pictureDir") == 0) {
809            ++argv;  // This case is dealt with in registerPictFileSamples().
810        } else if (strcmp(*argv, "--picture") == 0) {
811            ++argv;  // This case is dealt with in registerPictFileSample().
812        }
813        else {
814            usage(commandName);
815        }
816    }
817
818    if (fCurrIndex < 0) {
819        SkString title;
820        if (readTitleFromPrefs(&title)) {
821            fCurrIndex = findByTitle(title.c_str());
822        }
823    }
824
825    if (fCurrIndex < 0) {
826        fCurrIndex = 0;
827    }
828
829    gSampleWindow = this;
830
831#ifdef  PIPE_FILE
832    //Clear existing file or create file if it doesn't exist
833    FILE* f = fopen(FILE_PATH, "wb");
834    fclose(f);
835#endif
836
837    fDeviceType = kRaster_DeviceType;
838
839#if DEFAULT_TO_GPU
840    fDeviceType = kGPU_DeviceType;
841#endif
842#if SK_ANGLE && DEFAULT_TO_ANGLE
843    fDeviceType = kANGLE_DeviceType;
844#endif
845
846    fUseClip = false;
847    fNClip = false;
848    fAnimating = false;
849    fRotate = false;
850    fRotateAnimTime = 0;
851    fPerspAnim = false;
852    fPerspAnimTime = 0;
853    fRequestGrabImage = false;
854    fPipeState = SkOSMenu::kOffState;
855    fTilingMode = kNo_Tiling;
856    fMeasureFPS = false;
857    fLCDState = SkOSMenu::kMixedState;
858    fAAState = SkOSMenu::kMixedState;
859    fSubpixelState = SkOSMenu::kMixedState;
860    fHintingState = 0;
861    fFilterLevelIndex = 0;
862    fFlipAxis = 0;
863    fScrollTestX = fScrollTestY = 0;
864
865    fMouseX = fMouseY = 0;
866    fFatBitsScale = 8;
867    fTypeface = SkTypeface::CreateFromTypeface(NULL, SkTypeface::kBold);
868    fShowZoomer = false;
869
870    fZoomLevel = 0;
871    fZoomScale = SK_Scalar1;
872
873    fMagnify = false;
874
875    fSaveToPdf = false;
876    fPdfCanvas = NULL;
877
878    fTransitionNext = 6;
879    fTransitionPrev = 2;
880
881    int sinkID = this->getSinkID();
882    fAppMenu = new SkOSMenu;
883    fAppMenu->setTitle("Global Settings");
884    int itemID;
885
886    itemID =fAppMenu->appendList("Device Type", "Device Type", sinkID, 0,
887                                "Raster", "Picture", "OpenGL",
888#if SK_ANGLE
889                                "ANGLE",
890#endif
891                                NULL);
892    fAppMenu->assignKeyEquivalentToItem(itemID, 'd');
893    itemID = fAppMenu->appendTriState("AA", "AA", sinkID, fAAState);
894    fAppMenu->assignKeyEquivalentToItem(itemID, 'b');
895    itemID = fAppMenu->appendTriState("LCD", "LCD", sinkID, fLCDState);
896    fAppMenu->assignKeyEquivalentToItem(itemID, 'l');
897    itemID = fAppMenu->appendList("FilterLevel", "FilterLevel", sinkID, fFilterLevelIndex,
898                                  gFilterLevelStates[0].fName,
899                                  gFilterLevelStates[1].fName,
900                                  gFilterLevelStates[2].fName,
901                                  gFilterLevelStates[3].fName,
902                                  gFilterLevelStates[4].fName,
903                                  NULL);
904    fAppMenu->assignKeyEquivalentToItem(itemID, 'n');
905    itemID = fAppMenu->appendTriState("Subpixel", "Subpixel", sinkID, fSubpixelState);
906    fAppMenu->assignKeyEquivalentToItem(itemID, 's');
907    itemID = fAppMenu->appendList("Hinting", "Hinting", sinkID, fHintingState,
908                                  gHintingStates[0].name,
909                                  gHintingStates[1].name,
910                                  gHintingStates[2].name,
911                                  gHintingStates[3].name,
912                                  gHintingStates[4].name,
913                                  NULL);
914    fAppMenu->assignKeyEquivalentToItem(itemID, 'h');
915
916    fUsePipeMenuItemID = fAppMenu->appendTriState("Pipe", "Pipe" , sinkID,
917                                                  fPipeState);
918    fAppMenu->assignKeyEquivalentToItem(fUsePipeMenuItemID, 'P');
919
920    itemID =fAppMenu->appendList("Tiling", "Tiling", sinkID, fTilingMode,
921                                 gTilingInfo[kNo_Tiling].label,
922                                 gTilingInfo[kAbs_128x128_Tiling].label,
923                                 gTilingInfo[kAbs_256x256_Tiling].label,
924                                 gTilingInfo[kRel_4x4_Tiling].label,
925                                 gTilingInfo[kRel_1x16_Tiling].label,
926                                 gTilingInfo[kRel_16x1_Tiling].label,
927                                 NULL);
928    fAppMenu->assignKeyEquivalentToItem(itemID, 't');
929
930    itemID = fAppMenu->appendSwitch("Slide Show", "Slide Show" , sinkID, false);
931    fAppMenu->assignKeyEquivalentToItem(itemID, 'a');
932    itemID = fAppMenu->appendSwitch("Clip", "Clip" , sinkID, fUseClip);
933    fAppMenu->assignKeyEquivalentToItem(itemID, 'c');
934    itemID = fAppMenu->appendSwitch("Flip X", "Flip X" , sinkID, false);
935    fAppMenu->assignKeyEquivalentToItem(itemID, 'x');
936    itemID = fAppMenu->appendSwitch("Flip Y", "Flip Y" , sinkID, false);
937    fAppMenu->assignKeyEquivalentToItem(itemID, 'y');
938    itemID = fAppMenu->appendSwitch("Zoomer", "Zoomer" , sinkID, fShowZoomer);
939    fAppMenu->assignKeyEquivalentToItem(itemID, 'z');
940    itemID = fAppMenu->appendSwitch("Magnify", "Magnify" , sinkID, fMagnify);
941    fAppMenu->assignKeyEquivalentToItem(itemID, 'm');
942    itemID =fAppMenu->appendList("Transition-Next", "Transition-Next", sinkID,
943                                fTransitionNext, "Up", "Up and Right", "Right",
944                                "Down and Right", "Down", "Down and Left",
945                                "Left", "Up and Left", NULL);
946    fAppMenu->assignKeyEquivalentToItem(itemID, 'j');
947    itemID =fAppMenu->appendList("Transition-Prev", "Transition-Prev", sinkID,
948                                fTransitionPrev, "Up", "Up and Right", "Right",
949                                "Down and Right", "Down", "Down and Left",
950                                "Left", "Up and Left", NULL);
951    fAppMenu->assignKeyEquivalentToItem(itemID, 'k');
952    itemID = fAppMenu->appendAction("Save to PDF", sinkID);
953    fAppMenu->assignKeyEquivalentToItem(itemID, 'e');
954
955    this->addMenu(fAppMenu);
956    fSlideMenu = new SkOSMenu;
957    this->addMenu(fSlideMenu);
958
959    this->setColorType(kN32_SkColorType);
960    this->setVisibleP(true);
961    this->setClipToBounds(false);
962
963    skiagm::GM::SetResourcePath(resourcePath);
964
965    this->loadView((*fSamples[fCurrIndex])());
966
967    fPDFData = NULL;
968
969    if (NULL == devManager) {
970        fDevManager = new DefaultDeviceManager();
971    } else {
972        devManager->ref();
973        fDevManager = devManager;
974    }
975    fDevManager->setUpBackend(this, fMSAASampleCount);
976
977    // If another constructor set our dimensions, ensure that our
978    // onSizeChange gets called.
979    if (this->height() && this->width()) {
980        this->onSizeChange();
981    }
982
983    // can't call this synchronously, since it may require a subclass to
984    // to implement, or the caller may need us to have returned from the
985    // constructor first. Hence we post an event to ourselves.
986//    this->updateTitle();
987    post_event_to_sink(new SkEvent(gUpdateWindowTitleEvtName), this);
988}
989
990SampleWindow::~SampleWindow() {
991    delete fPdfCanvas;
992    fTypeface->unref();
993
994    SkSafeUnref(fDevManager);
995}
996
997static void make_filepath(SkString* path, const char* dir, const SkString& name) {
998    size_t len = strlen(dir);
999    path->set(dir);
1000    if (len > 0 && dir[len - 1] != '/') {
1001        path->append("/");
1002    }
1003    path->append(name);
1004}
1005
1006void SampleWindow::registerPictFileSample(char** argv, int argc) {
1007    const char* pict = NULL;
1008
1009    for (int i = 0; i < argc; ++i) {
1010        if (!strcmp(argv[i], "--picture")) {
1011            i += 1;
1012            if (i < argc) {
1013                pict = argv[i];
1014                break;
1015            }
1016        }
1017    }
1018    if (pict) {
1019        SkString path(pict);
1020        fCurrIndex = fSamples.count();
1021        *fSamples.append() = new PictFileFactory(path);
1022    }
1023}
1024
1025void SampleWindow::registerPictFileSamples(char** argv, int argc) {
1026    const char* pictDir = NULL;
1027
1028    for (int i = 0; i < argc; ++i) {
1029        if (!strcmp(argv[i], "--pictureDir")) {
1030            i += 1;
1031            if (i < argc) {
1032                pictDir = argv[i];
1033                break;
1034            }
1035        }
1036    }
1037    if (pictDir) {
1038        SkOSFile::Iter iter(pictDir, "skp");
1039        SkString filename;
1040        while (iter.next(&filename)) {
1041            SkString path;
1042            make_filepath(&path, pictDir, filename);
1043            *fSamples.append() = new PictFileFactory(path);
1044        }
1045    }
1046}
1047
1048#ifdef SAMPLE_PDF_FILE_VIEWER
1049void SampleWindow::registerPdfFileViewerSamples(char** argv, int argc) {
1050    const char* pdfDir = NULL;
1051
1052    for (int i = 0; i < argc; ++i) {
1053        if (!strcmp(argv[i], "--pdfDir")) {
1054            i += 1;
1055            if (i < argc) {
1056                pdfDir = argv[i];
1057                break;
1058            }
1059        }
1060    }
1061    if (pdfDir) {
1062        SkOSFile::Iter iter(pdfDir, "pdf");
1063        SkString filename;
1064        while (iter.next(&filename)) {
1065            SkString path;
1066            make_filepath(&path, pdfDir, filename);
1067            *fSamples.append() = new PdfFileViewerFactory(path);
1068        }
1069    }
1070}
1071#endif  // SAMPLE_PDF_FILE_VIEWER
1072
1073
1074int SampleWindow::findByTitle(const char title[]) {
1075    int i, count = fSamples.count();
1076    for (i = 0; i < count; i++) {
1077        if (getSampleTitle(i).equals(title)) {
1078            return i;
1079        }
1080    }
1081    return -1;
1082}
1083
1084void SampleWindow::listTitles() {
1085    int count = fSamples.count();
1086    SkDebugf("All Slides:\n");
1087    for (int i = 0; i < count; i++) {
1088        SkDebugf("    %s\n", getSampleTitle(i).c_str());
1089    }
1090}
1091
1092static SkBitmap capture_bitmap(SkCanvas* canvas) {
1093    SkBitmap bm;
1094    if (bm.allocPixels(canvas->imageInfo())) {
1095        canvas->readPixels(&bm, 0, 0);
1096    }
1097    return bm;
1098}
1099
1100static bool bitmap_diff(SkCanvas* canvas, const SkBitmap& orig,
1101                        SkBitmap* diff) {
1102    const SkBitmap& src = canvas->getDevice()->accessBitmap(false);
1103
1104    SkAutoLockPixels alp0(src);
1105    SkAutoLockPixels alp1(orig);
1106    for (int y = 0; y < src.height(); y++) {
1107        const void* srcP = src.getAddr(0, y);
1108        const void* origP = orig.getAddr(0, y);
1109        size_t bytes = src.width() * src.bytesPerPixel();
1110        if (memcmp(srcP, origP, bytes)) {
1111            SkDebugf("---------- difference on line %d\n", y);
1112            return true;
1113        }
1114    }
1115    return false;
1116}
1117
1118static void drawText(SkCanvas* canvas, SkString string, SkScalar left, SkScalar top, SkPaint& paint)
1119{
1120    SkColor desiredColor = paint.getColor();
1121    paint.setColor(SK_ColorWHITE);
1122    const char* c_str = string.c_str();
1123    size_t size = string.size();
1124    SkRect bounds;
1125    paint.measureText(c_str, size, &bounds);
1126    bounds.offset(left, top);
1127    SkScalar inset = SkIntToScalar(-2);
1128    bounds.inset(inset, inset);
1129    canvas->drawRect(bounds, paint);
1130    if (desiredColor != SK_ColorBLACK) {
1131        paint.setColor(SK_ColorBLACK);
1132        canvas->drawText(c_str, size, left + SK_Scalar1, top + SK_Scalar1, paint);
1133    }
1134    paint.setColor(desiredColor);
1135    canvas->drawText(c_str, size, left, top, paint);
1136}
1137
1138#define XCLIP_N  8
1139#define YCLIP_N  8
1140
1141void SampleWindow::draw(SkCanvas* canvas) {
1142    // update the animation time
1143    if (!gAnimTimePrev && !gAnimTime) {
1144        // first time make delta be 0
1145        gAnimTime = SkTime::GetMSecs();
1146        gAnimTimePrev = gAnimTime;
1147    } else {
1148        gAnimTimePrev = gAnimTime;
1149        gAnimTime = SkTime::GetMSecs();
1150    }
1151
1152    if (fGesture.isActive()) {
1153        this->updateMatrix();
1154    }
1155
1156    if (fMeasureFPS) {
1157        fMeasureFPS_Time = 0;
1158    }
1159
1160    if (fNClip) {
1161        this->INHERITED::draw(canvas);
1162        SkBitmap orig = capture_bitmap(canvas);
1163
1164        const SkScalar w = this->width();
1165        const SkScalar h = this->height();
1166        const SkScalar cw = w / XCLIP_N;
1167        const SkScalar ch = h / YCLIP_N;
1168        for (int y = 0; y < YCLIP_N; y++) {
1169            SkRect r;
1170            r.fTop = y * ch;
1171            r.fBottom = (y + 1) * ch;
1172            if (y == YCLIP_N - 1) {
1173                r.fBottom = h;
1174            }
1175            for (int x = 0; x < XCLIP_N; x++) {
1176                SkAutoCanvasRestore acr(canvas, true);
1177                r.fLeft = x * cw;
1178                r.fRight = (x + 1) * cw;
1179                if (x == XCLIP_N - 1) {
1180                    r.fRight = w;
1181                }
1182                canvas->clipRect(r);
1183                this->INHERITED::draw(canvas);
1184            }
1185        }
1186
1187        SkBitmap diff;
1188        if (bitmap_diff(canvas, orig, &diff)) {
1189        }
1190    } else {
1191        SkSize tile = this->tileSize();
1192
1193        for (SkScalar y = 0; y < height(); y += tile.height()) {
1194            for (SkScalar x = 0; x < width(); x += tile.width()) {
1195                SkAutoCanvasRestore acr(canvas, true);
1196                canvas->clipRect(SkRect::MakeXYWH(x, y,
1197                                                  tile.width(),
1198                                                  tile.height()));
1199                this->INHERITED::draw(canvas);
1200            }
1201        }
1202
1203        if (fTilingMode != kNo_Tiling) {
1204            SkPaint paint;
1205            paint.setColor(0x60FF00FF);
1206            paint.setStyle(SkPaint::kStroke_Style);
1207
1208            for (SkScalar y = 0; y < height(); y += tile.height()) {
1209                for (SkScalar x = 0; x < width(); x += tile.width()) {
1210                    canvas->drawRect(SkRect::MakeXYWH(x, y,
1211                                                      tile.width(),
1212                                                      tile.height()),
1213                                     paint);
1214                }
1215            }
1216        }
1217    }
1218    if (fShowZoomer && !fSaveToPdf) {
1219        showZoomer(canvas);
1220    }
1221    if (fMagnify && !fSaveToPdf) {
1222        magnify(canvas);
1223    }
1224
1225    if (fMeasureFPS && fMeasureFPS_Time) {
1226        this->updateTitle();
1227        this->postInvalDelay();
1228    }
1229
1230    // do this last
1231    fDevManager->publishCanvas(fDeviceType, canvas, this);
1232}
1233
1234static float clipW = 200;
1235static float clipH = 200;
1236void SampleWindow::magnify(SkCanvas* canvas) {
1237    SkRect r;
1238    int count = canvas->save();
1239
1240    SkMatrix m = canvas->getTotalMatrix();
1241    if (!m.invert(&m)) {
1242        return;
1243    }
1244    SkPoint offset, center;
1245    SkScalar mouseX = fMouseX * SK_Scalar1;
1246    SkScalar mouseY = fMouseY * SK_Scalar1;
1247    m.mapXY(mouseX - clipW/2, mouseY - clipH/2, &offset);
1248    m.mapXY(mouseX, mouseY, &center);
1249
1250    r.set(0, 0, clipW * m.getScaleX(), clipH * m.getScaleX());
1251    r.offset(offset.fX, offset.fY);
1252
1253    SkPaint paint;
1254    paint.setColor(0xFF66AAEE);
1255    paint.setStyle(SkPaint::kStroke_Style);
1256    paint.setStrokeWidth(10.f * m.getScaleX());
1257    //lense offset
1258    //canvas->translate(0, -250);
1259    canvas->drawRect(r, paint);
1260    canvas->clipRect(r);
1261
1262    m = canvas->getTotalMatrix();
1263    m.setTranslate(-center.fX, -center.fY);
1264    m.postScale(0.5f * fFatBitsScale, 0.5f * fFatBitsScale);
1265    m.postTranslate(center.fX, center.fY);
1266    canvas->concat(m);
1267
1268    this->INHERITED::draw(canvas);
1269
1270    canvas->restoreToCount(count);
1271}
1272
1273void SampleWindow::showZoomer(SkCanvas* canvas) {
1274        int count = canvas->save();
1275        canvas->resetMatrix();
1276        // Ensure the mouse position is on screen.
1277        int width = SkScalarRoundToInt(this->width());
1278        int height = SkScalarRoundToInt(this->height());
1279        if (fMouseX >= width) fMouseX = width - 1;
1280        else if (fMouseX < 0) fMouseX = 0;
1281        if (fMouseY >= height) fMouseY = height - 1;
1282        else if (fMouseY < 0) fMouseY = 0;
1283
1284        SkBitmap bitmap = capture_bitmap(canvas);
1285        bitmap.lockPixels();
1286
1287        // Find the size of the zoomed in view, forced to be odd, so the examined pixel is in the middle.
1288        int zoomedWidth = (width >> 1) | 1;
1289        int zoomedHeight = (height >> 1) | 1;
1290        SkIRect src;
1291        src.set(0, 0, zoomedWidth / fFatBitsScale, zoomedHeight / fFatBitsScale);
1292        src.offset(fMouseX - (src.width()>>1), fMouseY - (src.height()>>1));
1293        SkRect dest;
1294        dest.set(0, 0, SkIntToScalar(zoomedWidth), SkIntToScalar(zoomedHeight));
1295        dest.offset(SkIntToScalar(width - zoomedWidth), SkIntToScalar(height - zoomedHeight));
1296        SkPaint paint;
1297        // Clear the background behind our zoomed in view
1298        paint.setColor(SK_ColorWHITE);
1299        canvas->drawRect(dest, paint);
1300        canvas->drawBitmapRect(bitmap, &src, dest);
1301        paint.setColor(SK_ColorBLACK);
1302        paint.setStyle(SkPaint::kStroke_Style);
1303        // Draw a border around the pixel in the middle
1304        SkRect originalPixel;
1305        originalPixel.set(SkIntToScalar(fMouseX), SkIntToScalar(fMouseY), SkIntToScalar(fMouseX + 1), SkIntToScalar(fMouseY + 1));
1306        SkMatrix matrix;
1307        SkRect scalarSrc;
1308        scalarSrc.set(src);
1309        SkColor color = bitmap.getColor(fMouseX, fMouseY);
1310        if (matrix.setRectToRect(scalarSrc, dest, SkMatrix::kFill_ScaleToFit)) {
1311            SkRect pixel;
1312            matrix.mapRect(&pixel, originalPixel);
1313            // TODO Perhaps measure the values and make the outline white if it's "dark"
1314            if (color == SK_ColorBLACK) {
1315                paint.setColor(SK_ColorWHITE);
1316            }
1317            canvas->drawRect(pixel, paint);
1318        }
1319        paint.setColor(SK_ColorBLACK);
1320        // Draw a border around the destination rectangle
1321        canvas->drawRect(dest, paint);
1322        paint.setStyle(SkPaint::kStrokeAndFill_Style);
1323        // Identify the pixel and its color on screen
1324        paint.setTypeface(fTypeface);
1325        paint.setAntiAlias(true);
1326        SkScalar lineHeight = paint.getFontMetrics(NULL);
1327        SkString string;
1328        string.appendf("(%i, %i)", fMouseX, fMouseY);
1329        SkScalar left = dest.fLeft + SkIntToScalar(3);
1330        SkScalar i = SK_Scalar1;
1331        drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1332        // Alpha
1333        i += SK_Scalar1;
1334        string.reset();
1335        string.appendf("A: %X", SkColorGetA(color));
1336        drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1337        // Red
1338        i += SK_Scalar1;
1339        string.reset();
1340        string.appendf("R: %X", SkColorGetR(color));
1341        paint.setColor(SK_ColorRED);
1342        drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1343        // Green
1344        i += SK_Scalar1;
1345        string.reset();
1346        string.appendf("G: %X", SkColorGetG(color));
1347        paint.setColor(SK_ColorGREEN);
1348        drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1349        // Blue
1350        i += SK_Scalar1;
1351        string.reset();
1352        string.appendf("B: %X", SkColorGetB(color));
1353        paint.setColor(SK_ColorBLUE);
1354        drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1355        canvas->restoreToCount(count);
1356}
1357
1358void SampleWindow::onDraw(SkCanvas* canvas) {
1359}
1360
1361#include "SkColorPriv.h"
1362
1363void SampleWindow::saveToPdf()
1364{
1365    fSaveToPdf = true;
1366    this->inval(NULL);
1367}
1368
1369SkCanvas* SampleWindow::beforeChildren(SkCanvas* canvas) {
1370    if (fSaveToPdf) {
1371        const SkBitmap& bmp = canvas->getDevice()->accessBitmap(false);
1372        SkISize size = SkISize::Make(bmp.width(), bmp.height());
1373        SkPDFDevice* pdfDevice = new SkPDFDevice(size, size,
1374                canvas->getTotalMatrix());
1375        fPdfCanvas = new SkCanvas(pdfDevice);
1376        pdfDevice->unref();
1377        canvas = fPdfCanvas;
1378    } else if (kPicture_DeviceType == fDeviceType) {
1379        canvas = fRecorder.beginRecording(9999, 9999, NULL, 0);
1380    } else {
1381#if SK_SUPPORT_GPU
1382        if (kNullGPU_DeviceType != fDeviceType)
1383#endif
1384        {
1385            canvas = this->INHERITED::beforeChildren(canvas);
1386        }
1387    }
1388
1389    if (fUseClip) {
1390        canvas->drawColor(0xFFFF88FF);
1391        canvas->clipPath(fClipPath, SkRegion::kIntersect_Op, true);
1392    }
1393
1394    return canvas;
1395}
1396
1397static void paint_rgn(const SkBitmap& bm, const SkIRect& r,
1398                      const SkRegion& rgn) {
1399    SkCanvas    canvas(bm);
1400    SkRegion    inval(rgn);
1401
1402    inval.translate(r.fLeft, r.fTop);
1403    canvas.clipRegion(inval);
1404    canvas.drawColor(0xFFFF8080);
1405}
1406#include "SkData.h"
1407void SampleWindow::afterChildren(SkCanvas* orig) {
1408    if (fSaveToPdf) {
1409        fSaveToPdf = false;
1410        if (fShowZoomer) {
1411            showZoomer(fPdfCanvas);
1412        }
1413        SkString name;
1414        name.printf("%s.pdf", this->getTitle());
1415        SkPDFDocument doc;
1416        SkPDFDevice* device = static_cast<SkPDFDevice*>(fPdfCanvas->getDevice());
1417        doc.appendPage(device);
1418#ifdef SK_BUILD_FOR_ANDROID
1419        name.prepend("/sdcard/");
1420#endif
1421
1422#ifdef SK_BUILD_FOR_IOS
1423        SkDynamicMemoryWStream mstream;
1424        doc.emitPDF(&mstream);
1425        fPDFData = mstream.copyToData();
1426#endif
1427        SkFILEWStream stream(name.c_str());
1428        if (stream.isValid()) {
1429            doc.emitPDF(&stream);
1430            const char* desc = "File saved from Skia SampleApp";
1431            this->onPDFSaved(this->getTitle(), desc, name.c_str());
1432        }
1433
1434        delete fPdfCanvas;
1435        fPdfCanvas = NULL;
1436
1437        // We took over the draw calls in order to create the PDF, so we need
1438        // to redraw.
1439        this->inval(NULL);
1440        return;
1441    }
1442
1443    if (fRequestGrabImage) {
1444        fRequestGrabImage = false;
1445
1446        SkBaseDevice* device = orig->getDevice();
1447        SkBitmap bmp;
1448        if (device->accessBitmap(false).copyTo(&bmp, kN32_SkColorType)) {
1449            static int gSampleGrabCounter;
1450            SkString name;
1451            name.printf("sample_grab_%d.png", gSampleGrabCounter++);
1452            SkImageEncoder::EncodeFile(name.c_str(), bmp,
1453                                       SkImageEncoder::kPNG_Type, 100);
1454        }
1455    }
1456
1457    if (kPicture_DeviceType == fDeviceType) {
1458        SkAutoTUnref<SkPicture> picture(fRecorder.endRecording());
1459
1460        if (true) {
1461            SkPicture* pict = new SkPicture(*picture);
1462            this->installDrawFilter(orig);
1463            orig->drawPicture(*pict);
1464            pict->unref();
1465        } else if (true) {
1466            SkDynamicMemoryWStream ostream;
1467            picture->serialize(&ostream);
1468
1469            SkAutoDataUnref data(ostream.copyToData());
1470            SkMemoryStream istream(data->data(), data->size());
1471            SkAutoTUnref<SkPicture> pict(SkPicture::CreateFromStream(&istream));
1472            if (pict.get() != NULL) {
1473                orig->drawPicture(*pict.get());
1474            }
1475        } else {
1476            picture->draw(orig);
1477        }
1478    }
1479
1480    // Do this after presentGL and other finishing, rather than in afterChild
1481    if (fMeasureFPS && fMeasureFPS_StartTime) {
1482        fMeasureFPS_Time += SkTime::GetMSecs() - fMeasureFPS_StartTime;
1483    }
1484
1485    //    if ((fScrollTestX | fScrollTestY) != 0)
1486    if (false) {
1487        const SkBitmap& bm = orig->getDevice()->accessBitmap(true);
1488        int dx = fScrollTestX * 7;
1489        int dy = fScrollTestY * 7;
1490        SkIRect r;
1491        SkRegion inval;
1492
1493        r.set(50, 50, 50+100, 50+100);
1494        bm.scrollRect(&r, dx, dy, &inval);
1495        paint_rgn(bm, r, inval);
1496    }
1497}
1498
1499void SampleWindow::beforeChild(SkView* child, SkCanvas* canvas) {
1500    if (fRotate) {
1501        fRotateAnimTime += SampleCode::GetAnimSecondsDelta();
1502
1503        SkScalar cx = this->width() / 2;
1504        SkScalar cy = this->height() / 2;
1505        canvas->translate(cx, cy);
1506        canvas->rotate(fRotateAnimTime * 10);
1507        canvas->translate(-cx, -cy);
1508    }
1509
1510    if (fPerspAnim) {
1511        fPerspAnimTime += SampleCode::GetAnimSecondsDelta();
1512
1513        static const SkScalar gAnimPeriod = 10 * SK_Scalar1;
1514        static const SkScalar gAnimMag = SK_Scalar1 / 1000;
1515        SkScalar t = SkScalarMod(fPerspAnimTime, gAnimPeriod);
1516        if (SkScalarFloorToInt(SkScalarDiv(fPerspAnimTime, gAnimPeriod)) & 0x1) {
1517            t = gAnimPeriod - t;
1518        }
1519        t = 2 * t - gAnimPeriod;
1520        t = SkScalarMul(SkScalarDiv(t, gAnimPeriod), gAnimMag);
1521        SkMatrix m;
1522        m.reset();
1523        m.setPerspY(t);
1524        canvas->concat(m);
1525    }
1526
1527    this->installDrawFilter(canvas);
1528
1529    if (fMeasureFPS) {
1530        if (SampleView::SetRepeatDraw(child, FPS_REPEAT_COUNT)) {
1531            fMeasureFPS_StartTime = SkTime::GetMSecs();
1532        }
1533    } else {
1534        (void)SampleView::SetRepeatDraw(child, 1);
1535    }
1536    if (fPerspAnim || fRotate) {
1537        this->inval(NULL);
1538    }
1539}
1540
1541void SampleWindow::afterChild(SkView* child, SkCanvas* canvas) {
1542    canvas->setDrawFilter(NULL);
1543}
1544
1545static SkColorType gColorTypeCycle[] = {
1546    kUnknown_SkColorType,           // none -> none
1547    kUnknown_SkColorType,           // a8 -> none
1548    kARGB_4444_SkColorType,         // 565 -> 4444
1549    kN32_SkColorType,               // 4444 -> 8888
1550    kRGB_565_SkColorType,           // 8888 -> 565
1551    kRGB_565_SkColorType,           // 8888 -> 565
1552    kUnknown_SkColorType,           // index8 -> none
1553};
1554
1555static SkColorType cycle_colortypes(SkColorType c) {
1556    return gColorTypeCycle[c];
1557}
1558
1559void SampleWindow::changeZoomLevel(float delta) {
1560    fZoomLevel += delta;
1561    if (fZoomLevel > 0) {
1562        fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL);
1563        fZoomScale = fZoomLevel + SK_Scalar1;
1564    } else if (fZoomLevel < 0) {
1565        fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL);
1566        fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel);
1567    } else {
1568        fZoomScale = SK_Scalar1;
1569    }
1570    this->updateMatrix();
1571}
1572
1573void SampleWindow::updateMatrix(){
1574    SkMatrix m;
1575    m.reset();
1576    if (fZoomLevel) {
1577        SkPoint center;
1578        //m = this->getLocalMatrix();//.invert(&m);
1579        m.mapXY(fZoomCenterX, fZoomCenterY, &center);
1580        SkScalar cx = center.fX;
1581        SkScalar cy = center.fY;
1582
1583        m.setTranslate(-cx, -cy);
1584        m.postScale(fZoomScale, fZoomScale);
1585        m.postTranslate(cx, cy);
1586    }
1587
1588    if (fFlipAxis) {
1589        m.preTranslate(fZoomCenterX, fZoomCenterY);
1590        if (fFlipAxis & kFlipAxis_X) {
1591            m.preScale(-SK_Scalar1, SK_Scalar1);
1592        }
1593        if (fFlipAxis & kFlipAxis_Y) {
1594            m.preScale(SK_Scalar1, -SK_Scalar1);
1595        }
1596        m.preTranslate(-fZoomCenterX, -fZoomCenterY);
1597        //canvas->concat(m);
1598    }
1599    // Apply any gesture matrix
1600    m.preConcat(fGesture.localM());
1601    m.preConcat(fGesture.globalM());
1602
1603    this->setLocalMatrix(m);
1604
1605    this->updateTitle();
1606    this->inval(NULL);
1607}
1608bool SampleWindow::previousSample() {
1609    fCurrIndex = (fCurrIndex - 1 + fSamples.count()) % fSamples.count();
1610    this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(),
1611                                     fTransitionPrev));
1612    return true;
1613}
1614
1615bool SampleWindow::nextSample() {
1616    fCurrIndex = (fCurrIndex + 1) % fSamples.count();
1617    this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(),
1618                                     fTransitionNext));
1619    return true;
1620}
1621
1622bool SampleWindow::goToSample(int i) {
1623    fCurrIndex = (i) % fSamples.count();
1624    this->loadView(create_transition(curr_view(this),(*fSamples[fCurrIndex])(), 6));
1625    return true;
1626}
1627
1628SkString SampleWindow::getSampleTitle(int i) {
1629    return ::getSampleTitle(fSamples[i]);
1630}
1631
1632int SampleWindow::sampleCount() {
1633    return fSamples.count();
1634}
1635
1636void SampleWindow::showOverview() {
1637    this->loadView(create_transition(curr_view(this),
1638                                     create_overview(fSamples.count(), fSamples.begin()),
1639                                     4));
1640}
1641
1642void SampleWindow::installDrawFilter(SkCanvas* canvas) {
1643    canvas->setDrawFilter(new FlagsDrawFilter(fLCDState, fAAState, fSubpixelState,
1644                                              fHintingState, fFilterLevelIndex))->unref();
1645}
1646
1647void SampleWindow::postAnimatingEvent() {
1648    if (fAnimating) {
1649        (new SkEvent(ANIMATING_EVENTTYPE, this->getSinkID()))->postDelay(ANIMATING_DELAY);
1650    }
1651}
1652
1653bool SampleWindow::onEvent(const SkEvent& evt) {
1654    if (evt.isType(gUpdateWindowTitleEvtName)) {
1655        this->updateTitle();
1656        return true;
1657    }
1658    if (evt.isType(ANIMATING_EVENTTYPE)) {
1659        if (fAnimating) {
1660            this->nextSample();
1661            this->postAnimatingEvent();
1662        }
1663        return true;
1664    }
1665    if (evt.isType("replace-transition-view")) {
1666        this->loadView((SkView*)SkEventSink::FindSink(evt.getFast32()));
1667        return true;
1668    }
1669    if (evt.isType("set-curr-index")) {
1670        this->goToSample(evt.getFast32());
1671        return true;
1672    }
1673    if (isInvalEvent(evt)) {
1674        this->inval(NULL);
1675        return true;
1676    }
1677    int selected = -1;
1678    if (SkOSMenu::FindListIndex(evt, "Device Type", &selected)) {
1679        this->setDeviceType((DeviceType)selected);
1680        return true;
1681    }
1682    if (SkOSMenu::FindTriState(evt, "Pipe", &fPipeState)) {
1683#ifdef PIPE_NET
1684        if (!fPipeState != SkOSMenu::kOnState)
1685            gServer.disconnectAll();
1686#endif
1687        (void)SampleView::SetUsePipe(curr_view(this), fPipeState);
1688        this->updateTitle();
1689        this->inval(NULL);
1690        return true;
1691    }
1692    if (SkOSMenu::FindSwitchState(evt, "Slide Show", NULL)) {
1693        this->toggleSlideshow();
1694        return true;
1695    }
1696    if (SkOSMenu::FindTriState(evt, "AA", &fAAState) ||
1697        SkOSMenu::FindTriState(evt, "LCD", &fLCDState) ||
1698        SkOSMenu::FindListIndex(evt, "FilterLevel", &fFilterLevelIndex) ||
1699        SkOSMenu::FindTriState(evt, "Subpixel", &fSubpixelState) ||
1700        SkOSMenu::FindListIndex(evt, "Hinting", &fHintingState) ||
1701        SkOSMenu::FindSwitchState(evt, "Clip", &fUseClip) ||
1702        SkOSMenu::FindSwitchState(evt, "Zoomer", &fShowZoomer) ||
1703        SkOSMenu::FindSwitchState(evt, "Magnify", &fMagnify) ||
1704        SkOSMenu::FindListIndex(evt, "Transition-Next", &fTransitionNext) ||
1705        SkOSMenu::FindListIndex(evt, "Transition-Prev", &fTransitionPrev)) {
1706        this->inval(NULL);
1707        this->updateTitle();
1708        return true;
1709    }
1710    if (SkOSMenu::FindListIndex(evt, "Tiling", &fTilingMode)) {
1711        if (SampleView::IsSampleView(curr_view(this))) {
1712            ((SampleView*)curr_view(this))->onTileSizeChanged(this->tileSize());
1713        }
1714        this->inval(NULL);
1715        this->updateTitle();
1716        return true;
1717    }
1718    if (SkOSMenu::FindSwitchState(evt, "Flip X", NULL)) {
1719        fFlipAxis ^= kFlipAxis_X;
1720        this->updateMatrix();
1721        return true;
1722    }
1723    if (SkOSMenu::FindSwitchState(evt, "Flip Y", NULL)) {
1724        fFlipAxis ^= kFlipAxis_Y;
1725        this->updateMatrix();
1726        return true;
1727    }
1728    if (SkOSMenu::FindAction(evt,"Save to PDF")) {
1729        this->saveToPdf();
1730        return true;
1731    }
1732    return this->INHERITED::onEvent(evt);
1733}
1734
1735bool SampleWindow::onQuery(SkEvent* query) {
1736    if (query->isType("get-slide-count")) {
1737        query->setFast32(fSamples.count());
1738        return true;
1739    }
1740    if (query->isType("get-slide-title")) {
1741        SkView* view = (*fSamples[query->getFast32()])();
1742        SkEvent evt(gTitleEvtName);
1743        if (view->doQuery(&evt)) {
1744            query->setString("title", evt.findString(gTitleEvtName));
1745        }
1746        SkSafeUnref(view);
1747        return true;
1748    }
1749    if (query->isType("use-fast-text")) {
1750        SkEvent evt(gFastTextEvtName);
1751        return curr_view(this)->doQuery(&evt);
1752    }
1753    if (query->isType("ignore-window-bitmap")) {
1754        query->setFast32(this->getGrContext() != NULL);
1755        return true;
1756    }
1757    return this->INHERITED::onQuery(query);
1758}
1759
1760#if 0 // UNUSED
1761static void cleanup_for_filename(SkString* name) {
1762    char* str = name->writable_str();
1763    for (size_t i = 0; i < name->size(); i++) {
1764        switch (str[i]) {
1765            case ':': str[i] = '-'; break;
1766            case '/': str[i] = '-'; break;
1767            case ' ': str[i] = '_'; break;
1768            default: break;
1769        }
1770    }
1771}
1772#endif
1773
1774bool SampleWindow::onHandleChar(SkUnichar uni) {
1775    {
1776        SkView* view = curr_view(this);
1777        if (view) {
1778            SkEvent evt(gCharEvtName);
1779            evt.setFast32(uni);
1780            if (view->doQuery(&evt)) {
1781                return true;
1782            }
1783        }
1784    }
1785
1786    int dx = 0xFF;
1787    int dy = 0xFF;
1788
1789    switch (uni) {
1790        case '5': dx =  0; dy =  0; break;
1791        case '8': dx =  0; dy = -1; break;
1792        case '6': dx =  1; dy =  0; break;
1793        case '2': dx =  0; dy =  1; break;
1794        case '4': dx = -1; dy =  0; break;
1795        case '7': dx = -1; dy = -1; break;
1796        case '9': dx =  1; dy = -1; break;
1797        case '3': dx =  1; dy =  1; break;
1798        case '1': dx = -1; dy =  1; break;
1799
1800        default:
1801            break;
1802    }
1803
1804    if (0xFF != dx && 0xFF != dy) {
1805        if ((dx | dy) == 0) {
1806            fScrollTestX = fScrollTestY = 0;
1807        } else {
1808            fScrollTestX += dx;
1809            fScrollTestY += dy;
1810        }
1811        this->inval(NULL);
1812        return true;
1813    }
1814
1815    switch (uni) {
1816        case 'B':
1817            post_event_to_sink(SkNEW_ARGS(SkEvent, ("PictFileView::toggleBBox")), curr_view(this));
1818            // Cannot call updateTitle() synchronously, because the toggleBBox event is still in
1819            // the queue.
1820            post_event_to_sink(SkNEW_ARGS(SkEvent, (gUpdateWindowTitleEvtName)), this);
1821            this->inval(NULL);
1822            break;
1823        case 'f':
1824            // only
1825            toggleFPS();
1826            break;
1827        case 'g':
1828            fRequestGrabImage = true;
1829            this->inval(NULL);
1830            break;
1831        case 'G':
1832            gShowGMBounds = !gShowGMBounds;
1833            post_event_to_sink(GMSampleView::NewShowSizeEvt(gShowGMBounds),
1834                            curr_view(this));
1835            this->inval(NULL);
1836            break;
1837        case 'i':
1838            this->zoomIn();
1839            break;
1840        case 'o':
1841            this->zoomOut();
1842            break;
1843        case 'r':
1844            fRotate = !fRotate;
1845            fRotateAnimTime = 0;
1846            this->inval(NULL);
1847            this->updateTitle();
1848            return true;
1849        case 'k':
1850            fPerspAnim = !fPerspAnim;
1851            this->inval(NULL);
1852            this->updateTitle();
1853            return true;
1854#if SK_SUPPORT_GPU
1855        case '\\':
1856            this->setDeviceType(kNullGPU_DeviceType);
1857            this->inval(NULL);
1858            this->updateTitle();
1859            return true;
1860        case 'p':
1861            {
1862                GrContext* grContext = this->getGrContext();
1863                if (grContext) {
1864                    size_t cacheBytes = grContext->getGpuTextureCacheBytes();
1865                    grContext->freeGpuResources();
1866                    SkDebugf("Purged %d bytes from the GPU resource cache.\n",
1867                             cacheBytes);
1868                }
1869            }
1870            return true;
1871#endif
1872        default:
1873            break;
1874    }
1875
1876    if (fAppMenu->handleKeyEquivalent(uni)|| fSlideMenu->handleKeyEquivalent(uni)) {
1877        this->onUpdateMenu(fAppMenu);
1878        this->onUpdateMenu(fSlideMenu);
1879        return true;
1880    }
1881    return this->INHERITED::onHandleChar(uni);
1882}
1883
1884void SampleWindow::setDeviceType(DeviceType type) {
1885    if (type == fDeviceType)
1886        return;
1887
1888    fDevManager->tearDownBackend(this);
1889
1890    fDeviceType = type;
1891
1892    fDevManager->setUpBackend(this, fMSAASampleCount);
1893
1894    this->updateTitle();
1895    this->inval(NULL);
1896}
1897
1898void SampleWindow::toggleSlideshow() {
1899    fAnimating = !fAnimating;
1900    this->postAnimatingEvent();
1901    this->updateTitle();
1902}
1903
1904void SampleWindow::toggleRendering() {
1905    this->setDeviceType(cycle_devicetype(fDeviceType));
1906    this->updateTitle();
1907    this->inval(NULL);
1908}
1909
1910void SampleWindow::toggleFPS() {
1911    fMeasureFPS = !fMeasureFPS;
1912    this->updateTitle();
1913    this->inval(NULL);
1914}
1915
1916#include "SkDumpCanvas.h"
1917
1918bool SampleWindow::onHandleKey(SkKey key) {
1919    {
1920        SkView* view = curr_view(this);
1921        if (view) {
1922            SkEvent evt(gKeyEvtName);
1923            evt.setFast32(key);
1924            if (view->doQuery(&evt)) {
1925                return true;
1926            }
1927        }
1928    }
1929    switch (key) {
1930        case kRight_SkKey:
1931            if (this->nextSample()) {
1932                return true;
1933            }
1934            break;
1935        case kLeft_SkKey:
1936            if (this->previousSample()) {
1937                return true;
1938            }
1939            return true;
1940        case kUp_SkKey:
1941            if (USE_ARROWS_FOR_ZOOM) {
1942                this->changeZoomLevel(1.f / 32.f);
1943            } else {
1944                fNClip = !fNClip;
1945                this->inval(NULL);
1946                this->updateTitle();
1947            }
1948            return true;
1949        case kDown_SkKey:
1950            if (USE_ARROWS_FOR_ZOOM) {
1951                this->changeZoomLevel(-1.f / 32.f);
1952            } else {
1953                this->setColorType(cycle_colortypes(this->getBitmap().colorType()));
1954                this->updateTitle();
1955            }
1956            return true;
1957        case kOK_SkKey: {
1958            SkString title;
1959            if (curr_title(this, &title)) {
1960                writeTitleToPrefs(title.c_str());
1961            }
1962            return true;
1963        }
1964        case kBack_SkKey:
1965            this->showOverview();
1966            return true;
1967        default:
1968            break;
1969    }
1970    return this->INHERITED::onHandleKey(key);
1971}
1972
1973///////////////////////////////////////////////////////////////////////////////
1974
1975static const char gGestureClickType[] = "GestureClickType";
1976
1977bool SampleWindow::onDispatchClick(int x, int y, Click::State state,
1978        void* owner, unsigned modi) {
1979    if (Click::kMoved_State == state) {
1980        updatePointer(x, y);
1981    }
1982    int w = SkScalarRoundToInt(this->width());
1983    int h = SkScalarRoundToInt(this->height());
1984
1985    // check for the resize-box
1986    if (w - x < 16 && h - y < 16) {
1987        return false;   // let the OS handle the click
1988    }
1989    else if (fMagnify) {
1990        //it's only necessary to update the drawing if there's a click
1991        this->inval(NULL);
1992        return false; //prevent dragging while magnify is enabled
1993    } else {
1994        // capture control+option, and trigger debugger
1995        if ((modi & kControl_SkModifierKey) && (modi & kOption_SkModifierKey)) {
1996            if (Click::kDown_State == state) {
1997                SkEvent evt("debug-hit-test");
1998                evt.setS32("debug-hit-test-x", x);
1999                evt.setS32("debug-hit-test-y", y);
2000                curr_view(this)->doEvent(evt);
2001            }
2002            return true;
2003        } else {
2004            return this->INHERITED::onDispatchClick(x, y, state, owner, modi);
2005        }
2006    }
2007}
2008
2009class GestureClick : public SkView::Click {
2010public:
2011    GestureClick(SkView* target) : SkView::Click(target) {
2012        this->setType(gGestureClickType);
2013    }
2014
2015    static bool IsGesture(Click* click) {
2016        return click->isType(gGestureClickType);
2017    }
2018};
2019
2020SkView::Click* SampleWindow::onFindClickHandler(SkScalar x, SkScalar y,
2021                                                unsigned modi) {
2022    return new GestureClick(this);
2023}
2024
2025bool SampleWindow::onClick(Click* click) {
2026    if (GestureClick::IsGesture(click)) {
2027        float x = static_cast<float>(click->fICurr.fX);
2028        float y = static_cast<float>(click->fICurr.fY);
2029
2030        switch (click->fState) {
2031            case SkView::Click::kDown_State:
2032                fGesture.touchBegin(click->fOwner, x, y);
2033                break;
2034            case SkView::Click::kMoved_State:
2035                fGesture.touchMoved(click->fOwner, x, y);
2036                this->updateMatrix();
2037                break;
2038            case SkView::Click::kUp_State:
2039                fGesture.touchEnd(click->fOwner);
2040                this->updateMatrix();
2041                break;
2042        }
2043        return true;
2044    }
2045    return false;
2046}
2047
2048///////////////////////////////////////////////////////////////////////////////
2049
2050void SampleWindow::loadView(SkView* view) {
2051    SkView::F2BIter iter(this);
2052    SkView* prev = iter.next();
2053    if (prev) {
2054        prev->detachFromParent();
2055    }
2056
2057    view->setVisibleP(true);
2058    view->setClipToBounds(false);
2059    this->attachChildToFront(view)->unref();
2060    view->setSize(this->width(), this->height());
2061
2062    //repopulate the slide menu when a view is loaded
2063    fSlideMenu->reset();
2064
2065    (void)SampleView::SetUsePipe(view, fPipeState);
2066    if (SampleView::IsSampleView(view)) {
2067        SampleView* sampleView = (SampleView*)view;
2068        sampleView->requestMenu(fSlideMenu);
2069        sampleView->onTileSizeChanged(this->tileSize());
2070    }
2071    this->onUpdateMenu(fSlideMenu);
2072    this->updateTitle();
2073}
2074
2075static const char* gConfigNames[] = {
2076    "unknown config",
2077    "A8",
2078    "Index8",
2079    "565",
2080    "4444",
2081    "8888"
2082};
2083
2084static const char* configToString(SkBitmap::Config c) {
2085    return gConfigNames[c];
2086}
2087
2088static const char* gDeviceTypePrefix[] = {
2089    "raster: ",
2090    "picture: ",
2091#if SK_SUPPORT_GPU
2092    "opengl: ",
2093#if SK_ANGLE
2094    "angle: ",
2095#endif // SK_ANGLE
2096    "null-gl: "
2097#endif // SK_SUPPORT_GPU
2098};
2099SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gDeviceTypePrefix) == SampleWindow::kDeviceTypeCnt,
2100                  array_size_mismatch);
2101
2102static const char* trystate_str(SkOSMenu::TriState state,
2103                                const char trueStr[], const char falseStr[]) {
2104    if (SkOSMenu::kOnState == state) {
2105        return trueStr;
2106    } else if (SkOSMenu::kOffState == state) {
2107        return falseStr;
2108    }
2109    return NULL;
2110}
2111
2112void SampleWindow::updateTitle() {
2113    SkView* view = curr_view(this);
2114
2115    SkString title;
2116    if (!curr_title(this, &title)) {
2117        title.set("<unknown>");
2118    }
2119
2120    title.prepend(gDeviceTypePrefix[fDeviceType]);
2121
2122    title.prepend(" ");
2123    title.prepend(configToString(this->getBitmap().config()));
2124
2125    if (fTilingMode != kNo_Tiling) {
2126        title.prependf("<T: %s> ", gTilingInfo[fTilingMode].label);
2127    }
2128    if (fAnimating) {
2129        title.prepend("<A> ");
2130    }
2131    if (fRotate) {
2132        title.prepend("<R> ");
2133    }
2134    if (fNClip) {
2135        title.prepend("<C> ");
2136    }
2137    if (fPerspAnim) {
2138        title.prepend("<K> ");
2139    }
2140
2141    title.prepend(trystate_str(fLCDState, "LCD ", "lcd "));
2142    title.prepend(trystate_str(fAAState, "AA ", "aa "));
2143    title.prepend(gFilterLevelStates[fFilterLevelIndex].fLabel);
2144    title.prepend(trystate_str(fSubpixelState, "S ", "s "));
2145    title.prepend(fFlipAxis & kFlipAxis_X ? "X " : NULL);
2146    title.prepend(fFlipAxis & kFlipAxis_Y ? "Y " : NULL);
2147    title.prepend(gHintingStates[fHintingState].label);
2148
2149    if (fZoomLevel) {
2150        title.prependf("{%.2f} ", SkScalarToFloat(fZoomLevel));
2151    }
2152
2153    if (fMeasureFPS) {
2154        title.appendf(" %8.3f ms", fMeasureFPS_Time / (float)FPS_REPEAT_COUNT);
2155    }
2156    if (SampleView::IsSampleView(view)) {
2157        switch (fPipeState) {
2158            case SkOSMenu::kOnState:
2159                title.prepend("<Pipe> ");
2160                break;
2161            case SkOSMenu::kMixedState:
2162                title.prepend("<Tiled Pipe> ");
2163                break;
2164
2165            default:
2166                break;
2167        }
2168        title.prepend("! ");
2169    }
2170
2171#if SK_SUPPORT_GPU
2172    if (IsGpuDeviceType(fDeviceType) &&
2173        NULL != fDevManager &&
2174        fDevManager->getGrRenderTarget() &&
2175        fDevManager->getGrRenderTarget()->numSamples() > 0) {
2176        title.appendf(" [MSAA: %d]",
2177                       fDevManager->getGrRenderTarget()->numSamples());
2178    }
2179#endif
2180
2181    this->setTitle(title.c_str());
2182}
2183
2184void SampleWindow::onSizeChange() {
2185    this->INHERITED::onSizeChange();
2186
2187    SkView::F2BIter iter(this);
2188    SkView* view = iter.next();
2189    view->setSize(this->width(), this->height());
2190
2191    // rebuild our clippath
2192    {
2193        const SkScalar W = this->width();
2194        const SkScalar H = this->height();
2195
2196        fClipPath.reset();
2197#if 0
2198        for (SkScalar y = SK_Scalar1; y < H; y += SkIntToScalar(32)) {
2199            SkRect r;
2200            r.set(SK_Scalar1, y, SkIntToScalar(30), y + SkIntToScalar(30));
2201            for (; r.fLeft < W; r.offset(SkIntToScalar(32), 0))
2202                fClipPath.addRect(r);
2203        }
2204#else
2205        SkRect r;
2206        r.set(0, 0, W, H);
2207        fClipPath.addRect(r, SkPath::kCCW_Direction);
2208        r.set(W/4, H/4, W*3/4, H*3/4);
2209        fClipPath.addRect(r, SkPath::kCW_Direction);
2210#endif
2211    }
2212
2213    fZoomCenterX = SkScalarHalf(this->width());
2214    fZoomCenterY = SkScalarHalf(this->height());
2215
2216#ifdef SK_BUILD_FOR_ANDROID
2217    // FIXME: The first draw after a size change does not work on Android, so
2218    // we post an invalidate.
2219    this->postInvalDelay();
2220#endif
2221    this->updateTitle();    // to refresh our config
2222    fDevManager->windowSizeChanged(this);
2223
2224    if (fTilingMode != kNo_Tiling && SampleView::IsSampleView(view)) {
2225        ((SampleView*)view)->onTileSizeChanged(this->tileSize());
2226    }
2227}
2228
2229///////////////////////////////////////////////////////////////////////////////
2230
2231static const char is_sample_view_tag[] = "sample-is-sample-view";
2232static const char repeat_count_tag[] = "sample-set-repeat-count";
2233static const char set_use_pipe_tag[] = "sample-set-use-pipe";
2234
2235bool SampleView::IsSampleView(SkView* view) {
2236    SkEvent evt(is_sample_view_tag);
2237    return view->doQuery(&evt);
2238}
2239
2240bool SampleView::SetRepeatDraw(SkView* view, int count) {
2241    SkEvent evt(repeat_count_tag);
2242    evt.setFast32(count);
2243    return view->doEvent(evt);
2244}
2245
2246bool SampleView::SetUsePipe(SkView* view, SkOSMenu::TriState state) {
2247    SkEvent evt;
2248    evt.setS32(set_use_pipe_tag, state);
2249    return view->doEvent(evt);
2250}
2251
2252bool SampleView::onEvent(const SkEvent& evt) {
2253    if (evt.isType(repeat_count_tag)) {
2254        fRepeatCount = evt.getFast32();
2255        return true;
2256    }
2257
2258    int32_t pipeHolder;
2259    if (evt.findS32(set_use_pipe_tag, &pipeHolder)) {
2260        fPipeState = static_cast<SkOSMenu::TriState>(pipeHolder);
2261        return true;
2262    }
2263
2264    if (evt.isType("debug-hit-test")) {
2265        fDebugHitTest = true;
2266        evt.findS32("debug-hit-test-x", &fDebugHitTestLoc.fX);
2267        evt.findS32("debug-hit-test-y", &fDebugHitTestLoc.fY);
2268        this->inval(NULL);
2269        return true;
2270    }
2271
2272    return this->INHERITED::onEvent(evt);
2273}
2274
2275bool SampleView::onQuery(SkEvent* evt) {
2276    if (evt->isType(is_sample_view_tag)) {
2277        return true;
2278    }
2279    return this->INHERITED::onQuery(evt);
2280}
2281
2282
2283class SimplePC : public SkGPipeController {
2284public:
2285    SimplePC(SkCanvas* target);
2286    ~SimplePC();
2287
2288    virtual void* requestBlock(size_t minRequest, size_t* actual);
2289    virtual void notifyWritten(size_t bytes);
2290
2291private:
2292    SkGPipeReader   fReader;
2293    void*           fBlock;
2294    size_t          fBlockSize;
2295    size_t          fBytesWritten;
2296    int             fAtomsWritten;
2297    SkGPipeReader::Status   fStatus;
2298
2299    size_t        fTotalWritten;
2300};
2301
2302SimplePC::SimplePC(SkCanvas* target) : fReader(target) {
2303    fBlock = NULL;
2304    fBlockSize = fBytesWritten = 0;
2305    fStatus = SkGPipeReader::kDone_Status;
2306    fTotalWritten = 0;
2307    fAtomsWritten = 0;
2308    fReader.setBitmapDecoder(&SkImageDecoder::DecodeMemory);
2309}
2310
2311SimplePC::~SimplePC() {
2312//    SkASSERT(SkGPipeReader::kDone_Status == fStatus);
2313    if (fTotalWritten) {
2314        SkDebugf("--- %d bytes %d atoms, status %d\n", fTotalWritten,
2315                 fAtomsWritten, fStatus);
2316#ifdef  PIPE_FILE
2317        //File is open in append mode
2318        FILE* f = fopen(FILE_PATH, "ab");
2319        SkASSERT(f != NULL);
2320        fwrite((const char*)fBlock + fBytesWritten, 1, bytes, f);
2321        fclose(f);
2322#endif
2323#ifdef PIPE_NET
2324        if (fAtomsWritten > 1 && fTotalWritten > 4) { //ignore done
2325            gServer.acceptConnections();
2326            gServer.writePacket(fBlock, fTotalWritten);
2327        }
2328#endif
2329    }
2330    sk_free(fBlock);
2331}
2332
2333void* SimplePC::requestBlock(size_t minRequest, size_t* actual) {
2334    sk_free(fBlock);
2335
2336    fBlockSize = minRequest * 4;
2337    fBlock = sk_malloc_throw(fBlockSize);
2338    fBytesWritten = 0;
2339    *actual = fBlockSize;
2340    return fBlock;
2341}
2342
2343void SimplePC::notifyWritten(size_t bytes) {
2344    SkASSERT(fBytesWritten + bytes <= fBlockSize);
2345    fStatus = fReader.playback((const char*)fBlock + fBytesWritten, bytes);
2346    SkASSERT(SkGPipeReader::kError_Status != fStatus);
2347    fBytesWritten += bytes;
2348    fTotalWritten += bytes;
2349
2350    fAtomsWritten += 1;
2351}
2352
2353void SampleView::draw(SkCanvas* canvas) {
2354    if (SkOSMenu::kOffState == fPipeState) {
2355        this->INHERITED::draw(canvas);
2356    } else {
2357        SkGPipeWriter writer;
2358        SimplePC controller(canvas);
2359        TiledPipeController tc(canvas->getDevice()->accessBitmap(false),
2360                               &SkImageDecoder::DecodeMemory,
2361                               &canvas->getTotalMatrix());
2362        SkGPipeController* pc;
2363        if (SkOSMenu::kMixedState == fPipeState) {
2364            pc = &tc;
2365        } else {
2366            pc = &controller;
2367        }
2368        uint32_t flags = SkGPipeWriter::kCrossProcess_Flag;
2369
2370        canvas = writer.startRecording(pc, flags);
2371        //Must draw before controller goes out of scope and sends data
2372        this->INHERITED::draw(canvas);
2373        //explicitly end recording to ensure writer is flushed before the memory
2374        //is freed in the deconstructor of the controller
2375        writer.endRecording();
2376    }
2377}
2378
2379#include "SkBounder.h"
2380
2381class DebugHitTestBounder : public SkBounder {
2382public:
2383    DebugHitTestBounder(int x, int y) {
2384        fLoc.set(x, y);
2385    }
2386
2387    virtual bool onIRect(const SkIRect& bounds) SK_OVERRIDE {
2388        if (bounds.contains(fLoc.x(), fLoc.y())) {
2389            //
2390            // Set a break-point here to see what was being drawn under
2391            // the click point (just needed a line of code to stop the debugger)
2392            //
2393            bounds.centerX();
2394        }
2395        return true;
2396    }
2397
2398private:
2399    SkIPoint fLoc;
2400    typedef SkBounder INHERITED;
2401};
2402
2403void SampleView::onDraw(SkCanvas* canvas) {
2404    this->onDrawBackground(canvas);
2405
2406    DebugHitTestBounder bounder(fDebugHitTestLoc.x(), fDebugHitTestLoc.y());
2407    if (fDebugHitTest) {
2408        canvas->setBounder(&bounder);
2409    }
2410
2411    for (int i = 0; i < fRepeatCount; i++) {
2412        SkAutoCanvasRestore acr(canvas, true);
2413        this->onDrawContent(canvas);
2414    }
2415
2416    fDebugHitTest = false;
2417    canvas->setBounder(NULL);
2418}
2419
2420void SampleView::onDrawBackground(SkCanvas* canvas) {
2421    canvas->drawColor(fBGColor);
2422}
2423
2424///////////////////////////////////////////////////////////////////////////////
2425
2426template <typename T> void SkTBSort(T array[], int count) {
2427    for (int i = 1; i < count - 1; i++) {
2428        bool didSwap = false;
2429        for (int j = count - 1; j > i; --j) {
2430            if (array[j] < array[j-1]) {
2431                T tmp(array[j-1]);
2432                array[j-1] = array[j];
2433                array[j] = tmp;
2434                didSwap = true;
2435            }
2436        }
2437        if (!didSwap) {
2438            break;
2439        }
2440    }
2441
2442    for (int k = 0; k < count - 1; k++) {
2443        SkASSERT(!(array[k+1] < array[k]));
2444    }
2445}
2446
2447#include "SkRandom.h"
2448
2449static void rand_rect(SkIRect* rect, SkRandom& rand) {
2450    int bits = 8;
2451    int shift = 32 - bits;
2452    rect->set(rand.nextU() >> shift, rand.nextU() >> shift,
2453              rand.nextU() >> shift, rand.nextU() >> shift);
2454    rect->sort();
2455}
2456
2457static void dumpRect(const SkIRect& r) {
2458    SkDebugf(" { %d, %d, %d, %d },\n",
2459             r.fLeft, r.fTop,
2460             r.fRight, r.fBottom);
2461}
2462
2463static void test_rects(const SkIRect rect[], int count) {
2464    SkRegion rgn0, rgn1;
2465
2466    for (int i = 0; i < count; i++) {
2467        rgn0.op(rect[i], SkRegion::kUnion_Op);
2468     //   dumpRect(rect[i]);
2469    }
2470    rgn1.setRects(rect, count);
2471
2472    if (rgn0 != rgn1) {
2473        SkDebugf("\n");
2474        for (int i = 0; i < count; i++) {
2475            dumpRect(rect[i]);
2476        }
2477        SkDebugf("\n");
2478    }
2479}
2480
2481static void test() {
2482    size_t i;
2483
2484    const SkIRect r0[] = {
2485        { 0, 0, 1, 1 },
2486        { 2, 2, 3, 3 },
2487    };
2488    const SkIRect r1[] = {
2489        { 0, 0, 1, 3 },
2490        { 1, 1, 2, 2 },
2491        { 2, 0, 3, 3 },
2492    };
2493    const SkIRect r2[] = {
2494        { 0, 0, 1, 2 },
2495        { 2, 1, 3, 3 },
2496        { 4, 0, 5, 1 },
2497        { 6, 0, 7, 4 },
2498    };
2499
2500    static const struct {
2501        const SkIRect* fRects;
2502        int            fCount;
2503    } gRecs[] = {
2504        { r0, SK_ARRAY_COUNT(r0) },
2505        { r1, SK_ARRAY_COUNT(r1) },
2506        { r2, SK_ARRAY_COUNT(r2) },
2507    };
2508
2509    for (i = 0; i < SK_ARRAY_COUNT(gRecs); i++) {
2510        test_rects(gRecs[i].fRects, gRecs[i].fCount);
2511    }
2512
2513    SkRandom rand;
2514    for (i = 0; i < 10000; i++) {
2515        SkRegion rgn0, rgn1;
2516
2517        const int N = 8;
2518        SkIRect rect[N];
2519        for (int j = 0; j < N; j++) {
2520            rand_rect(&rect[j], rand);
2521        }
2522        test_rects(rect, N);
2523    }
2524}
2525
2526// FIXME: this should be in a header
2527SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv);
2528SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
2529    if (false) { // avoid bit rot, suppress warning
2530        test();
2531    }
2532    return new SampleWindow(hwnd, argc, argv, NULL);
2533}
2534
2535// FIXME: this should be in a header
2536void get_preferred_size(int* x, int* y, int* width, int* height);
2537void get_preferred_size(int* x, int* y, int* width, int* height) {
2538    *x = 10;
2539    *y = 50;
2540    *width = 640;
2541    *height = 480;
2542}
2543
2544#ifdef SK_BUILD_FOR_IOS
2545void save_args(int argc, char *argv[]) {
2546}
2547#endif
2548
2549// FIXME: this should be in a header
2550void application_init();
2551void application_init() {
2552//    setenv("ANDROID_ROOT", "../../../data", 0);
2553#ifdef SK_BUILD_FOR_MAC
2554    setenv("ANDROID_ROOT", "/android/device/data", 0);
2555#endif
2556    SkGraphics::Init();
2557    SkEvent::Init();
2558}
2559
2560// FIXME: this should be in a header
2561void application_term();
2562void application_term() {
2563    SkEvent::Term();
2564    SkGraphics::Term();
2565}
2566