2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
11 #include "Resources.h"
12 #include "SampleCode.h"
13 #include "SamplePipeControllers.h"
15 #include "SkCommandLineFlags.h"
19 #include "SkGraphics.h"
20 #include "SkImageEncoder.h"
22 #include "SkPDFDevice.h"
23 #include "SkPDFDocument.h"
25 #include "SkPicture.h"
26 #include "SkPictureRecorder.h"
28 #include "SkSurface.h"
31 #include "SkTypeface.h"
33 #include "TransitionView.h"
34 #include "sk_tool_utils.h"
37 #include "gl/GrGLInterface.h"
38 #include "gl/GrGLUtil.h"
39 #include "GrRenderTarget.h"
40 #include "GrContext.h"
41 #include "SkGpuDevice.h"
46 extern SampleView* CreateSamplePictFileView(const char filename[]);
48 class PictFileFactory : public SkViewFactory {
51 PictFileFactory(const SkString& filename) : fFilename(filename) {}
52 virtual SkView* operator() () const SK_OVERRIDE {
53 return CreateSamplePictFileView(fFilename.c_str());
57 #ifdef SAMPLE_PDF_FILE_VIEWER
58 extern SampleView* CreateSamplePdfFileViewer(const char filename[]);
60 class PdfFileViewerFactory : public SkViewFactory {
63 PdfFileViewerFactory(const SkString& filename) : fFilename(filename) {}
64 virtual SkView* operator() () const SK_OVERRIDE {
65 return CreateSamplePdfFileViewer(fFilename.c_str());
68 #endif // SAMPLE_PDF_FILE_VIEWER
72 #define FILE_PATH "/path/to/drawing.data"
77 #include "SkSockets.h"
81 #define USE_ARROWS_FOR_ZOOM true
84 //#define DEFAULT_TO_ANGLE 1
86 #define DEFAULT_TO_GPU 0 // if 1 default rendering is on GPU
89 #define ANIMATING_EVENTTYPE "nextSample"
90 #define ANIMATING_DELAY 250
93 #define FPS_REPEAT_MULTIPLIER 1
95 #define FPS_REPEAT_MULTIPLIER 10
97 #define FPS_REPEAT_COUNT (10 * FPS_REPEAT_MULTIPLIER)
99 static SampleWindow* gSampleWindow;
101 static bool gShowGMBounds;
103 static void post_event_to_sink(SkEvent* evt, SkEventSink* sink) {
104 evt->setTargetID(sink->getSinkID())->post();
107 ///////////////////////////////////////////////////////////////////////////////
109 static const char* skip_until(const char* str, const char* skip) {
113 return strstr(str, skip);
116 static const char* skip_past(const char* str, const char* skip) {
117 const char* found = skip_until(str, skip);
121 return found + strlen(skip);
124 static const char* gPrefFileName = "sampleapp_prefs.txt";
126 static bool readTitleFromPrefs(SkString* title) {
127 SkFILEStream stream(gPrefFileName);
128 if (!stream.isValid()) {
132 size_t len = stream.getLength();
134 stream.read(data.writable_str(), len);
135 const char* s = data.c_str();
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, "\"");
142 title->set(s, stop - s);
148 static void writeTitleToPrefs(const char* title) {
149 SkFILEWStream stream(gPrefFileName);
151 data.printf("curr-slide-title = \"%s\"\n", title);
152 stream.write(data.c_str(), data.size());
155 ///////////////////////////////////////////////////////////////////////////////
157 class SampleWindow::DefaultDeviceManager : public SampleWindow::DeviceManager {
160 DefaultDeviceManager() {
164 fCurRenderTarget = NULL;
165 fMSAASampleCount = 0;
167 fBackend = kNone_BackEndType;
170 virtual ~DefaultDeviceManager() {
172 SkSafeUnref(fCurContext);
173 SkSafeUnref(fCurIntf);
174 SkSafeUnref(fCurRenderTarget);
178 virtual void setUpBackend(SampleWindow* win, int msaaSampleCount) {
179 SkASSERT(kNone_BackEndType == fBackend);
181 fBackend = kNone_BackEndType;
184 switch (win->getDeviceType()) {
185 case kRaster_DeviceType:
187 case kPicture_DeviceType:
189 case kGPU_DeviceType:
191 case kNullGPU_DeviceType:
192 // all these guys use the native backend
193 fBackend = kNativeGL_BackEndType;
196 case kANGLE_DeviceType:
197 // ANGLE is really the only odd man out
198 fBackend = kANGLE_BackEndType;
205 AttachmentInfo attachmentInfo;
206 bool result = win->attach(fBackend, msaaSampleCount, &attachmentInfo);
208 SkDebugf("Failed to initialize GL");
211 fMSAASampleCount = msaaSampleCount;
213 SkASSERT(NULL == fCurIntf);
214 SkAutoTUnref<const GrGLInterface> glInterface;
215 switch (win->getDeviceType()) {
216 case kRaster_DeviceType:
218 case kPicture_DeviceType:
220 case kGPU_DeviceType:
221 // all these guys use the native interface
222 glInterface.reset(GrGLCreateNativeInterface());
225 case kANGLE_DeviceType:
226 glInterface.reset(GrGLCreateANGLEInterface());
229 case kNullGPU_DeviceType:
230 glInterface.reset(GrGLCreateNullInterface());
237 // Currently SampleApp does not use NVPR. TODO: Provide an NVPR device type that is skipped
238 // when the driver doesn't support NVPR.
239 fCurIntf = GrGLInterfaceRemoveNVPR(glInterface.get());
241 SkASSERT(NULL == fCurContext);
242 fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf);
244 if (NULL == fCurContext || NULL == fCurIntf) {
245 // We need some context and interface to see results
246 SkSafeUnref(fCurContext);
247 SkSafeUnref(fCurIntf);
250 SkDebugf("Failed to setup 3D");
254 #endif // SK_SUPPORT_GPU
255 // call windowSizeChanged to create the render target
256 this->windowSizeChanged(win);
259 virtual void tearDownBackend(SampleWindow *win) {
261 SkSafeUnref(fCurContext);
264 SkSafeUnref(fCurIntf);
267 SkSafeUnref(fCurRenderTarget);
268 fCurRenderTarget = NULL;
271 fBackend = kNone_BackEndType;
274 virtual SkSurface* createSurface(SampleWindow::DeviceType dType,
275 SampleWindow* win) SK_OVERRIDE {
277 if (IsGpuDeviceType(dType) && fCurContext) {
278 return SkSurface::NewRenderTargetDirect(fCurRenderTarget);
284 virtual void publishCanvas(SampleWindow::DeviceType dType,
289 // in case we have queued drawing calls
290 fCurContext->flush();
292 if (!IsGpuDeviceType(dType)) {
293 // need to send the raster bits to the (gpu) window
294 fCurContext->setRenderTarget(fCurRenderTarget);
295 const SkBitmap& bm = win->getBitmap();
296 fCurRenderTarget->writePixels(0, 0, bm.width(), bm.height(),
297 SkImageInfo2GrPixelConfig(bm.colorType(),
308 virtual void windowSizeChanged(SampleWindow* win) {
311 AttachmentInfo attachmentInfo;
312 win->attach(fBackend, fMSAASampleCount, &attachmentInfo);
314 GrBackendRenderTargetDesc desc;
315 desc.fWidth = SkScalarRoundToInt(win->width());
316 desc.fHeight = SkScalarRoundToInt(win->height());
317 desc.fConfig = kSkia8888_GrPixelConfig;
318 desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
319 desc.fSampleCnt = attachmentInfo.fSampleCount;
320 desc.fStencilBits = attachmentInfo.fStencilBits;
322 GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
323 desc.fRenderTargetHandle = buffer;
325 SkSafeUnref(fCurRenderTarget);
326 fCurRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
331 virtual GrContext* getGrContext() {
339 virtual GrRenderTarget* getGrRenderTarget() SK_OVERRIDE {
341 return fCurRenderTarget;
350 GrContext* fCurContext;
351 const GrGLInterface* fCurIntf;
352 GrRenderTarget* fCurRenderTarget;
353 int fMSAASampleCount;
356 SkOSWindow::SkBackEndTypes fBackend;
358 typedef SampleWindow::DeviceManager INHERITED;
362 static const char view_inval_msg[] = "view-inval-msg";
364 void SampleWindow::postInvalDelay() {
365 (new SkEvent(view_inval_msg, this->getSinkID()))->postDelay(1);
368 static bool isInvalEvent(const SkEvent& evt) {
369 return evt.isType(view_inval_msg);
373 SkFuncViewFactory::SkFuncViewFactory(SkViewCreateFunc func)
374 : fCreateFunc(func) {
377 SkView* SkFuncViewFactory::operator() () const {
378 return (*fCreateFunc)();
381 #include "GMSampleView.h"
383 SkGMSampleViewFactory::SkGMSampleViewFactory(GMFactoryFunc func)
387 SkView* SkGMSampleViewFactory::operator() () const {
388 skiagm::GM* gm = fFunc(NULL);
389 gm->setMode(skiagm::GM::kSample_Mode);
390 return new GMSampleView(gm);
393 SkViewRegister* SkViewRegister::gHead;
394 SkViewRegister::SkViewRegister(SkViewFactory* fact) : fFact(fact) {
400 SkViewRegister::SkViewRegister(SkViewCreateFunc func) {
401 fFact = new SkFuncViewFactory(func);
406 SkViewRegister::SkViewRegister(GMFactoryFunc func) {
407 fFact = new SkGMSampleViewFactory(func);
412 class AutoUnrefArray {
416 int count = fObjs.count();
417 for (int i = 0; i < count; ++i) {
421 SkRefCnt*& push_back() { return *fObjs.append(); }
424 SkTDArray<SkRefCnt*> fObjs;
427 // registers GMs as Samples
428 // This can't be performed during static initialization because it could be
429 // run before GMRegistry has been fully built.
430 static void SkGMRegistyToSampleRegistry() {
432 static AutoUnrefArray fRegisters;
435 const skiagm::GMRegistry* gmreg = skiagm::GMRegistry::Head();
437 fRegisters.push_back() = new SkViewRegister(gmreg->factory());
438 gmreg = gmreg->next();
444 //////////////////////////////////////////////////////////////////////////////
447 kFlipAxis_X = (1 << 0),
448 kFlipAxis_Y = (1 << 1)
451 #include "SkDrawFilter.h"
453 struct HintingState {
454 SkPaint::Hinting hinting;
458 static HintingState gHintingStates[] = {
459 {SkPaint::kNo_Hinting, "Mixed", NULL },
460 {SkPaint::kNo_Hinting, "None", "H0 " },
461 {SkPaint::kSlight_Hinting, "Slight", "Hs " },
462 {SkPaint::kNormal_Hinting, "Normal", "Hn " },
463 {SkPaint::kFull_Hinting, "Full", "Hf " },
466 struct FilterLevelState {
467 SkPaint::FilterLevel fLevel;
471 static FilterLevelState gFilterLevelStates[] = {
472 { SkPaint::kNone_FilterLevel, "Mixed", NULL },
473 { SkPaint::kNone_FilterLevel, "None", "F0 " },
474 { SkPaint::kLow_FilterLevel, "Low", "F1 " },
475 { SkPaint::kMedium_FilterLevel, "Medium", "F2 " },
476 { SkPaint::kHigh_FilterLevel, "High", "F3 " },
479 class FlagsDrawFilter : public SkDrawFilter {
481 FlagsDrawFilter(SkOSMenu::TriState lcd, SkOSMenu::TriState aa,
482 SkOSMenu::TriState subpixel, int hinting, int filterlevel)
485 , fSubpixelState(subpixel)
486 , fHintingState(hinting)
487 , fFilterLevelIndex(filterlevel)
489 SkASSERT((unsigned)filterlevel < SK_ARRAY_COUNT(gFilterLevelStates));
492 virtual bool filter(SkPaint* paint, Type t) {
493 if (kText_Type == t && SkOSMenu::kMixedState != fLCDState) {
494 paint->setLCDRenderText(SkOSMenu::kOnState == fLCDState);
496 if (SkOSMenu::kMixedState != fAAState) {
497 paint->setAntiAlias(SkOSMenu::kOnState == fAAState);
499 if (0 != fFilterLevelIndex) {
500 paint->setFilterLevel(gFilterLevelStates[fFilterLevelIndex].fLevel);
502 if (SkOSMenu::kMixedState != fSubpixelState) {
503 paint->setSubpixelText(SkOSMenu::kOnState == fSubpixelState);
505 if (0 != fHintingState && fHintingState < (int)SK_ARRAY_COUNT(gHintingStates)) {
506 paint->setHinting(gHintingStates[fHintingState].hinting);
512 SkOSMenu::TriState fLCDState;
513 SkOSMenu::TriState fAAState;
514 SkOSMenu::TriState fSubpixelState;
516 int fFilterLevelIndex;
519 //////////////////////////////////////////////////////////////////////////////
521 #define MAX_ZOOM_LEVEL 8
522 #define MIN_ZOOM_LEVEL -8
524 static const char gCharEvtName[] = "SampleCode_Char_Event";
525 static const char gKeyEvtName[] = "SampleCode_Key_Event";
526 static const char gTitleEvtName[] = "SampleCode_Title_Event";
527 static const char gPrefSizeEvtName[] = "SampleCode_PrefSize_Event";
528 static const char gFastTextEvtName[] = "SampleCode_FastText_Event";
529 static const char gUpdateWindowTitleEvtName[] = "SampleCode_UpdateWindowTitle";
531 bool SampleCode::CharQ(const SkEvent& evt, SkUnichar* outUni) {
532 if (evt.isType(gCharEvtName, sizeof(gCharEvtName) - 1)) {
534 *outUni = evt.getFast32();
541 bool SampleCode::KeyQ(const SkEvent& evt, SkKey* outKey) {
542 if (evt.isType(gKeyEvtName, sizeof(gKeyEvtName) - 1)) {
544 *outKey = (SkKey)evt.getFast32();
551 bool SampleCode::TitleQ(const SkEvent& evt) {
552 return evt.isType(gTitleEvtName, sizeof(gTitleEvtName) - 1);
555 void SampleCode::TitleR(SkEvent* evt, const char title[]) {
556 SkASSERT(evt && TitleQ(*evt));
557 evt->setString(gTitleEvtName, title);
560 bool SampleCode::RequestTitle(SkView* view, SkString* title) {
561 SkEvent evt(gTitleEvtName);
562 if (view->doQuery(&evt)) {
563 title->set(evt.findString(gTitleEvtName));
569 bool SampleCode::PrefSizeQ(const SkEvent& evt) {
570 return evt.isType(gPrefSizeEvtName, sizeof(gPrefSizeEvtName) - 1);
573 void SampleCode::PrefSizeR(SkEvent* evt, SkScalar width, SkScalar height) {
574 SkASSERT(evt && PrefSizeQ(*evt));
578 evt->setScalars(gPrefSizeEvtName, 2, size);
581 bool SampleCode::FastTextQ(const SkEvent& evt) {
582 return evt.isType(gFastTextEvtName, sizeof(gFastTextEvtName) - 1);
585 ///////////////////////////////////////////////////////////////////////////////
587 static SkMSec gAnimTime;
588 static SkMSec gAnimTimePrev;
590 SkMSec SampleCode::GetAnimTime() { return gAnimTime; }
591 SkMSec SampleCode::GetAnimTimeDelta() { return gAnimTime - gAnimTimePrev; }
592 SkScalar SampleCode::GetAnimSecondsDelta() {
593 return SkDoubleToScalar(GetAnimTimeDelta() / 1000.0);
596 SkScalar SampleCode::GetAnimScalar(SkScalar speed, SkScalar period) {
597 // since gAnimTime can be up to 32 bits, we can't convert it to a float
598 // or we'll lose the low bits. Hence we use doubles for the intermediate
600 double seconds = (double)gAnimTime / 1000.0;
601 double value = SkScalarToDouble(speed) * seconds;
603 value = ::fmod(value, SkScalarToDouble(period));
605 return SkDoubleToScalar(value);
608 SkScalar SampleCode::GetAnimSinScalar(SkScalar amplitude,
609 SkScalar periodInSec,
610 SkScalar phaseInSec) {
614 double t = (double)gAnimTime / 1000.0 + phaseInSec;
615 t *= SkScalarToFloat(2 * SK_ScalarPI) / periodInSec;
616 amplitude = SK_ScalarHalf * amplitude;
617 return SkScalarMul(amplitude, SkDoubleToScalar(sin(t))) + amplitude;
628 kLast_TilingMode_Enum
636 static const struct TilingInfo gTilingInfo[] = {
637 { "No tiling", SK_Scalar1 , SK_Scalar1 }, // kNo_Tiling
638 { "128x128" , SkIntToScalar(128), SkIntToScalar(128) }, // kAbs_128x128_Tiling
639 { "256x256" , SkIntToScalar(256), SkIntToScalar(256) }, // kAbs_256x256_Tiling
640 { "1/4x1/4" , SK_Scalar1 / 4 , SK_Scalar1 / 4 }, // kRel_4x4_Tiling
641 { "1/1x1/16" , SK_Scalar1 , SK_Scalar1 / 16 }, // kRel_1x16_Tiling
642 { "1/16x1/1" , SK_Scalar1 / 16 , SK_Scalar1 }, // kRel_16x1_Tiling
644 SK_COMPILE_ASSERT((SK_ARRAY_COUNT(gTilingInfo) == kLast_TilingMode_Enum),
645 Incomplete_tiling_labels);
647 SkSize SampleWindow::tileSize() const {
648 SkASSERT((TilingMode)fTilingMode < kLast_TilingMode_Enum);
649 const struct TilingInfo* info = gTilingInfo + fTilingMode;
650 return SkSize::Make(info->w > SK_Scalar1 ? info->w : this->width() * info->w,
651 info->h > SK_Scalar1 ? info->h : this->height() * info->h);
653 //////////////////////////////////////////////////////////////////////////////
655 static SkView* curr_view(SkWindow* wind) {
656 SkView::F2BIter iter(wind);
660 static bool curr_title(SkWindow* wind, SkString* title) {
661 SkView* view = curr_view(wind);
663 SkEvent evt(gTitleEvtName);
664 if (view->doQuery(&evt)) {
665 title->set(evt.findString(gTitleEvtName));
672 void SampleWindow::setZoomCenter(float x, float y)
678 bool SampleWindow::zoomIn()
680 // Arbitrarily decided
681 if (fFatBitsScale == 25) return false;
687 bool SampleWindow::zoomOut()
689 if (fFatBitsScale == 1) return false;
695 void SampleWindow::updatePointer(int x, int y)
704 static inline SampleWindow::DeviceType cycle_devicetype(SampleWindow::DeviceType ct) {
705 static const SampleWindow::DeviceType gCT[] = {
706 SampleWindow::kPicture_DeviceType,
708 SampleWindow::kGPU_DeviceType,
710 SampleWindow::kANGLE_DeviceType,
712 SampleWindow::kRaster_DeviceType, // skip the null gpu device in normal cycling
713 #endif // SK_SUPPORT_GPU
714 SampleWindow::kRaster_DeviceType
716 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gCT) == SampleWindow::kDeviceTypeCnt, array_size_mismatch);
720 static SkString getSampleTitle(const SkViewFactory* sampleFactory) {
721 SkView* view = (*sampleFactory)();
723 SampleCode::RequestTitle(view, &title);
728 static bool compareSampleTitle(const SkViewFactory* first, const SkViewFactory* second) {
729 return strcmp(getSampleTitle(first).c_str(), getSampleTitle(second).c_str()) < 0;
732 DEFINE_string(slide, "", "Start on this sample.");
733 DEFINE_int32(msaa, 0, "Request multisampling with this count.");
734 DEFINE_string(pictureDir, "", "Read pictures from here.");
735 DEFINE_string(picture, "", "Path to single picture.");
736 DEFINE_bool(sort, false, "Sort samples by title.");
737 DEFINE_bool(list, false, "List samples?");
738 #ifdef SAMPLE_PDF_FILE_VIEWER
739 DEFINE_string(pdfPath, "", "Path to direcotry of pdf files.");
742 SampleWindow::SampleWindow(void* hwnd, int argc, char** argv, DeviceManager* devManager)
744 , fDevManager(NULL) {
746 SkCommandLineFlags::Parse(argc, argv);
750 if (!FLAGS_pictureDir.isEmpty()) {
751 SkOSFile::Iter iter(FLAGS_pictureDir[0], "skp");
753 while (iter.next(&filename)) {
754 *fSamples.append() = new PictFileFactory(
755 SkOSPath::Join(FLAGS_pictureDir[0], filename.c_str()));
758 if (!FLAGS_picture.isEmpty()) {
759 SkString path(FLAGS_picture[0]);
760 fCurrIndex = fSamples.count();
761 *fSamples.append() = new PictFileFactory(path);
763 #ifdef SAMPLE_PDF_FILE_VIEWER
764 if (!FLAGS_pdfPath.isEmpty()) {
765 SkOSFile::Iter iter(FLAGS_pdfPath[0], "pdf");
767 while (iter.next(&filename)) {
768 *fSamples.append() = new PdfFileViewerFactory(
769 SkOSPath::Join(FLAGS_pictureDir[0], filename.c_str()));
773 SkGMRegistyToSampleRegistry();
775 const SkViewRegister* reg = SkViewRegister::Head();
777 *fSamples.append() = reg->factory();
783 // Sort samples, so foo.skp and foo.pdf are consecutive and we can quickly spot where
784 // skp -> pdf -> png fails.
785 SkTQSort(fSamples.begin(), fSamples.end() ? fSamples.end() - 1 : NULL, compareSampleTitle);
788 if (!FLAGS_slide.isEmpty()) {
789 fCurrIndex = findByTitle(FLAGS_slide[0]);
790 if (fCurrIndex < 0) {
791 fprintf(stderr, "Unknown sample \"%s\"\n", FLAGS_slide[0]);
796 fMSAASampleCount = FLAGS_msaa;
802 if (fCurrIndex < 0) {
804 if (readTitleFromPrefs(&title)) {
805 fCurrIndex = findByTitle(title.c_str());
809 if (fCurrIndex < 0) {
813 gSampleWindow = this;
816 //Clear existing file or create file if it doesn't exist
817 FILE* f = fopen(FILE_PATH, "wb");
821 fDeviceType = kRaster_DeviceType;
824 fDeviceType = kGPU_DeviceType;
826 #if SK_ANGLE && DEFAULT_TO_ANGLE
827 fDeviceType = kANGLE_DeviceType;
837 fRequestGrabImage = false;
838 fPipeState = SkOSMenu::kOffState;
839 fTilingMode = kNo_Tiling;
841 fLCDState = SkOSMenu::kMixedState;
842 fAAState = SkOSMenu::kMixedState;
843 fSubpixelState = SkOSMenu::kMixedState;
845 fFilterLevelIndex = 0;
847 fScrollTestX = fScrollTestY = 0;
849 fMouseX = fMouseY = 0;
851 fTypeface = SkTypeface::CreateFromTypeface(NULL, SkTypeface::kBold);
855 fZoomScale = SK_Scalar1;
865 int sinkID = this->getSinkID();
866 fAppMenu = new SkOSMenu;
867 fAppMenu->setTitle("Global Settings");
870 itemID =fAppMenu->appendList("Device Type", "Device Type", sinkID, 0,
871 "Raster", "Picture", "OpenGL",
876 fAppMenu->assignKeyEquivalentToItem(itemID, 'd');
877 itemID = fAppMenu->appendTriState("AA", "AA", sinkID, fAAState);
878 fAppMenu->assignKeyEquivalentToItem(itemID, 'b');
879 itemID = fAppMenu->appendTriState("LCD", "LCD", sinkID, fLCDState);
880 fAppMenu->assignKeyEquivalentToItem(itemID, 'l');
881 itemID = fAppMenu->appendList("FilterLevel", "FilterLevel", sinkID, fFilterLevelIndex,
882 gFilterLevelStates[0].fName,
883 gFilterLevelStates[1].fName,
884 gFilterLevelStates[2].fName,
885 gFilterLevelStates[3].fName,
886 gFilterLevelStates[4].fName,
888 fAppMenu->assignKeyEquivalentToItem(itemID, 'n');
889 itemID = fAppMenu->appendTriState("Subpixel", "Subpixel", sinkID, fSubpixelState);
890 fAppMenu->assignKeyEquivalentToItem(itemID, 's');
891 itemID = fAppMenu->appendList("Hinting", "Hinting", sinkID, fHintingState,
892 gHintingStates[0].name,
893 gHintingStates[1].name,
894 gHintingStates[2].name,
895 gHintingStates[3].name,
896 gHintingStates[4].name,
898 fAppMenu->assignKeyEquivalentToItem(itemID, 'h');
900 fUsePipeMenuItemID = fAppMenu->appendTriState("Pipe", "Pipe" , sinkID,
902 fAppMenu->assignKeyEquivalentToItem(fUsePipeMenuItemID, 'P');
904 itemID =fAppMenu->appendList("Tiling", "Tiling", sinkID, fTilingMode,
905 gTilingInfo[kNo_Tiling].label,
906 gTilingInfo[kAbs_128x128_Tiling].label,
907 gTilingInfo[kAbs_256x256_Tiling].label,
908 gTilingInfo[kRel_4x4_Tiling].label,
909 gTilingInfo[kRel_1x16_Tiling].label,
910 gTilingInfo[kRel_16x1_Tiling].label,
912 fAppMenu->assignKeyEquivalentToItem(itemID, 't');
914 itemID = fAppMenu->appendSwitch("Slide Show", "Slide Show" , sinkID, false);
915 fAppMenu->assignKeyEquivalentToItem(itemID, 'a');
916 itemID = fAppMenu->appendSwitch("Clip", "Clip" , sinkID, fUseClip);
917 fAppMenu->assignKeyEquivalentToItem(itemID, 'c');
918 itemID = fAppMenu->appendSwitch("Flip X", "Flip X" , sinkID, false);
919 fAppMenu->assignKeyEquivalentToItem(itemID, 'x');
920 itemID = fAppMenu->appendSwitch("Flip Y", "Flip Y" , sinkID, false);
921 fAppMenu->assignKeyEquivalentToItem(itemID, 'y');
922 itemID = fAppMenu->appendSwitch("Zoomer", "Zoomer" , sinkID, fShowZoomer);
923 fAppMenu->assignKeyEquivalentToItem(itemID, 'z');
924 itemID = fAppMenu->appendSwitch("Magnify", "Magnify" , sinkID, fMagnify);
925 fAppMenu->assignKeyEquivalentToItem(itemID, 'm');
926 itemID =fAppMenu->appendList("Transition-Next", "Transition-Next", sinkID,
927 fTransitionNext, "Up", "Up and Right", "Right",
928 "Down and Right", "Down", "Down and Left",
929 "Left", "Up and Left", NULL);
930 fAppMenu->assignKeyEquivalentToItem(itemID, 'j');
931 itemID =fAppMenu->appendList("Transition-Prev", "Transition-Prev", sinkID,
932 fTransitionPrev, "Up", "Up and Right", "Right",
933 "Down and Right", "Down", "Down and Left",
934 "Left", "Up and Left", NULL);
935 fAppMenu->assignKeyEquivalentToItem(itemID, 'k');
936 itemID = fAppMenu->appendAction("Save to PDF", sinkID);
937 fAppMenu->assignKeyEquivalentToItem(itemID, 'e');
939 this->addMenu(fAppMenu);
940 fSlideMenu = new SkOSMenu;
941 this->addMenu(fSlideMenu);
943 this->setColorType(kN32_SkColorType);
944 this->setVisibleP(true);
945 this->setClipToBounds(false);
947 this->loadView((*fSamples[fCurrIndex])());
951 if (NULL == devManager) {
952 fDevManager = new DefaultDeviceManager();
955 fDevManager = devManager;
957 fDevManager->setUpBackend(this, fMSAASampleCount);
959 // If another constructor set our dimensions, ensure that our
960 // onSizeChange gets called.
961 if (this->height() && this->width()) {
962 this->onSizeChange();
965 // can't call this synchronously, since it may require a subclass to
966 // to implement, or the caller may need us to have returned from the
967 // constructor first. Hence we post an event to ourselves.
968 // this->updateTitle();
969 post_event_to_sink(new SkEvent(gUpdateWindowTitleEvtName), this);
972 SampleWindow::~SampleWindow() {
974 SkSafeUnref(fTypeface);
975 SkSafeUnref(fDevManager);
979 int SampleWindow::findByTitle(const char title[]) {
980 int i, count = fSamples.count();
981 for (i = 0; i < count; i++) {
982 if (getSampleTitle(i).equals(title)) {
989 void SampleWindow::listTitles() {
990 int count = fSamples.count();
991 SkDebugf("All Slides:\n");
992 for (int i = 0; i < count; i++) {
993 SkDebugf(" %s\n", getSampleTitle(i).c_str());
997 static SkBitmap capture_bitmap(SkCanvas* canvas) {
999 if (bm.tryAllocPixels(canvas->imageInfo())) {
1000 canvas->readPixels(&bm, 0, 0);
1005 static bool bitmap_diff(SkCanvas* canvas, const SkBitmap& orig,
1007 SkBitmap src = capture_bitmap(canvas);
1009 SkAutoLockPixels alp0(src);
1010 SkAutoLockPixels alp1(orig);
1011 for (int y = 0; y < src.height(); y++) {
1012 const void* srcP = src.getAddr(0, y);
1013 const void* origP = orig.getAddr(0, y);
1014 size_t bytes = src.width() * src.bytesPerPixel();
1015 if (memcmp(srcP, origP, bytes)) {
1016 SkDebugf("---------- difference on line %d\n", y);
1023 static void drawText(SkCanvas* canvas, SkString string, SkScalar left, SkScalar top, SkPaint& paint)
1025 SkColor desiredColor = paint.getColor();
1026 paint.setColor(SK_ColorWHITE);
1027 const char* c_str = string.c_str();
1028 size_t size = string.size();
1030 paint.measureText(c_str, size, &bounds);
1031 bounds.offset(left, top);
1032 SkScalar inset = SkIntToScalar(-2);
1033 bounds.inset(inset, inset);
1034 canvas->drawRect(bounds, paint);
1035 if (desiredColor != SK_ColorBLACK) {
1036 paint.setColor(SK_ColorBLACK);
1037 canvas->drawText(c_str, size, left + SK_Scalar1, top + SK_Scalar1, paint);
1039 paint.setColor(desiredColor);
1040 canvas->drawText(c_str, size, left, top, paint);
1046 void SampleWindow::draw(SkCanvas* canvas) {
1047 // update the animation time
1048 if (!gAnimTimePrev && !gAnimTime) {
1049 // first time make delta be 0
1050 gAnimTime = SkTime::GetMSecs();
1051 gAnimTimePrev = gAnimTime;
1053 gAnimTimePrev = gAnimTime;
1054 gAnimTime = SkTime::GetMSecs();
1057 if (fGesture.isActive()) {
1058 this->updateMatrix();
1062 fMeasureFPS_Time = 0;
1066 this->INHERITED::draw(canvas);
1067 SkBitmap orig = capture_bitmap(canvas);
1069 const SkScalar w = this->width();
1070 const SkScalar h = this->height();
1071 const SkScalar cw = w / XCLIP_N;
1072 const SkScalar ch = h / YCLIP_N;
1073 for (int y = 0; y < YCLIP_N; y++) {
1076 r.fBottom = (y + 1) * ch;
1077 if (y == YCLIP_N - 1) {
1080 for (int x = 0; x < XCLIP_N; x++) {
1081 SkAutoCanvasRestore acr(canvas, true);
1083 r.fRight = (x + 1) * cw;
1084 if (x == XCLIP_N - 1) {
1087 canvas->clipRect(r);
1088 this->INHERITED::draw(canvas);
1093 if (bitmap_diff(canvas, orig, &diff)) {
1096 SkSize tile = this->tileSize();
1098 if (kNo_Tiling == fTilingMode) {
1099 this->INHERITED::draw(canvas); // no looping or surfaces needed
1101 const int w = SkScalarRoundToInt(tile.width());
1102 const int h = SkScalarRoundToInt(tile.height());
1103 SkImageInfo info = SkImageInfo::MakeN32Premul(w, h);
1104 SkAutoTUnref<SkSurface> surface(canvas->newSurface(info));
1105 SkCanvas* tileCanvas = surface->getCanvas();
1107 for (SkScalar y = 0; y < height(); y += tile.height()) {
1108 for (SkScalar x = 0; x < width(); x += tile.width()) {
1109 SkAutoCanvasRestore acr(tileCanvas, true);
1110 tileCanvas->translate(-x, -y);
1111 tileCanvas->clear(0);
1112 this->INHERITED::draw(tileCanvas);
1113 surface->draw(canvas, x, y, NULL);
1117 // for drawing the borders between tiles
1119 paint.setColor(0x60FF00FF);
1120 paint.setStyle(SkPaint::kStroke_Style);
1122 for (SkScalar y = 0; y < height(); y += tile.height()) {
1123 for (SkScalar x = 0; x < width(); x += tile.width()) {
1124 canvas->drawRect(SkRect::MakeXYWH(x, y, tile.width(), tile.height()), paint);
1129 if (fShowZoomer && !fSaveToPdf) {
1132 if (fMagnify && !fSaveToPdf) {
1136 if (fMeasureFPS && fMeasureFPS_Time) {
1137 this->updateTitle();
1138 this->postInvalDelay();
1142 fDevManager->publishCanvas(fDeviceType, canvas, this);
1145 static float clipW = 200;
1146 static float clipH = 200;
1147 void SampleWindow::magnify(SkCanvas* canvas) {
1149 int count = canvas->save();
1151 SkMatrix m = canvas->getTotalMatrix();
1152 if (!m.invert(&m)) {
1155 SkPoint offset, center;
1156 SkScalar mouseX = fMouseX * SK_Scalar1;
1157 SkScalar mouseY = fMouseY * SK_Scalar1;
1158 m.mapXY(mouseX - clipW/2, mouseY - clipH/2, &offset);
1159 m.mapXY(mouseX, mouseY, ¢er);
1161 r.set(0, 0, clipW * m.getScaleX(), clipH * m.getScaleX());
1162 r.offset(offset.fX, offset.fY);
1165 paint.setColor(0xFF66AAEE);
1166 paint.setStyle(SkPaint::kStroke_Style);
1167 paint.setStrokeWidth(10.f * m.getScaleX());
1169 //canvas->translate(0, -250);
1170 canvas->drawRect(r, paint);
1171 canvas->clipRect(r);
1173 m = canvas->getTotalMatrix();
1174 m.setTranslate(-center.fX, -center.fY);
1175 m.postScale(0.5f * fFatBitsScale, 0.5f * fFatBitsScale);
1176 m.postTranslate(center.fX, center.fY);
1179 this->INHERITED::draw(canvas);
1181 canvas->restoreToCount(count);
1184 void SampleWindow::showZoomer(SkCanvas* canvas) {
1185 int count = canvas->save();
1186 canvas->resetMatrix();
1187 // Ensure the mouse position is on screen.
1188 int width = SkScalarRoundToInt(this->width());
1189 int height = SkScalarRoundToInt(this->height());
1190 if (fMouseX >= width) fMouseX = width - 1;
1191 else if (fMouseX < 0) fMouseX = 0;
1192 if (fMouseY >= height) fMouseY = height - 1;
1193 else if (fMouseY < 0) fMouseY = 0;
1195 SkBitmap bitmap = capture_bitmap(canvas);
1196 bitmap.lockPixels();
1198 // Find the size of the zoomed in view, forced to be odd, so the examined pixel is in the middle.
1199 int zoomedWidth = (width >> 1) | 1;
1200 int zoomedHeight = (height >> 1) | 1;
1202 src.set(0, 0, zoomedWidth / fFatBitsScale, zoomedHeight / fFatBitsScale);
1203 src.offset(fMouseX - (src.width()>>1), fMouseY - (src.height()>>1));
1205 dest.set(0, 0, SkIntToScalar(zoomedWidth), SkIntToScalar(zoomedHeight));
1206 dest.offset(SkIntToScalar(width - zoomedWidth), SkIntToScalar(height - zoomedHeight));
1208 // Clear the background behind our zoomed in view
1209 paint.setColor(SK_ColorWHITE);
1210 canvas->drawRect(dest, paint);
1211 canvas->drawBitmapRect(bitmap, &src, dest);
1212 paint.setColor(SK_ColorBLACK);
1213 paint.setStyle(SkPaint::kStroke_Style);
1214 // Draw a border around the pixel in the middle
1215 SkRect originalPixel;
1216 originalPixel.set(SkIntToScalar(fMouseX), SkIntToScalar(fMouseY), SkIntToScalar(fMouseX + 1), SkIntToScalar(fMouseY + 1));
1220 SkColor color = bitmap.getColor(fMouseX, fMouseY);
1221 if (matrix.setRectToRect(scalarSrc, dest, SkMatrix::kFill_ScaleToFit)) {
1223 matrix.mapRect(&pixel, originalPixel);
1224 // TODO Perhaps measure the values and make the outline white if it's "dark"
1225 if (color == SK_ColorBLACK) {
1226 paint.setColor(SK_ColorWHITE);
1228 canvas->drawRect(pixel, paint);
1230 paint.setColor(SK_ColorBLACK);
1231 // Draw a border around the destination rectangle
1232 canvas->drawRect(dest, paint);
1233 paint.setStyle(SkPaint::kStrokeAndFill_Style);
1234 // Identify the pixel and its color on screen
1235 paint.setTypeface(fTypeface);
1236 paint.setAntiAlias(true);
1237 SkScalar lineHeight = paint.getFontMetrics(NULL);
1239 string.appendf("(%i, %i)", fMouseX, fMouseY);
1240 SkScalar left = dest.fLeft + SkIntToScalar(3);
1241 SkScalar i = SK_Scalar1;
1242 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1246 string.appendf("A: %X", SkColorGetA(color));
1247 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1251 string.appendf("R: %X", SkColorGetR(color));
1252 paint.setColor(SK_ColorRED);
1253 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1257 string.appendf("G: %X", SkColorGetG(color));
1258 paint.setColor(SK_ColorGREEN);
1259 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1263 string.appendf("B: %X", SkColorGetB(color));
1264 paint.setColor(SK_ColorBLUE);
1265 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1266 canvas->restoreToCount(count);
1269 void SampleWindow::onDraw(SkCanvas* canvas) {
1272 #include "SkColorPriv.h"
1274 void SampleWindow::saveToPdf()
1280 SkCanvas* SampleWindow::beforeChildren(SkCanvas* canvas) {
1282 const SkBitmap bmp = capture_bitmap(canvas);
1283 SkISize size = SkISize::Make(bmp.width(), bmp.height());
1284 SkPDFDevice* pdfDevice = new SkPDFDevice(size, size,
1285 canvas->getTotalMatrix());
1286 fPdfCanvas = new SkCanvas(pdfDevice);
1288 canvas = fPdfCanvas;
1289 } else if (kPicture_DeviceType == fDeviceType) {
1290 canvas = fRecorder.beginRecording(9999, 9999, NULL, 0);
1293 if (kNullGPU_DeviceType != fDeviceType)
1296 canvas = this->INHERITED::beforeChildren(canvas);
1301 canvas->drawColor(0xFFFF88FF);
1302 canvas->clipPath(fClipPath, SkRegion::kIntersect_Op, true);
1309 void SampleWindow::afterChildren(SkCanvas* orig) {
1313 showZoomer(fPdfCanvas);
1316 name.printf("%s.pdf", this->getTitle());
1318 SkPDFDevice* device = NULL;//static_cast<SkPDFDevice*>(fPdfCanvas->getDevice());
1320 doc.appendPage(device);
1321 #ifdef SK_BUILD_FOR_ANDROID
1322 name.prepend("/sdcard/");
1325 #ifdef SK_BUILD_FOR_IOS
1326 SkDynamicMemoryWStream mstream;
1327 doc.emitPDF(&mstream);
1328 fPDFData = mstream.copyToData();
1330 SkFILEWStream stream(name.c_str());
1331 if (stream.isValid()) {
1332 doc.emitPDF(&stream);
1333 const char* desc = "File saved from Skia SampleApp";
1334 this->onPDFSaved(this->getTitle(), desc, name.c_str());
1340 // We took over the draw calls in order to create the PDF, so we need
1346 if (fRequestGrabImage) {
1347 fRequestGrabImage = false;
1349 SkBitmap bmp = capture_bitmap(orig);
1350 if (!bmp.isNull()) {
1351 static int gSampleGrabCounter;
1353 name.printf("sample_grab_%d.png", gSampleGrabCounter++);
1354 SkImageEncoder::EncodeFile(name.c_str(), bmp,
1355 SkImageEncoder::kPNG_Type, 100);
1359 if (kPicture_DeviceType == fDeviceType) {
1360 SkAutoTUnref<const SkPicture> picture(fRecorder.endRecording());
1363 this->installDrawFilter(orig);
1364 orig->drawPicture(picture);
1366 SkDynamicMemoryWStream ostream;
1367 picture->serialize(&ostream);
1369 SkAutoDataUnref data(ostream.copyToData());
1370 SkMemoryStream istream(data->data(), data->size());
1371 SkAutoTUnref<SkPicture> pict(SkPicture::CreateFromStream(&istream));
1372 if (pict.get() != NULL) {
1373 orig->drawPicture(pict.get());
1376 picture->playback(orig);
1380 // Do this after presentGL and other finishing, rather than in afterChild
1381 if (fMeasureFPS && fMeasureFPS_StartTime) {
1382 fMeasureFPS_Time += SkTime::GetMSecs() - fMeasureFPS_StartTime;
1386 void SampleWindow::beforeChild(SkView* child, SkCanvas* canvas) {
1388 fRotateAnimTime += SampleCode::GetAnimSecondsDelta();
1390 SkScalar cx = this->width() / 2;
1391 SkScalar cy = this->height() / 2;
1392 canvas->translate(cx, cy);
1393 canvas->rotate(fRotateAnimTime * 10);
1394 canvas->translate(-cx, -cy);
1398 fPerspAnimTime += SampleCode::GetAnimSecondsDelta();
1400 static const SkScalar gAnimPeriod = 10 * SK_Scalar1;
1401 static const SkScalar gAnimMag = SK_Scalar1 / 1000;
1402 SkScalar t = SkScalarMod(fPerspAnimTime, gAnimPeriod);
1403 if (SkScalarFloorToInt(SkScalarDiv(fPerspAnimTime, gAnimPeriod)) & 0x1) {
1404 t = gAnimPeriod - t;
1406 t = 2 * t - gAnimPeriod;
1407 t = SkScalarMul(SkScalarDiv(t, gAnimPeriod), gAnimMag);
1413 m.setPerspY(SK_Scalar1 / 1000);
1414 m.setSkewX(SkScalarDiv(8, 25));
1420 this->installDrawFilter(canvas);
1423 if (SampleView::SetRepeatDraw(child, FPS_REPEAT_COUNT)) {
1424 fMeasureFPS_StartTime = SkTime::GetMSecs();
1427 (void)SampleView::SetRepeatDraw(child, 1);
1429 if (fPerspAnim || fRotate) {
1434 void SampleWindow::afterChild(SkView* child, SkCanvas* canvas) {
1435 canvas->setDrawFilter(NULL);
1438 static SkColorType gColorTypeCycle[] = {
1439 kUnknown_SkColorType, // none -> none
1440 kUnknown_SkColorType, // a8 -> none
1441 kN32_SkColorType, // 565 -> 8888
1442 kN32_SkColorType, // 4444 -> 8888
1443 kRGB_565_SkColorType, // 8888 -> 565
1444 kRGB_565_SkColorType, // 8888 -> 565
1445 kUnknown_SkColorType, // index8 -> none
1448 static SkColorType cycle_colortypes(SkColorType c) {
1449 return gColorTypeCycle[c];
1452 void SampleWindow::changeZoomLevel(float delta) {
1453 fZoomLevel += delta;
1454 if (fZoomLevel > 0) {
1455 fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL);
1456 fZoomScale = fZoomLevel + SK_Scalar1;
1457 } else if (fZoomLevel < 0) {
1458 fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL);
1459 fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel);
1461 fZoomScale = SK_Scalar1;
1463 this->updateMatrix();
1466 void SampleWindow::updateMatrix(){
1471 //m = this->getLocalMatrix();//.invert(&m);
1472 m.mapXY(fZoomCenterX, fZoomCenterY, ¢er);
1473 SkScalar cx = center.fX;
1474 SkScalar cy = center.fY;
1476 m.setTranslate(-cx, -cy);
1477 m.postScale(fZoomScale, fZoomScale);
1478 m.postTranslate(cx, cy);
1482 m.preTranslate(fZoomCenterX, fZoomCenterY);
1483 if (fFlipAxis & kFlipAxis_X) {
1484 m.preScale(-SK_Scalar1, SK_Scalar1);
1486 if (fFlipAxis & kFlipAxis_Y) {
1487 m.preScale(SK_Scalar1, -SK_Scalar1);
1489 m.preTranslate(-fZoomCenterX, -fZoomCenterY);
1490 //canvas->concat(m);
1492 // Apply any gesture matrix
1493 m.preConcat(fGesture.localM());
1494 m.preConcat(fGesture.globalM());
1496 this->setLocalMatrix(m);
1498 this->updateTitle();
1501 bool SampleWindow::previousSample() {
1502 fCurrIndex = (fCurrIndex - 1 + fSamples.count()) % fSamples.count();
1503 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(),
1508 bool SampleWindow::nextSample() {
1509 fCurrIndex = (fCurrIndex + 1) % fSamples.count();
1510 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(),
1515 bool SampleWindow::goToSample(int i) {
1516 fCurrIndex = (i) % fSamples.count();
1517 this->loadView(create_transition(curr_view(this),(*fSamples[fCurrIndex])(), 6));
1521 SkString SampleWindow::getSampleTitle(int i) {
1522 return ::getSampleTitle(fSamples[i]);
1525 int SampleWindow::sampleCount() {
1526 return fSamples.count();
1529 void SampleWindow::showOverview() {
1530 this->loadView(create_transition(curr_view(this),
1531 create_overview(fSamples.count(), fSamples.begin()),
1535 void SampleWindow::installDrawFilter(SkCanvas* canvas) {
1536 canvas->setDrawFilter(new FlagsDrawFilter(fLCDState, fAAState, fSubpixelState,
1537 fHintingState, fFilterLevelIndex))->unref();
1540 void SampleWindow::postAnimatingEvent() {
1542 (new SkEvent(ANIMATING_EVENTTYPE, this->getSinkID()))->postDelay(ANIMATING_DELAY);
1546 bool SampleWindow::onEvent(const SkEvent& evt) {
1547 if (evt.isType(gUpdateWindowTitleEvtName)) {
1548 this->updateTitle();
1551 if (evt.isType(ANIMATING_EVENTTYPE)) {
1554 this->postAnimatingEvent();
1558 if (evt.isType("replace-transition-view")) {
1559 this->loadView((SkView*)SkEventSink::FindSink(evt.getFast32()));
1562 if (evt.isType("set-curr-index")) {
1563 this->goToSample(evt.getFast32());
1566 if (isInvalEvent(evt)) {
1571 if (SkOSMenu::FindListIndex(evt, "Device Type", &selected)) {
1572 this->setDeviceType((DeviceType)selected);
1575 if (SkOSMenu::FindTriState(evt, "Pipe", &fPipeState)) {
1577 if (!fPipeState != SkOSMenu::kOnState)
1578 gServer.disconnectAll();
1580 (void)SampleView::SetUsePipe(curr_view(this), fPipeState);
1581 this->updateTitle();
1585 if (SkOSMenu::FindSwitchState(evt, "Slide Show", NULL)) {
1586 this->toggleSlideshow();
1589 if (SkOSMenu::FindTriState(evt, "AA", &fAAState) ||
1590 SkOSMenu::FindTriState(evt, "LCD", &fLCDState) ||
1591 SkOSMenu::FindListIndex(evt, "FilterLevel", &fFilterLevelIndex) ||
1592 SkOSMenu::FindTriState(evt, "Subpixel", &fSubpixelState) ||
1593 SkOSMenu::FindListIndex(evt, "Hinting", &fHintingState) ||
1594 SkOSMenu::FindSwitchState(evt, "Clip", &fUseClip) ||
1595 SkOSMenu::FindSwitchState(evt, "Zoomer", &fShowZoomer) ||
1596 SkOSMenu::FindSwitchState(evt, "Magnify", &fMagnify) ||
1597 SkOSMenu::FindListIndex(evt, "Transition-Next", &fTransitionNext) ||
1598 SkOSMenu::FindListIndex(evt, "Transition-Prev", &fTransitionPrev)) {
1600 this->updateTitle();
1603 if (SkOSMenu::FindListIndex(evt, "Tiling", &fTilingMode)) {
1604 if (SampleView::IsSampleView(curr_view(this))) {
1605 ((SampleView*)curr_view(this))->onTileSizeChanged(this->tileSize());
1608 this->updateTitle();
1611 if (SkOSMenu::FindSwitchState(evt, "Flip X", NULL)) {
1612 fFlipAxis ^= kFlipAxis_X;
1613 this->updateMatrix();
1616 if (SkOSMenu::FindSwitchState(evt, "Flip Y", NULL)) {
1617 fFlipAxis ^= kFlipAxis_Y;
1618 this->updateMatrix();
1621 if (SkOSMenu::FindAction(evt,"Save to PDF")) {
1625 return this->INHERITED::onEvent(evt);
1628 bool SampleWindow::onQuery(SkEvent* query) {
1629 if (query->isType("get-slide-count")) {
1630 query->setFast32(fSamples.count());
1633 if (query->isType("get-slide-title")) {
1634 SkView* view = (*fSamples[query->getFast32()])();
1635 SkEvent evt(gTitleEvtName);
1636 if (view->doQuery(&evt)) {
1637 query->setString("title", evt.findString(gTitleEvtName));
1642 if (query->isType("use-fast-text")) {
1643 SkEvent evt(gFastTextEvtName);
1644 return curr_view(this)->doQuery(&evt);
1646 if (query->isType("ignore-window-bitmap")) {
1647 query->setFast32(this->getGrContext() != NULL);
1650 return this->INHERITED::onQuery(query);
1654 static void cleanup_for_filename(SkString* name) {
1655 char* str = name->writable_str();
1656 for (size_t i = 0; i < name->size(); i++) {
1658 case ':': str[i] = '-'; break;
1659 case '/': str[i] = '-'; break;
1660 case ' ': str[i] = '_'; break;
1667 DECLARE_bool(portableFonts);
1669 bool SampleWindow::onHandleChar(SkUnichar uni) {
1671 SkView* view = curr_view(this);
1673 SkEvent evt(gCharEvtName);
1675 if (view->doQuery(&evt)) {
1685 case '5': dx = 0; dy = 0; break;
1686 case '8': dx = 0; dy = -1; break;
1687 case '6': dx = 1; dy = 0; break;
1688 case '2': dx = 0; dy = 1; break;
1689 case '4': dx = -1; dy = 0; break;
1690 case '7': dx = -1; dy = -1; break;
1691 case '9': dx = 1; dy = -1; break;
1692 case '3': dx = 1; dy = 1; break;
1693 case '1': dx = -1; dy = 1; break;
1699 if (0xFF != dx && 0xFF != dy) {
1700 if ((dx | dy) == 0) {
1701 fScrollTestX = fScrollTestY = 0;
1712 post_event_to_sink(SkNEW_ARGS(SkEvent, ("PictFileView::toggleBBox")), curr_view(this));
1713 // Cannot call updateTitle() synchronously, because the toggleBBox event is still in
1715 post_event_to_sink(SkNEW_ARGS(SkEvent, (gUpdateWindowTitleEvtName)), this);
1723 FLAGS_portableFonts ^= true;
1727 fRequestGrabImage = true;
1731 gShowGMBounds = !gShowGMBounds;
1732 post_event_to_sink(GMSampleView::NewShowSizeEvt(gShowGMBounds),
1744 fRotateAnimTime = 0;
1746 this->updateTitle();
1749 fPerspAnim = !fPerspAnim;
1751 this->updateTitle();
1755 this->setDeviceType(kNullGPU_DeviceType);
1757 this->updateTitle();
1761 GrContext* grContext = this->getGrContext();
1764 grContext->getResourceCacheUsage(NULL, &cacheBytes);
1765 grContext->freeGpuResources();
1766 SkDebugf("Purged %d bytes from the GPU resource cache.\n", cacheBytes);
1775 if (fAppMenu->handleKeyEquivalent(uni)|| fSlideMenu->handleKeyEquivalent(uni)) {
1776 this->onUpdateMenu(fAppMenu);
1777 this->onUpdateMenu(fSlideMenu);
1780 return this->INHERITED::onHandleChar(uni);
1783 void SampleWindow::setDeviceType(DeviceType type) {
1784 if (type == fDeviceType)
1787 fDevManager->tearDownBackend(this);
1791 fDevManager->setUpBackend(this, fMSAASampleCount);
1793 this->updateTitle();
1797 void SampleWindow::toggleSlideshow() {
1798 fAnimating = !fAnimating;
1799 this->postAnimatingEvent();
1800 this->updateTitle();
1803 void SampleWindow::toggleRendering() {
1804 this->setDeviceType(cycle_devicetype(fDeviceType));
1805 this->updateTitle();
1809 void SampleWindow::toggleFPS() {
1810 fMeasureFPS = !fMeasureFPS;
1811 this->updateTitle();
1815 #include "SkDumpCanvas.h"
1817 bool SampleWindow::onHandleKey(SkKey key) {
1819 SkView* view = curr_view(this);
1821 SkEvent evt(gKeyEvtName);
1823 if (view->doQuery(&evt)) {
1830 if (this->nextSample()) {
1835 if (this->previousSample()) {
1840 if (USE_ARROWS_FOR_ZOOM) {
1841 this->changeZoomLevel(1.f / 32.f);
1845 this->updateTitle();
1849 if (USE_ARROWS_FOR_ZOOM) {
1850 this->changeZoomLevel(-1.f / 32.f);
1852 this->setColorType(cycle_colortypes(this->getBitmap().colorType()));
1853 this->updateTitle();
1858 if (curr_title(this, &title)) {
1859 writeTitleToPrefs(title.c_str());
1864 this->showOverview();
1869 return this->INHERITED::onHandleKey(key);
1872 ///////////////////////////////////////////////////////////////////////////////
1874 static const char gGestureClickType[] = "GestureClickType";
1876 bool SampleWindow::onDispatchClick(int x, int y, Click::State state,
1877 void* owner, unsigned modi) {
1878 if (Click::kMoved_State == state) {
1879 updatePointer(x, y);
1881 int w = SkScalarRoundToInt(this->width());
1882 int h = SkScalarRoundToInt(this->height());
1884 // check for the resize-box
1885 if (w - x < 16 && h - y < 16) {
1886 return false; // let the OS handle the click
1888 else if (fMagnify) {
1889 //it's only necessary to update the drawing if there's a click
1891 return false; //prevent dragging while magnify is enabled
1893 // capture control+option, and trigger debugger
1894 if ((modi & kControl_SkModifierKey) && (modi & kOption_SkModifierKey)) {
1895 if (Click::kDown_State == state) {
1896 SkEvent evt("debug-hit-test");
1897 evt.setS32("debug-hit-test-x", x);
1898 evt.setS32("debug-hit-test-y", y);
1899 curr_view(this)->doEvent(evt);
1903 return this->INHERITED::onDispatchClick(x, y, state, owner, modi);
1908 class GestureClick : public SkView::Click {
1910 GestureClick(SkView* target) : SkView::Click(target) {
1911 this->setType(gGestureClickType);
1914 static bool IsGesture(Click* click) {
1915 return click->isType(gGestureClickType);
1919 SkView::Click* SampleWindow::onFindClickHandler(SkScalar x, SkScalar y,
1921 return new GestureClick(this);
1924 bool SampleWindow::onClick(Click* click) {
1925 if (GestureClick::IsGesture(click)) {
1926 float x = static_cast<float>(click->fICurr.fX);
1927 float y = static_cast<float>(click->fICurr.fY);
1929 switch (click->fState) {
1930 case SkView::Click::kDown_State:
1931 fGesture.touchBegin(click->fOwner, x, y);
1933 case SkView::Click::kMoved_State:
1934 fGesture.touchMoved(click->fOwner, x, y);
1935 this->updateMatrix();
1937 case SkView::Click::kUp_State:
1938 fGesture.touchEnd(click->fOwner);
1939 this->updateMatrix();
1947 ///////////////////////////////////////////////////////////////////////////////
1949 void SampleWindow::loadView(SkView* view) {
1950 SkView::F2BIter iter(this);
1951 SkView* prev = iter.next();
1953 prev->detachFromParent();
1956 view->setVisibleP(true);
1957 view->setClipToBounds(false);
1958 this->attachChildToFront(view)->unref();
1959 view->setSize(this->width(), this->height());
1961 //repopulate the slide menu when a view is loaded
1962 fSlideMenu->reset();
1964 (void)SampleView::SetUsePipe(view, fPipeState);
1965 if (SampleView::IsSampleView(view)) {
1966 SampleView* sampleView = (SampleView*)view;
1967 sampleView->requestMenu(fSlideMenu);
1968 sampleView->onTileSizeChanged(this->tileSize());
1970 this->onUpdateMenu(fSlideMenu);
1971 this->updateTitle();
1974 static const char* gDeviceTypePrefix[] = {
1983 #endif // SK_SUPPORT_GPU
1985 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gDeviceTypePrefix) == SampleWindow::kDeviceTypeCnt,
1986 array_size_mismatch);
1988 static const char* trystate_str(SkOSMenu::TriState state,
1989 const char trueStr[], const char falseStr[]) {
1990 if (SkOSMenu::kOnState == state) {
1992 } else if (SkOSMenu::kOffState == state) {
1998 void SampleWindow::updateTitle() {
1999 SkView* view = curr_view(this);
2002 if (!curr_title(this, &title)) {
2003 title.set("<unknown>");
2006 title.prepend(gDeviceTypePrefix[fDeviceType]);
2009 title.prepend(sk_tool_utils::colortype_name(this->getBitmap().colorType()));
2011 if (fTilingMode != kNo_Tiling) {
2012 title.prependf("<T: %s> ", gTilingInfo[fTilingMode].label);
2015 title.prepend("<A> ");
2018 title.prepend("<R> ");
2021 title.prepend("<C> ");
2024 title.prepend("<K> ");
2027 title.prepend(trystate_str(fLCDState, "LCD ", "lcd "));
2028 title.prepend(trystate_str(fAAState, "AA ", "aa "));
2029 title.prepend(gFilterLevelStates[fFilterLevelIndex].fLabel);
2030 title.prepend(trystate_str(fSubpixelState, "S ", "s "));
2031 title.prepend(fFlipAxis & kFlipAxis_X ? "X " : NULL);
2032 title.prepend(fFlipAxis & kFlipAxis_Y ? "Y " : NULL);
2033 title.prepend(gHintingStates[fHintingState].label);
2036 title.prependf("{%.2f} ", SkScalarToFloat(fZoomLevel));
2040 title.appendf(" %8.3f ms", fMeasureFPS_Time / (float)FPS_REPEAT_COUNT);
2042 if (SampleView::IsSampleView(view)) {
2043 switch (fPipeState) {
2044 case SkOSMenu::kOnState:
2045 title.prepend("<Pipe> ");
2047 case SkOSMenu::kMixedState:
2048 title.prepend("<Tiled Pipe> ");
2054 title.prepend("! ");
2058 if (IsGpuDeviceType(fDeviceType) &&
2060 fDevManager->getGrRenderTarget() &&
2061 fDevManager->getGrRenderTarget()->numSamples() > 0) {
2062 title.appendf(" [MSAA: %d]",
2063 fDevManager->getGrRenderTarget()->numSamples());
2067 this->setTitle(title.c_str());
2070 void SampleWindow::onSizeChange() {
2071 this->INHERITED::onSizeChange();
2073 SkView::F2BIter iter(this);
2074 SkView* view = iter.next();
2075 view->setSize(this->width(), this->height());
2077 // rebuild our clippath
2079 const SkScalar W = this->width();
2080 const SkScalar H = this->height();
2084 for (SkScalar y = SK_Scalar1; y < H; y += SkIntToScalar(32)) {
2086 r.set(SK_Scalar1, y, SkIntToScalar(30), y + SkIntToScalar(30));
2087 for (; r.fLeft < W; r.offset(SkIntToScalar(32), 0))
2088 fClipPath.addRect(r);
2093 fClipPath.addRect(r, SkPath::kCCW_Direction);
2094 r.set(W/4, H/4, W*3/4, H*3/4);
2095 fClipPath.addRect(r, SkPath::kCW_Direction);
2099 fZoomCenterX = SkScalarHalf(this->width());
2100 fZoomCenterY = SkScalarHalf(this->height());
2102 #ifdef SK_BUILD_FOR_ANDROID
2103 // FIXME: The first draw after a size change does not work on Android, so
2104 // we post an invalidate.
2105 this->postInvalDelay();
2107 this->updateTitle(); // to refresh our config
2108 fDevManager->windowSizeChanged(this);
2110 if (fTilingMode != kNo_Tiling && SampleView::IsSampleView(view)) {
2111 ((SampleView*)view)->onTileSizeChanged(this->tileSize());
2115 ///////////////////////////////////////////////////////////////////////////////
2117 static const char is_sample_view_tag[] = "sample-is-sample-view";
2118 static const char repeat_count_tag[] = "sample-set-repeat-count";
2119 static const char set_use_pipe_tag[] = "sample-set-use-pipe";
2121 bool SampleView::IsSampleView(SkView* view) {
2122 SkEvent evt(is_sample_view_tag);
2123 return view->doQuery(&evt);
2126 bool SampleView::SetRepeatDraw(SkView* view, int count) {
2127 SkEvent evt(repeat_count_tag);
2128 evt.setFast32(count);
2129 return view->doEvent(evt);
2132 bool SampleView::SetUsePipe(SkView* view, SkOSMenu::TriState state) {
2134 evt.setS32(set_use_pipe_tag, state);
2135 return view->doEvent(evt);
2138 bool SampleView::onEvent(const SkEvent& evt) {
2139 if (evt.isType(repeat_count_tag)) {
2140 fRepeatCount = evt.getFast32();
2145 if (evt.findS32(set_use_pipe_tag, &pipeHolder)) {
2146 fPipeState = static_cast<SkOSMenu::TriState>(pipeHolder);
2150 return this->INHERITED::onEvent(evt);
2153 bool SampleView::onQuery(SkEvent* evt) {
2154 if (evt->isType(is_sample_view_tag)) {
2157 return this->INHERITED::onQuery(evt);
2161 class SimplePC : public SkGPipeController {
2163 SimplePC(SkCanvas* target);
2166 virtual void* requestBlock(size_t minRequest, size_t* actual);
2167 virtual void notifyWritten(size_t bytes);
2170 SkGPipeReader fReader;
2173 size_t fBytesWritten;
2175 SkGPipeReader::Status fStatus;
2177 size_t fTotalWritten;
2180 SimplePC::SimplePC(SkCanvas* target) : fReader(target) {
2182 fBlockSize = fBytesWritten = 0;
2183 fStatus = SkGPipeReader::kDone_Status;
2186 fReader.setBitmapDecoder(&SkImageDecoder::DecodeMemory);
2189 SimplePC::~SimplePC() {
2190 // SkASSERT(SkGPipeReader::kDone_Status == fStatus);
2191 if (fTotalWritten) {
2192 SkDebugf("--- %d bytes %d atoms, status %d\n", fTotalWritten,
2193 fAtomsWritten, fStatus);
2195 //File is open in append mode
2196 FILE* f = fopen(FILE_PATH, "ab");
2197 SkASSERT(f != NULL);
2198 fwrite((const char*)fBlock + fBytesWritten, 1, bytes, f);
2202 if (fAtomsWritten > 1 && fTotalWritten > 4) { //ignore done
2203 gServer.acceptConnections();
2204 gServer.writePacket(fBlock, fTotalWritten);
2211 void* SimplePC::requestBlock(size_t minRequest, size_t* actual) {
2214 fBlockSize = minRequest * 4;
2215 fBlock = sk_malloc_throw(fBlockSize);
2217 *actual = fBlockSize;
2221 void SimplePC::notifyWritten(size_t bytes) {
2222 SkASSERT(fBytesWritten + bytes <= fBlockSize);
2223 fStatus = fReader.playback((const char*)fBlock + fBytesWritten, bytes);
2224 SkASSERT(SkGPipeReader::kError_Status != fStatus);
2225 fBytesWritten += bytes;
2226 fTotalWritten += bytes;
2231 void SampleView::draw(SkCanvas* canvas) {
2232 if (SkOSMenu::kOffState == fPipeState) {
2233 this->INHERITED::draw(canvas);
2235 SkGPipeWriter writer;
2236 SimplePC controller(canvas);
2237 SkBitmap bitmap = capture_bitmap(canvas);
2238 TiledPipeController tc(bitmap, &SkImageDecoder::DecodeMemory, &canvas->getTotalMatrix());
2239 SkGPipeController* pc;
2240 if (SkOSMenu::kMixedState == fPipeState) {
2245 uint32_t flags = SkGPipeWriter::kCrossProcess_Flag;
2247 canvas = writer.startRecording(pc, flags);
2248 //Must draw before controller goes out of scope and sends data
2249 this->INHERITED::draw(canvas);
2250 //explicitly end recording to ensure writer is flushed before the memory
2251 //is freed in the deconstructor of the controller
2252 writer.endRecording();
2256 void SampleView::onDraw(SkCanvas* canvas) {
2257 this->onDrawBackground(canvas);
2259 for (int i = 0; i < fRepeatCount; i++) {
2260 SkAutoCanvasRestore acr(canvas, true);
2261 this->onDrawContent(canvas);
2265 void SampleView::onDrawBackground(SkCanvas* canvas) {
2266 canvas->drawColor(fBGColor);
2269 ///////////////////////////////////////////////////////////////////////////////
2271 template <typename T> void SkTBSort(T array[], int count) {
2272 for (int i = 1; i < count - 1; i++) {
2273 bool didSwap = false;
2274 for (int j = count - 1; j > i; --j) {
2275 if (array[j] < array[j-1]) {
2277 array[j-1] = array[j];
2287 for (int k = 0; k < count - 1; k++) {
2288 SkASSERT(!(array[k+1] < array[k]));
2292 #include "SkRandom.h"
2294 static void rand_rect(SkIRect* rect, SkRandom& rand) {
2296 int shift = 32 - bits;
2297 rect->set(rand.nextU() >> shift, rand.nextU() >> shift,
2298 rand.nextU() >> shift, rand.nextU() >> shift);
2302 static void dumpRect(const SkIRect& r) {
2303 SkDebugf(" { %d, %d, %d, %d },\n",
2305 r.fRight, r.fBottom);
2308 static void test_rects(const SkIRect rect[], int count) {
2309 SkRegion rgn0, rgn1;
2311 for (int i = 0; i < count; i++) {
2312 rgn0.op(rect[i], SkRegion::kUnion_Op);
2313 // dumpRect(rect[i]);
2315 rgn1.setRects(rect, count);
2319 for (int i = 0; i < count; i++) {
2326 static void test() {
2329 const SkIRect r0[] = {
2333 const SkIRect r1[] = {
2338 const SkIRect r2[] = {
2345 static const struct {
2346 const SkIRect* fRects;
2349 { r0, SK_ARRAY_COUNT(r0) },
2350 { r1, SK_ARRAY_COUNT(r1) },
2351 { r2, SK_ARRAY_COUNT(r2) },
2354 for (i = 0; i < SK_ARRAY_COUNT(gRecs); i++) {
2355 test_rects(gRecs[i].fRects, gRecs[i].fCount);
2359 for (i = 0; i < 10000; i++) {
2360 SkRegion rgn0, rgn1;
2364 for (int j = 0; j < N; j++) {
2365 rand_rect(&rect[j], rand);
2367 test_rects(rect, N);
2371 // FIXME: this should be in a header
2372 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv);
2373 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
2374 if (false) { // avoid bit rot, suppress warning
2377 return new SampleWindow(hwnd, argc, argv, NULL);
2380 // FIXME: this should be in a header
2381 void get_preferred_size(int* x, int* y, int* width, int* height);
2382 void get_preferred_size(int* x, int* y, int* width, int* height) {
2389 #ifdef SK_BUILD_FOR_IOS
2390 IOS_launch_type set_cmd_line_args(int , char *[], const char* resourceDir) {
2391 SetResourcePath(resourceDir);
2392 return kApplication__iOSLaunchType;
2396 void application_init() {
2397 // setenv("ANDROID_ROOT", "../../../data", 0);
2398 #ifdef SK_BUILD_FOR_MAC
2399 setenv("ANDROID_ROOT", "/android/device/data", 0);
2405 void application_term() {