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 "SkDeferredCanvas.h"
19 #include "SkDevice.h"
20 #include "SkDocument.h"
21 #include "SkGPipe.h"
22 #include "SkGraphics.h"
23 #include "SkImageEncoder.h"
24 #include "SkOSFile.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 "sk_tool_utils.h"
35
36 #if SK_SUPPORT_GPU
37 #include "gl/GrGLInterface.h"
38 #include "gl/GrGLUtil.h"
39 #include "GrRenderTarget.h"
40 #include "GrContext.h"
41 #include "SkGpuDevice.h"
42 #else
43 class GrContext;
44 #endif
45
46 extern SampleView* CreateSamplePictFileView(const char filename[]);
47
48 class PictFileFactory : public SkViewFactory {
49 SkString fFilename;
50 public:
PictFileFactory(const SkString & filename)51 PictFileFactory(const SkString& filename) : fFilename(filename) {}
operator ()() const52 SkView* operator() () const override {
53 return CreateSamplePictFileView(fFilename.c_str());
54 }
55 };
56
57 #ifdef SAMPLE_PDF_FILE_VIEWER
58 extern SampleView* CreateSamplePdfFileViewer(const char filename[]);
59
60 class PdfFileViewerFactory : public SkViewFactory {
61 SkString fFilename;
62 public:
PdfFileViewerFactory(const SkString & filename)63 PdfFileViewerFactory(const SkString& filename) : fFilename(filename) {}
operator ()() const64 SkView* operator() () const override {
65 return CreateSamplePdfFileViewer(fFilename.c_str());
66 }
67 };
68 #endif // SAMPLE_PDF_FILE_VIEWER
69
70 #define PIPE_FILEx
71 #ifdef PIPE_FILE
72 #define FILE_PATH "/path/to/drawing.data"
73 #endif
74
75 #define PIPE_NETx
76 #ifdef PIPE_NET
77 #include "SkSockets.h"
78 SkTCPServer gServer;
79 #endif
80
81 #if SK_ANGLE
82 //#define DEFAULT_TO_ANGLE 1
83 #else
84 #define DEFAULT_TO_GPU 0 // if 1 default rendering is on GPU
85 #endif
86
87 #define ANIMATING_EVENTTYPE "nextSample"
88 #define ANIMATING_DELAY 250
89
90 #ifdef SK_DEBUG
91 #define FPS_REPEAT_MULTIPLIER 1
92 #else
93 #define FPS_REPEAT_MULTIPLIER 10
94 #endif
95 #define FPS_REPEAT_COUNT (10 * FPS_REPEAT_MULTIPLIER)
96
97 static SampleWindow* gSampleWindow;
98
99 static bool gShowGMBounds;
100
post_event_to_sink(SkEvent * evt,SkEventSink * sink)101 static void post_event_to_sink(SkEvent* evt, SkEventSink* sink) {
102 evt->setTargetID(sink->getSinkID())->post();
103 }
104
105 static SkAnimTimer gAnimTimer;
106
107 ///////////////////////////////////////////////////////////////////////////////
108
skip_until(const char * str,const char * skip)109 static const char* skip_until(const char* str, const char* skip) {
110 if (!str) {
111 return NULL;
112 }
113 return strstr(str, skip);
114 }
115
skip_past(const char * str,const char * skip)116 static const char* skip_past(const char* str, const char* skip) {
117 const char* found = skip_until(str, skip);
118 if (!found) {
119 return NULL;
120 }
121 return found + strlen(skip);
122 }
123
124 static const char* gPrefFileName = "sampleapp_prefs.txt";
125
readTitleFromPrefs(SkString * title)126 static bool readTitleFromPrefs(SkString* title) {
127 SkFILEStream stream(gPrefFileName);
128 if (!stream.isValid()) {
129 return false;
130 }
131
132 size_t len = stream.getLength();
133 SkString data(len);
134 stream.read(data.writable_str(), len);
135 const char* s = data.c_str();
136
137 s = skip_past(s, "curr-slide-title");
138 s = skip_past(s, "=");
139 s = skip_past(s, "\"");
140 const char* stop = skip_until(s, "\"");
141 if (stop > s) {
142 title->set(s, stop - s);
143 return true;
144 }
145 return false;
146 }
147
writeTitleToPrefs(const char * title)148 static void writeTitleToPrefs(const char* title) {
149 SkFILEWStream stream(gPrefFileName);
150 SkString data;
151 data.printf("curr-slide-title = \"%s\"\n", title);
152 stream.write(data.c_str(), data.size());
153 }
154
155 ///////////////////////////////////////////////////////////////////////////////
156
157 class SampleWindow::DefaultDeviceManager : public SampleWindow::DeviceManager {
158 public:
159
DefaultDeviceManager()160 DefaultDeviceManager() {
161 #if SK_SUPPORT_GPU
162 fCurContext = NULL;
163 fCurIntf = NULL;
164 fCurRenderTarget = NULL;
165 fMSAASampleCount = 0;
166 #endif
167 fBackend = kNone_BackEndType;
168 }
169
~DefaultDeviceManager()170 virtual ~DefaultDeviceManager() {
171 #if SK_SUPPORT_GPU
172 SkSafeUnref(fCurContext);
173 SkSafeUnref(fCurIntf);
174 SkSafeUnref(fCurRenderTarget);
175 #endif
176 }
177
setUpBackend(SampleWindow * win,int msaaSampleCount)178 virtual void setUpBackend(SampleWindow* win, int msaaSampleCount) {
179 SkASSERT(kNone_BackEndType == fBackend);
180
181 fBackend = kNone_BackEndType;
182
183 #if SK_SUPPORT_GPU
184 switch (win->getDeviceType()) {
185 case kRaster_DeviceType: // fallthrough
186 case kPicture_DeviceType: // fallthrough
187 case kDeferred_DeviceType: // 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: // fallthrough
214 case kPicture_DeviceType: // fallthrough
215 case kDeferred_DeviceType: // fallthrough
216 case kGPU_DeviceType:
217 // all these guys use the native interface
218 glInterface.reset(GrGLCreateNativeInterface());
219 break;
220 #if SK_ANGLE
221 case kANGLE_DeviceType:
222 glInterface.reset(GrGLCreateANGLEInterface());
223 break;
224 #endif // SK_ANGLE
225 default:
226 SkASSERT(false);
227 break;
228 }
229
230 // Currently SampleApp does not use NVPR. TODO: Provide an NVPR device type that is skipped
231 // when the driver doesn't support NVPR.
232 fCurIntf = GrGLInterfaceRemoveNVPR(glInterface.get());
233
234 SkASSERT(NULL == fCurContext);
235 fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf);
236
237 if (NULL == fCurContext || NULL == fCurIntf) {
238 // We need some context and interface to see results
239 SkSafeUnref(fCurContext);
240 SkSafeUnref(fCurIntf);
241 fCurContext = NULL;
242 fCurIntf = NULL;
243 SkDebugf("Failed to setup 3D");
244
245 win->detach();
246 }
247 #endif // SK_SUPPORT_GPU
248 // call windowSizeChanged to create the render target
249 this->windowSizeChanged(win);
250 }
251
tearDownBackend(SampleWindow * win)252 virtual void tearDownBackend(SampleWindow *win) {
253 #if SK_SUPPORT_GPU
254 if (fCurContext) {
255 // in case we have outstanding refs to this guy (lua?)
256 fCurContext->abandonContext();
257 fCurContext->unref();
258 fCurContext = NULL;
259 }
260
261 SkSafeUnref(fCurIntf);
262 fCurIntf = NULL;
263
264 SkSafeUnref(fCurRenderTarget);
265 fCurRenderTarget = NULL;
266 #endif
267 win->detach();
268 fBackend = kNone_BackEndType;
269 }
270
createSurface(SampleWindow::DeviceType dType,SampleWindow * win)271 virtual SkSurface* createSurface(SampleWindow::DeviceType dType,
272 SampleWindow* win) override {
273 #if SK_SUPPORT_GPU
274 if (IsGpuDeviceType(dType) && fCurContext) {
275 SkSurfaceProps props(win->getSurfaceProps());
276 return SkSurface::NewRenderTargetDirect(fCurRenderTarget, &props);
277 }
278 #endif
279 return NULL;
280 }
281
publishCanvas(SampleWindow::DeviceType dType,SkCanvas * canvas,SampleWindow * win)282 virtual void publishCanvas(SampleWindow::DeviceType dType,
283 SkCanvas* canvas,
284 SampleWindow* win) {
285 #if SK_SUPPORT_GPU
286 if (fCurContext) {
287 // in case we have queued drawing calls
288 fCurContext->flush();
289
290 if (!IsGpuDeviceType(dType)) {
291 // need to send the raster bits to the (gpu) window
292 const SkBitmap& bm = win->getBitmap();
293 fCurRenderTarget->writePixels(0, 0, bm.width(), bm.height(),
294 SkImageInfo2GrPixelConfig(bm.colorType(),
295 bm.alphaType(),
296 bm.profileType()),
297 bm.getPixels(),
298 bm.rowBytes(),
299 GrContext::kFlushWrites_PixelOp);
300 }
301 }
302 #endif
303
304 win->present();
305 }
306
windowSizeChanged(SampleWindow * win)307 virtual void windowSizeChanged(SampleWindow* win) {
308 #if SK_SUPPORT_GPU
309 if (fCurContext) {
310 AttachmentInfo attachmentInfo;
311 win->attach(fBackend, fMSAASampleCount, &attachmentInfo);
312 SkSafeUnref(fCurRenderTarget);
313 fCurRenderTarget = win->renderTarget(attachmentInfo, fCurIntf, fCurContext);
314 }
315 #endif
316 }
317
getGrContext()318 virtual GrContext* getGrContext() {
319 #if SK_SUPPORT_GPU
320 return fCurContext;
321 #else
322 return NULL;
323 #endif
324 }
325
getGrRenderTarget()326 GrRenderTarget* getGrRenderTarget() override {
327 #if SK_SUPPORT_GPU
328 return fCurRenderTarget;
329 #else
330 return NULL;
331 #endif
332 }
333
334 private:
335
336 #if SK_SUPPORT_GPU
337 GrContext* fCurContext;
338 const GrGLInterface* fCurIntf;
339 GrRenderTarget* fCurRenderTarget;
340 int fMSAASampleCount;
341 #endif
342
343 SkOSWindow::SkBackEndTypes fBackend;
344
345 typedef SampleWindow::DeviceManager INHERITED;
346 };
347
348 ///////////////
349 static const char view_inval_msg[] = "view-inval-msg";
350
postInvalDelay()351 void SampleWindow::postInvalDelay() {
352 (new SkEvent(view_inval_msg, this->getSinkID()))->postDelay(1);
353 }
354
isInvalEvent(const SkEvent & evt)355 static bool isInvalEvent(const SkEvent& evt) {
356 return evt.isType(view_inval_msg);
357 }
358 //////////////////
359
SkFuncViewFactory(SkViewCreateFunc func)360 SkFuncViewFactory::SkFuncViewFactory(SkViewCreateFunc func)
361 : fCreateFunc(func) {
362 }
363
operator ()() const364 SkView* SkFuncViewFactory::operator() () const {
365 return (*fCreateFunc)();
366 }
367
368 #include "GMSampleView.h"
369
SkGMSampleViewFactory(GMFactoryFunc func)370 SkGMSampleViewFactory::SkGMSampleViewFactory(GMFactoryFunc func)
371 : fFunc(func) {
372 }
373
operator ()() const374 SkView* SkGMSampleViewFactory::operator() () const {
375 skiagm::GM* gm = fFunc(NULL);
376 gm->setMode(skiagm::GM::kSample_Mode);
377 return new GMSampleView(gm);
378 }
379
380 SkViewRegister* SkViewRegister::gHead;
SkViewRegister(SkViewFactory * fact)381 SkViewRegister::SkViewRegister(SkViewFactory* fact) : fFact(fact) {
382 fFact->ref();
383 fChain = gHead;
384 gHead = this;
385 }
386
SkViewRegister(SkViewCreateFunc func)387 SkViewRegister::SkViewRegister(SkViewCreateFunc func) {
388 fFact = new SkFuncViewFactory(func);
389 fChain = gHead;
390 gHead = this;
391 }
392
SkViewRegister(GMFactoryFunc func)393 SkViewRegister::SkViewRegister(GMFactoryFunc func) {
394 fFact = new SkGMSampleViewFactory(func);
395 fChain = gHead;
396 gHead = this;
397 }
398
399 class AutoUnrefArray {
400 public:
AutoUnrefArray()401 AutoUnrefArray() {}
~AutoUnrefArray()402 ~AutoUnrefArray() {
403 int count = fObjs.count();
404 for (int i = 0; i < count; ++i) {
405 fObjs[i]->unref();
406 }
407 }
push_back()408 SkRefCnt*& push_back() { return *fObjs.append(); }
409
410 private:
411 SkTDArray<SkRefCnt*> fObjs;
412 };
413
414 // registers GMs as Samples
415 // This can't be performed during static initialization because it could be
416 // run before GMRegistry has been fully built.
SkGMRegistyToSampleRegistry()417 static void SkGMRegistyToSampleRegistry() {
418 static bool gOnce;
419 static AutoUnrefArray fRegisters;
420
421 if (!gOnce) {
422 const skiagm::GMRegistry* gmreg = skiagm::GMRegistry::Head();
423 while (gmreg) {
424 fRegisters.push_back() = new SkViewRegister(gmreg->factory());
425 gmreg = gmreg->next();
426 }
427 gOnce = true;
428 }
429 }
430
431 //////////////////////////////////////////////////////////////////////////////
432
433 enum FlipAxisEnum {
434 kFlipAxis_X = (1 << 0),
435 kFlipAxis_Y = (1 << 1)
436 };
437
438 #include "SkDrawFilter.h"
439
440 struct HintingState {
441 SkPaint::Hinting hinting;
442 const char* name;
443 const char* label;
444 };
445 static HintingState gHintingStates[] = {
446 {SkPaint::kNo_Hinting, "Mixed", NULL },
447 {SkPaint::kNo_Hinting, "None", "H0 " },
448 {SkPaint::kSlight_Hinting, "Slight", "Hs " },
449 {SkPaint::kNormal_Hinting, "Normal", "Hn " },
450 {SkPaint::kFull_Hinting, "Full", "Hf " },
451 };
452
453 struct FilterQualityState {
454 SkFilterQuality fQuality;
455 const char* fName;
456 const char* fLabel;
457 };
458 static FilterQualityState gFilterQualityStates[] = {
459 { kNone_SkFilterQuality, "Mixed", NULL },
460 { kNone_SkFilterQuality, "None", "F0 " },
461 { kLow_SkFilterQuality, "Low", "F1 " },
462 { kMedium_SkFilterQuality, "Medium", "F2 " },
463 { kHigh_SkFilterQuality, "High", "F3 " },
464 };
465
466 class FlagsDrawFilter : public SkDrawFilter {
467 public:
FlagsDrawFilter(SkOSMenu::TriState lcd,SkOSMenu::TriState aa,SkOSMenu::TriState subpixel,int hinting,int filterQuality)468 FlagsDrawFilter(SkOSMenu::TriState lcd, SkOSMenu::TriState aa,
469 SkOSMenu::TriState subpixel, int hinting, int filterQuality)
470 : fLCDState(lcd)
471 , fAAState(aa)
472 , fSubpixelState(subpixel)
473 , fHintingState(hinting)
474 , fFilterQualityIndex(filterQuality)
475 {
476 SkASSERT((unsigned)filterQuality < SK_ARRAY_COUNT(gFilterQualityStates));
477 }
478
filter(SkPaint * paint,Type t)479 virtual bool filter(SkPaint* paint, Type t) {
480 if (kText_Type == t && SkOSMenu::kMixedState != fLCDState) {
481 paint->setLCDRenderText(SkOSMenu::kOnState == fLCDState);
482 }
483 if (SkOSMenu::kMixedState != fAAState) {
484 paint->setAntiAlias(SkOSMenu::kOnState == fAAState);
485 }
486 if (0 != fFilterQualityIndex) {
487 paint->setFilterQuality(gFilterQualityStates[fFilterQualityIndex].fQuality);
488 }
489 if (SkOSMenu::kMixedState != fSubpixelState) {
490 paint->setSubpixelText(SkOSMenu::kOnState == fSubpixelState);
491 }
492 if (0 != fHintingState && fHintingState < (int)SK_ARRAY_COUNT(gHintingStates)) {
493 paint->setHinting(gHintingStates[fHintingState].hinting);
494 }
495 return true;
496 }
497
498 private:
499 SkOSMenu::TriState fLCDState;
500 SkOSMenu::TriState fAAState;
501 SkOSMenu::TriState fSubpixelState;
502 int fHintingState;
503 int fFilterQualityIndex;
504 };
505
506 //////////////////////////////////////////////////////////////////////////////
507
508 #define MAX_ZOOM_LEVEL 8
509 #define MIN_ZOOM_LEVEL -8
510
511 static const char gCharEvtName[] = "SampleCode_Char_Event";
512 static const char gKeyEvtName[] = "SampleCode_Key_Event";
513 static const char gTitleEvtName[] = "SampleCode_Title_Event";
514 static const char gPrefSizeEvtName[] = "SampleCode_PrefSize_Event";
515 static const char gFastTextEvtName[] = "SampleCode_FastText_Event";
516 static const char gUpdateWindowTitleEvtName[] = "SampleCode_UpdateWindowTitle";
517
CharQ(const SkEvent & evt,SkUnichar * outUni)518 bool SampleCode::CharQ(const SkEvent& evt, SkUnichar* outUni) {
519 if (evt.isType(gCharEvtName, sizeof(gCharEvtName) - 1)) {
520 if (outUni) {
521 *outUni = evt.getFast32();
522 }
523 return true;
524 }
525 return false;
526 }
527
KeyQ(const SkEvent & evt,SkKey * outKey)528 bool SampleCode::KeyQ(const SkEvent& evt, SkKey* outKey) {
529 if (evt.isType(gKeyEvtName, sizeof(gKeyEvtName) - 1)) {
530 if (outKey) {
531 *outKey = (SkKey)evt.getFast32();
532 }
533 return true;
534 }
535 return false;
536 }
537
TitleQ(const SkEvent & evt)538 bool SampleCode::TitleQ(const SkEvent& evt) {
539 return evt.isType(gTitleEvtName, sizeof(gTitleEvtName) - 1);
540 }
541
TitleR(SkEvent * evt,const char title[])542 void SampleCode::TitleR(SkEvent* evt, const char title[]) {
543 SkASSERT(evt && TitleQ(*evt));
544 evt->setString(gTitleEvtName, title);
545 }
546
RequestTitle(SkView * view,SkString * title)547 bool SampleCode::RequestTitle(SkView* view, SkString* title) {
548 SkEvent evt(gTitleEvtName);
549 if (view->doQuery(&evt)) {
550 title->set(evt.findString(gTitleEvtName));
551 return true;
552 }
553 return false;
554 }
555
PrefSizeQ(const SkEvent & evt)556 bool SampleCode::PrefSizeQ(const SkEvent& evt) {
557 return evt.isType(gPrefSizeEvtName, sizeof(gPrefSizeEvtName) - 1);
558 }
559
PrefSizeR(SkEvent * evt,SkScalar width,SkScalar height)560 void SampleCode::PrefSizeR(SkEvent* evt, SkScalar width, SkScalar height) {
561 SkASSERT(evt && PrefSizeQ(*evt));
562 SkScalar size[2];
563 size[0] = width;
564 size[1] = height;
565 evt->setScalars(gPrefSizeEvtName, 2, size);
566 }
567
FastTextQ(const SkEvent & evt)568 bool SampleCode::FastTextQ(const SkEvent& evt) {
569 return evt.isType(gFastTextEvtName, sizeof(gFastTextEvtName) - 1);
570 }
571
572 ///////////////////////////////////////////////////////////////////////////////
573
574 enum TilingMode {
575 kNo_Tiling,
576 kAbs_128x128_Tiling,
577 kAbs_256x256_Tiling,
578 kRel_4x4_Tiling,
579 kRel_1x16_Tiling,
580 kRel_16x1_Tiling,
581
582 kLast_TilingMode_Enum
583 };
584
585 struct TilingInfo {
586 const char* label;
587 SkScalar w, h;
588 };
589
590 static const struct TilingInfo gTilingInfo[] = {
591 { "No tiling", SK_Scalar1 , SK_Scalar1 }, // kNo_Tiling
592 { "128x128" , SkIntToScalar(128), SkIntToScalar(128) }, // kAbs_128x128_Tiling
593 { "256x256" , SkIntToScalar(256), SkIntToScalar(256) }, // kAbs_256x256_Tiling
594 { "1/4x1/4" , SK_Scalar1 / 4 , SK_Scalar1 / 4 }, // kRel_4x4_Tiling
595 { "1/1x1/16" , SK_Scalar1 , SK_Scalar1 / 16 }, // kRel_1x16_Tiling
596 { "1/16x1/1" , SK_Scalar1 / 16 , SK_Scalar1 }, // kRel_16x1_Tiling
597 };
598 SK_COMPILE_ASSERT((SK_ARRAY_COUNT(gTilingInfo) == kLast_TilingMode_Enum),
599 Incomplete_tiling_labels);
600
tileSize() const601 SkSize SampleWindow::tileSize() const {
602 SkASSERT((TilingMode)fTilingMode < kLast_TilingMode_Enum);
603 const struct TilingInfo* info = gTilingInfo + fTilingMode;
604 return SkSize::Make(info->w > SK_Scalar1 ? info->w : this->width() * info->w,
605 info->h > SK_Scalar1 ? info->h : this->height() * info->h);
606 }
607 //////////////////////////////////////////////////////////////////////////////
608
curr_view(SkWindow * wind)609 static SkView* curr_view(SkWindow* wind) {
610 SkView::F2BIter iter(wind);
611 return iter.next();
612 }
613
curr_title(SkWindow * wind,SkString * title)614 static bool curr_title(SkWindow* wind, SkString* title) {
615 SkView* view = curr_view(wind);
616 if (view) {
617 SkEvent evt(gTitleEvtName);
618 if (view->doQuery(&evt)) {
619 title->set(evt.findString(gTitleEvtName));
620 return true;
621 }
622 }
623 return false;
624 }
625
sendAnimatePulse()626 bool SampleWindow::sendAnimatePulse() {
627 SkView* view = curr_view(this);
628 if (SampleView::IsSampleView(view)) {
629 return ((SampleView*)view)->animate(gAnimTimer);
630 }
631 return false;
632 }
633
setZoomCenter(float x,float y)634 void SampleWindow::setZoomCenter(float x, float y)
635 {
636 fZoomCenterX = x;
637 fZoomCenterY = y;
638 }
639
zoomIn()640 bool SampleWindow::zoomIn()
641 {
642 // Arbitrarily decided
643 if (fFatBitsScale == 25) return false;
644 fFatBitsScale++;
645 this->inval(NULL);
646 return true;
647 }
648
zoomOut()649 bool SampleWindow::zoomOut()
650 {
651 if (fFatBitsScale == 1) return false;
652 fFatBitsScale--;
653 this->inval(NULL);
654 return true;
655 }
656
updatePointer(int x,int y)657 void SampleWindow::updatePointer(int x, int y)
658 {
659 fMouseX = x;
660 fMouseY = y;
661 if (fShowZoomer) {
662 this->inval(NULL);
663 }
664 }
665
cycle_devicetype(SampleWindow::DeviceType ct)666 static inline SampleWindow::DeviceType cycle_devicetype(SampleWindow::DeviceType ct) {
667 static const SampleWindow::DeviceType gCT[] = {
668 SampleWindow::kPicture_DeviceType,
669 #if SK_SUPPORT_GPU
670 SampleWindow::kGPU_DeviceType,
671 #if SK_ANGLE
672 SampleWindow::kANGLE_DeviceType,
673 #endif // SK_ANGLE
674 #endif // SK_SUPPORT_GPU
675 SampleWindow::kDeferred_DeviceType,
676 SampleWindow::kRaster_DeviceType,
677 };
678 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gCT) == SampleWindow::kDeviceTypeCnt, array_size_mismatch);
679 return gCT[ct];
680 }
681
getSampleTitle(const SkViewFactory * sampleFactory)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
compareSampleTitle(const SkViewFactory * first,const SkViewFactory * second)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
SampleWindow(void * hwnd,int argc,char ** argv,DeviceManager * devManager)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", "Deferred",
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
~SampleWindow()932 SampleWindow::~SampleWindow() {
933 SkSafeUnref(fTypeface);
934 SkSafeUnref(fDevManager);
935 }
936
937
findByTitle(const char title[])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
listTitles()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
capture_bitmap(SkCanvas * canvas)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
drawText(SkCanvas * canvas,SkString str,SkScalar left,SkScalar top,SkPaint & paint)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
draw(SkCanvas * canvas)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;
magnify(SkCanvas * canvas)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, ¢er);
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
showZoomer(SkCanvas * canvas)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
onDraw(SkCanvas * canvas)1174 void SampleWindow::onDraw(SkCanvas* canvas) {
1175 }
1176
1177 #include "SkColorPriv.h"
1178
saveToPdf()1179 void SampleWindow::saveToPdf()
1180 {
1181 fSaveToPdf = true;
1182 this->inval(NULL);
1183 }
1184
beforeChildren(SkCanvas * canvas)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 if (kDeferred_DeviceType == fDeviceType) {
1200 fDeferredSurface.reset(canvas->newSurface(canvas->imageInfo()));
1201 if (fDeferredSurface.get()) {
1202 fDeferredCanvas.reset(SkDeferredCanvas::Create(fDeferredSurface));
1203 canvas = fDeferredCanvas;
1204 }
1205 } else {
1206 canvas = this->INHERITED::beforeChildren(canvas);
1207 }
1208
1209 if (fUseClip) {
1210 canvas->drawColor(0xFFFF88FF);
1211 canvas->clipPath(fClipPath, SkRegion::kIntersect_Op, true);
1212 }
1213
1214 return canvas;
1215 }
1216 #include "SkMultiPictureDraw.h"
afterChildren(SkCanvas * orig)1217 void SampleWindow::afterChildren(SkCanvas* orig) {
1218 if (fSaveToPdf) {
1219 fSaveToPdf = false;
1220 fPDFDocument->endPage();
1221 fPDFDocument.reset(NULL);
1222 // We took over the draw calls in order to create the PDF, so we need
1223 // to redraw.
1224 this->inval(NULL);
1225 return;
1226 }
1227
1228 if (fRequestGrabImage) {
1229 fRequestGrabImage = false;
1230
1231 SkBitmap bmp = capture_bitmap(orig);
1232 if (!bmp.isNull()) {
1233 static int gSampleGrabCounter;
1234 SkString name;
1235 name.printf("sample_grab_%d.png", gSampleGrabCounter++);
1236 SkImageEncoder::EncodeFile(name.c_str(), bmp,
1237 SkImageEncoder::kPNG_Type, 100);
1238 }
1239 }
1240
1241 if (kPicture_DeviceType == fDeviceType) {
1242 SkAutoTUnref<const SkPicture> picture(fRecorder.endRecording());
1243
1244 if (true) {
1245 this->installDrawFilter(orig);
1246
1247 if (true) {
1248 SkImageInfo info;
1249 size_t rowBytes;
1250 void* addr = orig->accessTopLayerPixels(&info, &rowBytes);
1251 if (addr) {
1252 SkSurface* surfs[4];
1253 SkMultiPictureDraw md;
1254
1255 SkImageInfo n = SkImageInfo::Make(info.width()/2, info.height()/2,
1256 info.colorType(), info.alphaType());
1257 int index = 0;
1258 for (int y = 0; y < 2; ++y) {
1259 for (int x = 0; x < 2; ++x) {
1260 char* p = (char*)addr;
1261 p += y * n.height() * rowBytes;
1262 p += x * n.width() * sizeof(SkPMColor);
1263 surfs[index] = SkSurface::NewRasterDirect(n, p, rowBytes);
1264 SkCanvas* c = surfs[index]->getCanvas();
1265 c->translate(SkIntToScalar(-x * n.width()),
1266 SkIntToScalar(-y * n.height()));
1267 c->concat(orig->getTotalMatrix());
1268 md.add(c, picture, NULL, NULL);
1269 index++;
1270 }
1271 }
1272 md.draw();
1273 for (int i = 0; i < 4; ++i) {
1274 surfs[i]->unref();
1275 }
1276 }
1277 } else {
1278 orig->drawPicture(picture);
1279 }
1280 } else if (true) {
1281 SkDynamicMemoryWStream ostream;
1282 picture->serialize(&ostream);
1283
1284 SkAutoDataUnref data(ostream.copyToData());
1285 SkMemoryStream istream(data->data(), data->size());
1286 SkAutoTUnref<SkPicture> pict(SkPicture::CreateFromStream(&istream));
1287 if (pict.get() != NULL) {
1288 orig->drawPicture(pict.get());
1289 }
1290 } else {
1291 picture->playback(orig);
1292 }
1293 } else if (kDeferred_DeviceType == fDeviceType) {
1294 SkAutoTUnref<SkImage> image(fDeferredCanvas->newImageSnapshot());
1295 if (image) {
1296 orig->drawImage(image, 0, 0, NULL);
1297 }
1298 fDeferredCanvas.reset(NULL);
1299 fDeferredSurface.reset(NULL);
1300 }
1301
1302 // Do this after presentGL and other finishing, rather than in afterChild
1303 if (fMeasureFPS && fMeasureFPS_StartTime) {
1304 fMeasureFPS_Time += SkTime::GetMSecs() - fMeasureFPS_StartTime;
1305 }
1306 }
1307
beforeChild(SkView * child,SkCanvas * canvas)1308 void SampleWindow::beforeChild(SkView* child, SkCanvas* canvas) {
1309 if (fRotate) {
1310 SkScalar cx = this->width() / 2;
1311 SkScalar cy = this->height() / 2;
1312 canvas->translate(cx, cy);
1313 canvas->rotate(gAnimTimer.scaled(10));
1314 canvas->translate(-cx, -cy);
1315 }
1316
1317 if (fPerspAnim) {
1318 SkScalar secs = gAnimTimer.scaled(1);
1319
1320 static const SkScalar gAnimPeriod = 10 * SK_Scalar1;
1321 static const SkScalar gAnimMag = SK_Scalar1 / 1000;
1322 SkScalar t = SkScalarMod(secs, gAnimPeriod);
1323 if (SkScalarFloorToInt(secs / gAnimPeriod) & 0x1) {
1324 t = gAnimPeriod - t;
1325 }
1326 t = 2 * t - gAnimPeriod;
1327 t *= gAnimMag / gAnimPeriod;
1328 SkMatrix m;
1329 m.reset();
1330 #if 1
1331 m.setPerspY(t);
1332 #else
1333 m.setPerspY(SK_Scalar1 / 1000);
1334 m.setSkewX(8.0f / 25);
1335 m.dump();
1336 #endif
1337 canvas->concat(m);
1338 }
1339
1340 this->installDrawFilter(canvas);
1341
1342 if (fMeasureFPS) {
1343 if (SampleView::SetRepeatDraw(child, FPS_REPEAT_COUNT)) {
1344 fMeasureFPS_StartTime = SkTime::GetMSecs();
1345 }
1346 } else {
1347 (void)SampleView::SetRepeatDraw(child, 1);
1348 }
1349 if (fPerspAnim || fRotate) {
1350 this->inval(NULL);
1351 }
1352 }
1353
afterChild(SkView * child,SkCanvas * canvas)1354 void SampleWindow::afterChild(SkView* child, SkCanvas* canvas) {
1355 canvas->setDrawFilter(NULL);
1356 }
1357
changeZoomLevel(float delta)1358 void SampleWindow::changeZoomLevel(float delta) {
1359 fZoomLevel += delta;
1360 if (fZoomLevel > 0) {
1361 fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL);
1362 fZoomScale = fZoomLevel + SK_Scalar1;
1363 } else if (fZoomLevel < 0) {
1364 fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL);
1365 fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel);
1366 } else {
1367 fZoomScale = SK_Scalar1;
1368 }
1369 this->updateMatrix();
1370 }
1371
updateMatrix()1372 void SampleWindow::updateMatrix(){
1373 SkMatrix m;
1374 m.reset();
1375 if (fZoomLevel) {
1376 SkPoint center;
1377 //m = this->getLocalMatrix();//.invert(&m);
1378 m.mapXY(fZoomCenterX, fZoomCenterY, ¢er);
1379 SkScalar cx = center.fX;
1380 SkScalar cy = center.fY;
1381
1382 m.setTranslate(-cx, -cy);
1383 m.postScale(fZoomScale, fZoomScale);
1384 m.postTranslate(cx, cy);
1385 }
1386
1387 if (fFlipAxis) {
1388 m.preTranslate(fZoomCenterX, fZoomCenterY);
1389 if (fFlipAxis & kFlipAxis_X) {
1390 m.preScale(-SK_Scalar1, SK_Scalar1);
1391 }
1392 if (fFlipAxis & kFlipAxis_Y) {
1393 m.preScale(SK_Scalar1, -SK_Scalar1);
1394 }
1395 m.preTranslate(-fZoomCenterX, -fZoomCenterY);
1396 //canvas->concat(m);
1397 }
1398 // Apply any gesture matrix
1399 m.preConcat(fGesture.localM());
1400 m.preConcat(fGesture.globalM());
1401
1402 this->setLocalMatrix(m);
1403
1404 this->updateTitle();
1405 this->inval(NULL);
1406 }
previousSample()1407 bool SampleWindow::previousSample() {
1408 fCurrIndex = (fCurrIndex - 1 + fSamples.count()) % fSamples.count();
1409 this->loadView((*fSamples[fCurrIndex])());
1410 return true;
1411 }
1412
nextSample()1413 bool SampleWindow::nextSample() {
1414 fCurrIndex = (fCurrIndex + 1) % fSamples.count();
1415 this->loadView((*fSamples[fCurrIndex])());
1416 return true;
1417 }
1418
goToSample(int i)1419 bool SampleWindow::goToSample(int i) {
1420 fCurrIndex = (i) % fSamples.count();
1421 this->loadView((*fSamples[fCurrIndex])());
1422 return true;
1423 }
1424
getSampleTitle(int i)1425 SkString SampleWindow::getSampleTitle(int i) {
1426 return ::getSampleTitle(fSamples[i]);
1427 }
1428
sampleCount()1429 int SampleWindow::sampleCount() {
1430 return fSamples.count();
1431 }
1432
showOverview()1433 void SampleWindow::showOverview() {
1434 this->loadView(create_overview(fSamples.count(), fSamples.begin()));
1435 }
1436
installDrawFilter(SkCanvas * canvas)1437 void SampleWindow::installDrawFilter(SkCanvas* canvas) {
1438 canvas->setDrawFilter(new FlagsDrawFilter(fLCDState, fAAState, fSubpixelState,
1439 fHintingState, fFilterQualityIndex))->unref();
1440 }
1441
postAnimatingEvent()1442 void SampleWindow::postAnimatingEvent() {
1443 if (fAnimating) {
1444 (new SkEvent(ANIMATING_EVENTTYPE, this->getSinkID()))->postDelay(ANIMATING_DELAY);
1445 }
1446 }
1447
onEvent(const SkEvent & evt)1448 bool SampleWindow::onEvent(const SkEvent& evt) {
1449 if (evt.isType(gUpdateWindowTitleEvtName)) {
1450 this->updateTitle();
1451 return true;
1452 }
1453 if (evt.isType(ANIMATING_EVENTTYPE)) {
1454 if (fAnimating) {
1455 this->nextSample();
1456 this->postAnimatingEvent();
1457 }
1458 return true;
1459 }
1460 if (evt.isType("set-curr-index")) {
1461 this->goToSample(evt.getFast32());
1462 return true;
1463 }
1464 if (isInvalEvent(evt)) {
1465 this->inval(NULL);
1466 return true;
1467 }
1468 int selected = -1;
1469 if (SkOSMenu::FindListIndex(evt, "Device Type", &selected)) {
1470 this->setDeviceType((DeviceType)selected);
1471 return true;
1472 }
1473 if (SkOSMenu::FindTriState(evt, "Pipe", &fPipeState)) {
1474 #ifdef PIPE_NET
1475 if (!fPipeState != SkOSMenu::kOnState)
1476 gServer.disconnectAll();
1477 #endif
1478 (void)SampleView::SetUsePipe(curr_view(this), fPipeState);
1479 this->updateTitle();
1480 this->inval(NULL);
1481 return true;
1482 }
1483 if (SkOSMenu::FindSwitchState(evt, "Slide Show", NULL)) {
1484 this->toggleSlideshow();
1485 return true;
1486 }
1487 if (SkOSMenu::FindTriState(evt, "AA", &fAAState) ||
1488 SkOSMenu::FindTriState(evt, "LCD", &fLCDState) ||
1489 SkOSMenu::FindListIndex(evt, "FilterQuality", &fFilterQualityIndex) ||
1490 SkOSMenu::FindTriState(evt, "Subpixel", &fSubpixelState) ||
1491 SkOSMenu::FindListIndex(evt, "Hinting", &fHintingState) ||
1492 SkOSMenu::FindSwitchState(evt, "Clip", &fUseClip) ||
1493 SkOSMenu::FindSwitchState(evt, "Zoomer", &fShowZoomer) ||
1494 SkOSMenu::FindSwitchState(evt, "Magnify", &fMagnify) ||
1495 SkOSMenu::FindListIndex(evt, "Transition-Next", &fTransitionNext) ||
1496 SkOSMenu::FindListIndex(evt, "Transition-Prev", &fTransitionPrev)) {
1497 this->inval(NULL);
1498 this->updateTitle();
1499 return true;
1500 }
1501 if (SkOSMenu::FindListIndex(evt, "Tiling", &fTilingMode)) {
1502 if (SampleView::IsSampleView(curr_view(this))) {
1503 ((SampleView*)curr_view(this))->onTileSizeChanged(this->tileSize());
1504 }
1505 this->inval(NULL);
1506 this->updateTitle();
1507 return true;
1508 }
1509 if (SkOSMenu::FindSwitchState(evt, "Flip X", NULL)) {
1510 fFlipAxis ^= kFlipAxis_X;
1511 this->updateMatrix();
1512 return true;
1513 }
1514 if (SkOSMenu::FindSwitchState(evt, "Flip Y", NULL)) {
1515 fFlipAxis ^= kFlipAxis_Y;
1516 this->updateMatrix();
1517 return true;
1518 }
1519 if (SkOSMenu::FindAction(evt,"Save to PDF")) {
1520 this->saveToPdf();
1521 return true;
1522 }
1523 return this->INHERITED::onEvent(evt);
1524 }
1525
onQuery(SkEvent * query)1526 bool SampleWindow::onQuery(SkEvent* query) {
1527 if (query->isType("get-slide-count")) {
1528 query->setFast32(fSamples.count());
1529 return true;
1530 }
1531 if (query->isType("get-slide-title")) {
1532 SkView* view = (*fSamples[query->getFast32()])();
1533 SkEvent evt(gTitleEvtName);
1534 if (view->doQuery(&evt)) {
1535 query->setString("title", evt.findString(gTitleEvtName));
1536 }
1537 SkSafeUnref(view);
1538 return true;
1539 }
1540 if (query->isType("use-fast-text")) {
1541 SkEvent evt(gFastTextEvtName);
1542 return curr_view(this)->doQuery(&evt);
1543 }
1544 if (query->isType("ignore-window-bitmap")) {
1545 query->setFast32(this->getGrContext() != NULL);
1546 return true;
1547 }
1548 return this->INHERITED::onQuery(query);
1549 }
1550
1551 DECLARE_bool(portableFonts);
1552
onHandleChar(SkUnichar uni)1553 bool SampleWindow::onHandleChar(SkUnichar uni) {
1554 {
1555 SkView* view = curr_view(this);
1556 if (view) {
1557 SkEvent evt(gCharEvtName);
1558 evt.setFast32(uni);
1559 if (view->doQuery(&evt)) {
1560 return true;
1561 }
1562 }
1563 }
1564
1565 int dx = 0xFF;
1566 int dy = 0xFF;
1567
1568 switch (uni) {
1569 case '5': dx = 0; dy = 0; break;
1570 case '8': dx = 0; dy = -1; break;
1571 case '6': dx = 1; dy = 0; break;
1572 case '2': dx = 0; dy = 1; break;
1573 case '4': dx = -1; dy = 0; break;
1574 case '7': dx = -1; dy = -1; break;
1575 case '9': dx = 1; dy = -1; break;
1576 case '3': dx = 1; dy = 1; break;
1577 case '1': dx = -1; dy = 1; break;
1578
1579 default:
1580 break;
1581 }
1582
1583 if (0xFF != dx && 0xFF != dy) {
1584 if ((dx | dy) == 0) {
1585 fScrollTestX = fScrollTestY = 0;
1586 } else {
1587 fScrollTestX += dx;
1588 fScrollTestY += dy;
1589 }
1590 this->inval(NULL);
1591 return true;
1592 }
1593
1594 switch (uni) {
1595 case 27: // ESC
1596 gAnimTimer.stop();
1597 if (this->sendAnimatePulse()) {
1598 this->inval(NULL);
1599 }
1600 break;
1601 case ' ':
1602 gAnimTimer.togglePauseResume();
1603 if (this->sendAnimatePulse()) {
1604 this->inval(NULL);
1605 }
1606 break;
1607 case 'B':
1608 post_event_to_sink(SkNEW_ARGS(SkEvent, ("PictFileView::toggleBBox")), curr_view(this));
1609 // Cannot call updateTitle() synchronously, because the toggleBBox event is still in
1610 // the queue.
1611 post_event_to_sink(SkNEW_ARGS(SkEvent, (gUpdateWindowTitleEvtName)), this);
1612 this->inval(NULL);
1613 break;
1614 case 'D':
1615 toggleDistanceFieldFonts();
1616 break;
1617 case 'f':
1618 // only
1619 toggleFPS();
1620 break;
1621 case 'F':
1622 FLAGS_portableFonts ^= true;
1623 this->inval(NULL);
1624 break;
1625 case 'g':
1626 fRequestGrabImage = true;
1627 this->inval(NULL);
1628 break;
1629 case 'G':
1630 gShowGMBounds = !gShowGMBounds;
1631 post_event_to_sink(GMSampleView::NewShowSizeEvt(gShowGMBounds),
1632 curr_view(this));
1633 this->inval(NULL);
1634 break;
1635 case 'i':
1636 this->zoomIn();
1637 break;
1638 case 'o':
1639 this->zoomOut();
1640 break;
1641 case 'r':
1642 fRotate = !fRotate;
1643 this->inval(NULL);
1644 this->updateTitle();
1645 return true;
1646 case 'k':
1647 fPerspAnim = !fPerspAnim;
1648 this->inval(NULL);
1649 this->updateTitle();
1650 return true;
1651 #if SK_SUPPORT_GPU
1652 case 'p':
1653 {
1654 GrContext* grContext = this->getGrContext();
1655 if (grContext) {
1656 size_t cacheBytes;
1657 grContext->getResourceCacheUsage(NULL, &cacheBytes);
1658 grContext->freeGpuResources();
1659 SkDebugf("Purged %d bytes from the GPU resource cache.\n", cacheBytes);
1660 }
1661 }
1662 return true;
1663 #endif
1664 default:
1665 break;
1666 }
1667
1668 if (fAppMenu->handleKeyEquivalent(uni)|| fSlideMenu->handleKeyEquivalent(uni)) {
1669 this->onUpdateMenu(fAppMenu);
1670 this->onUpdateMenu(fSlideMenu);
1671 return true;
1672 }
1673 return this->INHERITED::onHandleChar(uni);
1674 }
1675
setDeviceType(DeviceType type)1676 void SampleWindow::setDeviceType(DeviceType type) {
1677 if (type == fDeviceType)
1678 return;
1679
1680 fDevManager->tearDownBackend(this);
1681
1682 fDeviceType = type;
1683
1684 fDevManager->setUpBackend(this, fMSAASampleCount);
1685
1686 this->updateTitle();
1687 this->inval(NULL);
1688 }
1689
toggleSlideshow()1690 void SampleWindow::toggleSlideshow() {
1691 fAnimating = !fAnimating;
1692 this->postAnimatingEvent();
1693 this->updateTitle();
1694 }
1695
toggleRendering()1696 void SampleWindow::toggleRendering() {
1697 this->setDeviceType(cycle_devicetype(fDeviceType));
1698 this->updateTitle();
1699 this->inval(NULL);
1700 }
1701
toggleFPS()1702 void SampleWindow::toggleFPS() {
1703 fMeasureFPS = !fMeasureFPS;
1704 this->updateTitle();
1705 this->inval(NULL);
1706 }
1707
toggleDistanceFieldFonts()1708 void SampleWindow::toggleDistanceFieldFonts() {
1709 SkSurfaceProps props = this->getSurfaceProps();
1710 uint32_t flags = props.flags() ^ SkSurfaceProps::kUseDistanceFieldFonts_Flag;
1711 this->setSurfaceProps(SkSurfaceProps(flags, props.pixelGeometry()));
1712
1713 this->updateTitle();
1714 this->inval(NULL);
1715 }
1716
1717 #include "SkDumpCanvas.h"
1718
onHandleKey(SkKey key)1719 bool SampleWindow::onHandleKey(SkKey key) {
1720 {
1721 SkView* view = curr_view(this);
1722 if (view) {
1723 SkEvent evt(gKeyEvtName);
1724 evt.setFast32(key);
1725 if (view->doQuery(&evt)) {
1726 return true;
1727 }
1728 }
1729 }
1730 switch (key) {
1731 case kRight_SkKey:
1732 if (this->nextSample()) {
1733 return true;
1734 }
1735 break;
1736 case kLeft_SkKey:
1737 if (this->previousSample()) {
1738 return true;
1739 }
1740 return true;
1741 case kUp_SkKey:
1742 this->changeZoomLevel(1.f / 32.f);
1743 return true;
1744 case kDown_SkKey:
1745 this->changeZoomLevel(-1.f / 32.f);
1746 return true;
1747 case kOK_SkKey: {
1748 SkString title;
1749 if (curr_title(this, &title)) {
1750 writeTitleToPrefs(title.c_str());
1751 }
1752 return true;
1753 }
1754 case kBack_SkKey:
1755 this->showOverview();
1756 return true;
1757 default:
1758 break;
1759 }
1760 return this->INHERITED::onHandleKey(key);
1761 }
1762
1763 ///////////////////////////////////////////////////////////////////////////////
1764
1765 static const char gGestureClickType[] = "GestureClickType";
1766
onDispatchClick(int x,int y,Click::State state,void * owner,unsigned modi)1767 bool SampleWindow::onDispatchClick(int x, int y, Click::State state,
1768 void* owner, unsigned modi) {
1769 if (Click::kMoved_State == state) {
1770 updatePointer(x, y);
1771 }
1772 int w = SkScalarRoundToInt(this->width());
1773 int h = SkScalarRoundToInt(this->height());
1774
1775 // check for the resize-box
1776 if (w - x < 16 && h - y < 16) {
1777 return false; // let the OS handle the click
1778 }
1779 else if (fMagnify) {
1780 //it's only necessary to update the drawing if there's a click
1781 this->inval(NULL);
1782 return false; //prevent dragging while magnify is enabled
1783 } else {
1784 // capture control+option, and trigger debugger
1785 if ((modi & kControl_SkModifierKey) && (modi & kOption_SkModifierKey)) {
1786 if (Click::kDown_State == state) {
1787 SkEvent evt("debug-hit-test");
1788 evt.setS32("debug-hit-test-x", x);
1789 evt.setS32("debug-hit-test-y", y);
1790 curr_view(this)->doEvent(evt);
1791 }
1792 return true;
1793 } else {
1794 return this->INHERITED::onDispatchClick(x, y, state, owner, modi);
1795 }
1796 }
1797 }
1798
1799 class GestureClick : public SkView::Click {
1800 public:
GestureClick(SkView * target)1801 GestureClick(SkView* target) : SkView::Click(target) {
1802 this->setType(gGestureClickType);
1803 }
1804
IsGesture(Click * click)1805 static bool IsGesture(Click* click) {
1806 return click->isType(gGestureClickType);
1807 }
1808 };
1809
onFindClickHandler(SkScalar x,SkScalar y,unsigned modi)1810 SkView::Click* SampleWindow::onFindClickHandler(SkScalar x, SkScalar y,
1811 unsigned modi) {
1812 return new GestureClick(this);
1813 }
1814
onClick(Click * click)1815 bool SampleWindow::onClick(Click* click) {
1816 if (GestureClick::IsGesture(click)) {
1817 float x = static_cast<float>(click->fICurr.fX);
1818 float y = static_cast<float>(click->fICurr.fY);
1819
1820 switch (click->fState) {
1821 case SkView::Click::kDown_State:
1822 fGesture.touchBegin(click->fOwner, x, y);
1823 break;
1824 case SkView::Click::kMoved_State:
1825 fGesture.touchMoved(click->fOwner, x, y);
1826 this->updateMatrix();
1827 break;
1828 case SkView::Click::kUp_State:
1829 fGesture.touchEnd(click->fOwner);
1830 this->updateMatrix();
1831 break;
1832 }
1833 return true;
1834 }
1835 return false;
1836 }
1837
1838 ///////////////////////////////////////////////////////////////////////////////
1839
loadView(SkView * view)1840 void SampleWindow::loadView(SkView* view) {
1841 SkView::F2BIter iter(this);
1842 SkView* prev = iter.next();
1843 if (prev) {
1844 prev->detachFromParent();
1845 }
1846
1847 view->setVisibleP(true);
1848 view->setClipToBounds(false);
1849 this->attachChildToFront(view)->unref();
1850 view->setSize(this->width(), this->height());
1851
1852 //repopulate the slide menu when a view is loaded
1853 fSlideMenu->reset();
1854
1855 (void)SampleView::SetUsePipe(view, fPipeState);
1856 if (SampleView::IsSampleView(view)) {
1857 SampleView* sampleView = (SampleView*)view;
1858 sampleView->requestMenu(fSlideMenu);
1859 sampleView->onTileSizeChanged(this->tileSize());
1860 }
1861 this->onUpdateMenu(fSlideMenu);
1862 this->updateTitle();
1863 }
1864
1865 static const char* gDeviceTypePrefix[] = {
1866 "raster: ",
1867 "picture: ",
1868 #if SK_SUPPORT_GPU
1869 "opengl: ",
1870 #if SK_ANGLE
1871 "angle: ",
1872 #endif // SK_ANGLE
1873 #endif // SK_SUPPORT_GPU
1874 "deferred: ",
1875 };
1876 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gDeviceTypePrefix) == SampleWindow::kDeviceTypeCnt,
1877 array_size_mismatch);
1878
trystate_str(SkOSMenu::TriState state,const char trueStr[],const char falseStr[])1879 static const char* trystate_str(SkOSMenu::TriState state,
1880 const char trueStr[], const char falseStr[]) {
1881 if (SkOSMenu::kOnState == state) {
1882 return trueStr;
1883 } else if (SkOSMenu::kOffState == state) {
1884 return falseStr;
1885 }
1886 return NULL;
1887 }
1888
getRawTitle(SkString * title)1889 bool SampleWindow::getRawTitle(SkString* title) {
1890 return curr_title(this, title);
1891 }
1892
updateTitle()1893 void SampleWindow::updateTitle() {
1894 SkString title;
1895 if (!this->getRawTitle(&title)) {
1896 title.set("<unknown>");
1897 }
1898
1899 title.prepend(gDeviceTypePrefix[fDeviceType]);
1900
1901 title.prepend(" ");
1902 title.prepend(sk_tool_utils::colortype_name(this->getBitmap().colorType()));
1903
1904 if (fTilingMode != kNo_Tiling) {
1905 title.prependf("<T: %s> ", gTilingInfo[fTilingMode].label);
1906 }
1907 if (fAnimating) {
1908 title.prepend("<A> ");
1909 }
1910 if (fRotate) {
1911 title.prepend("<R> ");
1912 }
1913 if (fPerspAnim) {
1914 title.prepend("<K> ");
1915 }
1916 if (this->getSurfaceProps().flags() & SkSurfaceProps::kUseDistanceFieldFonts_Flag) {
1917 title.prepend("<DFF> ");
1918 }
1919
1920 title.prepend(trystate_str(fLCDState, "LCD ", "lcd "));
1921 title.prepend(trystate_str(fAAState, "AA ", "aa "));
1922 title.prepend(gFilterQualityStates[fFilterQualityIndex].fLabel);
1923 title.prepend(trystate_str(fSubpixelState, "S ", "s "));
1924 title.prepend(fFlipAxis & kFlipAxis_X ? "X " : NULL);
1925 title.prepend(fFlipAxis & kFlipAxis_Y ? "Y " : NULL);
1926 title.prepend(gHintingStates[fHintingState].label);
1927
1928 if (fZoomLevel) {
1929 title.prependf("{%.2f} ", SkScalarToFloat(fZoomLevel));
1930 }
1931
1932 if (fMeasureFPS) {
1933 title.appendf(" %8.3f ms", fMeasureFPS_Time / (float)FPS_REPEAT_COUNT);
1934 }
1935
1936 SkView* view = curr_view(this);
1937 if (SampleView::IsSampleView(view)) {
1938 switch (fPipeState) {
1939 case SkOSMenu::kOnState:
1940 title.prepend("<Pipe> ");
1941 break;
1942 case SkOSMenu::kMixedState:
1943 title.prepend("<Tiled Pipe> ");
1944 break;
1945
1946 default:
1947 break;
1948 }
1949 title.prepend("! ");
1950 }
1951
1952 #if SK_SUPPORT_GPU
1953 if (IsGpuDeviceType(fDeviceType) &&
1954 fDevManager &&
1955 fDevManager->getGrRenderTarget() &&
1956 fDevManager->getGrRenderTarget()->numSamples() > 0) {
1957 title.appendf(" [MSAA: %d]",
1958 fDevManager->getGrRenderTarget()->numSamples());
1959 }
1960 #endif
1961
1962 this->setTitle(title.c_str());
1963 }
1964
onSizeChange()1965 void SampleWindow::onSizeChange() {
1966 this->INHERITED::onSizeChange();
1967
1968 SkView::F2BIter iter(this);
1969 SkView* view = iter.next();
1970 view->setSize(this->width(), this->height());
1971
1972 // rebuild our clippath
1973 {
1974 const SkScalar W = this->width();
1975 const SkScalar H = this->height();
1976
1977 fClipPath.reset();
1978 #if 0
1979 for (SkScalar y = SK_Scalar1; y < H; y += SkIntToScalar(32)) {
1980 SkRect r;
1981 r.set(SK_Scalar1, y, SkIntToScalar(30), y + SkIntToScalar(30));
1982 for (; r.fLeft < W; r.offset(SkIntToScalar(32), 0))
1983 fClipPath.addRect(r);
1984 }
1985 #else
1986 SkRect r;
1987 r.set(0, 0, W, H);
1988 fClipPath.addRect(r, SkPath::kCCW_Direction);
1989 r.set(W/4, H/4, W*3/4, H*3/4);
1990 fClipPath.addRect(r, SkPath::kCW_Direction);
1991 #endif
1992 }
1993
1994 fZoomCenterX = SkScalarHalf(this->width());
1995 fZoomCenterY = SkScalarHalf(this->height());
1996
1997 #ifdef SK_BUILD_FOR_ANDROID
1998 // FIXME: The first draw after a size change does not work on Android, so
1999 // we post an invalidate.
2000 this->postInvalDelay();
2001 #endif
2002 this->updateTitle(); // to refresh our config
2003 fDevManager->windowSizeChanged(this);
2004
2005 if (fTilingMode != kNo_Tiling && SampleView::IsSampleView(view)) {
2006 ((SampleView*)view)->onTileSizeChanged(this->tileSize());
2007 }
2008 }
2009
2010 ///////////////////////////////////////////////////////////////////////////////
2011
2012 static const char is_sample_view_tag[] = "sample-is-sample-view";
2013 static const char repeat_count_tag[] = "sample-set-repeat-count";
2014 static const char set_use_pipe_tag[] = "sample-set-use-pipe";
2015
IsSampleView(SkView * view)2016 bool SampleView::IsSampleView(SkView* view) {
2017 SkEvent evt(is_sample_view_tag);
2018 return view->doQuery(&evt);
2019 }
2020
SetRepeatDraw(SkView * view,int count)2021 bool SampleView::SetRepeatDraw(SkView* view, int count) {
2022 SkEvent evt(repeat_count_tag);
2023 evt.setFast32(count);
2024 return view->doEvent(evt);
2025 }
2026
SetUsePipe(SkView * view,SkOSMenu::TriState state)2027 bool SampleView::SetUsePipe(SkView* view, SkOSMenu::TriState state) {
2028 SkEvent evt;
2029 evt.setS32(set_use_pipe_tag, state);
2030 return view->doEvent(evt);
2031 }
2032
onEvent(const SkEvent & evt)2033 bool SampleView::onEvent(const SkEvent& evt) {
2034 if (evt.isType(repeat_count_tag)) {
2035 fRepeatCount = evt.getFast32();
2036 return true;
2037 }
2038
2039 int32_t pipeHolder;
2040 if (evt.findS32(set_use_pipe_tag, &pipeHolder)) {
2041 fPipeState = static_cast<SkOSMenu::TriState>(pipeHolder);
2042 return true;
2043 }
2044
2045 return this->INHERITED::onEvent(evt);
2046 }
2047
onQuery(SkEvent * evt)2048 bool SampleView::onQuery(SkEvent* evt) {
2049 if (evt->isType(is_sample_view_tag)) {
2050 return true;
2051 }
2052 return this->INHERITED::onQuery(evt);
2053 }
2054
2055
2056 class SimplePC : public SkGPipeController {
2057 public:
2058 SimplePC(SkCanvas* target);
2059 ~SimplePC();
2060
2061 virtual void* requestBlock(size_t minRequest, size_t* actual);
2062 virtual void notifyWritten(size_t bytes);
2063
2064 private:
2065 SkGPipeReader fReader;
2066 void* fBlock;
2067 size_t fBlockSize;
2068 size_t fBytesWritten;
2069 int fAtomsWritten;
2070 SkGPipeReader::Status fStatus;
2071
2072 size_t fTotalWritten;
2073 };
2074
SimplePC(SkCanvas * target)2075 SimplePC::SimplePC(SkCanvas* target) : fReader(target) {
2076 fBlock = NULL;
2077 fBlockSize = fBytesWritten = 0;
2078 fStatus = SkGPipeReader::kDone_Status;
2079 fTotalWritten = 0;
2080 fAtomsWritten = 0;
2081 fReader.setBitmapDecoder(&SkImageDecoder::DecodeMemory);
2082 }
2083
~SimplePC()2084 SimplePC::~SimplePC() {
2085 // SkASSERT(SkGPipeReader::kDone_Status == fStatus);
2086 if (fTotalWritten) {
2087 SkDebugf("--- %d bytes %d atoms, status %d\n", fTotalWritten,
2088 fAtomsWritten, fStatus);
2089 #ifdef PIPE_FILE
2090 //File is open in append mode
2091 FILE* f = fopen(FILE_PATH, "ab");
2092 SkASSERT(f != NULL);
2093 fwrite((const char*)fBlock + fBytesWritten, 1, bytes, f);
2094 fclose(f);
2095 #endif
2096 #ifdef PIPE_NET
2097 if (fAtomsWritten > 1 && fTotalWritten > 4) { //ignore done
2098 gServer.acceptConnections();
2099 gServer.writePacket(fBlock, fTotalWritten);
2100 }
2101 #endif
2102 }
2103 sk_free(fBlock);
2104 }
2105
requestBlock(size_t minRequest,size_t * actual)2106 void* SimplePC::requestBlock(size_t minRequest, size_t* actual) {
2107 sk_free(fBlock);
2108
2109 fBlockSize = minRequest * 4;
2110 fBlock = sk_malloc_throw(fBlockSize);
2111 fBytesWritten = 0;
2112 *actual = fBlockSize;
2113 return fBlock;
2114 }
2115
notifyWritten(size_t bytes)2116 void SimplePC::notifyWritten(size_t bytes) {
2117 SkASSERT(fBytesWritten + bytes <= fBlockSize);
2118 fStatus = fReader.playback((const char*)fBlock + fBytesWritten, bytes);
2119 SkASSERT(SkGPipeReader::kError_Status != fStatus);
2120 fBytesWritten += bytes;
2121 fTotalWritten += bytes;
2122
2123 fAtomsWritten += 1;
2124 }
2125
draw(SkCanvas * canvas)2126 void SampleView::draw(SkCanvas* canvas) {
2127 if (SkOSMenu::kOffState == fPipeState) {
2128 this->INHERITED::draw(canvas);
2129 } else {
2130 SkGPipeWriter writer;
2131 SimplePC controller(canvas);
2132 SkBitmap bitmap = capture_bitmap(canvas);
2133 TiledPipeController tc(bitmap, &SkImageDecoder::DecodeMemory, &canvas->getTotalMatrix());
2134 SkGPipeController* pc;
2135 if (SkOSMenu::kMixedState == fPipeState) {
2136 pc = &tc;
2137 } else {
2138 pc = &controller;
2139 }
2140 uint32_t flags = SkGPipeWriter::kCrossProcess_Flag;
2141
2142 canvas = writer.startRecording(pc, flags);
2143 //Must draw before controller goes out of scope and sends data
2144 this->INHERITED::draw(canvas);
2145 //explicitly end recording to ensure writer is flushed before the memory
2146 //is freed in the deconstructor of the controller
2147 writer.endRecording();
2148 }
2149 }
2150
onDraw(SkCanvas * canvas)2151 void SampleView::onDraw(SkCanvas* canvas) {
2152 if (!fHaveCalledOnceBeforeDraw) {
2153 fHaveCalledOnceBeforeDraw = true;
2154 this->onOnceBeforeDraw();
2155 }
2156 this->onDrawBackground(canvas);
2157
2158 for (int i = 0; i < fRepeatCount; i++) {
2159 SkAutoCanvasRestore acr(canvas, true);
2160 this->onDrawContent(canvas);
2161 }
2162 }
2163
onDrawBackground(SkCanvas * canvas)2164 void SampleView::onDrawBackground(SkCanvas* canvas) {
2165 canvas->drawColor(fBGColor);
2166 }
2167
2168 ///////////////////////////////////////////////////////////////////////////////
2169
SkTBSort(T array[],int count)2170 template <typename T> void SkTBSort(T array[], int count) {
2171 for (int i = 1; i < count - 1; i++) {
2172 bool didSwap = false;
2173 for (int j = count - 1; j > i; --j) {
2174 if (array[j] < array[j-1]) {
2175 T tmp(array[j-1]);
2176 array[j-1] = array[j];
2177 array[j] = tmp;
2178 didSwap = true;
2179 }
2180 }
2181 if (!didSwap) {
2182 break;
2183 }
2184 }
2185
2186 for (int k = 0; k < count - 1; k++) {
2187 SkASSERT(!(array[k+1] < array[k]));
2188 }
2189 }
2190
2191 #include "SkRandom.h"
2192
rand_rect(SkIRect * rect,SkRandom & rand)2193 static void rand_rect(SkIRect* rect, SkRandom& rand) {
2194 int bits = 8;
2195 int shift = 32 - bits;
2196 rect->set(rand.nextU() >> shift, rand.nextU() >> shift,
2197 rand.nextU() >> shift, rand.nextU() >> shift);
2198 rect->sort();
2199 }
2200
dumpRect(const SkIRect & r)2201 static void dumpRect(const SkIRect& r) {
2202 SkDebugf(" { %d, %d, %d, %d },\n",
2203 r.fLeft, r.fTop,
2204 r.fRight, r.fBottom);
2205 }
2206
test_rects(const SkIRect rect[],int count)2207 static void test_rects(const SkIRect rect[], int count) {
2208 SkRegion rgn0, rgn1;
2209
2210 for (int i = 0; i < count; i++) {
2211 rgn0.op(rect[i], SkRegion::kUnion_Op);
2212 // dumpRect(rect[i]);
2213 }
2214 rgn1.setRects(rect, count);
2215
2216 if (rgn0 != rgn1) {
2217 SkDebugf("\n");
2218 for (int i = 0; i < count; i++) {
2219 dumpRect(rect[i]);
2220 }
2221 SkDebugf("\n");
2222 }
2223 }
2224
test()2225 static void test() {
2226 size_t i;
2227
2228 const SkIRect r0[] = {
2229 { 0, 0, 1, 1 },
2230 { 2, 2, 3, 3 },
2231 };
2232 const SkIRect r1[] = {
2233 { 0, 0, 1, 3 },
2234 { 1, 1, 2, 2 },
2235 { 2, 0, 3, 3 },
2236 };
2237 const SkIRect r2[] = {
2238 { 0, 0, 1, 2 },
2239 { 2, 1, 3, 3 },
2240 { 4, 0, 5, 1 },
2241 { 6, 0, 7, 4 },
2242 };
2243
2244 static const struct {
2245 const SkIRect* fRects;
2246 int fCount;
2247 } gRecs[] = {
2248 { r0, SK_ARRAY_COUNT(r0) },
2249 { r1, SK_ARRAY_COUNT(r1) },
2250 { r2, SK_ARRAY_COUNT(r2) },
2251 };
2252
2253 for (i = 0; i < SK_ARRAY_COUNT(gRecs); i++) {
2254 test_rects(gRecs[i].fRects, gRecs[i].fCount);
2255 }
2256
2257 SkRandom rand;
2258 for (i = 0; i < 10000; i++) {
2259 SkRegion rgn0, rgn1;
2260
2261 const int N = 8;
2262 SkIRect rect[N];
2263 for (int j = 0; j < N; j++) {
2264 rand_rect(&rect[j], rand);
2265 }
2266 test_rects(rect, N);
2267 }
2268 }
2269
2270 // FIXME: this should be in a header
2271 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv);
create_sk_window(void * hwnd,int argc,char ** argv)2272 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
2273 if (false) { // avoid bit rot, suppress warning
2274 test();
2275 }
2276 return new SampleWindow(hwnd, argc, argv, NULL);
2277 }
2278
2279 // FIXME: this should be in a header
2280 void get_preferred_size(int* x, int* y, int* width, int* height);
get_preferred_size(int * x,int * y,int * width,int * height)2281 void get_preferred_size(int* x, int* y, int* width, int* height) {
2282 *x = 10;
2283 *y = 50;
2284 *width = 640;
2285 *height = 480;
2286 }
2287
2288 #ifdef SK_BUILD_FOR_IOS
2289 #include "SkApplication.h"
set_cmd_line_args(int,char * [],const char * resourceDir)2290 IOS_launch_type set_cmd_line_args(int , char *[], const char* resourceDir) {
2291 SetResourcePath(resourceDir);
2292 return kApplication__iOSLaunchType;
2293 }
2294 #endif
2295
application_init()2296 void application_init() {
2297 // setenv("ANDROID_ROOT", "../../../data", 0);
2298 #ifdef SK_BUILD_FOR_MAC
2299 setenv("ANDROID_ROOT", "/android/device/data", 0);
2300 #endif
2301 SkGraphics::Init();
2302 SkEvent::Init();
2303 }
2304
application_term()2305 void application_term() {
2306 SkEvent::Term();
2307 SkGraphics::Term();
2308 }
2309