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