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