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