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