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"
18 #include "SkDocument.h"
20 #include "SkGraphics.h"
21 #include "SkImageEncoder.h"
23 //#include "SkPDFDevice.h"
24 //#include "SkPDFDocument.h"
26 #include "SkPicture.h"
27 #include "SkPictureRecorder.h"
29 #include "SkSurface.h"
32 #include "SkTypeface.h"
34 #include "TransitionView.h"
35 #include "sk_tool_utils.h"
38 #include "gl/GrGLInterface.h"
39 #include "gl/GrGLUtil.h"
40 #include "GrRenderTarget.h"
41 #include "GrContext.h"
42 #include "SkGpuDevice.h"
47 extern SampleView* CreateSamplePictFileView(const char filename[]);
49 class PictFileFactory : public SkViewFactory {
52 PictFileFactory(const SkString& filename) : fFilename(filename) {}
53 virtual SkView* operator() () const SK_OVERRIDE {
54 return CreateSamplePictFileView(fFilename.c_str());
58 #ifdef SAMPLE_PDF_FILE_VIEWER
59 extern SampleView* CreateSamplePdfFileViewer(const char filename[]);
61 class PdfFileViewerFactory : public SkViewFactory {
64 PdfFileViewerFactory(const SkString& filename) : fFilename(filename) {}
65 virtual SkView* operator() () const SK_OVERRIDE {
66 return CreateSamplePdfFileViewer(fFilename.c_str());
69 #endif // SAMPLE_PDF_FILE_VIEWER
73 #define FILE_PATH "/path/to/drawing.data"
78 #include "SkSockets.h"
82 #define USE_ARROWS_FOR_ZOOM true
85 //#define DEFAULT_TO_ANGLE 1
87 #define DEFAULT_TO_GPU 0 // if 1 default rendering is on GPU
90 #define ANIMATING_EVENTTYPE "nextSample"
91 #define ANIMATING_DELAY 250
94 #define FPS_REPEAT_MULTIPLIER 1
96 #define FPS_REPEAT_MULTIPLIER 10
98 #define FPS_REPEAT_COUNT (10 * FPS_REPEAT_MULTIPLIER)
100 static SampleWindow* gSampleWindow;
102 static bool gShowGMBounds;
104 static void post_event_to_sink(SkEvent* evt, SkEventSink* sink) {
105 evt->setTargetID(sink->getSinkID())->post();
108 ///////////////////////////////////////////////////////////////////////////////
110 static const char* skip_until(const char* str, const char* skip) {
114 return strstr(str, skip);
117 static const char* skip_past(const char* str, const char* skip) {
118 const char* found = skip_until(str, skip);
122 return found + strlen(skip);
125 static const char* gPrefFileName = "sampleapp_prefs.txt";
127 static bool readTitleFromPrefs(SkString* title) {
128 SkFILEStream stream(gPrefFileName);
129 if (!stream.isValid()) {
133 size_t len = stream.getLength();
135 stream.read(data.writable_str(), len);
136 const char* s = data.c_str();
138 s = skip_past(s, "curr-slide-title");
139 s = skip_past(s, "=");
140 s = skip_past(s, "\"");
141 const char* stop = skip_until(s, "\"");
143 title->set(s, stop - s);
149 static void writeTitleToPrefs(const char* title) {
150 SkFILEWStream stream(gPrefFileName);
152 data.printf("curr-slide-title = \"%s\"\n", title);
153 stream.write(data.c_str(), data.size());
156 ///////////////////////////////////////////////////////////////////////////////
158 class SampleWindow::DefaultDeviceManager : public SampleWindow::DeviceManager {
161 DefaultDeviceManager() {
165 fCurRenderTarget = NULL;
166 fMSAASampleCount = 0;
168 fBackend = kNone_BackEndType;
171 virtual ~DefaultDeviceManager() {
173 SkSafeUnref(fCurContext);
174 SkSafeUnref(fCurIntf);
175 SkSafeUnref(fCurRenderTarget);
179 virtual void setUpBackend(SampleWindow* win, int msaaSampleCount) {
180 SkASSERT(kNone_BackEndType == fBackend);
182 fBackend = kNone_BackEndType;
185 switch (win->getDeviceType()) {
186 case kRaster_DeviceType:
188 case kPicture_DeviceType:
190 case kGPU_DeviceType:
192 case kNullGPU_DeviceType:
193 // all these guys use the native backend
194 fBackend = kNativeGL_BackEndType;
197 case kANGLE_DeviceType:
198 // ANGLE is really the only odd man out
199 fBackend = kANGLE_BackEndType;
206 AttachmentInfo attachmentInfo;
207 bool result = win->attach(fBackend, msaaSampleCount, &attachmentInfo);
209 SkDebugf("Failed to initialize GL");
212 fMSAASampleCount = msaaSampleCount;
214 SkASSERT(NULL == fCurIntf);
215 SkAutoTUnref<const GrGLInterface> glInterface;
216 switch (win->getDeviceType()) {
217 case kRaster_DeviceType:
219 case kPicture_DeviceType:
221 case kGPU_DeviceType:
222 // all these guys use the native interface
223 glInterface.reset(GrGLCreateNativeInterface());
226 case kANGLE_DeviceType:
227 glInterface.reset(GrGLCreateANGLEInterface());
230 case kNullGPU_DeviceType:
231 glInterface.reset(GrGLCreateNullInterface());
238 // Currently SampleApp does not use NVPR. TODO: Provide an NVPR device type that is skipped
239 // when the driver doesn't support NVPR.
240 fCurIntf = GrGLInterfaceRemoveNVPR(glInterface.get());
242 SkASSERT(NULL == fCurContext);
243 fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf);
245 if (NULL == fCurContext || NULL == fCurIntf) {
246 // We need some context and interface to see results
247 SkSafeUnref(fCurContext);
248 SkSafeUnref(fCurIntf);
251 SkDebugf("Failed to setup 3D");
255 #endif // SK_SUPPORT_GPU
256 // call windowSizeChanged to create the render target
257 this->windowSizeChanged(win);
260 virtual void tearDownBackend(SampleWindow *win) {
263 // in case we have outstanding refs to this guy (lua?)
264 fCurContext->abandonContext();
265 fCurContext->unref();
269 SkSafeUnref(fCurIntf);
272 SkSafeUnref(fCurRenderTarget);
273 fCurRenderTarget = NULL;
276 fBackend = kNone_BackEndType;
279 virtual SkSurface* createSurface(SampleWindow::DeviceType dType,
280 SampleWindow* win) SK_OVERRIDE {
282 if (IsGpuDeviceType(dType) && fCurContext) {
283 SkSurfaceProps props(win->getSurfaceProps());
284 return SkSurface::NewRenderTargetDirect(fCurRenderTarget, &props);
290 virtual void publishCanvas(SampleWindow::DeviceType dType,
295 // in case we have queued drawing calls
296 fCurContext->flush();
298 if (!IsGpuDeviceType(dType)) {
299 // need to send the raster bits to the (gpu) window
300 fCurContext->setRenderTarget(fCurRenderTarget);
301 const SkBitmap& bm = win->getBitmap();
302 fCurRenderTarget->writePixels(0, 0, bm.width(), bm.height(),
303 SkImageInfo2GrPixelConfig(bm.colorType(),
307 GrContext::kFlushWrites_PixelOp);
315 virtual void windowSizeChanged(SampleWindow* win) {
318 AttachmentInfo attachmentInfo;
319 win->attach(fBackend, fMSAASampleCount, &attachmentInfo);
321 GrBackendRenderTargetDesc desc;
322 desc.fWidth = SkScalarRoundToInt(win->width());
323 desc.fHeight = SkScalarRoundToInt(win->height());
324 desc.fConfig = kSkia8888_GrPixelConfig;
325 desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
326 desc.fSampleCnt = attachmentInfo.fSampleCount;
327 desc.fStencilBits = attachmentInfo.fStencilBits;
329 GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
330 desc.fRenderTargetHandle = buffer;
332 SkSafeUnref(fCurRenderTarget);
333 fCurRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
338 virtual GrContext* getGrContext() {
346 virtual GrRenderTarget* getGrRenderTarget() SK_OVERRIDE {
348 return fCurRenderTarget;
357 GrContext* fCurContext;
358 const GrGLInterface* fCurIntf;
359 GrRenderTarget* fCurRenderTarget;
360 int fMSAASampleCount;
363 SkOSWindow::SkBackEndTypes fBackend;
365 typedef SampleWindow::DeviceManager INHERITED;
369 static const char view_inval_msg[] = "view-inval-msg";
371 void SampleWindow::postInvalDelay() {
372 (new SkEvent(view_inval_msg, this->getSinkID()))->postDelay(1);
375 static bool isInvalEvent(const SkEvent& evt) {
376 return evt.isType(view_inval_msg);
380 SkFuncViewFactory::SkFuncViewFactory(SkViewCreateFunc func)
381 : fCreateFunc(func) {
384 SkView* SkFuncViewFactory::operator() () const {
385 return (*fCreateFunc)();
388 #include "GMSampleView.h"
390 SkGMSampleViewFactory::SkGMSampleViewFactory(GMFactoryFunc func)
394 SkView* SkGMSampleViewFactory::operator() () const {
395 skiagm::GM* gm = fFunc(NULL);
396 gm->setMode(skiagm::GM::kSample_Mode);
397 return new GMSampleView(gm);
400 SkViewRegister* SkViewRegister::gHead;
401 SkViewRegister::SkViewRegister(SkViewFactory* fact) : fFact(fact) {
407 SkViewRegister::SkViewRegister(SkViewCreateFunc func) {
408 fFact = new SkFuncViewFactory(func);
413 SkViewRegister::SkViewRegister(GMFactoryFunc func) {
414 fFact = new SkGMSampleViewFactory(func);
419 class AutoUnrefArray {
423 int count = fObjs.count();
424 for (int i = 0; i < count; ++i) {
428 SkRefCnt*& push_back() { return *fObjs.append(); }
431 SkTDArray<SkRefCnt*> fObjs;
434 // registers GMs as Samples
435 // This can't be performed during static initialization because it could be
436 // run before GMRegistry has been fully built.
437 static void SkGMRegistyToSampleRegistry() {
439 static AutoUnrefArray fRegisters;
442 const skiagm::GMRegistry* gmreg = skiagm::GMRegistry::Head();
444 fRegisters.push_back() = new SkViewRegister(gmreg->factory());
445 gmreg = gmreg->next();
451 //////////////////////////////////////////////////////////////////////////////
454 kFlipAxis_X = (1 << 0),
455 kFlipAxis_Y = (1 << 1)
458 #include "SkDrawFilter.h"
460 struct HintingState {
461 SkPaint::Hinting hinting;
465 static HintingState gHintingStates[] = {
466 {SkPaint::kNo_Hinting, "Mixed", NULL },
467 {SkPaint::kNo_Hinting, "None", "H0 " },
468 {SkPaint::kSlight_Hinting, "Slight", "Hs " },
469 {SkPaint::kNormal_Hinting, "Normal", "Hn " },
470 {SkPaint::kFull_Hinting, "Full", "Hf " },
473 struct FilterLevelState {
474 SkPaint::FilterLevel fLevel;
478 static FilterLevelState gFilterLevelStates[] = {
479 { SkPaint::kNone_FilterLevel, "Mixed", NULL },
480 { SkPaint::kNone_FilterLevel, "None", "F0 " },
481 { SkPaint::kLow_FilterLevel, "Low", "F1 " },
482 { SkPaint::kMedium_FilterLevel, "Medium", "F2 " },
483 { SkPaint::kHigh_FilterLevel, "High", "F3 " },
486 class FlagsDrawFilter : public SkDrawFilter {
488 FlagsDrawFilter(SkOSMenu::TriState lcd, SkOSMenu::TriState aa,
489 SkOSMenu::TriState subpixel, int hinting, int filterlevel)
492 , fSubpixelState(subpixel)
493 , fHintingState(hinting)
494 , fFilterLevelIndex(filterlevel)
496 SkASSERT((unsigned)filterlevel < SK_ARRAY_COUNT(gFilterLevelStates));
499 virtual bool filter(SkPaint* paint, Type t) {
500 if (kText_Type == t && SkOSMenu::kMixedState != fLCDState) {
501 paint->setLCDRenderText(SkOSMenu::kOnState == fLCDState);
503 if (SkOSMenu::kMixedState != fAAState) {
504 paint->setAntiAlias(SkOSMenu::kOnState == fAAState);
506 if (0 != fFilterLevelIndex) {
507 paint->setFilterLevel(gFilterLevelStates[fFilterLevelIndex].fLevel);
509 if (SkOSMenu::kMixedState != fSubpixelState) {
510 paint->setSubpixelText(SkOSMenu::kOnState == fSubpixelState);
512 if (0 != fHintingState && fHintingState < (int)SK_ARRAY_COUNT(gHintingStates)) {
513 paint->setHinting(gHintingStates[fHintingState].hinting);
519 SkOSMenu::TriState fLCDState;
520 SkOSMenu::TriState fAAState;
521 SkOSMenu::TriState fSubpixelState;
523 int fFilterLevelIndex;
526 //////////////////////////////////////////////////////////////////////////////
528 #define MAX_ZOOM_LEVEL 8
529 #define MIN_ZOOM_LEVEL -8
531 static const char gCharEvtName[] = "SampleCode_Char_Event";
532 static const char gKeyEvtName[] = "SampleCode_Key_Event";
533 static const char gTitleEvtName[] = "SampleCode_Title_Event";
534 static const char gPrefSizeEvtName[] = "SampleCode_PrefSize_Event";
535 static const char gFastTextEvtName[] = "SampleCode_FastText_Event";
536 static const char gUpdateWindowTitleEvtName[] = "SampleCode_UpdateWindowTitle";
538 bool SampleCode::CharQ(const SkEvent& evt, SkUnichar* outUni) {
539 if (evt.isType(gCharEvtName, sizeof(gCharEvtName) - 1)) {
541 *outUni = evt.getFast32();
548 bool SampleCode::KeyQ(const SkEvent& evt, SkKey* outKey) {
549 if (evt.isType(gKeyEvtName, sizeof(gKeyEvtName) - 1)) {
551 *outKey = (SkKey)evt.getFast32();
558 bool SampleCode::TitleQ(const SkEvent& evt) {
559 return evt.isType(gTitleEvtName, sizeof(gTitleEvtName) - 1);
562 void SampleCode::TitleR(SkEvent* evt, const char title[]) {
563 SkASSERT(evt && TitleQ(*evt));
564 evt->setString(gTitleEvtName, title);
567 bool SampleCode::RequestTitle(SkView* view, SkString* title) {
568 SkEvent evt(gTitleEvtName);
569 if (view->doQuery(&evt)) {
570 title->set(evt.findString(gTitleEvtName));
576 bool SampleCode::PrefSizeQ(const SkEvent& evt) {
577 return evt.isType(gPrefSizeEvtName, sizeof(gPrefSizeEvtName) - 1);
580 void SampleCode::PrefSizeR(SkEvent* evt, SkScalar width, SkScalar height) {
581 SkASSERT(evt && PrefSizeQ(*evt));
585 evt->setScalars(gPrefSizeEvtName, 2, size);
588 bool SampleCode::FastTextQ(const SkEvent& evt) {
589 return evt.isType(gFastTextEvtName, sizeof(gFastTextEvtName) - 1);
592 ///////////////////////////////////////////////////////////////////////////////
594 static SkMSec gAnimTime;
595 static SkMSec gAnimTimePrev;
597 SkMSec SampleCode::GetAnimTime() { return gAnimTime; }
598 SkMSec SampleCode::GetAnimTimeDelta() { return gAnimTime - gAnimTimePrev; }
599 SkScalar SampleCode::GetAnimSecondsDelta() {
600 return SkDoubleToScalar(GetAnimTimeDelta() / 1000.0);
603 SkScalar SampleCode::GetAnimScalar(SkScalar speed, SkScalar period) {
604 // since gAnimTime can be up to 32 bits, we can't convert it to a float
605 // or we'll lose the low bits. Hence we use doubles for the intermediate
607 double seconds = (double)gAnimTime / 1000.0;
608 double value = SkScalarToDouble(speed) * seconds;
610 value = ::fmod(value, SkScalarToDouble(period));
612 return SkDoubleToScalar(value);
615 SkScalar SampleCode::GetAnimSinScalar(SkScalar amplitude,
616 SkScalar periodInSec,
617 SkScalar phaseInSec) {
621 double t = (double)gAnimTime / 1000.0 + phaseInSec;
622 t *= SkScalarToFloat(2 * SK_ScalarPI) / periodInSec;
623 amplitude = SK_ScalarHalf * amplitude;
624 return SkScalarMul(amplitude, SkDoubleToScalar(sin(t))) + amplitude;
635 kLast_TilingMode_Enum
643 static const struct TilingInfo gTilingInfo[] = {
644 { "No tiling", SK_Scalar1 , SK_Scalar1 }, // kNo_Tiling
645 { "128x128" , SkIntToScalar(128), SkIntToScalar(128) }, // kAbs_128x128_Tiling
646 { "256x256" , SkIntToScalar(256), SkIntToScalar(256) }, // kAbs_256x256_Tiling
647 { "1/4x1/4" , SK_Scalar1 / 4 , SK_Scalar1 / 4 }, // kRel_4x4_Tiling
648 { "1/1x1/16" , SK_Scalar1 , SK_Scalar1 / 16 }, // kRel_1x16_Tiling
649 { "1/16x1/1" , SK_Scalar1 / 16 , SK_Scalar1 }, // kRel_16x1_Tiling
651 SK_COMPILE_ASSERT((SK_ARRAY_COUNT(gTilingInfo) == kLast_TilingMode_Enum),
652 Incomplete_tiling_labels);
654 SkSize SampleWindow::tileSize() const {
655 SkASSERT((TilingMode)fTilingMode < kLast_TilingMode_Enum);
656 const struct TilingInfo* info = gTilingInfo + fTilingMode;
657 return SkSize::Make(info->w > SK_Scalar1 ? info->w : this->width() * info->w,
658 info->h > SK_Scalar1 ? info->h : this->height() * info->h);
660 //////////////////////////////////////////////////////////////////////////////
662 static SkView* curr_view(SkWindow* wind) {
663 SkView::F2BIter iter(wind);
667 static bool curr_title(SkWindow* wind, SkString* title) {
668 SkView* view = curr_view(wind);
670 SkEvent evt(gTitleEvtName);
671 if (view->doQuery(&evt)) {
672 title->set(evt.findString(gTitleEvtName));
679 void SampleWindow::setZoomCenter(float x, float y)
685 bool SampleWindow::zoomIn()
687 // Arbitrarily decided
688 if (fFatBitsScale == 25) return false;
694 bool SampleWindow::zoomOut()
696 if (fFatBitsScale == 1) return false;
702 void SampleWindow::updatePointer(int x, int y)
711 static inline SampleWindow::DeviceType cycle_devicetype(SampleWindow::DeviceType ct) {
712 static const SampleWindow::DeviceType gCT[] = {
713 SampleWindow::kPicture_DeviceType,
715 SampleWindow::kGPU_DeviceType,
717 SampleWindow::kANGLE_DeviceType,
719 SampleWindow::kRaster_DeviceType, // skip the null gpu device in normal cycling
720 #endif // SK_SUPPORT_GPU
721 SampleWindow::kRaster_DeviceType
723 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gCT) == SampleWindow::kDeviceTypeCnt, array_size_mismatch);
727 static SkString getSampleTitle(const SkViewFactory* sampleFactory) {
728 SkView* view = (*sampleFactory)();
730 SampleCode::RequestTitle(view, &title);
735 static bool compareSampleTitle(const SkViewFactory* first, const SkViewFactory* second) {
736 return strcmp(getSampleTitle(first).c_str(), getSampleTitle(second).c_str()) < 0;
739 DEFINE_string(slide, "", "Start on this sample.");
740 DEFINE_int32(msaa, 0, "Request multisampling with this count.");
741 DEFINE_string(pictureDir, "", "Read pictures from here.");
742 DEFINE_string(picture, "", "Path to single picture.");
743 DEFINE_bool(sort, false, "Sort samples by title.");
744 DEFINE_bool(list, false, "List samples?");
745 #ifdef SAMPLE_PDF_FILE_VIEWER
746 DEFINE_string(pdfPath, "", "Path to direcotry of pdf files.");
749 #include "SkTaskGroup.h"
751 SampleWindow::SampleWindow(void* hwnd, int argc, char** argv, DeviceManager* devManager)
753 , fDevManager(NULL) {
755 SkCommandLineFlags::Parse(argc, argv);
759 if (!FLAGS_pictureDir.isEmpty()) {
760 SkOSFile::Iter iter(FLAGS_pictureDir[0], "skp");
762 while (iter.next(&filename)) {
763 *fSamples.append() = new PictFileFactory(
764 SkOSPath::Join(FLAGS_pictureDir[0], filename.c_str()));
767 if (!FLAGS_picture.isEmpty()) {
768 SkString path(FLAGS_picture[0]);
769 fCurrIndex = fSamples.count();
770 *fSamples.append() = new PictFileFactory(path);
772 #ifdef SAMPLE_PDF_FILE_VIEWER
773 if (!FLAGS_pdfPath.isEmpty()) {
774 SkOSFile::Iter iter(FLAGS_pdfPath[0], "pdf");
776 while (iter.next(&filename)) {
777 *fSamples.append() = new PdfFileViewerFactory(
778 SkOSPath::Join(FLAGS_pictureDir[0], filename.c_str()));
782 SkGMRegistyToSampleRegistry();
784 const SkViewRegister* reg = SkViewRegister::Head();
786 *fSamples.append() = reg->factory();
792 // Sort samples, so foo.skp and foo.pdf are consecutive and we can quickly spot where
793 // skp -> pdf -> png fails.
794 SkTQSort(fSamples.begin(), fSamples.end() ? fSamples.end() - 1 : NULL, compareSampleTitle);
797 if (!FLAGS_slide.isEmpty()) {
798 fCurrIndex = findByTitle(FLAGS_slide[0]);
799 if (fCurrIndex < 0) {
800 fprintf(stderr, "Unknown sample \"%s\"\n", FLAGS_slide[0]);
805 fMSAASampleCount = FLAGS_msaa;
811 if (fCurrIndex < 0) {
813 if (readTitleFromPrefs(&title)) {
814 fCurrIndex = findByTitle(title.c_str());
818 if (fCurrIndex < 0) {
822 static SkTaskGroup::Enabler enabled(-1);
823 gSampleWindow = this;
826 //Clear existing file or create file if it doesn't exist
827 FILE* f = fopen(FILE_PATH, "wb");
831 fDeviceType = kRaster_DeviceType;
834 fDeviceType = kGPU_DeviceType;
836 #if SK_ANGLE && DEFAULT_TO_ANGLE
837 fDeviceType = kANGLE_DeviceType;
847 fRequestGrabImage = false;
848 fPipeState = SkOSMenu::kOffState;
849 fTilingMode = kNo_Tiling;
851 fLCDState = SkOSMenu::kMixedState;
852 fAAState = SkOSMenu::kMixedState;
853 fSubpixelState = SkOSMenu::kMixedState;
855 fFilterLevelIndex = 0;
857 fScrollTestX = fScrollTestY = 0;
859 fMouseX = fMouseY = 0;
861 fTypeface = SkTypeface::CreateFromTypeface(NULL, SkTypeface::kBold);
865 fZoomScale = SK_Scalar1;
874 int sinkID = this->getSinkID();
875 fAppMenu = new SkOSMenu;
876 fAppMenu->setTitle("Global Settings");
879 itemID =fAppMenu->appendList("Device Type", "Device Type", sinkID, 0,
880 "Raster", "Picture", "OpenGL",
885 fAppMenu->assignKeyEquivalentToItem(itemID, 'd');
886 itemID = fAppMenu->appendTriState("AA", "AA", sinkID, fAAState);
887 fAppMenu->assignKeyEquivalentToItem(itemID, 'b');
888 itemID = fAppMenu->appendTriState("LCD", "LCD", sinkID, fLCDState);
889 fAppMenu->assignKeyEquivalentToItem(itemID, 'l');
890 itemID = fAppMenu->appendList("FilterLevel", "FilterLevel", sinkID, fFilterLevelIndex,
891 gFilterLevelStates[0].fName,
892 gFilterLevelStates[1].fName,
893 gFilterLevelStates[2].fName,
894 gFilterLevelStates[3].fName,
895 gFilterLevelStates[4].fName,
897 fAppMenu->assignKeyEquivalentToItem(itemID, 'n');
898 itemID = fAppMenu->appendTriState("Subpixel", "Subpixel", sinkID, fSubpixelState);
899 fAppMenu->assignKeyEquivalentToItem(itemID, 's');
900 itemID = fAppMenu->appendList("Hinting", "Hinting", sinkID, fHintingState,
901 gHintingStates[0].name,
902 gHintingStates[1].name,
903 gHintingStates[2].name,
904 gHintingStates[3].name,
905 gHintingStates[4].name,
907 fAppMenu->assignKeyEquivalentToItem(itemID, 'h');
909 fUsePipeMenuItemID = fAppMenu->appendTriState("Pipe", "Pipe" , sinkID,
911 fAppMenu->assignKeyEquivalentToItem(fUsePipeMenuItemID, 'P');
913 itemID =fAppMenu->appendList("Tiling", "Tiling", sinkID, fTilingMode,
914 gTilingInfo[kNo_Tiling].label,
915 gTilingInfo[kAbs_128x128_Tiling].label,
916 gTilingInfo[kAbs_256x256_Tiling].label,
917 gTilingInfo[kRel_4x4_Tiling].label,
918 gTilingInfo[kRel_1x16_Tiling].label,
919 gTilingInfo[kRel_16x1_Tiling].label,
921 fAppMenu->assignKeyEquivalentToItem(itemID, 't');
923 itemID = fAppMenu->appendSwitch("Slide Show", "Slide Show" , sinkID, false);
924 fAppMenu->assignKeyEquivalentToItem(itemID, 'a');
925 itemID = fAppMenu->appendSwitch("Clip", "Clip" , sinkID, fUseClip);
926 fAppMenu->assignKeyEquivalentToItem(itemID, 'c');
927 itemID = fAppMenu->appendSwitch("Flip X", "Flip X" , sinkID, false);
928 fAppMenu->assignKeyEquivalentToItem(itemID, 'x');
929 itemID = fAppMenu->appendSwitch("Flip Y", "Flip Y" , sinkID, false);
930 fAppMenu->assignKeyEquivalentToItem(itemID, 'y');
931 itemID = fAppMenu->appendSwitch("Zoomer", "Zoomer" , sinkID, fShowZoomer);
932 fAppMenu->assignKeyEquivalentToItem(itemID, 'z');
933 itemID = fAppMenu->appendSwitch("Magnify", "Magnify" , sinkID, fMagnify);
934 fAppMenu->assignKeyEquivalentToItem(itemID, 'm');
935 itemID =fAppMenu->appendList("Transition-Next", "Transition-Next", sinkID,
936 fTransitionNext, "Up", "Up and Right", "Right",
937 "Down and Right", "Down", "Down and Left",
938 "Left", "Up and Left", NULL);
939 fAppMenu->assignKeyEquivalentToItem(itemID, 'j');
940 itemID =fAppMenu->appendList("Transition-Prev", "Transition-Prev", sinkID,
941 fTransitionPrev, "Up", "Up and Right", "Right",
942 "Down and Right", "Down", "Down and Left",
943 "Left", "Up and Left", NULL);
944 fAppMenu->assignKeyEquivalentToItem(itemID, 'k');
945 itemID = fAppMenu->appendAction("Save to PDF", sinkID);
946 fAppMenu->assignKeyEquivalentToItem(itemID, 'e');
948 this->addMenu(fAppMenu);
949 fSlideMenu = new SkOSMenu;
950 this->addMenu(fSlideMenu);
952 this->setColorType(kN32_SkColorType);
953 this->setVisibleP(true);
954 this->setClipToBounds(false);
956 this->loadView((*fSamples[fCurrIndex])());
958 if (NULL == devManager) {
959 fDevManager = new DefaultDeviceManager();
962 fDevManager = devManager;
964 fDevManager->setUpBackend(this, fMSAASampleCount);
966 // If another constructor set our dimensions, ensure that our
967 // onSizeChange gets called.
968 if (this->height() && this->width()) {
969 this->onSizeChange();
972 // can't call this synchronously, since it may require a subclass to
973 // to implement, or the caller may need us to have returned from the
974 // constructor first. Hence we post an event to ourselves.
975 // this->updateTitle();
976 post_event_to_sink(new SkEvent(gUpdateWindowTitleEvtName), this);
979 SampleWindow::~SampleWindow() {
980 SkSafeUnref(fTypeface);
981 SkSafeUnref(fDevManager);
985 int SampleWindow::findByTitle(const char title[]) {
986 int i, count = fSamples.count();
987 for (i = 0; i < count; i++) {
988 if (getSampleTitle(i).equals(title)) {
995 void SampleWindow::listTitles() {
996 int count = fSamples.count();
997 SkDebugf("All Slides:\n");
998 for (int i = 0; i < count; i++) {
999 SkDebugf(" %s\n", getSampleTitle(i).c_str());
1003 static SkBitmap capture_bitmap(SkCanvas* canvas) {
1005 if (bm.tryAllocPixels(canvas->imageInfo())) {
1006 canvas->readPixels(&bm, 0, 0);
1011 static bool bitmap_diff(SkCanvas* canvas, const SkBitmap& orig,
1013 SkBitmap src = capture_bitmap(canvas);
1015 SkAutoLockPixels alp0(src);
1016 SkAutoLockPixels alp1(orig);
1017 for (int y = 0; y < src.height(); y++) {
1018 const void* srcP = src.getAddr(0, y);
1019 const void* origP = orig.getAddr(0, y);
1020 size_t bytes = src.width() * src.bytesPerPixel();
1021 if (memcmp(srcP, origP, bytes)) {
1022 SkDebugf("---------- difference on line %d\n", y);
1029 static void drawText(SkCanvas* canvas, SkString string, SkScalar left, SkScalar top, SkPaint& paint)
1031 SkColor desiredColor = paint.getColor();
1032 paint.setColor(SK_ColorWHITE);
1033 const char* c_str = string.c_str();
1034 size_t size = string.size();
1036 paint.measureText(c_str, size, &bounds);
1037 bounds.offset(left, top);
1038 SkScalar inset = SkIntToScalar(-2);
1039 bounds.inset(inset, inset);
1040 canvas->drawRect(bounds, paint);
1041 if (desiredColor != SK_ColorBLACK) {
1042 paint.setColor(SK_ColorBLACK);
1043 canvas->drawText(c_str, size, left + SK_Scalar1, top + SK_Scalar1, paint);
1045 paint.setColor(desiredColor);
1046 canvas->drawText(c_str, size, left, top, paint);
1052 void SampleWindow::draw(SkCanvas* canvas) {
1053 // update the animation time
1054 if (!gAnimTimePrev && !gAnimTime) {
1055 // first time make delta be 0
1056 gAnimTime = SkTime::GetMSecs();
1057 gAnimTimePrev = gAnimTime;
1059 gAnimTimePrev = gAnimTime;
1060 gAnimTime = SkTime::GetMSecs();
1063 if (fGesture.isActive()) {
1064 this->updateMatrix();
1068 fMeasureFPS_Time = 0;
1072 this->INHERITED::draw(canvas);
1073 SkBitmap orig = capture_bitmap(canvas);
1075 const SkScalar w = this->width();
1076 const SkScalar h = this->height();
1077 const SkScalar cw = w / XCLIP_N;
1078 const SkScalar ch = h / YCLIP_N;
1079 for (int y = 0; y < YCLIP_N; y++) {
1082 r.fBottom = (y + 1) * ch;
1083 if (y == YCLIP_N - 1) {
1086 for (int x = 0; x < XCLIP_N; x++) {
1087 SkAutoCanvasRestore acr(canvas, true);
1089 r.fRight = (x + 1) * cw;
1090 if (x == XCLIP_N - 1) {
1093 canvas->clipRect(r);
1094 this->INHERITED::draw(canvas);
1099 if (bitmap_diff(canvas, orig, &diff)) {
1102 SkSize tile = this->tileSize();
1104 if (kNo_Tiling == fTilingMode) {
1105 this->INHERITED::draw(canvas); // no looping or surfaces needed
1107 const int w = SkScalarRoundToInt(tile.width());
1108 const int h = SkScalarRoundToInt(tile.height());
1109 SkImageInfo info = SkImageInfo::MakeN32Premul(w, h);
1110 SkAutoTUnref<SkSurface> surface(canvas->newSurface(info));
1111 SkCanvas* tileCanvas = surface->getCanvas();
1113 for (SkScalar y = 0; y < height(); y += tile.height()) {
1114 for (SkScalar x = 0; x < width(); x += tile.width()) {
1115 SkAutoCanvasRestore acr(tileCanvas, true);
1116 tileCanvas->translate(-x, -y);
1117 tileCanvas->clear(0);
1118 this->INHERITED::draw(tileCanvas);
1119 surface->draw(canvas, x, y, NULL);
1123 // for drawing the borders between tiles
1125 paint.setColor(0x60FF00FF);
1126 paint.setStyle(SkPaint::kStroke_Style);
1128 for (SkScalar y = 0; y < height(); y += tile.height()) {
1129 for (SkScalar x = 0; x < width(); x += tile.width()) {
1130 canvas->drawRect(SkRect::MakeXYWH(x, y, tile.width(), tile.height()), paint);
1135 if (fShowZoomer && !fSaveToPdf) {
1138 if (fMagnify && !fSaveToPdf) {
1142 if (fMeasureFPS && fMeasureFPS_Time) {
1143 this->updateTitle();
1144 this->postInvalDelay();
1148 fDevManager->publishCanvas(fDeviceType, canvas, this);
1151 static float clipW = 200;
1152 static float clipH = 200;
1153 void SampleWindow::magnify(SkCanvas* canvas) {
1155 int count = canvas->save();
1157 SkMatrix m = canvas->getTotalMatrix();
1158 if (!m.invert(&m)) {
1161 SkPoint offset, center;
1162 SkScalar mouseX = fMouseX * SK_Scalar1;
1163 SkScalar mouseY = fMouseY * SK_Scalar1;
1164 m.mapXY(mouseX - clipW/2, mouseY - clipH/2, &offset);
1165 m.mapXY(mouseX, mouseY, ¢er);
1167 r.set(0, 0, clipW * m.getScaleX(), clipH * m.getScaleX());
1168 r.offset(offset.fX, offset.fY);
1171 paint.setColor(0xFF66AAEE);
1172 paint.setStyle(SkPaint::kStroke_Style);
1173 paint.setStrokeWidth(10.f * m.getScaleX());
1175 //canvas->translate(0, -250);
1176 canvas->drawRect(r, paint);
1177 canvas->clipRect(r);
1179 m = canvas->getTotalMatrix();
1180 m.setTranslate(-center.fX, -center.fY);
1181 m.postScale(0.5f * fFatBitsScale, 0.5f * fFatBitsScale);
1182 m.postTranslate(center.fX, center.fY);
1185 this->INHERITED::draw(canvas);
1187 canvas->restoreToCount(count);
1190 void SampleWindow::showZoomer(SkCanvas* canvas) {
1191 int count = canvas->save();
1192 canvas->resetMatrix();
1193 // Ensure the mouse position is on screen.
1194 int width = SkScalarRoundToInt(this->width());
1195 int height = SkScalarRoundToInt(this->height());
1196 if (fMouseX >= width) fMouseX = width - 1;
1197 else if (fMouseX < 0) fMouseX = 0;
1198 if (fMouseY >= height) fMouseY = height - 1;
1199 else if (fMouseY < 0) fMouseY = 0;
1201 SkBitmap bitmap = capture_bitmap(canvas);
1202 bitmap.lockPixels();
1204 // Find the size of the zoomed in view, forced to be odd, so the examined pixel is in the middle.
1205 int zoomedWidth = (width >> 1) | 1;
1206 int zoomedHeight = (height >> 1) | 1;
1208 src.set(0, 0, zoomedWidth / fFatBitsScale, zoomedHeight / fFatBitsScale);
1209 src.offset(fMouseX - (src.width()>>1), fMouseY - (src.height()>>1));
1211 dest.set(0, 0, SkIntToScalar(zoomedWidth), SkIntToScalar(zoomedHeight));
1212 dest.offset(SkIntToScalar(width - zoomedWidth), SkIntToScalar(height - zoomedHeight));
1214 // Clear the background behind our zoomed in view
1215 paint.setColor(SK_ColorWHITE);
1216 canvas->drawRect(dest, paint);
1217 canvas->drawBitmapRect(bitmap, &src, dest);
1218 paint.setColor(SK_ColorBLACK);
1219 paint.setStyle(SkPaint::kStroke_Style);
1220 // Draw a border around the pixel in the middle
1221 SkRect originalPixel;
1222 originalPixel.set(SkIntToScalar(fMouseX), SkIntToScalar(fMouseY), SkIntToScalar(fMouseX + 1), SkIntToScalar(fMouseY + 1));
1226 SkColor color = bitmap.getColor(fMouseX, fMouseY);
1227 if (matrix.setRectToRect(scalarSrc, dest, SkMatrix::kFill_ScaleToFit)) {
1229 matrix.mapRect(&pixel, originalPixel);
1230 // TODO Perhaps measure the values and make the outline white if it's "dark"
1231 if (color == SK_ColorBLACK) {
1232 paint.setColor(SK_ColorWHITE);
1234 canvas->drawRect(pixel, paint);
1236 paint.setColor(SK_ColorBLACK);
1237 // Draw a border around the destination rectangle
1238 canvas->drawRect(dest, paint);
1239 paint.setStyle(SkPaint::kStrokeAndFill_Style);
1240 // Identify the pixel and its color on screen
1241 paint.setTypeface(fTypeface);
1242 paint.setAntiAlias(true);
1243 SkScalar lineHeight = paint.getFontMetrics(NULL);
1245 string.appendf("(%i, %i)", fMouseX, fMouseY);
1246 SkScalar left = dest.fLeft + SkIntToScalar(3);
1247 SkScalar i = SK_Scalar1;
1248 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1252 string.appendf("A: %X", SkColorGetA(color));
1253 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1257 string.appendf("R: %X", SkColorGetR(color));
1258 paint.setColor(SK_ColorRED);
1259 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1263 string.appendf("G: %X", SkColorGetG(color));
1264 paint.setColor(SK_ColorGREEN);
1265 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1269 string.appendf("B: %X", SkColorGetB(color));
1270 paint.setColor(SK_ColorBLUE);
1271 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1272 canvas->restoreToCount(count);
1275 void SampleWindow::onDraw(SkCanvas* canvas) {
1278 #include "SkColorPriv.h"
1280 void SampleWindow::saveToPdf()
1286 SkCanvas* SampleWindow::beforeChildren(SkCanvas* canvas) {
1289 if (!this->getRawTitle(&name)) {
1290 name.set("unknown_sample");
1292 name.append(".pdf");
1293 #ifdef SK_BUILD_FOR_ANDROID
1294 name.prepend("/sdcard/");
1296 fPDFDocument.reset(SkDocument::CreatePDF(name.c_str()));
1297 canvas = fPDFDocument->beginPage(this->width(), this->height());
1298 } else if (kPicture_DeviceType == fDeviceType) {
1299 canvas = fRecorder.beginRecording(9999, 9999, NULL, 0);
1302 if (kNullGPU_DeviceType != fDeviceType)
1305 canvas = this->INHERITED::beforeChildren(canvas);
1310 canvas->drawColor(0xFFFF88FF);
1311 canvas->clipPath(fClipPath, SkRegion::kIntersect_Op, true);
1316 #include "SkMultiPictureDraw.h"
1317 void SampleWindow::afterChildren(SkCanvas* orig) {
1320 fPDFDocument->endPage();
1321 fPDFDocument.reset(NULL);
1322 // We took over the draw calls in order to create the PDF, so we need
1328 if (fRequestGrabImage) {
1329 fRequestGrabImage = false;
1331 SkBitmap bmp = capture_bitmap(orig);
1332 if (!bmp.isNull()) {
1333 static int gSampleGrabCounter;
1335 name.printf("sample_grab_%d.png", gSampleGrabCounter++);
1336 SkImageEncoder::EncodeFile(name.c_str(), bmp,
1337 SkImageEncoder::kPNG_Type, 100);
1341 if (kPicture_DeviceType == fDeviceType) {
1342 SkAutoTUnref<const SkPicture> picture(fRecorder.endRecording());
1345 this->installDrawFilter(orig);
1350 void* addr = orig->accessTopLayerPixels(&info, &rowBytes);
1352 SkSurface* surfs[4];
1353 SkMultiPictureDraw md;
1355 SkImageInfo n = SkImageInfo::Make(info.width()/2, info.height()/2,
1356 info.colorType(), info.alphaType());
1358 for (int y = 0; y < 2; ++y) {
1359 for (int x = 0; x < 2; ++x) {
1360 char* p = (char*)addr;
1361 p += y * n.height() * rowBytes;
1362 p += x * n.width() * sizeof(SkPMColor);
1363 surfs[index] = SkSurface::NewRasterDirect(n, p, rowBytes);
1364 SkCanvas* c = surfs[index]->getCanvas();
1365 c->translate(SkIntToScalar(-x * n.width()),
1366 SkIntToScalar(-y * n.height()));
1367 md.add(c, picture, NULL, NULL);
1372 for (int i = 0; i < 4; ++i) {
1377 orig->drawPicture(picture);
1380 SkDynamicMemoryWStream ostream;
1381 picture->serialize(&ostream);
1383 SkAutoDataUnref data(ostream.copyToData());
1384 SkMemoryStream istream(data->data(), data->size());
1385 SkAutoTUnref<SkPicture> pict(SkPicture::CreateFromStream(&istream));
1386 if (pict.get() != NULL) {
1387 orig->drawPicture(pict.get());
1390 picture->playback(orig);
1394 // Do this after presentGL and other finishing, rather than in afterChild
1395 if (fMeasureFPS && fMeasureFPS_StartTime) {
1396 fMeasureFPS_Time += SkTime::GetMSecs() - fMeasureFPS_StartTime;
1400 void SampleWindow::beforeChild(SkView* child, SkCanvas* canvas) {
1402 fRotateAnimTime += SampleCode::GetAnimSecondsDelta();
1404 SkScalar cx = this->width() / 2;
1405 SkScalar cy = this->height() / 2;
1406 canvas->translate(cx, cy);
1407 canvas->rotate(fRotateAnimTime * 10);
1408 canvas->translate(-cx, -cy);
1412 fPerspAnimTime += SampleCode::GetAnimSecondsDelta();
1414 static const SkScalar gAnimPeriod = 10 * SK_Scalar1;
1415 static const SkScalar gAnimMag = SK_Scalar1 / 1000;
1416 SkScalar t = SkScalarMod(fPerspAnimTime, gAnimPeriod);
1417 if (SkScalarFloorToInt(SkScalarDiv(fPerspAnimTime, gAnimPeriod)) & 0x1) {
1418 t = gAnimPeriod - t;
1420 t = 2 * t - gAnimPeriod;
1421 t = SkScalarMul(SkScalarDiv(t, gAnimPeriod), gAnimMag);
1427 m.setPerspY(SK_Scalar1 / 1000);
1428 m.setSkewX(SkScalarDiv(8, 25));
1434 this->installDrawFilter(canvas);
1437 if (SampleView::SetRepeatDraw(child, FPS_REPEAT_COUNT)) {
1438 fMeasureFPS_StartTime = SkTime::GetMSecs();
1441 (void)SampleView::SetRepeatDraw(child, 1);
1443 if (fPerspAnim || fRotate) {
1448 void SampleWindow::afterChild(SkView* child, SkCanvas* canvas) {
1449 canvas->setDrawFilter(NULL);
1452 static SkColorType gColorTypeCycle[] = {
1453 kUnknown_SkColorType, // none -> none
1454 kUnknown_SkColorType, // a8 -> none
1455 kN32_SkColorType, // 565 -> 8888
1456 kN32_SkColorType, // 4444 -> 8888
1457 kRGB_565_SkColorType, // 8888 -> 565
1458 kRGB_565_SkColorType, // 8888 -> 565
1459 kUnknown_SkColorType, // index8 -> none
1462 static SkColorType cycle_colortypes(SkColorType c) {
1463 return gColorTypeCycle[c];
1466 void SampleWindow::changeZoomLevel(float delta) {
1467 fZoomLevel += delta;
1468 if (fZoomLevel > 0) {
1469 fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL);
1470 fZoomScale = fZoomLevel + SK_Scalar1;
1471 } else if (fZoomLevel < 0) {
1472 fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL);
1473 fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel);
1475 fZoomScale = SK_Scalar1;
1477 this->updateMatrix();
1480 void SampleWindow::updateMatrix(){
1485 //m = this->getLocalMatrix();//.invert(&m);
1486 m.mapXY(fZoomCenterX, fZoomCenterY, ¢er);
1487 SkScalar cx = center.fX;
1488 SkScalar cy = center.fY;
1490 m.setTranslate(-cx, -cy);
1491 m.postScale(fZoomScale, fZoomScale);
1492 m.postTranslate(cx, cy);
1496 m.preTranslate(fZoomCenterX, fZoomCenterY);
1497 if (fFlipAxis & kFlipAxis_X) {
1498 m.preScale(-SK_Scalar1, SK_Scalar1);
1500 if (fFlipAxis & kFlipAxis_Y) {
1501 m.preScale(SK_Scalar1, -SK_Scalar1);
1503 m.preTranslate(-fZoomCenterX, -fZoomCenterY);
1504 //canvas->concat(m);
1506 // Apply any gesture matrix
1507 m.preConcat(fGesture.localM());
1508 m.preConcat(fGesture.globalM());
1510 this->setLocalMatrix(m);
1512 this->updateTitle();
1515 bool SampleWindow::previousSample() {
1516 fCurrIndex = (fCurrIndex - 1 + fSamples.count()) % fSamples.count();
1517 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(),
1522 bool SampleWindow::nextSample() {
1523 fCurrIndex = (fCurrIndex + 1) % fSamples.count();
1524 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(),
1529 bool SampleWindow::goToSample(int i) {
1530 fCurrIndex = (i) % fSamples.count();
1531 this->loadView(create_transition(curr_view(this),(*fSamples[fCurrIndex])(), 6));
1535 SkString SampleWindow::getSampleTitle(int i) {
1536 return ::getSampleTitle(fSamples[i]);
1539 int SampleWindow::sampleCount() {
1540 return fSamples.count();
1543 void SampleWindow::showOverview() {
1544 this->loadView(create_transition(curr_view(this),
1545 create_overview(fSamples.count(), fSamples.begin()),
1549 void SampleWindow::installDrawFilter(SkCanvas* canvas) {
1550 canvas->setDrawFilter(new FlagsDrawFilter(fLCDState, fAAState, fSubpixelState,
1551 fHintingState, fFilterLevelIndex))->unref();
1554 void SampleWindow::postAnimatingEvent() {
1556 (new SkEvent(ANIMATING_EVENTTYPE, this->getSinkID()))->postDelay(ANIMATING_DELAY);
1560 bool SampleWindow::onEvent(const SkEvent& evt) {
1561 if (evt.isType(gUpdateWindowTitleEvtName)) {
1562 this->updateTitle();
1565 if (evt.isType(ANIMATING_EVENTTYPE)) {
1568 this->postAnimatingEvent();
1572 if (evt.isType("replace-transition-view")) {
1573 this->loadView((SkView*)SkEventSink::FindSink(evt.getFast32()));
1576 if (evt.isType("set-curr-index")) {
1577 this->goToSample(evt.getFast32());
1580 if (isInvalEvent(evt)) {
1585 if (SkOSMenu::FindListIndex(evt, "Device Type", &selected)) {
1586 this->setDeviceType((DeviceType)selected);
1589 if (SkOSMenu::FindTriState(evt, "Pipe", &fPipeState)) {
1591 if (!fPipeState != SkOSMenu::kOnState)
1592 gServer.disconnectAll();
1594 (void)SampleView::SetUsePipe(curr_view(this), fPipeState);
1595 this->updateTitle();
1599 if (SkOSMenu::FindSwitchState(evt, "Slide Show", NULL)) {
1600 this->toggleSlideshow();
1603 if (SkOSMenu::FindTriState(evt, "AA", &fAAState) ||
1604 SkOSMenu::FindTriState(evt, "LCD", &fLCDState) ||
1605 SkOSMenu::FindListIndex(evt, "FilterLevel", &fFilterLevelIndex) ||
1606 SkOSMenu::FindTriState(evt, "Subpixel", &fSubpixelState) ||
1607 SkOSMenu::FindListIndex(evt, "Hinting", &fHintingState) ||
1608 SkOSMenu::FindSwitchState(evt, "Clip", &fUseClip) ||
1609 SkOSMenu::FindSwitchState(evt, "Zoomer", &fShowZoomer) ||
1610 SkOSMenu::FindSwitchState(evt, "Magnify", &fMagnify) ||
1611 SkOSMenu::FindListIndex(evt, "Transition-Next", &fTransitionNext) ||
1612 SkOSMenu::FindListIndex(evt, "Transition-Prev", &fTransitionPrev)) {
1614 this->updateTitle();
1617 if (SkOSMenu::FindListIndex(evt, "Tiling", &fTilingMode)) {
1618 if (SampleView::IsSampleView(curr_view(this))) {
1619 ((SampleView*)curr_view(this))->onTileSizeChanged(this->tileSize());
1622 this->updateTitle();
1625 if (SkOSMenu::FindSwitchState(evt, "Flip X", NULL)) {
1626 fFlipAxis ^= kFlipAxis_X;
1627 this->updateMatrix();
1630 if (SkOSMenu::FindSwitchState(evt, "Flip Y", NULL)) {
1631 fFlipAxis ^= kFlipAxis_Y;
1632 this->updateMatrix();
1635 if (SkOSMenu::FindAction(evt,"Save to PDF")) {
1639 return this->INHERITED::onEvent(evt);
1642 bool SampleWindow::onQuery(SkEvent* query) {
1643 if (query->isType("get-slide-count")) {
1644 query->setFast32(fSamples.count());
1647 if (query->isType("get-slide-title")) {
1648 SkView* view = (*fSamples[query->getFast32()])();
1649 SkEvent evt(gTitleEvtName);
1650 if (view->doQuery(&evt)) {
1651 query->setString("title", evt.findString(gTitleEvtName));
1656 if (query->isType("use-fast-text")) {
1657 SkEvent evt(gFastTextEvtName);
1658 return curr_view(this)->doQuery(&evt);
1660 if (query->isType("ignore-window-bitmap")) {
1661 query->setFast32(this->getGrContext() != NULL);
1664 return this->INHERITED::onQuery(query);
1668 static void cleanup_for_filename(SkString* name) {
1669 char* str = name->writable_str();
1670 for (size_t i = 0; i < name->size(); i++) {
1672 case ':': str[i] = '-'; break;
1673 case '/': str[i] = '-'; break;
1674 case ' ': str[i] = '_'; break;
1681 DECLARE_bool(portableFonts);
1683 bool SampleWindow::onHandleChar(SkUnichar uni) {
1685 SkView* view = curr_view(this);
1687 SkEvent evt(gCharEvtName);
1689 if (view->doQuery(&evt)) {
1699 case '5': dx = 0; dy = 0; break;
1700 case '8': dx = 0; dy = -1; break;
1701 case '6': dx = 1; dy = 0; break;
1702 case '2': dx = 0; dy = 1; break;
1703 case '4': dx = -1; dy = 0; break;
1704 case '7': dx = -1; dy = -1; break;
1705 case '9': dx = 1; dy = -1; break;
1706 case '3': dx = 1; dy = 1; break;
1707 case '1': dx = -1; dy = 1; break;
1713 if (0xFF != dx && 0xFF != dy) {
1714 if ((dx | dy) == 0) {
1715 fScrollTestX = fScrollTestY = 0;
1726 post_event_to_sink(SkNEW_ARGS(SkEvent, ("PictFileView::toggleBBox")), curr_view(this));
1727 // Cannot call updateTitle() synchronously, because the toggleBBox event is still in
1729 post_event_to_sink(SkNEW_ARGS(SkEvent, (gUpdateWindowTitleEvtName)), this);
1733 toggleDistanceFieldFonts();
1740 FLAGS_portableFonts ^= true;
1744 fRequestGrabImage = true;
1748 gShowGMBounds = !gShowGMBounds;
1749 post_event_to_sink(GMSampleView::NewShowSizeEvt(gShowGMBounds),
1761 fRotateAnimTime = 0;
1763 this->updateTitle();
1766 fPerspAnim = !fPerspAnim;
1768 this->updateTitle();
1772 this->setDeviceType(kNullGPU_DeviceType);
1774 this->updateTitle();
1778 GrContext* grContext = this->getGrContext();
1781 grContext->getResourceCacheUsage(NULL, &cacheBytes);
1782 grContext->freeGpuResources();
1783 SkDebugf("Purged %d bytes from the GPU resource cache.\n", cacheBytes);
1792 if (fAppMenu->handleKeyEquivalent(uni)|| fSlideMenu->handleKeyEquivalent(uni)) {
1793 this->onUpdateMenu(fAppMenu);
1794 this->onUpdateMenu(fSlideMenu);
1797 return this->INHERITED::onHandleChar(uni);
1800 void SampleWindow::setDeviceType(DeviceType type) {
1801 if (type == fDeviceType)
1804 fDevManager->tearDownBackend(this);
1808 fDevManager->setUpBackend(this, fMSAASampleCount);
1810 this->updateTitle();
1814 void SampleWindow::toggleSlideshow() {
1815 fAnimating = !fAnimating;
1816 this->postAnimatingEvent();
1817 this->updateTitle();
1820 void SampleWindow::toggleRendering() {
1821 this->setDeviceType(cycle_devicetype(fDeviceType));
1822 this->updateTitle();
1826 void SampleWindow::toggleFPS() {
1827 fMeasureFPS = !fMeasureFPS;
1828 this->updateTitle();
1832 void SampleWindow::toggleDistanceFieldFonts() {
1833 SkSurfaceProps props = this->getSurfaceProps();
1834 uint32_t flags = props.flags() ^ SkSurfaceProps::kUseDistanceFieldFonts_Flag;
1835 this->setSurfaceProps(SkSurfaceProps(flags, props.pixelGeometry()));
1837 this->updateTitle();
1841 #include "SkDumpCanvas.h"
1843 bool SampleWindow::onHandleKey(SkKey key) {
1845 SkView* view = curr_view(this);
1847 SkEvent evt(gKeyEvtName);
1849 if (view->doQuery(&evt)) {
1856 if (this->nextSample()) {
1861 if (this->previousSample()) {
1866 if (USE_ARROWS_FOR_ZOOM) {
1867 this->changeZoomLevel(1.f / 32.f);
1871 this->updateTitle();
1875 if (USE_ARROWS_FOR_ZOOM) {
1876 this->changeZoomLevel(-1.f / 32.f);
1878 this->setColorType(cycle_colortypes(this->getBitmap().colorType()));
1879 this->updateTitle();
1884 if (curr_title(this, &title)) {
1885 writeTitleToPrefs(title.c_str());
1890 this->showOverview();
1895 return this->INHERITED::onHandleKey(key);
1898 ///////////////////////////////////////////////////////////////////////////////
1900 static const char gGestureClickType[] = "GestureClickType";
1902 bool SampleWindow::onDispatchClick(int x, int y, Click::State state,
1903 void* owner, unsigned modi) {
1904 if (Click::kMoved_State == state) {
1905 updatePointer(x, y);
1907 int w = SkScalarRoundToInt(this->width());
1908 int h = SkScalarRoundToInt(this->height());
1910 // check for the resize-box
1911 if (w - x < 16 && h - y < 16) {
1912 return false; // let the OS handle the click
1914 else if (fMagnify) {
1915 //it's only necessary to update the drawing if there's a click
1917 return false; //prevent dragging while magnify is enabled
1919 // capture control+option, and trigger debugger
1920 if ((modi & kControl_SkModifierKey) && (modi & kOption_SkModifierKey)) {
1921 if (Click::kDown_State == state) {
1922 SkEvent evt("debug-hit-test");
1923 evt.setS32("debug-hit-test-x", x);
1924 evt.setS32("debug-hit-test-y", y);
1925 curr_view(this)->doEvent(evt);
1929 return this->INHERITED::onDispatchClick(x, y, state, owner, modi);
1934 class GestureClick : public SkView::Click {
1936 GestureClick(SkView* target) : SkView::Click(target) {
1937 this->setType(gGestureClickType);
1940 static bool IsGesture(Click* click) {
1941 return click->isType(gGestureClickType);
1945 SkView::Click* SampleWindow::onFindClickHandler(SkScalar x, SkScalar y,
1947 return new GestureClick(this);
1950 bool SampleWindow::onClick(Click* click) {
1951 if (GestureClick::IsGesture(click)) {
1952 float x = static_cast<float>(click->fICurr.fX);
1953 float y = static_cast<float>(click->fICurr.fY);
1955 switch (click->fState) {
1956 case SkView::Click::kDown_State:
1957 fGesture.touchBegin(click->fOwner, x, y);
1959 case SkView::Click::kMoved_State:
1960 fGesture.touchMoved(click->fOwner, x, y);
1961 this->updateMatrix();
1963 case SkView::Click::kUp_State:
1964 fGesture.touchEnd(click->fOwner);
1965 this->updateMatrix();
1973 ///////////////////////////////////////////////////////////////////////////////
1975 void SampleWindow::loadView(SkView* view) {
1976 SkView::F2BIter iter(this);
1977 SkView* prev = iter.next();
1979 prev->detachFromParent();
1982 view->setVisibleP(true);
1983 view->setClipToBounds(false);
1984 this->attachChildToFront(view)->unref();
1985 view->setSize(this->width(), this->height());
1987 //repopulate the slide menu when a view is loaded
1988 fSlideMenu->reset();
1990 (void)SampleView::SetUsePipe(view, fPipeState);
1991 if (SampleView::IsSampleView(view)) {
1992 SampleView* sampleView = (SampleView*)view;
1993 sampleView->requestMenu(fSlideMenu);
1994 sampleView->onTileSizeChanged(this->tileSize());
1996 this->onUpdateMenu(fSlideMenu);
1997 this->updateTitle();
2000 static const char* gDeviceTypePrefix[] = {
2009 #endif // SK_SUPPORT_GPU
2011 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gDeviceTypePrefix) == SampleWindow::kDeviceTypeCnt,
2012 array_size_mismatch);
2014 static const char* trystate_str(SkOSMenu::TriState state,
2015 const char trueStr[], const char falseStr[]) {
2016 if (SkOSMenu::kOnState == state) {
2018 } else if (SkOSMenu::kOffState == state) {
2024 bool SampleWindow::getRawTitle(SkString* title) {
2025 return curr_title(this, title);
2028 void SampleWindow::updateTitle() {
2030 if (!this->getRawTitle(&title)) {
2031 title.set("<unknown>");
2034 title.prepend(gDeviceTypePrefix[fDeviceType]);
2037 title.prepend(sk_tool_utils::colortype_name(this->getBitmap().colorType()));
2039 if (fTilingMode != kNo_Tiling) {
2040 title.prependf("<T: %s> ", gTilingInfo[fTilingMode].label);
2043 title.prepend("<A> ");
2046 title.prepend("<R> ");
2049 title.prepend("<C> ");
2052 title.prepend("<K> ");
2054 if (this->getSurfaceProps().flags() & SkSurfaceProps::kUseDistanceFieldFonts_Flag) {
2055 title.prepend("<DFF> ");
2058 title.prepend(trystate_str(fLCDState, "LCD ", "lcd "));
2059 title.prepend(trystate_str(fAAState, "AA ", "aa "));
2060 title.prepend(gFilterLevelStates[fFilterLevelIndex].fLabel);
2061 title.prepend(trystate_str(fSubpixelState, "S ", "s "));
2062 title.prepend(fFlipAxis & kFlipAxis_X ? "X " : NULL);
2063 title.prepend(fFlipAxis & kFlipAxis_Y ? "Y " : NULL);
2064 title.prepend(gHintingStates[fHintingState].label);
2067 title.prependf("{%.2f} ", SkScalarToFloat(fZoomLevel));
2071 title.appendf(" %8.3f ms", fMeasureFPS_Time / (float)FPS_REPEAT_COUNT);
2074 SkView* view = curr_view(this);
2075 if (SampleView::IsSampleView(view)) {
2076 switch (fPipeState) {
2077 case SkOSMenu::kOnState:
2078 title.prepend("<Pipe> ");
2080 case SkOSMenu::kMixedState:
2081 title.prepend("<Tiled Pipe> ");
2087 title.prepend("! ");
2091 if (IsGpuDeviceType(fDeviceType) &&
2093 fDevManager->getGrRenderTarget() &&
2094 fDevManager->getGrRenderTarget()->numSamples() > 0) {
2095 title.appendf(" [MSAA: %d]",
2096 fDevManager->getGrRenderTarget()->numSamples());
2100 this->setTitle(title.c_str());
2103 void SampleWindow::onSizeChange() {
2104 this->INHERITED::onSizeChange();
2106 SkView::F2BIter iter(this);
2107 SkView* view = iter.next();
2108 view->setSize(this->width(), this->height());
2110 // rebuild our clippath
2112 const SkScalar W = this->width();
2113 const SkScalar H = this->height();
2117 for (SkScalar y = SK_Scalar1; y < H; y += SkIntToScalar(32)) {
2119 r.set(SK_Scalar1, y, SkIntToScalar(30), y + SkIntToScalar(30));
2120 for (; r.fLeft < W; r.offset(SkIntToScalar(32), 0))
2121 fClipPath.addRect(r);
2126 fClipPath.addRect(r, SkPath::kCCW_Direction);
2127 r.set(W/4, H/4, W*3/4, H*3/4);
2128 fClipPath.addRect(r, SkPath::kCW_Direction);
2132 fZoomCenterX = SkScalarHalf(this->width());
2133 fZoomCenterY = SkScalarHalf(this->height());
2135 #ifdef SK_BUILD_FOR_ANDROID
2136 // FIXME: The first draw after a size change does not work on Android, so
2137 // we post an invalidate.
2138 this->postInvalDelay();
2140 this->updateTitle(); // to refresh our config
2141 fDevManager->windowSizeChanged(this);
2143 if (fTilingMode != kNo_Tiling && SampleView::IsSampleView(view)) {
2144 ((SampleView*)view)->onTileSizeChanged(this->tileSize());
2148 ///////////////////////////////////////////////////////////////////////////////
2150 static const char is_sample_view_tag[] = "sample-is-sample-view";
2151 static const char repeat_count_tag[] = "sample-set-repeat-count";
2152 static const char set_use_pipe_tag[] = "sample-set-use-pipe";
2154 bool SampleView::IsSampleView(SkView* view) {
2155 SkEvent evt(is_sample_view_tag);
2156 return view->doQuery(&evt);
2159 bool SampleView::SetRepeatDraw(SkView* view, int count) {
2160 SkEvent evt(repeat_count_tag);
2161 evt.setFast32(count);
2162 return view->doEvent(evt);
2165 bool SampleView::SetUsePipe(SkView* view, SkOSMenu::TriState state) {
2167 evt.setS32(set_use_pipe_tag, state);
2168 return view->doEvent(evt);
2171 bool SampleView::onEvent(const SkEvent& evt) {
2172 if (evt.isType(repeat_count_tag)) {
2173 fRepeatCount = evt.getFast32();
2178 if (evt.findS32(set_use_pipe_tag, &pipeHolder)) {
2179 fPipeState = static_cast<SkOSMenu::TriState>(pipeHolder);
2183 return this->INHERITED::onEvent(evt);
2186 bool SampleView::onQuery(SkEvent* evt) {
2187 if (evt->isType(is_sample_view_tag)) {
2190 return this->INHERITED::onQuery(evt);
2194 class SimplePC : public SkGPipeController {
2196 SimplePC(SkCanvas* target);
2199 virtual void* requestBlock(size_t minRequest, size_t* actual);
2200 virtual void notifyWritten(size_t bytes);
2203 SkGPipeReader fReader;
2206 size_t fBytesWritten;
2208 SkGPipeReader::Status fStatus;
2210 size_t fTotalWritten;
2213 SimplePC::SimplePC(SkCanvas* target) : fReader(target) {
2215 fBlockSize = fBytesWritten = 0;
2216 fStatus = SkGPipeReader::kDone_Status;
2219 fReader.setBitmapDecoder(&SkImageDecoder::DecodeMemory);
2222 SimplePC::~SimplePC() {
2223 // SkASSERT(SkGPipeReader::kDone_Status == fStatus);
2224 if (fTotalWritten) {
2225 SkDebugf("--- %d bytes %d atoms, status %d\n", fTotalWritten,
2226 fAtomsWritten, fStatus);
2228 //File is open in append mode
2229 FILE* f = fopen(FILE_PATH, "ab");
2230 SkASSERT(f != NULL);
2231 fwrite((const char*)fBlock + fBytesWritten, 1, bytes, f);
2235 if (fAtomsWritten > 1 && fTotalWritten > 4) { //ignore done
2236 gServer.acceptConnections();
2237 gServer.writePacket(fBlock, fTotalWritten);
2244 void* SimplePC::requestBlock(size_t minRequest, size_t* actual) {
2247 fBlockSize = minRequest * 4;
2248 fBlock = sk_malloc_throw(fBlockSize);
2250 *actual = fBlockSize;
2254 void SimplePC::notifyWritten(size_t bytes) {
2255 SkASSERT(fBytesWritten + bytes <= fBlockSize);
2256 fStatus = fReader.playback((const char*)fBlock + fBytesWritten, bytes);
2257 SkASSERT(SkGPipeReader::kError_Status != fStatus);
2258 fBytesWritten += bytes;
2259 fTotalWritten += bytes;
2264 void SampleView::draw(SkCanvas* canvas) {
2265 if (SkOSMenu::kOffState == fPipeState) {
2266 this->INHERITED::draw(canvas);
2268 SkGPipeWriter writer;
2269 SimplePC controller(canvas);
2270 SkBitmap bitmap = capture_bitmap(canvas);
2271 TiledPipeController tc(bitmap, &SkImageDecoder::DecodeMemory, &canvas->getTotalMatrix());
2272 SkGPipeController* pc;
2273 if (SkOSMenu::kMixedState == fPipeState) {
2278 uint32_t flags = SkGPipeWriter::kCrossProcess_Flag;
2280 canvas = writer.startRecording(pc, flags);
2281 //Must draw before controller goes out of scope and sends data
2282 this->INHERITED::draw(canvas);
2283 //explicitly end recording to ensure writer is flushed before the memory
2284 //is freed in the deconstructor of the controller
2285 writer.endRecording();
2289 void SampleView::onDraw(SkCanvas* canvas) {
2290 this->onDrawBackground(canvas);
2292 for (int i = 0; i < fRepeatCount; i++) {
2293 SkAutoCanvasRestore acr(canvas, true);
2294 this->onDrawContent(canvas);
2298 void SampleView::onDrawBackground(SkCanvas* canvas) {
2299 canvas->drawColor(fBGColor);
2302 ///////////////////////////////////////////////////////////////////////////////
2304 template <typename T> void SkTBSort(T array[], int count) {
2305 for (int i = 1; i < count - 1; i++) {
2306 bool didSwap = false;
2307 for (int j = count - 1; j > i; --j) {
2308 if (array[j] < array[j-1]) {
2310 array[j-1] = array[j];
2320 for (int k = 0; k < count - 1; k++) {
2321 SkASSERT(!(array[k+1] < array[k]));
2325 #include "SkRandom.h"
2327 static void rand_rect(SkIRect* rect, SkRandom& rand) {
2329 int shift = 32 - bits;
2330 rect->set(rand.nextU() >> shift, rand.nextU() >> shift,
2331 rand.nextU() >> shift, rand.nextU() >> shift);
2335 static void dumpRect(const SkIRect& r) {
2336 SkDebugf(" { %d, %d, %d, %d },\n",
2338 r.fRight, r.fBottom);
2341 static void test_rects(const SkIRect rect[], int count) {
2342 SkRegion rgn0, rgn1;
2344 for (int i = 0; i < count; i++) {
2345 rgn0.op(rect[i], SkRegion::kUnion_Op);
2346 // dumpRect(rect[i]);
2348 rgn1.setRects(rect, count);
2352 for (int i = 0; i < count; i++) {
2359 static void test() {
2362 const SkIRect r0[] = {
2366 const SkIRect r1[] = {
2371 const SkIRect r2[] = {
2378 static const struct {
2379 const SkIRect* fRects;
2382 { r0, SK_ARRAY_COUNT(r0) },
2383 { r1, SK_ARRAY_COUNT(r1) },
2384 { r2, SK_ARRAY_COUNT(r2) },
2387 for (i = 0; i < SK_ARRAY_COUNT(gRecs); i++) {
2388 test_rects(gRecs[i].fRects, gRecs[i].fCount);
2392 for (i = 0; i < 10000; i++) {
2393 SkRegion rgn0, rgn1;
2397 for (int j = 0; j < N; j++) {
2398 rand_rect(&rect[j], rand);
2400 test_rects(rect, N);
2404 // FIXME: this should be in a header
2405 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv);
2406 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
2407 if (false) { // avoid bit rot, suppress warning
2410 return new SampleWindow(hwnd, argc, argv, NULL);
2413 // FIXME: this should be in a header
2414 void get_preferred_size(int* x, int* y, int* width, int* height);
2415 void get_preferred_size(int* x, int* y, int* width, int* height) {
2422 #ifdef SK_BUILD_FOR_IOS
2423 #include "SkApplication.h"
2424 IOS_launch_type set_cmd_line_args(int , char *[], const char* resourceDir) {
2425 SetResourcePath(resourceDir);
2426 return kApplication__iOSLaunchType;
2430 void application_init() {
2431 // setenv("ANDROID_ROOT", "../../../data", 0);
2432 #ifdef SK_BUILD_FOR_MAC
2433 setenv("ANDROID_ROOT", "/android/device/data", 0);
2439 void application_term() {