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 SkCanvas* createCanvas(SampleWindow::DeviceType dType,
277 if (IsGpuDeviceType(dType) && NULL != fCurContext) {
278 SkAutoTUnref<SkBaseDevice> device(new SkGpuDevice(fCurContext, fCurRenderTarget));
279 return new SkCanvas(device);
287 virtual void publishCanvas(SampleWindow::DeviceType dType,
292 // in case we have queued drawing calls
293 fCurContext->flush();
295 if (!IsGpuDeviceType(dType)) {
296 // need to send the raster bits to the (gpu) window
297 fCurContext->setRenderTarget(fCurRenderTarget);
298 const SkBitmap& bm = win->getBitmap();
299 fCurRenderTarget->writePixels(0, 0, bm.width(), bm.height(),
300 SkImageInfo2GrPixelConfig(bm.colorType(),
311 virtual void windowSizeChanged(SampleWindow* win) {
314 AttachmentInfo attachmentInfo;
315 win->attach(fBackend, fMSAASampleCount, &attachmentInfo);
317 GrBackendRenderTargetDesc desc;
318 desc.fWidth = SkScalarRoundToInt(win->width());
319 desc.fHeight = SkScalarRoundToInt(win->height());
320 desc.fConfig = kSkia8888_GrPixelConfig;
321 desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
322 desc.fSampleCnt = attachmentInfo.fSampleCount;
323 desc.fStencilBits = attachmentInfo.fStencilBits;
325 GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
326 desc.fRenderTargetHandle = buffer;
328 SkSafeUnref(fCurRenderTarget);
329 fCurRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
334 virtual GrContext* getGrContext() {
342 virtual GrRenderTarget* getGrRenderTarget() SK_OVERRIDE {
344 return fCurRenderTarget;
353 GrContext* fCurContext;
354 const GrGLInterface* fCurIntf;
355 GrRenderTarget* fCurRenderTarget;
356 int fMSAASampleCount;
359 SkOSWindow::SkBackEndTypes fBackend;
361 typedef SampleWindow::DeviceManager INHERITED;
365 static const char view_inval_msg[] = "view-inval-msg";
367 void SampleWindow::postInvalDelay() {
368 (new SkEvent(view_inval_msg, this->getSinkID()))->postDelay(1);
371 static bool isInvalEvent(const SkEvent& evt) {
372 return evt.isType(view_inval_msg);
376 SkFuncViewFactory::SkFuncViewFactory(SkViewCreateFunc func)
377 : fCreateFunc(func) {
380 SkView* SkFuncViewFactory::operator() () const {
381 return (*fCreateFunc)();
384 #include "GMSampleView.h"
386 SkGMSampleViewFactory::SkGMSampleViewFactory(GMFactoryFunc func)
390 SkView* SkGMSampleViewFactory::operator() () const {
391 skiagm::GM* gm = fFunc(NULL);
392 gm->setMode(skiagm::GM::kSample_Mode);
393 return new GMSampleView(gm);
396 SkViewRegister* SkViewRegister::gHead;
397 SkViewRegister::SkViewRegister(SkViewFactory* fact) : fFact(fact) {
403 SkViewRegister::SkViewRegister(SkViewCreateFunc func) {
404 fFact = new SkFuncViewFactory(func);
409 SkViewRegister::SkViewRegister(GMFactoryFunc func) {
410 fFact = new SkGMSampleViewFactory(func);
415 class AutoUnrefArray {
419 int count = fObjs.count();
420 for (int i = 0; i < count; ++i) {
424 SkRefCnt*& push_back() { return *fObjs.append(); }
427 SkTDArray<SkRefCnt*> fObjs;
430 // registers GMs as Samples
431 // This can't be performed during static initialization because it could be
432 // run before GMRegistry has been fully built.
433 static void SkGMRegistyToSampleRegistry() {
435 static AutoUnrefArray fRegisters;
438 const skiagm::GMRegistry* gmreg = skiagm::GMRegistry::Head();
440 fRegisters.push_back() = new SkViewRegister(gmreg->factory());
441 gmreg = gmreg->next();
447 //////////////////////////////////////////////////////////////////////////////
450 kFlipAxis_X = (1 << 0),
451 kFlipAxis_Y = (1 << 1)
454 #include "SkDrawFilter.h"
456 struct HintingState {
457 SkPaint::Hinting hinting;
461 static HintingState gHintingStates[] = {
462 {SkPaint::kNo_Hinting, "Mixed", NULL },
463 {SkPaint::kNo_Hinting, "None", "H0 " },
464 {SkPaint::kSlight_Hinting, "Slight", "Hs " },
465 {SkPaint::kNormal_Hinting, "Normal", "Hn " },
466 {SkPaint::kFull_Hinting, "Full", "Hf " },
469 struct FilterLevelState {
470 SkPaint::FilterLevel fLevel;
474 static FilterLevelState gFilterLevelStates[] = {
475 { SkPaint::kNone_FilterLevel, "Mixed", NULL },
476 { SkPaint::kNone_FilterLevel, "None", "F0 " },
477 { SkPaint::kLow_FilterLevel, "Low", "F1 " },
478 { SkPaint::kMedium_FilterLevel, "Medium", "F2 " },
479 { SkPaint::kHigh_FilterLevel, "High", "F3 " },
482 class FlagsDrawFilter : public SkDrawFilter {
484 FlagsDrawFilter(SkOSMenu::TriState lcd, SkOSMenu::TriState aa,
485 SkOSMenu::TriState subpixel, int hinting, int filterlevel)
488 , fSubpixelState(subpixel)
489 , fHintingState(hinting)
490 , fFilterLevelIndex(filterlevel)
492 SkASSERT((unsigned)filterlevel < SK_ARRAY_COUNT(gFilterLevelStates));
495 virtual bool filter(SkPaint* paint, Type t) {
496 if (kText_Type == t && SkOSMenu::kMixedState != fLCDState) {
497 paint->setLCDRenderText(SkOSMenu::kOnState == fLCDState);
499 if (SkOSMenu::kMixedState != fAAState) {
500 paint->setAntiAlias(SkOSMenu::kOnState == fAAState);
502 if (0 != fFilterLevelIndex) {
503 paint->setFilterLevel(gFilterLevelStates[fFilterLevelIndex].fLevel);
505 if (SkOSMenu::kMixedState != fSubpixelState) {
506 paint->setSubpixelText(SkOSMenu::kOnState == fSubpixelState);
508 if (0 != fHintingState && fHintingState < (int)SK_ARRAY_COUNT(gHintingStates)) {
509 paint->setHinting(gHintingStates[fHintingState].hinting);
515 SkOSMenu::TriState fLCDState;
516 SkOSMenu::TriState fAAState;
517 SkOSMenu::TriState fSubpixelState;
519 int fFilterLevelIndex;
522 //////////////////////////////////////////////////////////////////////////////
524 #define MAX_ZOOM_LEVEL 8
525 #define MIN_ZOOM_LEVEL -8
527 static const char gCharEvtName[] = "SampleCode_Char_Event";
528 static const char gKeyEvtName[] = "SampleCode_Key_Event";
529 static const char gTitleEvtName[] = "SampleCode_Title_Event";
530 static const char gPrefSizeEvtName[] = "SampleCode_PrefSize_Event";
531 static const char gFastTextEvtName[] = "SampleCode_FastText_Event";
532 static const char gUpdateWindowTitleEvtName[] = "SampleCode_UpdateWindowTitle";
534 bool SampleCode::CharQ(const SkEvent& evt, SkUnichar* outUni) {
535 if (evt.isType(gCharEvtName, sizeof(gCharEvtName) - 1)) {
537 *outUni = evt.getFast32();
544 bool SampleCode::KeyQ(const SkEvent& evt, SkKey* outKey) {
545 if (evt.isType(gKeyEvtName, sizeof(gKeyEvtName) - 1)) {
547 *outKey = (SkKey)evt.getFast32();
554 bool SampleCode::TitleQ(const SkEvent& evt) {
555 return evt.isType(gTitleEvtName, sizeof(gTitleEvtName) - 1);
558 void SampleCode::TitleR(SkEvent* evt, const char title[]) {
559 SkASSERT(evt && TitleQ(*evt));
560 evt->setString(gTitleEvtName, title);
563 bool SampleCode::RequestTitle(SkView* view, SkString* title) {
564 SkEvent evt(gTitleEvtName);
565 if (view->doQuery(&evt)) {
566 title->set(evt.findString(gTitleEvtName));
572 bool SampleCode::PrefSizeQ(const SkEvent& evt) {
573 return evt.isType(gPrefSizeEvtName, sizeof(gPrefSizeEvtName) - 1);
576 void SampleCode::PrefSizeR(SkEvent* evt, SkScalar width, SkScalar height) {
577 SkASSERT(evt && PrefSizeQ(*evt));
581 evt->setScalars(gPrefSizeEvtName, 2, size);
584 bool SampleCode::FastTextQ(const SkEvent& evt) {
585 return evt.isType(gFastTextEvtName, sizeof(gFastTextEvtName) - 1);
588 ///////////////////////////////////////////////////////////////////////////////
590 static SkMSec gAnimTime;
591 static SkMSec gAnimTimePrev;
593 SkMSec SampleCode::GetAnimTime() { return gAnimTime; }
594 SkMSec SampleCode::GetAnimTimeDelta() { return gAnimTime - gAnimTimePrev; }
595 SkScalar SampleCode::GetAnimSecondsDelta() {
596 return SkDoubleToScalar(GetAnimTimeDelta() / 1000.0);
599 SkScalar SampleCode::GetAnimScalar(SkScalar speed, SkScalar period) {
600 // since gAnimTime can be up to 32 bits, we can't convert it to a float
601 // or we'll lose the low bits. Hence we use doubles for the intermediate
603 double seconds = (double)gAnimTime / 1000.0;
604 double value = SkScalarToDouble(speed) * seconds;
606 value = ::fmod(value, SkScalarToDouble(period));
608 return SkDoubleToScalar(value);
611 SkScalar SampleCode::GetAnimSinScalar(SkScalar amplitude,
612 SkScalar periodInSec,
613 SkScalar phaseInSec) {
617 double t = (double)gAnimTime / 1000.0 + phaseInSec;
618 t *= SkScalarToFloat(2 * SK_ScalarPI) / periodInSec;
619 amplitude = SK_ScalarHalf * amplitude;
620 return SkScalarMul(amplitude, SkDoubleToScalar(sin(t))) + amplitude;
631 kLast_TilingMode_Enum
639 static const struct TilingInfo gTilingInfo[] = {
640 { "No tiling", SK_Scalar1 , SK_Scalar1 }, // kNo_Tiling
641 { "128x128" , SkIntToScalar(128), SkIntToScalar(128) }, // kAbs_128x128_Tiling
642 { "256x256" , SkIntToScalar(256), SkIntToScalar(256) }, // kAbs_256x256_Tiling
643 { "1/4x1/4" , SK_Scalar1 / 4 , SK_Scalar1 / 4 }, // kRel_4x4_Tiling
644 { "1/1x1/16" , SK_Scalar1 , SK_Scalar1 / 16 }, // kRel_1x16_Tiling
645 { "1/16x1/1" , SK_Scalar1 / 16 , SK_Scalar1 }, // kRel_16x1_Tiling
647 SK_COMPILE_ASSERT((SK_ARRAY_COUNT(gTilingInfo) == kLast_TilingMode_Enum),
648 Incomplete_tiling_labels);
650 SkSize SampleWindow::tileSize() const {
651 SkASSERT((TilingMode)fTilingMode < kLast_TilingMode_Enum);
652 const struct TilingInfo* info = gTilingInfo + fTilingMode;
653 return SkSize::Make(info->w > SK_Scalar1 ? info->w : this->width() * info->w,
654 info->h > SK_Scalar1 ? info->h : this->height() * info->h);
656 //////////////////////////////////////////////////////////////////////////////
658 static SkView* curr_view(SkWindow* wind) {
659 SkView::F2BIter iter(wind);
663 static bool curr_title(SkWindow* wind, SkString* title) {
664 SkView* view = curr_view(wind);
666 SkEvent evt(gTitleEvtName);
667 if (view->doQuery(&evt)) {
668 title->set(evt.findString(gTitleEvtName));
675 void SampleWindow::setZoomCenter(float x, float y)
681 bool SampleWindow::zoomIn()
683 // Arbitrarily decided
684 if (fFatBitsScale == 25) return false;
690 bool SampleWindow::zoomOut()
692 if (fFatBitsScale == 1) return false;
698 void SampleWindow::updatePointer(int x, int y)
707 static inline SampleWindow::DeviceType cycle_devicetype(SampleWindow::DeviceType ct) {
708 static const SampleWindow::DeviceType gCT[] = {
709 SampleWindow::kPicture_DeviceType,
711 SampleWindow::kGPU_DeviceType,
713 SampleWindow::kANGLE_DeviceType,
715 SampleWindow::kRaster_DeviceType, // skip the null gpu device in normal cycling
716 #endif // SK_SUPPORT_GPU
717 SampleWindow::kRaster_DeviceType
719 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gCT) == SampleWindow::kDeviceTypeCnt, array_size_mismatch);
723 static SkString getSampleTitle(const SkViewFactory* sampleFactory) {
724 SkView* view = (*sampleFactory)();
726 SampleCode::RequestTitle(view, &title);
731 static bool compareSampleTitle(const SkViewFactory* first, const SkViewFactory* second) {
732 return strcmp(getSampleTitle(first).c_str(), getSampleTitle(second).c_str()) < 0;
735 DEFINE_string(slide, "", "Start on this sample.");
736 DEFINE_int32(msaa, 0, "Request multisampling with this count.");
737 DEFINE_string(pictureDir, "", "Read pictures from here.");
738 DEFINE_string(picture, "", "Path to single picture.");
739 DEFINE_bool(sort, false, "Sort samples by title.");
740 DEFINE_bool(list, false, "List samples?");
741 #ifdef SAMPLE_PDF_FILE_VIEWER
742 DEFINE_string(pdfPath, "", "Path to direcotry of pdf files.");
745 SampleWindow::SampleWindow(void* hwnd, int argc, char** argv, DeviceManager* devManager)
747 , fDevManager(NULL) {
749 SkCommandLineFlags::Parse(argc, argv);
753 if (!FLAGS_pictureDir.isEmpty()) {
754 SkOSFile::Iter iter(FLAGS_pictureDir[0], "skp");
756 while (iter.next(&filename)) {
757 *fSamples.append() = new PictFileFactory(
758 SkOSPath::Join(FLAGS_pictureDir[0], filename.c_str()));
761 if (!FLAGS_picture.isEmpty()) {
762 SkString path(FLAGS_picture[0]);
763 fCurrIndex = fSamples.count();
764 *fSamples.append() = new PictFileFactory(path);
766 #ifdef SAMPLE_PDF_FILE_VIEWER
767 if (!FLAGS_pdfPath.isEmpty()) {
768 SkOSFile::Iter iter(FLAGS_pdfPath[0], "pdf");
770 while (iter.next(&filename)) {
771 *fSamples.append() = new PdfFileViewerFactory(
772 SkOSPath::Join(FLAGS_pictureDir[0], filename.c_str()));
776 SkGMRegistyToSampleRegistry();
778 const SkViewRegister* reg = SkViewRegister::Head();
780 *fSamples.append() = reg->factory();
786 // Sort samples, so foo.skp and foo.pdf are consecutive and we can quickly spot where
787 // skp -> pdf -> png fails.
788 SkTQSort(fSamples.begin(), fSamples.end() ? fSamples.end() - 1 : NULL, compareSampleTitle);
791 if (!FLAGS_slide.isEmpty()) {
792 fCurrIndex = findByTitle(FLAGS_slide[0]);
793 if (fCurrIndex < 0) {
794 fprintf(stderr, "Unknown sample \"%s\"\n", FLAGS_slide[0]);
799 fMSAASampleCount = FLAGS_msaa;
805 if (fCurrIndex < 0) {
807 if (readTitleFromPrefs(&title)) {
808 fCurrIndex = findByTitle(title.c_str());
812 if (fCurrIndex < 0) {
816 gSampleWindow = this;
819 //Clear existing file or create file if it doesn't exist
820 FILE* f = fopen(FILE_PATH, "wb");
824 fDeviceType = kRaster_DeviceType;
827 fDeviceType = kGPU_DeviceType;
829 #if SK_ANGLE && DEFAULT_TO_ANGLE
830 fDeviceType = kANGLE_DeviceType;
840 fRequestGrabImage = false;
841 fPipeState = SkOSMenu::kOffState;
842 fTilingMode = kNo_Tiling;
844 fLCDState = SkOSMenu::kMixedState;
845 fAAState = SkOSMenu::kMixedState;
846 fSubpixelState = SkOSMenu::kMixedState;
848 fFilterLevelIndex = 0;
850 fScrollTestX = fScrollTestY = 0;
852 fMouseX = fMouseY = 0;
854 fTypeface = SkTypeface::CreateFromTypeface(NULL, SkTypeface::kBold);
858 fZoomScale = SK_Scalar1;
868 int sinkID = this->getSinkID();
869 fAppMenu = new SkOSMenu;
870 fAppMenu->setTitle("Global Settings");
873 itemID =fAppMenu->appendList("Device Type", "Device Type", sinkID, 0,
874 "Raster", "Picture", "OpenGL",
879 fAppMenu->assignKeyEquivalentToItem(itemID, 'd');
880 itemID = fAppMenu->appendTriState("AA", "AA", sinkID, fAAState);
881 fAppMenu->assignKeyEquivalentToItem(itemID, 'b');
882 itemID = fAppMenu->appendTriState("LCD", "LCD", sinkID, fLCDState);
883 fAppMenu->assignKeyEquivalentToItem(itemID, 'l');
884 itemID = fAppMenu->appendList("FilterLevel", "FilterLevel", sinkID, fFilterLevelIndex,
885 gFilterLevelStates[0].fName,
886 gFilterLevelStates[1].fName,
887 gFilterLevelStates[2].fName,
888 gFilterLevelStates[3].fName,
889 gFilterLevelStates[4].fName,
891 fAppMenu->assignKeyEquivalentToItem(itemID, 'n');
892 itemID = fAppMenu->appendTriState("Subpixel", "Subpixel", sinkID, fSubpixelState);
893 fAppMenu->assignKeyEquivalentToItem(itemID, 's');
894 itemID = fAppMenu->appendList("Hinting", "Hinting", sinkID, fHintingState,
895 gHintingStates[0].name,
896 gHintingStates[1].name,
897 gHintingStates[2].name,
898 gHintingStates[3].name,
899 gHintingStates[4].name,
901 fAppMenu->assignKeyEquivalentToItem(itemID, 'h');
903 fUsePipeMenuItemID = fAppMenu->appendTriState("Pipe", "Pipe" , sinkID,
905 fAppMenu->assignKeyEquivalentToItem(fUsePipeMenuItemID, 'P');
907 itemID =fAppMenu->appendList("Tiling", "Tiling", sinkID, fTilingMode,
908 gTilingInfo[kNo_Tiling].label,
909 gTilingInfo[kAbs_128x128_Tiling].label,
910 gTilingInfo[kAbs_256x256_Tiling].label,
911 gTilingInfo[kRel_4x4_Tiling].label,
912 gTilingInfo[kRel_1x16_Tiling].label,
913 gTilingInfo[kRel_16x1_Tiling].label,
915 fAppMenu->assignKeyEquivalentToItem(itemID, 't');
917 itemID = fAppMenu->appendSwitch("Slide Show", "Slide Show" , sinkID, false);
918 fAppMenu->assignKeyEquivalentToItem(itemID, 'a');
919 itemID = fAppMenu->appendSwitch("Clip", "Clip" , sinkID, fUseClip);
920 fAppMenu->assignKeyEquivalentToItem(itemID, 'c');
921 itemID = fAppMenu->appendSwitch("Flip X", "Flip X" , sinkID, false);
922 fAppMenu->assignKeyEquivalentToItem(itemID, 'x');
923 itemID = fAppMenu->appendSwitch("Flip Y", "Flip Y" , sinkID, false);
924 fAppMenu->assignKeyEquivalentToItem(itemID, 'y');
925 itemID = fAppMenu->appendSwitch("Zoomer", "Zoomer" , sinkID, fShowZoomer);
926 fAppMenu->assignKeyEquivalentToItem(itemID, 'z');
927 itemID = fAppMenu->appendSwitch("Magnify", "Magnify" , sinkID, fMagnify);
928 fAppMenu->assignKeyEquivalentToItem(itemID, 'm');
929 itemID =fAppMenu->appendList("Transition-Next", "Transition-Next", sinkID,
930 fTransitionNext, "Up", "Up and Right", "Right",
931 "Down and Right", "Down", "Down and Left",
932 "Left", "Up and Left", NULL);
933 fAppMenu->assignKeyEquivalentToItem(itemID, 'j');
934 itemID =fAppMenu->appendList("Transition-Prev", "Transition-Prev", sinkID,
935 fTransitionPrev, "Up", "Up and Right", "Right",
936 "Down and Right", "Down", "Down and Left",
937 "Left", "Up and Left", NULL);
938 fAppMenu->assignKeyEquivalentToItem(itemID, 'k');
939 itemID = fAppMenu->appendAction("Save to PDF", sinkID);
940 fAppMenu->assignKeyEquivalentToItem(itemID, 'e');
942 this->addMenu(fAppMenu);
943 fSlideMenu = new SkOSMenu;
944 this->addMenu(fSlideMenu);
946 this->setColorType(kN32_SkColorType);
947 this->setVisibleP(true);
948 this->setClipToBounds(false);
950 this->loadView((*fSamples[fCurrIndex])());
954 if (NULL == devManager) {
955 fDevManager = new DefaultDeviceManager();
958 fDevManager = devManager;
960 fDevManager->setUpBackend(this, fMSAASampleCount);
962 // If another constructor set our dimensions, ensure that our
963 // onSizeChange gets called.
964 if (this->height() && this->width()) {
965 this->onSizeChange();
968 // can't call this synchronously, since it may require a subclass to
969 // to implement, or the caller may need us to have returned from the
970 // constructor first. Hence we post an event to ourselves.
971 // this->updateTitle();
972 post_event_to_sink(new SkEvent(gUpdateWindowTitleEvtName), this);
975 SampleWindow::~SampleWindow() {
977 SkSafeUnref(fTypeface);
978 SkSafeUnref(fDevManager);
982 int SampleWindow::findByTitle(const char title[]) {
983 int i, count = fSamples.count();
984 for (i = 0; i < count; i++) {
985 if (getSampleTitle(i).equals(title)) {
992 void SampleWindow::listTitles() {
993 int count = fSamples.count();
994 SkDebugf("All Slides:\n");
995 for (int i = 0; i < count; i++) {
996 SkDebugf(" %s\n", getSampleTitle(i).c_str());
1000 static SkBitmap capture_bitmap(SkCanvas* canvas) {
1002 if (bm.allocPixels(canvas->imageInfo())) {
1003 canvas->readPixels(&bm, 0, 0);
1008 static bool bitmap_diff(SkCanvas* canvas, const SkBitmap& orig,
1010 SkBitmap src = capture_bitmap(canvas);
1012 SkAutoLockPixels alp0(src);
1013 SkAutoLockPixels alp1(orig);
1014 for (int y = 0; y < src.height(); y++) {
1015 const void* srcP = src.getAddr(0, y);
1016 const void* origP = orig.getAddr(0, y);
1017 size_t bytes = src.width() * src.bytesPerPixel();
1018 if (memcmp(srcP, origP, bytes)) {
1019 SkDebugf("---------- difference on line %d\n", y);
1026 static void drawText(SkCanvas* canvas, SkString string, SkScalar left, SkScalar top, SkPaint& paint)
1028 SkColor desiredColor = paint.getColor();
1029 paint.setColor(SK_ColorWHITE);
1030 const char* c_str = string.c_str();
1031 size_t size = string.size();
1033 paint.measureText(c_str, size, &bounds);
1034 bounds.offset(left, top);
1035 SkScalar inset = SkIntToScalar(-2);
1036 bounds.inset(inset, inset);
1037 canvas->drawRect(bounds, paint);
1038 if (desiredColor != SK_ColorBLACK) {
1039 paint.setColor(SK_ColorBLACK);
1040 canvas->drawText(c_str, size, left + SK_Scalar1, top + SK_Scalar1, paint);
1042 paint.setColor(desiredColor);
1043 canvas->drawText(c_str, size, left, top, paint);
1049 void SampleWindow::draw(SkCanvas* canvas) {
1050 // update the animation time
1051 if (!gAnimTimePrev && !gAnimTime) {
1052 // first time make delta be 0
1053 gAnimTime = SkTime::GetMSecs();
1054 gAnimTimePrev = gAnimTime;
1056 gAnimTimePrev = gAnimTime;
1057 gAnimTime = SkTime::GetMSecs();
1060 if (fGesture.isActive()) {
1061 this->updateMatrix();
1065 fMeasureFPS_Time = 0;
1069 this->INHERITED::draw(canvas);
1070 SkBitmap orig = capture_bitmap(canvas);
1072 const SkScalar w = this->width();
1073 const SkScalar h = this->height();
1074 const SkScalar cw = w / XCLIP_N;
1075 const SkScalar ch = h / YCLIP_N;
1076 for (int y = 0; y < YCLIP_N; y++) {
1079 r.fBottom = (y + 1) * ch;
1080 if (y == YCLIP_N - 1) {
1083 for (int x = 0; x < XCLIP_N; x++) {
1084 SkAutoCanvasRestore acr(canvas, true);
1086 r.fRight = (x + 1) * cw;
1087 if (x == XCLIP_N - 1) {
1090 canvas->clipRect(r);
1091 this->INHERITED::draw(canvas);
1096 if (bitmap_diff(canvas, orig, &diff)) {
1099 SkSize tile = this->tileSize();
1101 if (kNo_Tiling == fTilingMode) {
1102 this->INHERITED::draw(canvas); // no looping or surfaces needed
1104 const int w = SkScalarRoundToInt(tile.width());
1105 const int h = SkScalarRoundToInt(tile.height());
1106 SkImageInfo info = SkImageInfo::MakeN32Premul(w, h);
1107 SkAutoTUnref<SkSurface> surface(canvas->newSurface(info));
1108 SkCanvas* tileCanvas = surface->getCanvas();
1110 for (SkScalar y = 0; y < height(); y += tile.height()) {
1111 for (SkScalar x = 0; x < width(); x += tile.width()) {
1112 SkAutoCanvasRestore acr(tileCanvas, true);
1113 tileCanvas->translate(-x, -y);
1114 tileCanvas->clear(0);
1115 this->INHERITED::draw(tileCanvas);
1116 surface->draw(canvas, x, y, NULL);
1120 // for drawing the borders between tiles
1122 paint.setColor(0x60FF00FF);
1123 paint.setStyle(SkPaint::kStroke_Style);
1125 for (SkScalar y = 0; y < height(); y += tile.height()) {
1126 for (SkScalar x = 0; x < width(); x += tile.width()) {
1127 canvas->drawRect(SkRect::MakeXYWH(x, y, tile.width(), tile.height()), paint);
1132 if (fShowZoomer && !fSaveToPdf) {
1135 if (fMagnify && !fSaveToPdf) {
1139 if (fMeasureFPS && fMeasureFPS_Time) {
1140 this->updateTitle();
1141 this->postInvalDelay();
1145 fDevManager->publishCanvas(fDeviceType, canvas, this);
1148 static float clipW = 200;
1149 static float clipH = 200;
1150 void SampleWindow::magnify(SkCanvas* canvas) {
1152 int count = canvas->save();
1154 SkMatrix m = canvas->getTotalMatrix();
1155 if (!m.invert(&m)) {
1158 SkPoint offset, center;
1159 SkScalar mouseX = fMouseX * SK_Scalar1;
1160 SkScalar mouseY = fMouseY * SK_Scalar1;
1161 m.mapXY(mouseX - clipW/2, mouseY - clipH/2, &offset);
1162 m.mapXY(mouseX, mouseY, ¢er);
1164 r.set(0, 0, clipW * m.getScaleX(), clipH * m.getScaleX());
1165 r.offset(offset.fX, offset.fY);
1168 paint.setColor(0xFF66AAEE);
1169 paint.setStyle(SkPaint::kStroke_Style);
1170 paint.setStrokeWidth(10.f * m.getScaleX());
1172 //canvas->translate(0, -250);
1173 canvas->drawRect(r, paint);
1174 canvas->clipRect(r);
1176 m = canvas->getTotalMatrix();
1177 m.setTranslate(-center.fX, -center.fY);
1178 m.postScale(0.5f * fFatBitsScale, 0.5f * fFatBitsScale);
1179 m.postTranslate(center.fX, center.fY);
1182 this->INHERITED::draw(canvas);
1184 canvas->restoreToCount(count);
1187 void SampleWindow::showZoomer(SkCanvas* canvas) {
1188 int count = canvas->save();
1189 canvas->resetMatrix();
1190 // Ensure the mouse position is on screen.
1191 int width = SkScalarRoundToInt(this->width());
1192 int height = SkScalarRoundToInt(this->height());
1193 if (fMouseX >= width) fMouseX = width - 1;
1194 else if (fMouseX < 0) fMouseX = 0;
1195 if (fMouseY >= height) fMouseY = height - 1;
1196 else if (fMouseY < 0) fMouseY = 0;
1198 SkBitmap bitmap = capture_bitmap(canvas);
1199 bitmap.lockPixels();
1201 // Find the size of the zoomed in view, forced to be odd, so the examined pixel is in the middle.
1202 int zoomedWidth = (width >> 1) | 1;
1203 int zoomedHeight = (height >> 1) | 1;
1205 src.set(0, 0, zoomedWidth / fFatBitsScale, zoomedHeight / fFatBitsScale);
1206 src.offset(fMouseX - (src.width()>>1), fMouseY - (src.height()>>1));
1208 dest.set(0, 0, SkIntToScalar(zoomedWidth), SkIntToScalar(zoomedHeight));
1209 dest.offset(SkIntToScalar(width - zoomedWidth), SkIntToScalar(height - zoomedHeight));
1211 // Clear the background behind our zoomed in view
1212 paint.setColor(SK_ColorWHITE);
1213 canvas->drawRect(dest, paint);
1214 canvas->drawBitmapRect(bitmap, &src, dest);
1215 paint.setColor(SK_ColorBLACK);
1216 paint.setStyle(SkPaint::kStroke_Style);
1217 // Draw a border around the pixel in the middle
1218 SkRect originalPixel;
1219 originalPixel.set(SkIntToScalar(fMouseX), SkIntToScalar(fMouseY), SkIntToScalar(fMouseX + 1), SkIntToScalar(fMouseY + 1));
1223 SkColor color = bitmap.getColor(fMouseX, fMouseY);
1224 if (matrix.setRectToRect(scalarSrc, dest, SkMatrix::kFill_ScaleToFit)) {
1226 matrix.mapRect(&pixel, originalPixel);
1227 // TODO Perhaps measure the values and make the outline white if it's "dark"
1228 if (color == SK_ColorBLACK) {
1229 paint.setColor(SK_ColorWHITE);
1231 canvas->drawRect(pixel, paint);
1233 paint.setColor(SK_ColorBLACK);
1234 // Draw a border around the destination rectangle
1235 canvas->drawRect(dest, paint);
1236 paint.setStyle(SkPaint::kStrokeAndFill_Style);
1237 // Identify the pixel and its color on screen
1238 paint.setTypeface(fTypeface);
1239 paint.setAntiAlias(true);
1240 SkScalar lineHeight = paint.getFontMetrics(NULL);
1242 string.appendf("(%i, %i)", fMouseX, fMouseY);
1243 SkScalar left = dest.fLeft + SkIntToScalar(3);
1244 SkScalar i = SK_Scalar1;
1245 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1249 string.appendf("A: %X", SkColorGetA(color));
1250 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1254 string.appendf("R: %X", SkColorGetR(color));
1255 paint.setColor(SK_ColorRED);
1256 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1260 string.appendf("G: %X", SkColorGetG(color));
1261 paint.setColor(SK_ColorGREEN);
1262 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1266 string.appendf("B: %X", SkColorGetB(color));
1267 paint.setColor(SK_ColorBLUE);
1268 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1269 canvas->restoreToCount(count);
1272 void SampleWindow::onDraw(SkCanvas* canvas) {
1275 #include "SkColorPriv.h"
1277 void SampleWindow::saveToPdf()
1283 SkCanvas* SampleWindow::beforeChildren(SkCanvas* canvas) {
1285 const SkBitmap bmp = capture_bitmap(canvas);
1286 SkISize size = SkISize::Make(bmp.width(), bmp.height());
1287 SkPDFDevice* pdfDevice = new SkPDFDevice(size, size,
1288 canvas->getTotalMatrix());
1289 fPdfCanvas = new SkCanvas(pdfDevice);
1291 canvas = fPdfCanvas;
1292 } else if (kPicture_DeviceType == fDeviceType) {
1293 canvas = fRecorder.beginRecording(9999, 9999, NULL, 0);
1296 if (kNullGPU_DeviceType != fDeviceType)
1299 canvas = this->INHERITED::beforeChildren(canvas);
1304 canvas->drawColor(0xFFFF88FF);
1305 canvas->clipPath(fClipPath, SkRegion::kIntersect_Op, true);
1312 void SampleWindow::afterChildren(SkCanvas* orig) {
1316 showZoomer(fPdfCanvas);
1319 name.printf("%s.pdf", this->getTitle());
1321 SkPDFDevice* device = NULL;//static_cast<SkPDFDevice*>(fPdfCanvas->getDevice());
1323 doc.appendPage(device);
1324 #ifdef SK_BUILD_FOR_ANDROID
1325 name.prepend("/sdcard/");
1328 #ifdef SK_BUILD_FOR_IOS
1329 SkDynamicMemoryWStream mstream;
1330 doc.emitPDF(&mstream);
1331 fPDFData = mstream.copyToData();
1333 SkFILEWStream stream(name.c_str());
1334 if (stream.isValid()) {
1335 doc.emitPDF(&stream);
1336 const char* desc = "File saved from Skia SampleApp";
1337 this->onPDFSaved(this->getTitle(), desc, name.c_str());
1343 // We took over the draw calls in order to create the PDF, so we need
1349 if (fRequestGrabImage) {
1350 fRequestGrabImage = false;
1352 SkBitmap bmp = capture_bitmap(orig);
1353 if (!bmp.isNull()) {
1354 static int gSampleGrabCounter;
1356 name.printf("sample_grab_%d.png", gSampleGrabCounter++);
1357 SkImageEncoder::EncodeFile(name.c_str(), bmp,
1358 SkImageEncoder::kPNG_Type, 100);
1362 if (kPicture_DeviceType == fDeviceType) {
1363 SkAutoTUnref<const SkPicture> picture(fRecorder.endRecording());
1366 this->installDrawFilter(orig);
1367 orig->drawPicture(picture);
1369 SkDynamicMemoryWStream ostream;
1370 picture->serialize(&ostream);
1372 SkAutoDataUnref data(ostream.copyToData());
1373 SkMemoryStream istream(data->data(), data->size());
1374 SkAutoTUnref<SkPicture> pict(SkPicture::CreateFromStream(&istream));
1375 if (pict.get() != NULL) {
1376 orig->drawPicture(pict.get());
1379 picture->draw(orig);
1383 // Do this after presentGL and other finishing, rather than in afterChild
1384 if (fMeasureFPS && fMeasureFPS_StartTime) {
1385 fMeasureFPS_Time += SkTime::GetMSecs() - fMeasureFPS_StartTime;
1389 void SampleWindow::beforeChild(SkView* child, SkCanvas* canvas) {
1391 fRotateAnimTime += SampleCode::GetAnimSecondsDelta();
1393 SkScalar cx = this->width() / 2;
1394 SkScalar cy = this->height() / 2;
1395 canvas->translate(cx, cy);
1396 canvas->rotate(fRotateAnimTime * 10);
1397 canvas->translate(-cx, -cy);
1401 fPerspAnimTime += SampleCode::GetAnimSecondsDelta();
1403 static const SkScalar gAnimPeriod = 10 * SK_Scalar1;
1404 static const SkScalar gAnimMag = SK_Scalar1 / 1000;
1405 SkScalar t = SkScalarMod(fPerspAnimTime, gAnimPeriod);
1406 if (SkScalarFloorToInt(SkScalarDiv(fPerspAnimTime, gAnimPeriod)) & 0x1) {
1407 t = gAnimPeriod - t;
1409 t = 2 * t - gAnimPeriod;
1410 t = SkScalarMul(SkScalarDiv(t, gAnimPeriod), gAnimMag);
1417 this->installDrawFilter(canvas);
1420 if (SampleView::SetRepeatDraw(child, FPS_REPEAT_COUNT)) {
1421 fMeasureFPS_StartTime = SkTime::GetMSecs();
1424 (void)SampleView::SetRepeatDraw(child, 1);
1426 if (fPerspAnim || fRotate) {
1431 void SampleWindow::afterChild(SkView* child, SkCanvas* canvas) {
1432 canvas->setDrawFilter(NULL);
1435 static SkColorType gColorTypeCycle[] = {
1436 kUnknown_SkColorType, // none -> none
1437 kUnknown_SkColorType, // a8 -> none
1438 kN32_SkColorType, // 565 -> 8888
1439 kN32_SkColorType, // 4444 -> 8888
1440 kRGB_565_SkColorType, // 8888 -> 565
1441 kRGB_565_SkColorType, // 8888 -> 565
1442 kUnknown_SkColorType, // index8 -> none
1445 static SkColorType cycle_colortypes(SkColorType c) {
1446 return gColorTypeCycle[c];
1449 void SampleWindow::changeZoomLevel(float delta) {
1450 fZoomLevel += delta;
1451 if (fZoomLevel > 0) {
1452 fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL);
1453 fZoomScale = fZoomLevel + SK_Scalar1;
1454 } else if (fZoomLevel < 0) {
1455 fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL);
1456 fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel);
1458 fZoomScale = SK_Scalar1;
1460 this->updateMatrix();
1463 void SampleWindow::updateMatrix(){
1468 //m = this->getLocalMatrix();//.invert(&m);
1469 m.mapXY(fZoomCenterX, fZoomCenterY, ¢er);
1470 SkScalar cx = center.fX;
1471 SkScalar cy = center.fY;
1473 m.setTranslate(-cx, -cy);
1474 m.postScale(fZoomScale, fZoomScale);
1475 m.postTranslate(cx, cy);
1479 m.preTranslate(fZoomCenterX, fZoomCenterY);
1480 if (fFlipAxis & kFlipAxis_X) {
1481 m.preScale(-SK_Scalar1, SK_Scalar1);
1483 if (fFlipAxis & kFlipAxis_Y) {
1484 m.preScale(SK_Scalar1, -SK_Scalar1);
1486 m.preTranslate(-fZoomCenterX, -fZoomCenterY);
1487 //canvas->concat(m);
1489 // Apply any gesture matrix
1490 m.preConcat(fGesture.localM());
1491 m.preConcat(fGesture.globalM());
1493 this->setLocalMatrix(m);
1495 this->updateTitle();
1498 bool SampleWindow::previousSample() {
1499 fCurrIndex = (fCurrIndex - 1 + fSamples.count()) % fSamples.count();
1500 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(),
1505 bool SampleWindow::nextSample() {
1506 fCurrIndex = (fCurrIndex + 1) % fSamples.count();
1507 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(),
1512 bool SampleWindow::goToSample(int i) {
1513 fCurrIndex = (i) % fSamples.count();
1514 this->loadView(create_transition(curr_view(this),(*fSamples[fCurrIndex])(), 6));
1518 SkString SampleWindow::getSampleTitle(int i) {
1519 return ::getSampleTitle(fSamples[i]);
1522 int SampleWindow::sampleCount() {
1523 return fSamples.count();
1526 void SampleWindow::showOverview() {
1527 this->loadView(create_transition(curr_view(this),
1528 create_overview(fSamples.count(), fSamples.begin()),
1532 void SampleWindow::installDrawFilter(SkCanvas* canvas) {
1533 canvas->setDrawFilter(new FlagsDrawFilter(fLCDState, fAAState, fSubpixelState,
1534 fHintingState, fFilterLevelIndex))->unref();
1537 void SampleWindow::postAnimatingEvent() {
1539 (new SkEvent(ANIMATING_EVENTTYPE, this->getSinkID()))->postDelay(ANIMATING_DELAY);
1543 bool SampleWindow::onEvent(const SkEvent& evt) {
1544 if (evt.isType(gUpdateWindowTitleEvtName)) {
1545 this->updateTitle();
1548 if (evt.isType(ANIMATING_EVENTTYPE)) {
1551 this->postAnimatingEvent();
1555 if (evt.isType("replace-transition-view")) {
1556 this->loadView((SkView*)SkEventSink::FindSink(evt.getFast32()));
1559 if (evt.isType("set-curr-index")) {
1560 this->goToSample(evt.getFast32());
1563 if (isInvalEvent(evt)) {
1568 if (SkOSMenu::FindListIndex(evt, "Device Type", &selected)) {
1569 this->setDeviceType((DeviceType)selected);
1572 if (SkOSMenu::FindTriState(evt, "Pipe", &fPipeState)) {
1574 if (!fPipeState != SkOSMenu::kOnState)
1575 gServer.disconnectAll();
1577 (void)SampleView::SetUsePipe(curr_view(this), fPipeState);
1578 this->updateTitle();
1582 if (SkOSMenu::FindSwitchState(evt, "Slide Show", NULL)) {
1583 this->toggleSlideshow();
1586 if (SkOSMenu::FindTriState(evt, "AA", &fAAState) ||
1587 SkOSMenu::FindTriState(evt, "LCD", &fLCDState) ||
1588 SkOSMenu::FindListIndex(evt, "FilterLevel", &fFilterLevelIndex) ||
1589 SkOSMenu::FindTriState(evt, "Subpixel", &fSubpixelState) ||
1590 SkOSMenu::FindListIndex(evt, "Hinting", &fHintingState) ||
1591 SkOSMenu::FindSwitchState(evt, "Clip", &fUseClip) ||
1592 SkOSMenu::FindSwitchState(evt, "Zoomer", &fShowZoomer) ||
1593 SkOSMenu::FindSwitchState(evt, "Magnify", &fMagnify) ||
1594 SkOSMenu::FindListIndex(evt, "Transition-Next", &fTransitionNext) ||
1595 SkOSMenu::FindListIndex(evt, "Transition-Prev", &fTransitionPrev)) {
1597 this->updateTitle();
1600 if (SkOSMenu::FindListIndex(evt, "Tiling", &fTilingMode)) {
1601 if (SampleView::IsSampleView(curr_view(this))) {
1602 ((SampleView*)curr_view(this))->onTileSizeChanged(this->tileSize());
1605 this->updateTitle();
1608 if (SkOSMenu::FindSwitchState(evt, "Flip X", NULL)) {
1609 fFlipAxis ^= kFlipAxis_X;
1610 this->updateMatrix();
1613 if (SkOSMenu::FindSwitchState(evt, "Flip Y", NULL)) {
1614 fFlipAxis ^= kFlipAxis_Y;
1615 this->updateMatrix();
1618 if (SkOSMenu::FindAction(evt,"Save to PDF")) {
1622 return this->INHERITED::onEvent(evt);
1625 bool SampleWindow::onQuery(SkEvent* query) {
1626 if (query->isType("get-slide-count")) {
1627 query->setFast32(fSamples.count());
1630 if (query->isType("get-slide-title")) {
1631 SkView* view = (*fSamples[query->getFast32()])();
1632 SkEvent evt(gTitleEvtName);
1633 if (view->doQuery(&evt)) {
1634 query->setString("title", evt.findString(gTitleEvtName));
1639 if (query->isType("use-fast-text")) {
1640 SkEvent evt(gFastTextEvtName);
1641 return curr_view(this)->doQuery(&evt);
1643 if (query->isType("ignore-window-bitmap")) {
1644 query->setFast32(this->getGrContext() != NULL);
1647 return this->INHERITED::onQuery(query);
1651 static void cleanup_for_filename(SkString* name) {
1652 char* str = name->writable_str();
1653 for (size_t i = 0; i < name->size(); i++) {
1655 case ':': str[i] = '-'; break;
1656 case '/': str[i] = '-'; break;
1657 case ' ': str[i] = '_'; break;
1664 DECLARE_bool(portableFonts);
1666 bool SampleWindow::onHandleChar(SkUnichar uni) {
1668 SkView* view = curr_view(this);
1670 SkEvent evt(gCharEvtName);
1672 if (view->doQuery(&evt)) {
1682 case '5': dx = 0; dy = 0; break;
1683 case '8': dx = 0; dy = -1; break;
1684 case '6': dx = 1; dy = 0; break;
1685 case '2': dx = 0; dy = 1; break;
1686 case '4': dx = -1; dy = 0; break;
1687 case '7': dx = -1; dy = -1; break;
1688 case '9': dx = 1; dy = -1; break;
1689 case '3': dx = 1; dy = 1; break;
1690 case '1': dx = -1; dy = 1; break;
1696 if (0xFF != dx && 0xFF != dy) {
1697 if ((dx | dy) == 0) {
1698 fScrollTestX = fScrollTestY = 0;
1709 post_event_to_sink(SkNEW_ARGS(SkEvent, ("PictFileView::toggleBBox")), curr_view(this));
1710 // Cannot call updateTitle() synchronously, because the toggleBBox event is still in
1712 post_event_to_sink(SkNEW_ARGS(SkEvent, (gUpdateWindowTitleEvtName)), this);
1720 FLAGS_portableFonts ^= true;
1724 fRequestGrabImage = true;
1728 gShowGMBounds = !gShowGMBounds;
1729 post_event_to_sink(GMSampleView::NewShowSizeEvt(gShowGMBounds),
1741 fRotateAnimTime = 0;
1743 this->updateTitle();
1746 fPerspAnim = !fPerspAnim;
1748 this->updateTitle();
1752 this->setDeviceType(kNullGPU_DeviceType);
1754 this->updateTitle();
1758 GrContext* grContext = this->getGrContext();
1761 grContext->getResourceCacheUsage(NULL, &cacheBytes);
1762 grContext->freeGpuResources();
1763 SkDebugf("Purged %d bytes from the GPU resource cache.\n", cacheBytes);
1772 if (fAppMenu->handleKeyEquivalent(uni)|| fSlideMenu->handleKeyEquivalent(uni)) {
1773 this->onUpdateMenu(fAppMenu);
1774 this->onUpdateMenu(fSlideMenu);
1777 return this->INHERITED::onHandleChar(uni);
1780 void SampleWindow::setDeviceType(DeviceType type) {
1781 if (type == fDeviceType)
1784 fDevManager->tearDownBackend(this);
1788 fDevManager->setUpBackend(this, fMSAASampleCount);
1790 this->updateTitle();
1794 void SampleWindow::toggleSlideshow() {
1795 fAnimating = !fAnimating;
1796 this->postAnimatingEvent();
1797 this->updateTitle();
1800 void SampleWindow::toggleRendering() {
1801 this->setDeviceType(cycle_devicetype(fDeviceType));
1802 this->updateTitle();
1806 void SampleWindow::toggleFPS() {
1807 fMeasureFPS = !fMeasureFPS;
1808 this->updateTitle();
1812 #include "SkDumpCanvas.h"
1814 bool SampleWindow::onHandleKey(SkKey key) {
1816 SkView* view = curr_view(this);
1818 SkEvent evt(gKeyEvtName);
1820 if (view->doQuery(&evt)) {
1827 if (this->nextSample()) {
1832 if (this->previousSample()) {
1837 if (USE_ARROWS_FOR_ZOOM) {
1838 this->changeZoomLevel(1.f / 32.f);
1842 this->updateTitle();
1846 if (USE_ARROWS_FOR_ZOOM) {
1847 this->changeZoomLevel(-1.f / 32.f);
1849 this->setColorType(cycle_colortypes(this->getBitmap().colorType()));
1850 this->updateTitle();
1855 if (curr_title(this, &title)) {
1856 writeTitleToPrefs(title.c_str());
1861 this->showOverview();
1866 return this->INHERITED::onHandleKey(key);
1869 ///////////////////////////////////////////////////////////////////////////////
1871 static const char gGestureClickType[] = "GestureClickType";
1873 bool SampleWindow::onDispatchClick(int x, int y, Click::State state,
1874 void* owner, unsigned modi) {
1875 if (Click::kMoved_State == state) {
1876 updatePointer(x, y);
1878 int w = SkScalarRoundToInt(this->width());
1879 int h = SkScalarRoundToInt(this->height());
1881 // check for the resize-box
1882 if (w - x < 16 && h - y < 16) {
1883 return false; // let the OS handle the click
1885 else if (fMagnify) {
1886 //it's only necessary to update the drawing if there's a click
1888 return false; //prevent dragging while magnify is enabled
1890 // capture control+option, and trigger debugger
1891 if ((modi & kControl_SkModifierKey) && (modi & kOption_SkModifierKey)) {
1892 if (Click::kDown_State == state) {
1893 SkEvent evt("debug-hit-test");
1894 evt.setS32("debug-hit-test-x", x);
1895 evt.setS32("debug-hit-test-y", y);
1896 curr_view(this)->doEvent(evt);
1900 return this->INHERITED::onDispatchClick(x, y, state, owner, modi);
1905 class GestureClick : public SkView::Click {
1907 GestureClick(SkView* target) : SkView::Click(target) {
1908 this->setType(gGestureClickType);
1911 static bool IsGesture(Click* click) {
1912 return click->isType(gGestureClickType);
1916 SkView::Click* SampleWindow::onFindClickHandler(SkScalar x, SkScalar y,
1918 return new GestureClick(this);
1921 bool SampleWindow::onClick(Click* click) {
1922 if (GestureClick::IsGesture(click)) {
1923 float x = static_cast<float>(click->fICurr.fX);
1924 float y = static_cast<float>(click->fICurr.fY);
1926 switch (click->fState) {
1927 case SkView::Click::kDown_State:
1928 fGesture.touchBegin(click->fOwner, x, y);
1930 case SkView::Click::kMoved_State:
1931 fGesture.touchMoved(click->fOwner, x, y);
1932 this->updateMatrix();
1934 case SkView::Click::kUp_State:
1935 fGesture.touchEnd(click->fOwner);
1936 this->updateMatrix();
1944 ///////////////////////////////////////////////////////////////////////////////
1946 void SampleWindow::loadView(SkView* view) {
1947 SkView::F2BIter iter(this);
1948 SkView* prev = iter.next();
1950 prev->detachFromParent();
1953 view->setVisibleP(true);
1954 view->setClipToBounds(false);
1955 this->attachChildToFront(view)->unref();
1956 view->setSize(this->width(), this->height());
1958 //repopulate the slide menu when a view is loaded
1959 fSlideMenu->reset();
1961 (void)SampleView::SetUsePipe(view, fPipeState);
1962 if (SampleView::IsSampleView(view)) {
1963 SampleView* sampleView = (SampleView*)view;
1964 sampleView->requestMenu(fSlideMenu);
1965 sampleView->onTileSizeChanged(this->tileSize());
1967 this->onUpdateMenu(fSlideMenu);
1968 this->updateTitle();
1971 static const char* gDeviceTypePrefix[] = {
1980 #endif // SK_SUPPORT_GPU
1982 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gDeviceTypePrefix) == SampleWindow::kDeviceTypeCnt,
1983 array_size_mismatch);
1985 static const char* trystate_str(SkOSMenu::TriState state,
1986 const char trueStr[], const char falseStr[]) {
1987 if (SkOSMenu::kOnState == state) {
1989 } else if (SkOSMenu::kOffState == state) {
1995 void SampleWindow::updateTitle() {
1996 SkView* view = curr_view(this);
1999 if (!curr_title(this, &title)) {
2000 title.set("<unknown>");
2003 title.prepend(gDeviceTypePrefix[fDeviceType]);
2006 title.prepend(sk_tool_utils::colortype_name(this->getBitmap().colorType()));
2008 if (fTilingMode != kNo_Tiling) {
2009 title.prependf("<T: %s> ", gTilingInfo[fTilingMode].label);
2012 title.prepend("<A> ");
2015 title.prepend("<R> ");
2018 title.prepend("<C> ");
2021 title.prepend("<K> ");
2024 title.prepend(trystate_str(fLCDState, "LCD ", "lcd "));
2025 title.prepend(trystate_str(fAAState, "AA ", "aa "));
2026 title.prepend(gFilterLevelStates[fFilterLevelIndex].fLabel);
2027 title.prepend(trystate_str(fSubpixelState, "S ", "s "));
2028 title.prepend(fFlipAxis & kFlipAxis_X ? "X " : NULL);
2029 title.prepend(fFlipAxis & kFlipAxis_Y ? "Y " : NULL);
2030 title.prepend(gHintingStates[fHintingState].label);
2033 title.prependf("{%.2f} ", SkScalarToFloat(fZoomLevel));
2037 title.appendf(" %8.3f ms", fMeasureFPS_Time / (float)FPS_REPEAT_COUNT);
2039 if (SampleView::IsSampleView(view)) {
2040 switch (fPipeState) {
2041 case SkOSMenu::kOnState:
2042 title.prepend("<Pipe> ");
2044 case SkOSMenu::kMixedState:
2045 title.prepend("<Tiled Pipe> ");
2051 title.prepend("! ");
2055 if (IsGpuDeviceType(fDeviceType) &&
2056 NULL != fDevManager &&
2057 fDevManager->getGrRenderTarget() &&
2058 fDevManager->getGrRenderTarget()->numSamples() > 0) {
2059 title.appendf(" [MSAA: %d]",
2060 fDevManager->getGrRenderTarget()->numSamples());
2064 this->setTitle(title.c_str());
2067 void SampleWindow::onSizeChange() {
2068 this->INHERITED::onSizeChange();
2070 SkView::F2BIter iter(this);
2071 SkView* view = iter.next();
2072 view->setSize(this->width(), this->height());
2074 // rebuild our clippath
2076 const SkScalar W = this->width();
2077 const SkScalar H = this->height();
2081 for (SkScalar y = SK_Scalar1; y < H; y += SkIntToScalar(32)) {
2083 r.set(SK_Scalar1, y, SkIntToScalar(30), y + SkIntToScalar(30));
2084 for (; r.fLeft < W; r.offset(SkIntToScalar(32), 0))
2085 fClipPath.addRect(r);
2090 fClipPath.addRect(r, SkPath::kCCW_Direction);
2091 r.set(W/4, H/4, W*3/4, H*3/4);
2092 fClipPath.addRect(r, SkPath::kCW_Direction);
2096 fZoomCenterX = SkScalarHalf(this->width());
2097 fZoomCenterY = SkScalarHalf(this->height());
2099 #ifdef SK_BUILD_FOR_ANDROID
2100 // FIXME: The first draw after a size change does not work on Android, so
2101 // we post an invalidate.
2102 this->postInvalDelay();
2104 this->updateTitle(); // to refresh our config
2105 fDevManager->windowSizeChanged(this);
2107 if (fTilingMode != kNo_Tiling && SampleView::IsSampleView(view)) {
2108 ((SampleView*)view)->onTileSizeChanged(this->tileSize());
2112 ///////////////////////////////////////////////////////////////////////////////
2114 static const char is_sample_view_tag[] = "sample-is-sample-view";
2115 static const char repeat_count_tag[] = "sample-set-repeat-count";
2116 static const char set_use_pipe_tag[] = "sample-set-use-pipe";
2118 bool SampleView::IsSampleView(SkView* view) {
2119 SkEvent evt(is_sample_view_tag);
2120 return view->doQuery(&evt);
2123 bool SampleView::SetRepeatDraw(SkView* view, int count) {
2124 SkEvent evt(repeat_count_tag);
2125 evt.setFast32(count);
2126 return view->doEvent(evt);
2129 bool SampleView::SetUsePipe(SkView* view, SkOSMenu::TriState state) {
2131 evt.setS32(set_use_pipe_tag, state);
2132 return view->doEvent(evt);
2135 bool SampleView::onEvent(const SkEvent& evt) {
2136 if (evt.isType(repeat_count_tag)) {
2137 fRepeatCount = evt.getFast32();
2142 if (evt.findS32(set_use_pipe_tag, &pipeHolder)) {
2143 fPipeState = static_cast<SkOSMenu::TriState>(pipeHolder);
2147 return this->INHERITED::onEvent(evt);
2150 bool SampleView::onQuery(SkEvent* evt) {
2151 if (evt->isType(is_sample_view_tag)) {
2154 return this->INHERITED::onQuery(evt);
2158 class SimplePC : public SkGPipeController {
2160 SimplePC(SkCanvas* target);
2163 virtual void* requestBlock(size_t minRequest, size_t* actual);
2164 virtual void notifyWritten(size_t bytes);
2167 SkGPipeReader fReader;
2170 size_t fBytesWritten;
2172 SkGPipeReader::Status fStatus;
2174 size_t fTotalWritten;
2177 SimplePC::SimplePC(SkCanvas* target) : fReader(target) {
2179 fBlockSize = fBytesWritten = 0;
2180 fStatus = SkGPipeReader::kDone_Status;
2183 fReader.setBitmapDecoder(&SkImageDecoder::DecodeMemory);
2186 SimplePC::~SimplePC() {
2187 // SkASSERT(SkGPipeReader::kDone_Status == fStatus);
2188 if (fTotalWritten) {
2189 SkDebugf("--- %d bytes %d atoms, status %d\n", fTotalWritten,
2190 fAtomsWritten, fStatus);
2192 //File is open in append mode
2193 FILE* f = fopen(FILE_PATH, "ab");
2194 SkASSERT(f != NULL);
2195 fwrite((const char*)fBlock + fBytesWritten, 1, bytes, f);
2199 if (fAtomsWritten > 1 && fTotalWritten > 4) { //ignore done
2200 gServer.acceptConnections();
2201 gServer.writePacket(fBlock, fTotalWritten);
2208 void* SimplePC::requestBlock(size_t minRequest, size_t* actual) {
2211 fBlockSize = minRequest * 4;
2212 fBlock = sk_malloc_throw(fBlockSize);
2214 *actual = fBlockSize;
2218 void SimplePC::notifyWritten(size_t bytes) {
2219 SkASSERT(fBytesWritten + bytes <= fBlockSize);
2220 fStatus = fReader.playback((const char*)fBlock + fBytesWritten, bytes);
2221 SkASSERT(SkGPipeReader::kError_Status != fStatus);
2222 fBytesWritten += bytes;
2223 fTotalWritten += bytes;
2228 void SampleView::draw(SkCanvas* canvas) {
2229 if (SkOSMenu::kOffState == fPipeState) {
2230 this->INHERITED::draw(canvas);
2232 SkGPipeWriter writer;
2233 SimplePC controller(canvas);
2234 SkBitmap bitmap = capture_bitmap(canvas);
2235 TiledPipeController tc(bitmap, &SkImageDecoder::DecodeMemory, &canvas->getTotalMatrix());
2236 SkGPipeController* pc;
2237 if (SkOSMenu::kMixedState == fPipeState) {
2242 uint32_t flags = SkGPipeWriter::kCrossProcess_Flag;
2244 canvas = writer.startRecording(pc, flags);
2245 //Must draw before controller goes out of scope and sends data
2246 this->INHERITED::draw(canvas);
2247 //explicitly end recording to ensure writer is flushed before the memory
2248 //is freed in the deconstructor of the controller
2249 writer.endRecording();
2253 void SampleView::onDraw(SkCanvas* canvas) {
2254 this->onDrawBackground(canvas);
2256 for (int i = 0; i < fRepeatCount; i++) {
2257 SkAutoCanvasRestore acr(canvas, true);
2258 this->onDrawContent(canvas);
2262 void SampleView::onDrawBackground(SkCanvas* canvas) {
2263 canvas->drawColor(fBGColor);
2266 ///////////////////////////////////////////////////////////////////////////////
2268 template <typename T> void SkTBSort(T array[], int count) {
2269 for (int i = 1; i < count - 1; i++) {
2270 bool didSwap = false;
2271 for (int j = count - 1; j > i; --j) {
2272 if (array[j] < array[j-1]) {
2274 array[j-1] = array[j];
2284 for (int k = 0; k < count - 1; k++) {
2285 SkASSERT(!(array[k+1] < array[k]));
2289 #include "SkRandom.h"
2291 static void rand_rect(SkIRect* rect, SkRandom& rand) {
2293 int shift = 32 - bits;
2294 rect->set(rand.nextU() >> shift, rand.nextU() >> shift,
2295 rand.nextU() >> shift, rand.nextU() >> shift);
2299 static void dumpRect(const SkIRect& r) {
2300 SkDebugf(" { %d, %d, %d, %d },\n",
2302 r.fRight, r.fBottom);
2305 static void test_rects(const SkIRect rect[], int count) {
2306 SkRegion rgn0, rgn1;
2308 for (int i = 0; i < count; i++) {
2309 rgn0.op(rect[i], SkRegion::kUnion_Op);
2310 // dumpRect(rect[i]);
2312 rgn1.setRects(rect, count);
2316 for (int i = 0; i < count; i++) {
2323 static void test() {
2326 const SkIRect r0[] = {
2330 const SkIRect r1[] = {
2335 const SkIRect r2[] = {
2342 static const struct {
2343 const SkIRect* fRects;
2346 { r0, SK_ARRAY_COUNT(r0) },
2347 { r1, SK_ARRAY_COUNT(r1) },
2348 { r2, SK_ARRAY_COUNT(r2) },
2351 for (i = 0; i < SK_ARRAY_COUNT(gRecs); i++) {
2352 test_rects(gRecs[i].fRects, gRecs[i].fCount);
2356 for (i = 0; i < 10000; i++) {
2357 SkRegion rgn0, rgn1;
2361 for (int j = 0; j < N; j++) {
2362 rand_rect(&rect[j], rand);
2364 test_rects(rect, N);
2368 // FIXME: this should be in a header
2369 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv);
2370 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
2371 if (false) { // avoid bit rot, suppress warning
2374 return new SampleWindow(hwnd, argc, argv, NULL);
2377 // FIXME: this should be in a header
2378 void get_preferred_size(int* x, int* y, int* width, int* height);
2379 void get_preferred_size(int* x, int* y, int* width, int* height) {
2386 #ifdef SK_BUILD_FOR_IOS
2387 IOS_launch_type set_cmd_line_args(int , char *[], const char* resourceDir) {
2388 SetResourcePath(resourceDir);
2389 return kApplication__iOSLaunchType;
2393 void application_init() {
2394 // setenv("ANDROID_ROOT", "../../../data", 0);
2395 #ifdef SK_BUILD_FOR_MAC
2396 setenv("ANDROID_ROOT", "/android/device/data", 0);
2402 void application_term() {