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"
14 #include "SkAnimTimer.h"
16 #include "SkCommandLineFlags.h"
19 #include "SkDocument.h"
21 #include "SkGraphics.h"
22 #include "SkImageEncoder.h"
25 #include "SkPicture.h"
26 #include "SkPictureRecorder.h"
28 #include "SkSurface.h"
31 #include "SkTypeface.h"
33 #include "sk_tool_utils.h"
36 #include "gl/GrGLInterface.h"
37 #include "gl/GrGLUtil.h"
38 #include "GrRenderTarget.h"
39 #include "GrContext.h"
40 #include "SkGpuDevice.h"
45 extern SampleView* CreateSamplePictFileView(const char filename[]);
47 class PictFileFactory : public SkViewFactory {
50 PictFileFactory(const SkString& filename) : fFilename(filename) {}
51 SkView* operator() () const SK_OVERRIDE {
52 return CreateSamplePictFileView(fFilename.c_str());
56 #ifdef SAMPLE_PDF_FILE_VIEWER
57 extern SampleView* CreateSamplePdfFileViewer(const char filename[]);
59 class PdfFileViewerFactory : public SkViewFactory {
62 PdfFileViewerFactory(const SkString& filename) : fFilename(filename) {}
63 SkView* operator() () const SK_OVERRIDE {
64 return CreateSamplePdfFileViewer(fFilename.c_str());
67 #endif // SAMPLE_PDF_FILE_VIEWER
71 #define FILE_PATH "/path/to/drawing.data"
76 #include "SkSockets.h"
81 //#define DEFAULT_TO_ANGLE 1
83 #define DEFAULT_TO_GPU 0 // if 1 default rendering is on GPU
86 #define ANIMATING_EVENTTYPE "nextSample"
87 #define ANIMATING_DELAY 250
90 #define FPS_REPEAT_MULTIPLIER 1
92 #define FPS_REPEAT_MULTIPLIER 10
94 #define FPS_REPEAT_COUNT (10 * FPS_REPEAT_MULTIPLIER)
96 static SampleWindow* gSampleWindow;
98 static bool gShowGMBounds;
100 static void post_event_to_sink(SkEvent* evt, SkEventSink* sink) {
101 evt->setTargetID(sink->getSinkID())->post();
104 static SkAnimTimer gAnimTimer;
106 ///////////////////////////////////////////////////////////////////////////////
108 static const char* skip_until(const char* str, const char* skip) {
112 return strstr(str, skip);
115 static const char* skip_past(const char* str, const char* skip) {
116 const char* found = skip_until(str, skip);
120 return found + strlen(skip);
123 static const char* gPrefFileName = "sampleapp_prefs.txt";
125 static bool readTitleFromPrefs(SkString* title) {
126 SkFILEStream stream(gPrefFileName);
127 if (!stream.isValid()) {
131 size_t len = stream.getLength();
133 stream.read(data.writable_str(), len);
134 const char* s = data.c_str();
136 s = skip_past(s, "curr-slide-title");
137 s = skip_past(s, "=");
138 s = skip_past(s, "\"");
139 const char* stop = skip_until(s, "\"");
141 title->set(s, stop - s);
147 static void writeTitleToPrefs(const char* title) {
148 SkFILEWStream stream(gPrefFileName);
150 data.printf("curr-slide-title = \"%s\"\n", title);
151 stream.write(data.c_str(), data.size());
154 ///////////////////////////////////////////////////////////////////////////////
156 class SampleWindow::DefaultDeviceManager : public SampleWindow::DeviceManager {
159 DefaultDeviceManager() {
163 fCurRenderTarget = NULL;
164 fMSAASampleCount = 0;
166 fBackend = kNone_BackEndType;
169 virtual ~DefaultDeviceManager() {
171 SkSafeUnref(fCurContext);
172 SkSafeUnref(fCurIntf);
173 SkSafeUnref(fCurRenderTarget);
177 virtual void setUpBackend(SampleWindow* win, int msaaSampleCount) {
178 SkASSERT(kNone_BackEndType == fBackend);
180 fBackend = kNone_BackEndType;
183 switch (win->getDeviceType()) {
184 case kRaster_DeviceType:
186 case kPicture_DeviceType:
188 case kGPU_DeviceType:
189 // all these guys use the native backend
190 fBackend = kNativeGL_BackEndType;
193 case kANGLE_DeviceType:
194 // ANGLE is really the only odd man out
195 fBackend = kANGLE_BackEndType;
202 AttachmentInfo attachmentInfo;
203 bool result = win->attach(fBackend, msaaSampleCount, &attachmentInfo);
205 SkDebugf("Failed to initialize GL");
208 fMSAASampleCount = msaaSampleCount;
210 SkASSERT(NULL == fCurIntf);
211 SkAutoTUnref<const GrGLInterface> glInterface;
212 switch (win->getDeviceType()) {
213 case kRaster_DeviceType:
215 case kPicture_DeviceType:
217 case kGPU_DeviceType:
218 // all these guys use the native interface
219 glInterface.reset(GrGLCreateNativeInterface());
222 case kANGLE_DeviceType:
223 glInterface.reset(GrGLCreateANGLEInterface());
231 // Currently SampleApp does not use NVPR. TODO: Provide an NVPR device type that is skipped
232 // when the driver doesn't support NVPR.
233 fCurIntf = GrGLInterfaceRemoveNVPR(glInterface.get());
235 SkASSERT(NULL == fCurContext);
236 fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf);
238 if (NULL == fCurContext || NULL == fCurIntf) {
239 // We need some context and interface to see results
240 SkSafeUnref(fCurContext);
241 SkSafeUnref(fCurIntf);
244 SkDebugf("Failed to setup 3D");
248 #endif // SK_SUPPORT_GPU
249 // call windowSizeChanged to create the render target
250 this->windowSizeChanged(win);
253 virtual void tearDownBackend(SampleWindow *win) {
256 // in case we have outstanding refs to this guy (lua?)
257 fCurContext->abandonContext();
258 fCurContext->unref();
262 SkSafeUnref(fCurIntf);
265 SkSafeUnref(fCurRenderTarget);
266 fCurRenderTarget = NULL;
269 fBackend = kNone_BackEndType;
272 virtual SkSurface* createSurface(SampleWindow::DeviceType dType,
273 SampleWindow* win) SK_OVERRIDE {
275 if (IsGpuDeviceType(dType) && fCurContext) {
276 SkSurfaceProps props(win->getSurfaceProps());
277 return SkSurface::NewRenderTargetDirect(fCurRenderTarget, &props);
283 virtual void publishCanvas(SampleWindow::DeviceType dType,
288 // in case we have queued drawing calls
289 fCurContext->flush();
291 if (!IsGpuDeviceType(dType)) {
292 // need to send the raster bits to the (gpu) window
293 const SkBitmap& bm = win->getBitmap();
294 fCurRenderTarget->writePixels(0, 0, bm.width(), bm.height(),
295 SkImageInfo2GrPixelConfig(bm.colorType(),
300 GrContext::kFlushWrites_PixelOp);
308 virtual void windowSizeChanged(SampleWindow* win) {
311 AttachmentInfo attachmentInfo;
312 win->attach(fBackend, fMSAASampleCount, &attachmentInfo);
313 SkSafeUnref(fCurRenderTarget);
314 fCurRenderTarget = win->renderTarget(attachmentInfo, fCurIntf, fCurContext);
319 virtual GrContext* getGrContext() {
327 GrRenderTarget* getGrRenderTarget() SK_OVERRIDE {
329 return fCurRenderTarget;
338 GrContext* fCurContext;
339 const GrGLInterface* fCurIntf;
340 GrRenderTarget* fCurRenderTarget;
341 int fMSAASampleCount;
344 SkOSWindow::SkBackEndTypes fBackend;
346 typedef SampleWindow::DeviceManager INHERITED;
350 static const char view_inval_msg[] = "view-inval-msg";
352 void SampleWindow::postInvalDelay() {
353 (new SkEvent(view_inval_msg, this->getSinkID()))->postDelay(1);
356 static bool isInvalEvent(const SkEvent& evt) {
357 return evt.isType(view_inval_msg);
361 SkFuncViewFactory::SkFuncViewFactory(SkViewCreateFunc func)
362 : fCreateFunc(func) {
365 SkView* SkFuncViewFactory::operator() () const {
366 return (*fCreateFunc)();
369 #include "GMSampleView.h"
371 SkGMSampleViewFactory::SkGMSampleViewFactory(GMFactoryFunc func)
375 SkView* SkGMSampleViewFactory::operator() () const {
376 skiagm::GM* gm = fFunc(NULL);
377 gm->setMode(skiagm::GM::kSample_Mode);
378 return new GMSampleView(gm);
381 SkViewRegister* SkViewRegister::gHead;
382 SkViewRegister::SkViewRegister(SkViewFactory* fact) : fFact(fact) {
388 SkViewRegister::SkViewRegister(SkViewCreateFunc func) {
389 fFact = new SkFuncViewFactory(func);
394 SkViewRegister::SkViewRegister(GMFactoryFunc func) {
395 fFact = new SkGMSampleViewFactory(func);
400 class AutoUnrefArray {
404 int count = fObjs.count();
405 for (int i = 0; i < count; ++i) {
409 SkRefCnt*& push_back() { return *fObjs.append(); }
412 SkTDArray<SkRefCnt*> fObjs;
415 // registers GMs as Samples
416 // This can't be performed during static initialization because it could be
417 // run before GMRegistry has been fully built.
418 static void SkGMRegistyToSampleRegistry() {
420 static AutoUnrefArray fRegisters;
423 const skiagm::GMRegistry* gmreg = skiagm::GMRegistry::Head();
425 fRegisters.push_back() = new SkViewRegister(gmreg->factory());
426 gmreg = gmreg->next();
432 //////////////////////////////////////////////////////////////////////////////
435 kFlipAxis_X = (1 << 0),
436 kFlipAxis_Y = (1 << 1)
439 #include "SkDrawFilter.h"
441 struct HintingState {
442 SkPaint::Hinting hinting;
446 static HintingState gHintingStates[] = {
447 {SkPaint::kNo_Hinting, "Mixed", NULL },
448 {SkPaint::kNo_Hinting, "None", "H0 " },
449 {SkPaint::kSlight_Hinting, "Slight", "Hs " },
450 {SkPaint::kNormal_Hinting, "Normal", "Hn " },
451 {SkPaint::kFull_Hinting, "Full", "Hf " },
454 struct FilterQualityState {
455 SkFilterQuality fQuality;
459 static FilterQualityState gFilterQualityStates[] = {
460 { kNone_SkFilterQuality, "Mixed", NULL },
461 { kNone_SkFilterQuality, "None", "F0 " },
462 { kLow_SkFilterQuality, "Low", "F1 " },
463 { kMedium_SkFilterQuality, "Medium", "F2 " },
464 { kHigh_SkFilterQuality, "High", "F3 " },
467 class FlagsDrawFilter : public SkDrawFilter {
469 FlagsDrawFilter(SkOSMenu::TriState lcd, SkOSMenu::TriState aa,
470 SkOSMenu::TriState subpixel, int hinting, int filterQuality)
473 , fSubpixelState(subpixel)
474 , fHintingState(hinting)
475 , fFilterQualityIndex(filterQuality)
477 SkASSERT((unsigned)filterQuality < SK_ARRAY_COUNT(gFilterQualityStates));
480 virtual bool filter(SkPaint* paint, Type t) {
481 if (kText_Type == t && SkOSMenu::kMixedState != fLCDState) {
482 paint->setLCDRenderText(SkOSMenu::kOnState == fLCDState);
484 if (SkOSMenu::kMixedState != fAAState) {
485 paint->setAntiAlias(SkOSMenu::kOnState == fAAState);
487 if (0 != fFilterQualityIndex) {
488 paint->setFilterQuality(gFilterQualityStates[fFilterQualityIndex].fQuality);
490 if (SkOSMenu::kMixedState != fSubpixelState) {
491 paint->setSubpixelText(SkOSMenu::kOnState == fSubpixelState);
493 if (0 != fHintingState && fHintingState < (int)SK_ARRAY_COUNT(gHintingStates)) {
494 paint->setHinting(gHintingStates[fHintingState].hinting);
500 SkOSMenu::TriState fLCDState;
501 SkOSMenu::TriState fAAState;
502 SkOSMenu::TriState fSubpixelState;
504 int fFilterQualityIndex;
507 //////////////////////////////////////////////////////////////////////////////
509 #define MAX_ZOOM_LEVEL 8
510 #define MIN_ZOOM_LEVEL -8
512 static const char gCharEvtName[] = "SampleCode_Char_Event";
513 static const char gKeyEvtName[] = "SampleCode_Key_Event";
514 static const char gTitleEvtName[] = "SampleCode_Title_Event";
515 static const char gPrefSizeEvtName[] = "SampleCode_PrefSize_Event";
516 static const char gFastTextEvtName[] = "SampleCode_FastText_Event";
517 static const char gUpdateWindowTitleEvtName[] = "SampleCode_UpdateWindowTitle";
519 bool SampleCode::CharQ(const SkEvent& evt, SkUnichar* outUni) {
520 if (evt.isType(gCharEvtName, sizeof(gCharEvtName) - 1)) {
522 *outUni = evt.getFast32();
529 bool SampleCode::KeyQ(const SkEvent& evt, SkKey* outKey) {
530 if (evt.isType(gKeyEvtName, sizeof(gKeyEvtName) - 1)) {
532 *outKey = (SkKey)evt.getFast32();
539 bool SampleCode::TitleQ(const SkEvent& evt) {
540 return evt.isType(gTitleEvtName, sizeof(gTitleEvtName) - 1);
543 void SampleCode::TitleR(SkEvent* evt, const char title[]) {
544 SkASSERT(evt && TitleQ(*evt));
545 evt->setString(gTitleEvtName, title);
548 bool SampleCode::RequestTitle(SkView* view, SkString* title) {
549 SkEvent evt(gTitleEvtName);
550 if (view->doQuery(&evt)) {
551 title->set(evt.findString(gTitleEvtName));
557 bool SampleCode::PrefSizeQ(const SkEvent& evt) {
558 return evt.isType(gPrefSizeEvtName, sizeof(gPrefSizeEvtName) - 1);
561 void SampleCode::PrefSizeR(SkEvent* evt, SkScalar width, SkScalar height) {
562 SkASSERT(evt && PrefSizeQ(*evt));
566 evt->setScalars(gPrefSizeEvtName, 2, size);
569 bool SampleCode::FastTextQ(const SkEvent& evt) {
570 return evt.isType(gFastTextEvtName, sizeof(gFastTextEvtName) - 1);
573 ///////////////////////////////////////////////////////////////////////////////
583 kLast_TilingMode_Enum
591 static const struct TilingInfo gTilingInfo[] = {
592 { "No tiling", SK_Scalar1 , SK_Scalar1 }, // kNo_Tiling
593 { "128x128" , SkIntToScalar(128), SkIntToScalar(128) }, // kAbs_128x128_Tiling
594 { "256x256" , SkIntToScalar(256), SkIntToScalar(256) }, // kAbs_256x256_Tiling
595 { "1/4x1/4" , SK_Scalar1 / 4 , SK_Scalar1 / 4 }, // kRel_4x4_Tiling
596 { "1/1x1/16" , SK_Scalar1 , SK_Scalar1 / 16 }, // kRel_1x16_Tiling
597 { "1/16x1/1" , SK_Scalar1 / 16 , SK_Scalar1 }, // kRel_16x1_Tiling
599 SK_COMPILE_ASSERT((SK_ARRAY_COUNT(gTilingInfo) == kLast_TilingMode_Enum),
600 Incomplete_tiling_labels);
602 SkSize SampleWindow::tileSize() const {
603 SkASSERT((TilingMode)fTilingMode < kLast_TilingMode_Enum);
604 const struct TilingInfo* info = gTilingInfo + fTilingMode;
605 return SkSize::Make(info->w > SK_Scalar1 ? info->w : this->width() * info->w,
606 info->h > SK_Scalar1 ? info->h : this->height() * info->h);
608 //////////////////////////////////////////////////////////////////////////////
610 static SkView* curr_view(SkWindow* wind) {
611 SkView::F2BIter iter(wind);
615 static bool curr_title(SkWindow* wind, SkString* title) {
616 SkView* view = curr_view(wind);
618 SkEvent evt(gTitleEvtName);
619 if (view->doQuery(&evt)) {
620 title->set(evt.findString(gTitleEvtName));
627 bool SampleWindow::sendAnimatePulse() {
628 SkView* view = curr_view(this);
629 if (SampleView::IsSampleView(view)) {
630 return ((SampleView*)view)->animate(gAnimTimer);
635 void SampleWindow::setZoomCenter(float x, float y)
641 bool SampleWindow::zoomIn()
643 // Arbitrarily decided
644 if (fFatBitsScale == 25) return false;
650 bool SampleWindow::zoomOut()
652 if (fFatBitsScale == 1) return false;
658 void SampleWindow::updatePointer(int x, int y)
667 static inline SampleWindow::DeviceType cycle_devicetype(SampleWindow::DeviceType ct) {
668 static const SampleWindow::DeviceType gCT[] = {
669 SampleWindow::kPicture_DeviceType,
671 SampleWindow::kGPU_DeviceType,
673 SampleWindow::kANGLE_DeviceType,
675 #endif // SK_SUPPORT_GPU
676 SampleWindow::kRaster_DeviceType
678 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gCT) == SampleWindow::kDeviceTypeCnt, array_size_mismatch);
682 static SkString getSampleTitle(const SkViewFactory* sampleFactory) {
683 SkView* view = (*sampleFactory)();
685 SampleCode::RequestTitle(view, &title);
690 static bool compareSampleTitle(const SkViewFactory* first, const SkViewFactory* second) {
691 return strcmp(getSampleTitle(first).c_str(), getSampleTitle(second).c_str()) < 0;
694 DEFINE_string(slide, "", "Start on this sample.");
695 DEFINE_int32(msaa, 0, "Request multisampling with this count.");
696 DEFINE_string(pictureDir, "", "Read pictures from here.");
697 DEFINE_string(picture, "", "Path to single picture.");
698 DEFINE_bool(sort, false, "Sort samples by title.");
699 DEFINE_bool(list, false, "List samples?");
700 #ifdef SAMPLE_PDF_FILE_VIEWER
701 DEFINE_string(pdfPath, "", "Path to direcotry of pdf files.");
704 #include "SkTaskGroup.h"
706 SampleWindow::SampleWindow(void* hwnd, int argc, char** argv, DeviceManager* devManager)
708 , fDevManager(NULL) {
710 SkCommandLineFlags::Parse(argc, argv);
714 if (!FLAGS_pictureDir.isEmpty()) {
715 SkOSFile::Iter iter(FLAGS_pictureDir[0], "skp");
717 while (iter.next(&filename)) {
718 *fSamples.append() = new PictFileFactory(
719 SkOSPath::Join(FLAGS_pictureDir[0], filename.c_str()));
722 if (!FLAGS_picture.isEmpty()) {
723 SkString path(FLAGS_picture[0]);
724 fCurrIndex = fSamples.count();
725 *fSamples.append() = new PictFileFactory(path);
727 #ifdef SAMPLE_PDF_FILE_VIEWER
728 if (!FLAGS_pdfPath.isEmpty()) {
729 SkOSFile::Iter iter(FLAGS_pdfPath[0], "pdf");
731 while (iter.next(&filename)) {
732 *fSamples.append() = new PdfFileViewerFactory(
733 SkOSPath::Join(FLAGS_pictureDir[0], filename.c_str()));
737 SkGMRegistyToSampleRegistry();
739 const SkViewRegister* reg = SkViewRegister::Head();
741 *fSamples.append() = reg->factory();
747 // Sort samples, so foo.skp and foo.pdf are consecutive and we can quickly spot where
748 // skp -> pdf -> png fails.
749 SkTQSort(fSamples.begin(), fSamples.end() ? fSamples.end() - 1 : NULL, compareSampleTitle);
752 if (!FLAGS_slide.isEmpty()) {
753 fCurrIndex = findByTitle(FLAGS_slide[0]);
754 if (fCurrIndex < 0) {
755 fprintf(stderr, "Unknown sample \"%s\"\n", FLAGS_slide[0]);
760 fMSAASampleCount = FLAGS_msaa;
766 if (fCurrIndex < 0) {
768 if (readTitleFromPrefs(&title)) {
769 fCurrIndex = findByTitle(title.c_str());
773 if (fCurrIndex < 0) {
777 static SkTaskGroup::Enabler enabled(-1);
778 gSampleWindow = this;
781 //Clear existing file or create file if it doesn't exist
782 FILE* f = fopen(FILE_PATH, "wb");
786 fDeviceType = kRaster_DeviceType;
789 fDeviceType = kGPU_DeviceType;
791 #if SK_ANGLE && DEFAULT_TO_ANGLE
792 fDeviceType = kANGLE_DeviceType;
799 fRequestGrabImage = false;
800 fPipeState = SkOSMenu::kOffState;
801 fTilingMode = kNo_Tiling;
803 fLCDState = SkOSMenu::kMixedState;
804 fAAState = SkOSMenu::kMixedState;
805 fSubpixelState = SkOSMenu::kMixedState;
807 fFilterQualityIndex = 0;
809 fScrollTestX = fScrollTestY = 0;
811 fMouseX = fMouseY = 0;
813 fTypeface = SkTypeface::CreateFromTypeface(NULL, SkTypeface::kBold);
817 fZoomScale = SK_Scalar1;
826 int sinkID = this->getSinkID();
827 fAppMenu = new SkOSMenu;
828 fAppMenu->setTitle("Global Settings");
831 itemID =fAppMenu->appendList("Device Type", "Device Type", sinkID, 0,
832 "Raster", "Picture", "OpenGL",
837 fAppMenu->assignKeyEquivalentToItem(itemID, 'd');
838 itemID = fAppMenu->appendTriState("AA", "AA", sinkID, fAAState);
839 fAppMenu->assignKeyEquivalentToItem(itemID, 'b');
840 itemID = fAppMenu->appendTriState("LCD", "LCD", sinkID, fLCDState);
841 fAppMenu->assignKeyEquivalentToItem(itemID, 'l');
842 itemID = fAppMenu->appendList("FilterQuality", "FilterQuality", sinkID, fFilterQualityIndex,
843 gFilterQualityStates[0].fName,
844 gFilterQualityStates[1].fName,
845 gFilterQualityStates[2].fName,
846 gFilterQualityStates[3].fName,
847 gFilterQualityStates[4].fName,
849 fAppMenu->assignKeyEquivalentToItem(itemID, 'n');
850 itemID = fAppMenu->appendTriState("Subpixel", "Subpixel", sinkID, fSubpixelState);
851 fAppMenu->assignKeyEquivalentToItem(itemID, 's');
852 itemID = fAppMenu->appendList("Hinting", "Hinting", sinkID, fHintingState,
853 gHintingStates[0].name,
854 gHintingStates[1].name,
855 gHintingStates[2].name,
856 gHintingStates[3].name,
857 gHintingStates[4].name,
859 fAppMenu->assignKeyEquivalentToItem(itemID, 'h');
861 fUsePipeMenuItemID = fAppMenu->appendTriState("Pipe", "Pipe" , sinkID,
863 fAppMenu->assignKeyEquivalentToItem(fUsePipeMenuItemID, 'P');
865 itemID =fAppMenu->appendList("Tiling", "Tiling", sinkID, fTilingMode,
866 gTilingInfo[kNo_Tiling].label,
867 gTilingInfo[kAbs_128x128_Tiling].label,
868 gTilingInfo[kAbs_256x256_Tiling].label,
869 gTilingInfo[kRel_4x4_Tiling].label,
870 gTilingInfo[kRel_1x16_Tiling].label,
871 gTilingInfo[kRel_16x1_Tiling].label,
873 fAppMenu->assignKeyEquivalentToItem(itemID, 't');
875 itemID = fAppMenu->appendSwitch("Slide Show", "Slide Show" , sinkID, false);
876 fAppMenu->assignKeyEquivalentToItem(itemID, 'a');
877 itemID = fAppMenu->appendSwitch("Clip", "Clip" , sinkID, fUseClip);
878 fAppMenu->assignKeyEquivalentToItem(itemID, 'c');
879 itemID = fAppMenu->appendSwitch("Flip X", "Flip X" , sinkID, false);
880 fAppMenu->assignKeyEquivalentToItem(itemID, 'x');
881 itemID = fAppMenu->appendSwitch("Flip Y", "Flip Y" , sinkID, false);
882 fAppMenu->assignKeyEquivalentToItem(itemID, 'y');
883 itemID = fAppMenu->appendSwitch("Zoomer", "Zoomer" , sinkID, fShowZoomer);
884 fAppMenu->assignKeyEquivalentToItem(itemID, 'z');
885 itemID = fAppMenu->appendSwitch("Magnify", "Magnify" , sinkID, fMagnify);
886 fAppMenu->assignKeyEquivalentToItem(itemID, 'm');
887 itemID =fAppMenu->appendList("Transition-Next", "Transition-Next", sinkID,
888 fTransitionNext, "Up", "Up and Right", "Right",
889 "Down and Right", "Down", "Down and Left",
890 "Left", "Up and Left", NULL);
891 fAppMenu->assignKeyEquivalentToItem(itemID, 'j');
892 itemID =fAppMenu->appendList("Transition-Prev", "Transition-Prev", sinkID,
893 fTransitionPrev, "Up", "Up and Right", "Right",
894 "Down and Right", "Down", "Down and Left",
895 "Left", "Up and Left", NULL);
896 fAppMenu->assignKeyEquivalentToItem(itemID, 'k');
897 itemID = fAppMenu->appendAction("Save to PDF", sinkID);
898 fAppMenu->assignKeyEquivalentToItem(itemID, 'e');
900 this->addMenu(fAppMenu);
901 fSlideMenu = new SkOSMenu;
902 this->addMenu(fSlideMenu);
904 this->setVisibleP(true);
905 this->setClipToBounds(false);
907 this->loadView((*fSamples[fCurrIndex])());
909 if (NULL == devManager) {
910 fDevManager = new DefaultDeviceManager();
913 fDevManager = devManager;
915 fDevManager->setUpBackend(this, fMSAASampleCount);
917 // If another constructor set our dimensions, ensure that our
918 // onSizeChange gets called.
919 if (this->height() && this->width()) {
920 this->onSizeChange();
923 // can't call this synchronously, since it may require a subclass to
924 // to implement, or the caller may need us to have returned from the
925 // constructor first. Hence we post an event to ourselves.
926 // this->updateTitle();
927 post_event_to_sink(new SkEvent(gUpdateWindowTitleEvtName), this);
932 SampleWindow::~SampleWindow() {
933 SkSafeUnref(fTypeface);
934 SkSafeUnref(fDevManager);
938 int SampleWindow::findByTitle(const char title[]) {
939 int i, count = fSamples.count();
940 for (i = 0; i < count; i++) {
941 if (getSampleTitle(i).equals(title)) {
948 void SampleWindow::listTitles() {
949 int count = fSamples.count();
950 SkDebugf("All Slides:\n");
951 for (int i = 0; i < count; i++) {
952 SkDebugf(" %s\n", getSampleTitle(i).c_str());
956 static SkBitmap capture_bitmap(SkCanvas* canvas) {
958 if (bm.tryAllocPixels(canvas->imageInfo())) {
959 canvas->readPixels(&bm, 0, 0);
964 static void drawText(SkCanvas* canvas, SkString str, SkScalar left, SkScalar top, SkPaint& paint) {
965 SkColor desiredColor = paint.getColor();
966 paint.setColor(SK_ColorWHITE);
967 const char* c_str = str.c_str();
968 size_t size = str.size();
970 paint.measureText(c_str, size, &bounds);
971 bounds.offset(left, top);
972 SkScalar inset = SkIntToScalar(-2);
973 bounds.inset(inset, inset);
974 canvas->drawRect(bounds, paint);
975 if (desiredColor != SK_ColorBLACK) {
976 paint.setColor(SK_ColorBLACK);
977 canvas->drawText(c_str, size, left + SK_Scalar1, top + SK_Scalar1, paint);
979 paint.setColor(desiredColor);
980 canvas->drawText(c_str, size, left, top, paint);
986 void SampleWindow::draw(SkCanvas* canvas) {
987 gAnimTimer.updateTime();
989 if (fGesture.isActive()) {
990 this->updateMatrix();
994 fMeasureFPS_Time = 0;
997 SkSize tile = this->tileSize();
999 if (kNo_Tiling == fTilingMode) {
1000 this->INHERITED::draw(canvas); // no looping or surfaces needed
1002 const int w = SkScalarRoundToInt(tile.width());
1003 const int h = SkScalarRoundToInt(tile.height());
1004 SkImageInfo info = SkImageInfo::MakeN32Premul(w, h);
1005 SkAutoTUnref<SkSurface> surface(canvas->newSurface(info));
1006 SkCanvas* tileCanvas = surface->getCanvas();
1008 for (SkScalar y = 0; y < height(); y += tile.height()) {
1009 for (SkScalar x = 0; x < width(); x += tile.width()) {
1010 SkAutoCanvasRestore acr(tileCanvas, true);
1011 tileCanvas->translate(-x, -y);
1012 tileCanvas->clear(0);
1013 this->INHERITED::draw(tileCanvas);
1014 surface->draw(canvas, x, y, NULL);
1018 // for drawing the borders between tiles
1020 paint.setColor(0x60FF00FF);
1021 paint.setStyle(SkPaint::kStroke_Style);
1023 for (SkScalar y = 0; y < height(); y += tile.height()) {
1024 for (SkScalar x = 0; x < width(); x += tile.width()) {
1025 canvas->drawRect(SkRect::MakeXYWH(x, y, tile.width(), tile.height()), paint);
1030 if (fShowZoomer && !fSaveToPdf) {
1033 if (fMagnify && !fSaveToPdf) {
1037 if (fMeasureFPS && fMeasureFPS_Time) {
1038 this->updateTitle();
1039 this->postInvalDelay();
1042 if (this->sendAnimatePulse()) {
1047 fDevManager->publishCanvas(fDeviceType, canvas, this);
1050 static float clipW = 200;
1051 static float clipH = 200;
1052 void SampleWindow::magnify(SkCanvas* canvas) {
1054 int count = canvas->save();
1056 SkMatrix m = canvas->getTotalMatrix();
1057 if (!m.invert(&m)) {
1060 SkPoint offset, center;
1061 SkScalar mouseX = fMouseX * SK_Scalar1;
1062 SkScalar mouseY = fMouseY * SK_Scalar1;
1063 m.mapXY(mouseX - clipW/2, mouseY - clipH/2, &offset);
1064 m.mapXY(mouseX, mouseY, ¢er);
1066 r.set(0, 0, clipW * m.getScaleX(), clipH * m.getScaleX());
1067 r.offset(offset.fX, offset.fY);
1070 paint.setColor(0xFF66AAEE);
1071 paint.setStyle(SkPaint::kStroke_Style);
1072 paint.setStrokeWidth(10.f * m.getScaleX());
1074 //canvas->translate(0, -250);
1075 canvas->drawRect(r, paint);
1076 canvas->clipRect(r);
1078 m = canvas->getTotalMatrix();
1079 m.setTranslate(-center.fX, -center.fY);
1080 m.postScale(0.5f * fFatBitsScale, 0.5f * fFatBitsScale);
1081 m.postTranslate(center.fX, center.fY);
1084 this->INHERITED::draw(canvas);
1086 canvas->restoreToCount(count);
1089 void SampleWindow::showZoomer(SkCanvas* canvas) {
1090 int count = canvas->save();
1091 canvas->resetMatrix();
1092 // Ensure the mouse position is on screen.
1093 int width = SkScalarRoundToInt(this->width());
1094 int height = SkScalarRoundToInt(this->height());
1095 if (fMouseX >= width) fMouseX = width - 1;
1096 else if (fMouseX < 0) fMouseX = 0;
1097 if (fMouseY >= height) fMouseY = height - 1;
1098 else if (fMouseY < 0) fMouseY = 0;
1100 SkBitmap bitmap = capture_bitmap(canvas);
1101 bitmap.lockPixels();
1103 // Find the size of the zoomed in view, forced to be odd, so the examined pixel is in the middle.
1104 int zoomedWidth = (width >> 1) | 1;
1105 int zoomedHeight = (height >> 1) | 1;
1107 src.set(0, 0, zoomedWidth / fFatBitsScale, zoomedHeight / fFatBitsScale);
1108 src.offset(fMouseX - (src.width()>>1), fMouseY - (src.height()>>1));
1110 dest.set(0, 0, SkIntToScalar(zoomedWidth), SkIntToScalar(zoomedHeight));
1111 dest.offset(SkIntToScalar(width - zoomedWidth), SkIntToScalar(height - zoomedHeight));
1113 // Clear the background behind our zoomed in view
1114 paint.setColor(SK_ColorWHITE);
1115 canvas->drawRect(dest, paint);
1116 canvas->drawBitmapRect(bitmap, &src, dest);
1117 paint.setColor(SK_ColorBLACK);
1118 paint.setStyle(SkPaint::kStroke_Style);
1119 // Draw a border around the pixel in the middle
1120 SkRect originalPixel;
1121 originalPixel.set(SkIntToScalar(fMouseX), SkIntToScalar(fMouseY), SkIntToScalar(fMouseX + 1), SkIntToScalar(fMouseY + 1));
1125 SkColor color = bitmap.getColor(fMouseX, fMouseY);
1126 if (matrix.setRectToRect(scalarSrc, dest, SkMatrix::kFill_ScaleToFit)) {
1128 matrix.mapRect(&pixel, originalPixel);
1129 // TODO Perhaps measure the values and make the outline white if it's "dark"
1130 if (color == SK_ColorBLACK) {
1131 paint.setColor(SK_ColorWHITE);
1133 canvas->drawRect(pixel, paint);
1135 paint.setColor(SK_ColorBLACK);
1136 // Draw a border around the destination rectangle
1137 canvas->drawRect(dest, paint);
1138 paint.setStyle(SkPaint::kStrokeAndFill_Style);
1139 // Identify the pixel and its color on screen
1140 paint.setTypeface(fTypeface);
1141 paint.setAntiAlias(true);
1142 SkScalar lineHeight = paint.getFontMetrics(NULL);
1144 string.appendf("(%i, %i)", fMouseX, fMouseY);
1145 SkScalar left = dest.fLeft + SkIntToScalar(3);
1146 SkScalar i = SK_Scalar1;
1147 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1151 string.appendf("A: %X", SkColorGetA(color));
1152 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1156 string.appendf("R: %X", SkColorGetR(color));
1157 paint.setColor(SK_ColorRED);
1158 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1162 string.appendf("G: %X", SkColorGetG(color));
1163 paint.setColor(SK_ColorGREEN);
1164 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1168 string.appendf("B: %X", SkColorGetB(color));
1169 paint.setColor(SK_ColorBLUE);
1170 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint);
1171 canvas->restoreToCount(count);
1174 void SampleWindow::onDraw(SkCanvas* canvas) {
1177 #include "SkColorPriv.h"
1179 void SampleWindow::saveToPdf()
1185 SkCanvas* SampleWindow::beforeChildren(SkCanvas* canvas) {
1188 if (!this->getRawTitle(&name)) {
1189 name.set("unknown_sample");
1191 name.append(".pdf");
1192 #ifdef SK_BUILD_FOR_ANDROID
1193 name.prepend("/sdcard/");
1195 fPDFDocument.reset(SkDocument::CreatePDF(name.c_str()));
1196 canvas = fPDFDocument->beginPage(this->width(), this->height());
1197 } else if (kPicture_DeviceType == fDeviceType) {
1198 canvas = fRecorder.beginRecording(9999, 9999, NULL, 0);
1200 canvas = this->INHERITED::beforeChildren(canvas);
1204 canvas->drawColor(0xFFFF88FF);
1205 canvas->clipPath(fClipPath, SkRegion::kIntersect_Op, true);
1210 #include "SkMultiPictureDraw.h"
1211 void SampleWindow::afterChildren(SkCanvas* orig) {
1214 fPDFDocument->endPage();
1215 fPDFDocument.reset(NULL);
1216 // We took over the draw calls in order to create the PDF, so we need
1222 if (fRequestGrabImage) {
1223 fRequestGrabImage = false;
1225 SkBitmap bmp = capture_bitmap(orig);
1226 if (!bmp.isNull()) {
1227 static int gSampleGrabCounter;
1229 name.printf("sample_grab_%d.png", gSampleGrabCounter++);
1230 SkImageEncoder::EncodeFile(name.c_str(), bmp,
1231 SkImageEncoder::kPNG_Type, 100);
1235 if (kPicture_DeviceType == fDeviceType) {
1236 SkAutoTUnref<const SkPicture> picture(fRecorder.endRecording());
1239 this->installDrawFilter(orig);
1244 void* addr = orig->accessTopLayerPixels(&info, &rowBytes);
1246 SkSurface* surfs[4];
1247 SkMultiPictureDraw md;
1249 SkImageInfo n = SkImageInfo::Make(info.width()/2, info.height()/2,
1250 info.colorType(), info.alphaType());
1252 for (int y = 0; y < 2; ++y) {
1253 for (int x = 0; x < 2; ++x) {
1254 char* p = (char*)addr;
1255 p += y * n.height() * rowBytes;
1256 p += x * n.width() * sizeof(SkPMColor);
1257 surfs[index] = SkSurface::NewRasterDirect(n, p, rowBytes);
1258 SkCanvas* c = surfs[index]->getCanvas();
1259 c->translate(SkIntToScalar(-x * n.width()),
1260 SkIntToScalar(-y * n.height()));
1261 c->concat(orig->getTotalMatrix());
1262 md.add(c, picture, NULL, NULL);
1267 for (int i = 0; i < 4; ++i) {
1272 orig->drawPicture(picture);
1275 SkDynamicMemoryWStream ostream;
1276 picture->serialize(&ostream);
1278 SkAutoDataUnref data(ostream.copyToData());
1279 SkMemoryStream istream(data->data(), data->size());
1280 SkAutoTUnref<SkPicture> pict(SkPicture::CreateFromStream(&istream));
1281 if (pict.get() != NULL) {
1282 orig->drawPicture(pict.get());
1285 picture->playback(orig);
1289 // Do this after presentGL and other finishing, rather than in afterChild
1290 if (fMeasureFPS && fMeasureFPS_StartTime) {
1291 fMeasureFPS_Time += SkTime::GetMSecs() - fMeasureFPS_StartTime;
1295 void SampleWindow::beforeChild(SkView* child, SkCanvas* canvas) {
1297 SkScalar cx = this->width() / 2;
1298 SkScalar cy = this->height() / 2;
1299 canvas->translate(cx, cy);
1300 canvas->rotate(gAnimTimer.scaled(10));
1301 canvas->translate(-cx, -cy);
1305 SkScalar secs = gAnimTimer.scaled(1);
1307 static const SkScalar gAnimPeriod = 10 * SK_Scalar1;
1308 static const SkScalar gAnimMag = SK_Scalar1 / 1000;
1309 SkScalar t = SkScalarMod(secs, gAnimPeriod);
1310 if (SkScalarFloorToInt(SkScalarDiv(secs, gAnimPeriod)) & 0x1) {
1311 t = gAnimPeriod - t;
1313 t = 2 * t - gAnimPeriod;
1314 t = SkScalarMul(SkScalarDiv(t, gAnimPeriod), gAnimMag);
1320 m.setPerspY(SK_Scalar1 / 1000);
1321 m.setSkewX(SkScalarDiv(8, 25));
1327 this->installDrawFilter(canvas);
1330 if (SampleView::SetRepeatDraw(child, FPS_REPEAT_COUNT)) {
1331 fMeasureFPS_StartTime = SkTime::GetMSecs();
1334 (void)SampleView::SetRepeatDraw(child, 1);
1336 if (fPerspAnim || fRotate) {
1341 void SampleWindow::afterChild(SkView* child, SkCanvas* canvas) {
1342 canvas->setDrawFilter(NULL);
1345 void SampleWindow::changeZoomLevel(float delta) {
1346 fZoomLevel += delta;
1347 if (fZoomLevel > 0) {
1348 fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL);
1349 fZoomScale = fZoomLevel + SK_Scalar1;
1350 } else if (fZoomLevel < 0) {
1351 fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL);
1352 fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel);
1354 fZoomScale = SK_Scalar1;
1356 this->updateMatrix();
1359 void SampleWindow::updateMatrix(){
1364 //m = this->getLocalMatrix();//.invert(&m);
1365 m.mapXY(fZoomCenterX, fZoomCenterY, ¢er);
1366 SkScalar cx = center.fX;
1367 SkScalar cy = center.fY;
1369 m.setTranslate(-cx, -cy);
1370 m.postScale(fZoomScale, fZoomScale);
1371 m.postTranslate(cx, cy);
1375 m.preTranslate(fZoomCenterX, fZoomCenterY);
1376 if (fFlipAxis & kFlipAxis_X) {
1377 m.preScale(-SK_Scalar1, SK_Scalar1);
1379 if (fFlipAxis & kFlipAxis_Y) {
1380 m.preScale(SK_Scalar1, -SK_Scalar1);
1382 m.preTranslate(-fZoomCenterX, -fZoomCenterY);
1383 //canvas->concat(m);
1385 // Apply any gesture matrix
1386 m.preConcat(fGesture.localM());
1387 m.preConcat(fGesture.globalM());
1389 this->setLocalMatrix(m);
1391 this->updateTitle();
1394 bool SampleWindow::previousSample() {
1395 fCurrIndex = (fCurrIndex - 1 + fSamples.count()) % fSamples.count();
1396 this->loadView((*fSamples[fCurrIndex])());
1400 bool SampleWindow::nextSample() {
1401 fCurrIndex = (fCurrIndex + 1) % fSamples.count();
1402 this->loadView((*fSamples[fCurrIndex])());
1406 bool SampleWindow::goToSample(int i) {
1407 fCurrIndex = (i) % fSamples.count();
1408 this->loadView((*fSamples[fCurrIndex])());
1412 SkString SampleWindow::getSampleTitle(int i) {
1413 return ::getSampleTitle(fSamples[i]);
1416 int SampleWindow::sampleCount() {
1417 return fSamples.count();
1420 void SampleWindow::showOverview() {
1421 this->loadView(create_overview(fSamples.count(), fSamples.begin()));
1424 void SampleWindow::installDrawFilter(SkCanvas* canvas) {
1425 canvas->setDrawFilter(new FlagsDrawFilter(fLCDState, fAAState, fSubpixelState,
1426 fHintingState, fFilterQualityIndex))->unref();
1429 void SampleWindow::postAnimatingEvent() {
1431 (new SkEvent(ANIMATING_EVENTTYPE, this->getSinkID()))->postDelay(ANIMATING_DELAY);
1435 bool SampleWindow::onEvent(const SkEvent& evt) {
1436 if (evt.isType(gUpdateWindowTitleEvtName)) {
1437 this->updateTitle();
1440 if (evt.isType(ANIMATING_EVENTTYPE)) {
1443 this->postAnimatingEvent();
1447 if (evt.isType("set-curr-index")) {
1448 this->goToSample(evt.getFast32());
1451 if (isInvalEvent(evt)) {
1456 if (SkOSMenu::FindListIndex(evt, "Device Type", &selected)) {
1457 this->setDeviceType((DeviceType)selected);
1460 if (SkOSMenu::FindTriState(evt, "Pipe", &fPipeState)) {
1462 if (!fPipeState != SkOSMenu::kOnState)
1463 gServer.disconnectAll();
1465 (void)SampleView::SetUsePipe(curr_view(this), fPipeState);
1466 this->updateTitle();
1470 if (SkOSMenu::FindSwitchState(evt, "Slide Show", NULL)) {
1471 this->toggleSlideshow();
1474 if (SkOSMenu::FindTriState(evt, "AA", &fAAState) ||
1475 SkOSMenu::FindTriState(evt, "LCD", &fLCDState) ||
1476 SkOSMenu::FindListIndex(evt, "FilterQuality", &fFilterQualityIndex) ||
1477 SkOSMenu::FindTriState(evt, "Subpixel", &fSubpixelState) ||
1478 SkOSMenu::FindListIndex(evt, "Hinting", &fHintingState) ||
1479 SkOSMenu::FindSwitchState(evt, "Clip", &fUseClip) ||
1480 SkOSMenu::FindSwitchState(evt, "Zoomer", &fShowZoomer) ||
1481 SkOSMenu::FindSwitchState(evt, "Magnify", &fMagnify) ||
1482 SkOSMenu::FindListIndex(evt, "Transition-Next", &fTransitionNext) ||
1483 SkOSMenu::FindListIndex(evt, "Transition-Prev", &fTransitionPrev)) {
1485 this->updateTitle();
1488 if (SkOSMenu::FindListIndex(evt, "Tiling", &fTilingMode)) {
1489 if (SampleView::IsSampleView(curr_view(this))) {
1490 ((SampleView*)curr_view(this))->onTileSizeChanged(this->tileSize());
1493 this->updateTitle();
1496 if (SkOSMenu::FindSwitchState(evt, "Flip X", NULL)) {
1497 fFlipAxis ^= kFlipAxis_X;
1498 this->updateMatrix();
1501 if (SkOSMenu::FindSwitchState(evt, "Flip Y", NULL)) {
1502 fFlipAxis ^= kFlipAxis_Y;
1503 this->updateMatrix();
1506 if (SkOSMenu::FindAction(evt,"Save to PDF")) {
1510 return this->INHERITED::onEvent(evt);
1513 bool SampleWindow::onQuery(SkEvent* query) {
1514 if (query->isType("get-slide-count")) {
1515 query->setFast32(fSamples.count());
1518 if (query->isType("get-slide-title")) {
1519 SkView* view = (*fSamples[query->getFast32()])();
1520 SkEvent evt(gTitleEvtName);
1521 if (view->doQuery(&evt)) {
1522 query->setString("title", evt.findString(gTitleEvtName));
1527 if (query->isType("use-fast-text")) {
1528 SkEvent evt(gFastTextEvtName);
1529 return curr_view(this)->doQuery(&evt);
1531 if (query->isType("ignore-window-bitmap")) {
1532 query->setFast32(this->getGrContext() != NULL);
1535 return this->INHERITED::onQuery(query);
1538 DECLARE_bool(portableFonts);
1540 bool SampleWindow::onHandleChar(SkUnichar uni) {
1542 SkView* view = curr_view(this);
1544 SkEvent evt(gCharEvtName);
1546 if (view->doQuery(&evt)) {
1556 case '5': dx = 0; dy = 0; break;
1557 case '8': dx = 0; dy = -1; break;
1558 case '6': dx = 1; dy = 0; break;
1559 case '2': dx = 0; dy = 1; break;
1560 case '4': dx = -1; dy = 0; break;
1561 case '7': dx = -1; dy = -1; break;
1562 case '9': dx = 1; dy = -1; break;
1563 case '3': dx = 1; dy = 1; break;
1564 case '1': dx = -1; dy = 1; break;
1570 if (0xFF != dx && 0xFF != dy) {
1571 if ((dx | dy) == 0) {
1572 fScrollTestX = fScrollTestY = 0;
1584 if (this->sendAnimatePulse()) {
1589 gAnimTimer.togglePauseResume();
1590 if (this->sendAnimatePulse()) {
1595 post_event_to_sink(SkNEW_ARGS(SkEvent, ("PictFileView::toggleBBox")), curr_view(this));
1596 // Cannot call updateTitle() synchronously, because the toggleBBox event is still in
1598 post_event_to_sink(SkNEW_ARGS(SkEvent, (gUpdateWindowTitleEvtName)), this);
1602 toggleDistanceFieldFonts();
1609 FLAGS_portableFonts ^= true;
1613 fRequestGrabImage = true;
1617 gShowGMBounds = !gShowGMBounds;
1618 post_event_to_sink(GMSampleView::NewShowSizeEvt(gShowGMBounds),
1631 this->updateTitle();
1634 fPerspAnim = !fPerspAnim;
1636 this->updateTitle();
1641 GrContext* grContext = this->getGrContext();
1644 grContext->getResourceCacheUsage(NULL, &cacheBytes);
1645 grContext->freeGpuResources();
1646 SkDebugf("Purged %d bytes from the GPU resource cache.\n", cacheBytes);
1655 if (fAppMenu->handleKeyEquivalent(uni)|| fSlideMenu->handleKeyEquivalent(uni)) {
1656 this->onUpdateMenu(fAppMenu);
1657 this->onUpdateMenu(fSlideMenu);
1660 return this->INHERITED::onHandleChar(uni);
1663 void SampleWindow::setDeviceType(DeviceType type) {
1664 if (type == fDeviceType)
1667 fDevManager->tearDownBackend(this);
1671 fDevManager->setUpBackend(this, fMSAASampleCount);
1673 this->updateTitle();
1677 void SampleWindow::toggleSlideshow() {
1678 fAnimating = !fAnimating;
1679 this->postAnimatingEvent();
1680 this->updateTitle();
1683 void SampleWindow::toggleRendering() {
1684 this->setDeviceType(cycle_devicetype(fDeviceType));
1685 this->updateTitle();
1689 void SampleWindow::toggleFPS() {
1690 fMeasureFPS = !fMeasureFPS;
1691 this->updateTitle();
1695 void SampleWindow::toggleDistanceFieldFonts() {
1696 SkSurfaceProps props = this->getSurfaceProps();
1697 uint32_t flags = props.flags() ^ SkSurfaceProps::kUseDistanceFieldFonts_Flag;
1698 this->setSurfaceProps(SkSurfaceProps(flags, props.pixelGeometry()));
1700 this->updateTitle();
1704 #include "SkDumpCanvas.h"
1706 bool SampleWindow::onHandleKey(SkKey key) {
1708 SkView* view = curr_view(this);
1710 SkEvent evt(gKeyEvtName);
1712 if (view->doQuery(&evt)) {
1719 if (this->nextSample()) {
1724 if (this->previousSample()) {
1729 this->changeZoomLevel(1.f / 32.f);
1732 this->changeZoomLevel(-1.f / 32.f);
1736 if (curr_title(this, &title)) {
1737 writeTitleToPrefs(title.c_str());
1742 this->showOverview();
1747 return this->INHERITED::onHandleKey(key);
1750 ///////////////////////////////////////////////////////////////////////////////
1752 static const char gGestureClickType[] = "GestureClickType";
1754 bool SampleWindow::onDispatchClick(int x, int y, Click::State state,
1755 void* owner, unsigned modi) {
1756 if (Click::kMoved_State == state) {
1757 updatePointer(x, y);
1759 int w = SkScalarRoundToInt(this->width());
1760 int h = SkScalarRoundToInt(this->height());
1762 // check for the resize-box
1763 if (w - x < 16 && h - y < 16) {
1764 return false; // let the OS handle the click
1766 else if (fMagnify) {
1767 //it's only necessary to update the drawing if there's a click
1769 return false; //prevent dragging while magnify is enabled
1771 // capture control+option, and trigger debugger
1772 if ((modi & kControl_SkModifierKey) && (modi & kOption_SkModifierKey)) {
1773 if (Click::kDown_State == state) {
1774 SkEvent evt("debug-hit-test");
1775 evt.setS32("debug-hit-test-x", x);
1776 evt.setS32("debug-hit-test-y", y);
1777 curr_view(this)->doEvent(evt);
1781 return this->INHERITED::onDispatchClick(x, y, state, owner, modi);
1786 class GestureClick : public SkView::Click {
1788 GestureClick(SkView* target) : SkView::Click(target) {
1789 this->setType(gGestureClickType);
1792 static bool IsGesture(Click* click) {
1793 return click->isType(gGestureClickType);
1797 SkView::Click* SampleWindow::onFindClickHandler(SkScalar x, SkScalar y,
1799 return new GestureClick(this);
1802 bool SampleWindow::onClick(Click* click) {
1803 if (GestureClick::IsGesture(click)) {
1804 float x = static_cast<float>(click->fICurr.fX);
1805 float y = static_cast<float>(click->fICurr.fY);
1807 switch (click->fState) {
1808 case SkView::Click::kDown_State:
1809 fGesture.touchBegin(click->fOwner, x, y);
1811 case SkView::Click::kMoved_State:
1812 fGesture.touchMoved(click->fOwner, x, y);
1813 this->updateMatrix();
1815 case SkView::Click::kUp_State:
1816 fGesture.touchEnd(click->fOwner);
1817 this->updateMatrix();
1825 ///////////////////////////////////////////////////////////////////////////////
1827 void SampleWindow::loadView(SkView* view) {
1828 SkView::F2BIter iter(this);
1829 SkView* prev = iter.next();
1831 prev->detachFromParent();
1834 view->setVisibleP(true);
1835 view->setClipToBounds(false);
1836 this->attachChildToFront(view)->unref();
1837 view->setSize(this->width(), this->height());
1839 //repopulate the slide menu when a view is loaded
1840 fSlideMenu->reset();
1842 (void)SampleView::SetUsePipe(view, fPipeState);
1843 if (SampleView::IsSampleView(view)) {
1844 SampleView* sampleView = (SampleView*)view;
1845 sampleView->requestMenu(fSlideMenu);
1846 sampleView->onTileSizeChanged(this->tileSize());
1848 this->onUpdateMenu(fSlideMenu);
1849 this->updateTitle();
1852 static const char* gDeviceTypePrefix[] = {
1860 #endif // SK_SUPPORT_GPU
1862 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gDeviceTypePrefix) == SampleWindow::kDeviceTypeCnt,
1863 array_size_mismatch);
1865 static const char* trystate_str(SkOSMenu::TriState state,
1866 const char trueStr[], const char falseStr[]) {
1867 if (SkOSMenu::kOnState == state) {
1869 } else if (SkOSMenu::kOffState == state) {
1875 bool SampleWindow::getRawTitle(SkString* title) {
1876 return curr_title(this, title);
1879 void SampleWindow::updateTitle() {
1881 if (!this->getRawTitle(&title)) {
1882 title.set("<unknown>");
1885 title.prepend(gDeviceTypePrefix[fDeviceType]);
1888 title.prepend(sk_tool_utils::colortype_name(this->getBitmap().colorType()));
1890 if (fTilingMode != kNo_Tiling) {
1891 title.prependf("<T: %s> ", gTilingInfo[fTilingMode].label);
1894 title.prepend("<A> ");
1897 title.prepend("<R> ");
1900 title.prepend("<K> ");
1902 if (this->getSurfaceProps().flags() & SkSurfaceProps::kUseDistanceFieldFonts_Flag) {
1903 title.prepend("<DFF> ");
1906 title.prepend(trystate_str(fLCDState, "LCD ", "lcd "));
1907 title.prepend(trystate_str(fAAState, "AA ", "aa "));
1908 title.prepend(gFilterQualityStates[fFilterQualityIndex].fLabel);
1909 title.prepend(trystate_str(fSubpixelState, "S ", "s "));
1910 title.prepend(fFlipAxis & kFlipAxis_X ? "X " : NULL);
1911 title.prepend(fFlipAxis & kFlipAxis_Y ? "Y " : NULL);
1912 title.prepend(gHintingStates[fHintingState].label);
1915 title.prependf("{%.2f} ", SkScalarToFloat(fZoomLevel));
1919 title.appendf(" %8.3f ms", fMeasureFPS_Time / (float)FPS_REPEAT_COUNT);
1922 SkView* view = curr_view(this);
1923 if (SampleView::IsSampleView(view)) {
1924 switch (fPipeState) {
1925 case SkOSMenu::kOnState:
1926 title.prepend("<Pipe> ");
1928 case SkOSMenu::kMixedState:
1929 title.prepend("<Tiled Pipe> ");
1935 title.prepend("! ");
1939 if (IsGpuDeviceType(fDeviceType) &&
1941 fDevManager->getGrRenderTarget() &&
1942 fDevManager->getGrRenderTarget()->numSamples() > 0) {
1943 title.appendf(" [MSAA: %d]",
1944 fDevManager->getGrRenderTarget()->numSamples());
1948 this->setTitle(title.c_str());
1951 void SampleWindow::onSizeChange() {
1952 this->INHERITED::onSizeChange();
1954 SkView::F2BIter iter(this);
1955 SkView* view = iter.next();
1956 view->setSize(this->width(), this->height());
1958 // rebuild our clippath
1960 const SkScalar W = this->width();
1961 const SkScalar H = this->height();
1965 for (SkScalar y = SK_Scalar1; y < H; y += SkIntToScalar(32)) {
1967 r.set(SK_Scalar1, y, SkIntToScalar(30), y + SkIntToScalar(30));
1968 for (; r.fLeft < W; r.offset(SkIntToScalar(32), 0))
1969 fClipPath.addRect(r);
1974 fClipPath.addRect(r, SkPath::kCCW_Direction);
1975 r.set(W/4, H/4, W*3/4, H*3/4);
1976 fClipPath.addRect(r, SkPath::kCW_Direction);
1980 fZoomCenterX = SkScalarHalf(this->width());
1981 fZoomCenterY = SkScalarHalf(this->height());
1983 #ifdef SK_BUILD_FOR_ANDROID
1984 // FIXME: The first draw after a size change does not work on Android, so
1985 // we post an invalidate.
1986 this->postInvalDelay();
1988 this->updateTitle(); // to refresh our config
1989 fDevManager->windowSizeChanged(this);
1991 if (fTilingMode != kNo_Tiling && SampleView::IsSampleView(view)) {
1992 ((SampleView*)view)->onTileSizeChanged(this->tileSize());
1996 ///////////////////////////////////////////////////////////////////////////////
1998 static const char is_sample_view_tag[] = "sample-is-sample-view";
1999 static const char repeat_count_tag[] = "sample-set-repeat-count";
2000 static const char set_use_pipe_tag[] = "sample-set-use-pipe";
2002 bool SampleView::IsSampleView(SkView* view) {
2003 SkEvent evt(is_sample_view_tag);
2004 return view->doQuery(&evt);
2007 bool SampleView::SetRepeatDraw(SkView* view, int count) {
2008 SkEvent evt(repeat_count_tag);
2009 evt.setFast32(count);
2010 return view->doEvent(evt);
2013 bool SampleView::SetUsePipe(SkView* view, SkOSMenu::TriState state) {
2015 evt.setS32(set_use_pipe_tag, state);
2016 return view->doEvent(evt);
2019 bool SampleView::onEvent(const SkEvent& evt) {
2020 if (evt.isType(repeat_count_tag)) {
2021 fRepeatCount = evt.getFast32();
2026 if (evt.findS32(set_use_pipe_tag, &pipeHolder)) {
2027 fPipeState = static_cast<SkOSMenu::TriState>(pipeHolder);
2031 return this->INHERITED::onEvent(evt);
2034 bool SampleView::onQuery(SkEvent* evt) {
2035 if (evt->isType(is_sample_view_tag)) {
2038 return this->INHERITED::onQuery(evt);
2042 class SimplePC : public SkGPipeController {
2044 SimplePC(SkCanvas* target);
2047 virtual void* requestBlock(size_t minRequest, size_t* actual);
2048 virtual void notifyWritten(size_t bytes);
2051 SkGPipeReader fReader;
2054 size_t fBytesWritten;
2056 SkGPipeReader::Status fStatus;
2058 size_t fTotalWritten;
2061 SimplePC::SimplePC(SkCanvas* target) : fReader(target) {
2063 fBlockSize = fBytesWritten = 0;
2064 fStatus = SkGPipeReader::kDone_Status;
2067 fReader.setBitmapDecoder(&SkImageDecoder::DecodeMemory);
2070 SimplePC::~SimplePC() {
2071 // SkASSERT(SkGPipeReader::kDone_Status == fStatus);
2072 if (fTotalWritten) {
2073 SkDebugf("--- %d bytes %d atoms, status %d\n", fTotalWritten,
2074 fAtomsWritten, fStatus);
2076 //File is open in append mode
2077 FILE* f = fopen(FILE_PATH, "ab");
2078 SkASSERT(f != NULL);
2079 fwrite((const char*)fBlock + fBytesWritten, 1, bytes, f);
2083 if (fAtomsWritten > 1 && fTotalWritten > 4) { //ignore done
2084 gServer.acceptConnections();
2085 gServer.writePacket(fBlock, fTotalWritten);
2092 void* SimplePC::requestBlock(size_t minRequest, size_t* actual) {
2095 fBlockSize = minRequest * 4;
2096 fBlock = sk_malloc_throw(fBlockSize);
2098 *actual = fBlockSize;
2102 void SimplePC::notifyWritten(size_t bytes) {
2103 SkASSERT(fBytesWritten + bytes <= fBlockSize);
2104 fStatus = fReader.playback((const char*)fBlock + fBytesWritten, bytes);
2105 SkASSERT(SkGPipeReader::kError_Status != fStatus);
2106 fBytesWritten += bytes;
2107 fTotalWritten += bytes;
2112 void SampleView::draw(SkCanvas* canvas) {
2113 if (SkOSMenu::kOffState == fPipeState) {
2114 this->INHERITED::draw(canvas);
2116 SkGPipeWriter writer;
2117 SimplePC controller(canvas);
2118 SkBitmap bitmap = capture_bitmap(canvas);
2119 TiledPipeController tc(bitmap, &SkImageDecoder::DecodeMemory, &canvas->getTotalMatrix());
2120 SkGPipeController* pc;
2121 if (SkOSMenu::kMixedState == fPipeState) {
2126 uint32_t flags = SkGPipeWriter::kCrossProcess_Flag;
2128 canvas = writer.startRecording(pc, flags);
2129 //Must draw before controller goes out of scope and sends data
2130 this->INHERITED::draw(canvas);
2131 //explicitly end recording to ensure writer is flushed before the memory
2132 //is freed in the deconstructor of the controller
2133 writer.endRecording();
2137 void SampleView::onDraw(SkCanvas* canvas) {
2138 if (!fHaveCalledOnceBeforeDraw) {
2139 fHaveCalledOnceBeforeDraw = true;
2140 this->onOnceBeforeDraw();
2142 this->onDrawBackground(canvas);
2144 for (int i = 0; i < fRepeatCount; i++) {
2145 SkAutoCanvasRestore acr(canvas, true);
2146 this->onDrawContent(canvas);
2150 void SampleView::onDrawBackground(SkCanvas* canvas) {
2151 canvas->drawColor(fBGColor);
2154 ///////////////////////////////////////////////////////////////////////////////
2156 template <typename T> void SkTBSort(T array[], int count) {
2157 for (int i = 1; i < count - 1; i++) {
2158 bool didSwap = false;
2159 for (int j = count - 1; j > i; --j) {
2160 if (array[j] < array[j-1]) {
2162 array[j-1] = array[j];
2172 for (int k = 0; k < count - 1; k++) {
2173 SkASSERT(!(array[k+1] < array[k]));
2177 #include "SkRandom.h"
2179 static void rand_rect(SkIRect* rect, SkRandom& rand) {
2181 int shift = 32 - bits;
2182 rect->set(rand.nextU() >> shift, rand.nextU() >> shift,
2183 rand.nextU() >> shift, rand.nextU() >> shift);
2187 static void dumpRect(const SkIRect& r) {
2188 SkDebugf(" { %d, %d, %d, %d },\n",
2190 r.fRight, r.fBottom);
2193 static void test_rects(const SkIRect rect[], int count) {
2194 SkRegion rgn0, rgn1;
2196 for (int i = 0; i < count; i++) {
2197 rgn0.op(rect[i], SkRegion::kUnion_Op);
2198 // dumpRect(rect[i]);
2200 rgn1.setRects(rect, count);
2204 for (int i = 0; i < count; i++) {
2211 static void test() {
2214 const SkIRect r0[] = {
2218 const SkIRect r1[] = {
2223 const SkIRect r2[] = {
2230 static const struct {
2231 const SkIRect* fRects;
2234 { r0, SK_ARRAY_COUNT(r0) },
2235 { r1, SK_ARRAY_COUNT(r1) },
2236 { r2, SK_ARRAY_COUNT(r2) },
2239 for (i = 0; i < SK_ARRAY_COUNT(gRecs); i++) {
2240 test_rects(gRecs[i].fRects, gRecs[i].fCount);
2244 for (i = 0; i < 10000; i++) {
2245 SkRegion rgn0, rgn1;
2249 for (int j = 0; j < N; j++) {
2250 rand_rect(&rect[j], rand);
2252 test_rects(rect, N);
2256 // FIXME: this should be in a header
2257 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv);
2258 SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
2259 if (false) { // avoid bit rot, suppress warning
2262 return new SampleWindow(hwnd, argc, argv, NULL);
2265 // FIXME: this should be in a header
2266 void get_preferred_size(int* x, int* y, int* width, int* height);
2267 void get_preferred_size(int* x, int* y, int* width, int* height) {
2274 #ifdef SK_BUILD_FOR_IOS
2275 #include "SkApplication.h"
2276 IOS_launch_type set_cmd_line_args(int , char *[], const char* resourceDir) {
2277 SetResourcePath(resourceDir);
2278 return kApplication__iOSLaunchType;
2282 void application_init() {
2283 // setenv("ANDROID_ROOT", "../../../data", 0);
2284 #ifdef SK_BUILD_FOR_MAC
2285 setenv("ANDROID_ROOT", "/android/device/data", 0);
2291 void application_term() {