SampleApp.cpp revision 28fcae2ec77eb16a79e155f8d788b20457f1c951
1/* 2 * Copyright 2011 Google Inc. 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7#include "SampleApp.h" 8 9#include "SkData.h" 10#include "SkCanvas.h" 11#include "SkDevice.h" 12#include "SkGraphics.h" 13#include "SkImageDecoder.h" 14#include "SkImageEncoder.h" 15#include "SkPaint.h" 16#include "SkPicture.h" 17#include "SkStream.h" 18#include "SkTSort.h" 19#include "SkTime.h" 20#include "SkWindow.h" 21 22#include "SampleCode.h" 23#include "SkTypeface.h" 24 25#if SK_SUPPORT_GPU 26#include "gl/GrGLInterface.h" 27#include "gl/GrGLUtil.h" 28#include "GrRenderTarget.h" 29#include "GrContext.h" 30#include "SkGpuDevice.h" 31#else 32class GrContext; 33#endif 34 35#include "SkOSFile.h" 36#include "SkPDFDevice.h" 37#include "SkPDFDocument.h" 38#include "SkStream.h" 39 40#include "SkGPipe.h" 41#include "SamplePipeControllers.h" 42#include "OverView.h" 43#include "TransitionView.h" 44 45extern SampleView* CreateSamplePictFileView(const char filename[]); 46 47class PictFileFactory : public SkViewFactory { 48 SkString fFilename; 49public: 50 PictFileFactory(const SkString& filename) : fFilename(filename) {} 51 virtual SkView* operator() () const SK_OVERRIDE { 52 return CreateSamplePictFileView(fFilename.c_str()); 53 } 54}; 55 56#ifdef SAMPLE_PDF_FILE_VIEWER 57extern SampleView* CreateSamplePdfFileViewer(const char filename[]); 58 59class PdfFileViewerFactory : public SkViewFactory { 60 SkString fFilename; 61public: 62 PdfFileViewerFactory(const SkString& filename) : fFilename(filename) {} 63 virtual SkView* operator() () const SK_OVERRIDE { 64 return CreateSamplePdfFileViewer(fFilename.c_str()); 65 } 66}; 67#endif // SAMPLE_PDF_FILE_VIEWER 68 69#define PIPE_FILEx 70#ifdef PIPE_FILE 71#define FILE_PATH "/path/to/drawing.data" 72#endif 73 74#define PIPE_NETx 75#ifdef PIPE_NET 76#include "SkSockets.h" 77SkTCPServer gServer; 78#endif 79 80#define USE_ARROWS_FOR_ZOOM true 81 82#if SK_ANGLE 83//#define DEFAULT_TO_ANGLE 1 84#else 85#define DEFAULT_TO_GPU 0 // if 1 default rendering is on GPU 86#endif 87 88#define ANIMATING_EVENTTYPE "nextSample" 89#define ANIMATING_DELAY 250 90 91#ifdef SK_DEBUG 92 #define FPS_REPEAT_MULTIPLIER 1 93#else 94 #define FPS_REPEAT_MULTIPLIER 10 95#endif 96#define FPS_REPEAT_COUNT (10 * FPS_REPEAT_MULTIPLIER) 97 98static SampleWindow* gSampleWindow; 99 100static bool gShowGMBounds; 101 102static void post_event_to_sink(SkEvent* evt, SkEventSink* sink) { 103 evt->setTargetID(sink->getSinkID())->post(); 104} 105 106/////////////////////////////////////////////////////////////////////////////// 107 108static const char* skip_until(const char* str, const char* skip) { 109 if (!str) { 110 return NULL; 111 } 112 return strstr(str, skip); 113} 114 115static const char* skip_past(const char* str, const char* skip) { 116 const char* found = skip_until(str, skip); 117 if (!found) { 118 return NULL; 119 } 120 return found + strlen(skip); 121} 122 123static const char* gPrefFileName = "sampleapp_prefs.txt"; 124 125static bool readTitleFromPrefs(SkString* title) { 126 SkFILEStream stream(gPrefFileName); 127 if (!stream.isValid()) { 128 return false; 129 } 130 131 size_t len = stream.getLength(); 132 SkString data(len); 133 stream.read(data.writable_str(), len); 134 const char* s = data.c_str(); 135 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, "\""); 140 if (stop > s) { 141 title->set(s, stop - s); 142 return true; 143 } 144 return false; 145} 146 147static void writeTitleToPrefs(const char* title) { 148 SkFILEWStream stream(gPrefFileName); 149 SkString data; 150 data.printf("curr-slide-title = \"%s\"\n", title); 151 stream.write(data.c_str(), data.size()); 152} 153 154/////////////////////////////////////////////////////////////////////////////// 155 156class SampleWindow::DefaultDeviceManager : public SampleWindow::DeviceManager { 157public: 158 159 DefaultDeviceManager() { 160#if SK_SUPPORT_GPU 161 fCurContext = NULL; 162 fCurIntf = NULL; 163 fCurRenderTarget = NULL; 164 fMSAASampleCount = 0; 165#endif 166 fBackend = kNone_BackEndType; 167 } 168 169 virtual ~DefaultDeviceManager() { 170#if SK_SUPPORT_GPU 171 SkSafeUnref(fCurContext); 172 SkSafeUnref(fCurIntf); 173 SkSafeUnref(fCurRenderTarget); 174#endif 175 } 176 177 virtual void setUpBackend(SampleWindow* win, int msaaSampleCount) { 178 SkASSERT(kNone_BackEndType == fBackend); 179 180 fBackend = kNone_BackEndType; 181 182#if SK_SUPPORT_GPU 183 switch (win->getDeviceType()) { 184 case kRaster_DeviceType: 185 // fallthrough 186 case kPicture_DeviceType: 187 // fallthrough 188 case kGPU_DeviceType: 189 // fallthrough 190 case kNullGPU_DeviceType: 191 // all these guys use the native backend 192 fBackend = kNativeGL_BackEndType; 193 break; 194#if SK_ANGLE 195 case kANGLE_DeviceType: 196 // ANGLE is really the only odd man out 197 fBackend = kANGLE_BackEndType; 198 break; 199#endif // SK_ANGLE 200 default: 201 SkASSERT(false); 202 break; 203 } 204 AttachmentInfo attachmentInfo; 205 bool result = win->attach(fBackend, msaaSampleCount, &attachmentInfo); 206 if (!result) { 207 SkDebugf("Failed to initialize GL"); 208 return; 209 } 210 fMSAASampleCount = msaaSampleCount; 211 212 SkASSERT(NULL == fCurIntf); 213 SkAutoTUnref<const GrGLInterface> glInterface; 214 switch (win->getDeviceType()) { 215 case kRaster_DeviceType: 216 // fallthrough 217 case kPicture_DeviceType: 218 // fallthrough 219 case kGPU_DeviceType: 220 // all these guys use the native interface 221 glInterface.reset(GrGLCreateNativeInterface()); 222 break; 223#if SK_ANGLE 224 case kANGLE_DeviceType: 225 glInterface.reset(GrGLCreateANGLEInterface()); 226 break; 227#endif // SK_ANGLE 228 case kNullGPU_DeviceType: 229 glInterface.reset(GrGLCreateNullInterface()); 230 break; 231 default: 232 SkASSERT(false); 233 break; 234 } 235 236 // Currently SampleApp does not use NVPR. TODO: Provide an NVPR device type that is skipped 237 // when the driver doesn't support NVPR. 238 fCurIntf = GrGLInterfaceRemoveNVPR(glInterface.get()); 239 240 SkASSERT(NULL == fCurContext); 241 fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf); 242 243 if (NULL == fCurContext || NULL == fCurIntf) { 244 // We need some context and interface to see results 245 SkSafeUnref(fCurContext); 246 SkSafeUnref(fCurIntf); 247 fCurContext = NULL; 248 fCurIntf = NULL; 249 SkDebugf("Failed to setup 3D"); 250 251 win->detach(); 252 } 253#endif // SK_SUPPORT_GPU 254 // call windowSizeChanged to create the render target 255 this->windowSizeChanged(win); 256 } 257 258 virtual void tearDownBackend(SampleWindow *win) { 259#if SK_SUPPORT_GPU 260 SkSafeUnref(fCurContext); 261 fCurContext = NULL; 262 263 SkSafeUnref(fCurIntf); 264 fCurIntf = NULL; 265 266 SkSafeUnref(fCurRenderTarget); 267 fCurRenderTarget = NULL; 268#endif 269 win->detach(); 270 fBackend = kNone_BackEndType; 271 } 272 273 virtual SkCanvas* createCanvas(SampleWindow::DeviceType dType, 274 SampleWindow* win) { 275#if SK_SUPPORT_GPU 276 if (IsGpuDeviceType(dType) && NULL != fCurContext) { 277 SkAutoTUnref<SkBaseDevice> device(new SkGpuDevice(fCurContext, fCurRenderTarget)); 278 return new SkCanvas(device); 279 } else 280#endif 281 { 282 return NULL; 283 } 284 } 285 286 virtual void publishCanvas(SampleWindow::DeviceType dType, 287 SkCanvas* canvas, 288 SampleWindow* win) { 289#if SK_SUPPORT_GPU 290 if (fCurContext) { 291 // in case we have queued drawing calls 292 fCurContext->flush(); 293 294 if (!IsGpuDeviceType(dType)) { 295 // need to send the raster bits to the (gpu) window 296 fCurContext->setRenderTarget(fCurRenderTarget); 297 const SkBitmap& bm = win->getBitmap(); 298 fCurRenderTarget->writePixels(0, 0, bm.width(), bm.height(), 299 kSkia8888_GrPixelConfig, 300 bm.getPixels(), 301 bm.rowBytes()); 302 } 303 } 304#endif 305 306 win->present(); 307 } 308 309 virtual void windowSizeChanged(SampleWindow* win) { 310#if SK_SUPPORT_GPU 311 if (fCurContext) { 312 AttachmentInfo attachmentInfo; 313 win->attach(fBackend, fMSAASampleCount, &attachmentInfo); 314 315 GrBackendRenderTargetDesc desc; 316 desc.fWidth = SkScalarRoundToInt(win->width()); 317 desc.fHeight = SkScalarRoundToInt(win->height()); 318 desc.fConfig = kSkia8888_GrPixelConfig; 319 desc.fOrigin = kBottomLeft_GrSurfaceOrigin; 320 desc.fSampleCnt = attachmentInfo.fSampleCount; 321 desc.fStencilBits = attachmentInfo.fStencilBits; 322 GrGLint buffer; 323 GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer); 324 desc.fRenderTargetHandle = buffer; 325 326 SkSafeUnref(fCurRenderTarget); 327 fCurRenderTarget = fCurContext->wrapBackendRenderTarget(desc); 328 } 329#endif 330 } 331 332 virtual GrContext* getGrContext() { 333#if SK_SUPPORT_GPU 334 return fCurContext; 335#else 336 return NULL; 337#endif 338 } 339 340 virtual GrRenderTarget* getGrRenderTarget() SK_OVERRIDE { 341#if SK_SUPPORT_GPU 342 return fCurRenderTarget; 343#else 344 return NULL; 345#endif 346 } 347 348private: 349 350#if SK_SUPPORT_GPU 351 GrContext* fCurContext; 352 const GrGLInterface* fCurIntf; 353 GrRenderTarget* fCurRenderTarget; 354 int fMSAASampleCount; 355#endif 356 357 SkOSWindow::SkBackEndTypes fBackend; 358 359 typedef SampleWindow::DeviceManager INHERITED; 360}; 361 362/////////////// 363static const char view_inval_msg[] = "view-inval-msg"; 364 365void SampleWindow::postInvalDelay() { 366 (new SkEvent(view_inval_msg, this->getSinkID()))->postDelay(1); 367} 368 369static bool isInvalEvent(const SkEvent& evt) { 370 return evt.isType(view_inval_msg); 371} 372////////////////// 373 374SkFuncViewFactory::SkFuncViewFactory(SkViewCreateFunc func) 375 : fCreateFunc(func) { 376} 377 378SkView* SkFuncViewFactory::operator() () const { 379 return (*fCreateFunc)(); 380} 381 382#include "GMSampleView.h" 383 384SkGMSampleViewFactory::SkGMSampleViewFactory(GMFactoryFunc func) 385 : fFunc(func) { 386} 387 388SkView* SkGMSampleViewFactory::operator() () const { 389 skiagm::GM* gm = fFunc(NULL); 390 gm->setMode(skiagm::GM::kSample_Mode); 391 return new GMSampleView(gm); 392} 393 394SkViewRegister* SkViewRegister::gHead; 395SkViewRegister::SkViewRegister(SkViewFactory* fact) : fFact(fact) { 396 fFact->ref(); 397 fChain = gHead; 398 gHead = this; 399} 400 401SkViewRegister::SkViewRegister(SkViewCreateFunc func) { 402 fFact = new SkFuncViewFactory(func); 403 fChain = gHead; 404 gHead = this; 405} 406 407SkViewRegister::SkViewRegister(GMFactoryFunc func) { 408 fFact = new SkGMSampleViewFactory(func); 409 fChain = gHead; 410 gHead = this; 411} 412 413class AutoUnrefArray { 414public: 415 AutoUnrefArray() {} 416 ~AutoUnrefArray() { 417 int count = fObjs.count(); 418 for (int i = 0; i < count; ++i) { 419 fObjs[i]->unref(); 420 } 421 } 422 SkRefCnt*& push_back() { return *fObjs.append(); } 423 424private: 425 SkTDArray<SkRefCnt*> fObjs; 426}; 427 428// registers GMs as Samples 429// This can't be performed during static initialization because it could be 430// run before GMRegistry has been fully built. 431static void SkGMRegistyToSampleRegistry() { 432 static bool gOnce; 433 static AutoUnrefArray fRegisters; 434 435 if (!gOnce) { 436 const skiagm::GMRegistry* gmreg = skiagm::GMRegistry::Head(); 437 while (gmreg) { 438 fRegisters.push_back() = new SkViewRegister(gmreg->factory()); 439 gmreg = gmreg->next(); 440 } 441 gOnce = true; 442 } 443} 444 445////////////////////////////////////////////////////////////////////////////// 446 447enum FlipAxisEnum { 448 kFlipAxis_X = (1 << 0), 449 kFlipAxis_Y = (1 << 1) 450}; 451 452#include "SkDrawFilter.h" 453 454struct HintingState { 455 SkPaint::Hinting hinting; 456 const char* name; 457 const char* label; 458}; 459static HintingState gHintingStates[] = { 460 {SkPaint::kNo_Hinting, "Mixed", NULL }, 461 {SkPaint::kNo_Hinting, "None", "H0 " }, 462 {SkPaint::kSlight_Hinting, "Slight", "Hs " }, 463 {SkPaint::kNormal_Hinting, "Normal", "Hn " }, 464 {SkPaint::kFull_Hinting, "Full", "Hf " }, 465}; 466 467struct FilterLevelState { 468 SkPaint::FilterLevel fLevel; 469 const char* fName; 470 const char* fLabel; 471}; 472static FilterLevelState gFilterLevelStates[] = { 473 { SkPaint::kNone_FilterLevel, "Mixed", NULL }, 474 { SkPaint::kNone_FilterLevel, "None", "F0 " }, 475 { SkPaint::kLow_FilterLevel, "Low", "F1 " }, 476 { SkPaint::kMedium_FilterLevel, "Medium", "F2 " }, 477 { SkPaint::kHigh_FilterLevel, "High", "F3 " }, 478}; 479 480class FlagsDrawFilter : public SkDrawFilter { 481public: 482 FlagsDrawFilter(SkOSMenu::TriState lcd, SkOSMenu::TriState aa, 483 SkOSMenu::TriState subpixel, int hinting, int filterlevel) 484 : fLCDState(lcd) 485 , fAAState(aa) 486 , fSubpixelState(subpixel) 487 , fHintingState(hinting) 488 , fFilterLevelIndex(filterlevel) 489 { 490 SkASSERT((unsigned)filterlevel < SK_ARRAY_COUNT(gFilterLevelStates)); 491 } 492 493 virtual bool filter(SkPaint* paint, Type t) { 494 if (kText_Type == t && SkOSMenu::kMixedState != fLCDState) { 495 paint->setLCDRenderText(SkOSMenu::kOnState == fLCDState); 496 } 497 if (SkOSMenu::kMixedState != fAAState) { 498 paint->setAntiAlias(SkOSMenu::kOnState == fAAState); 499 } 500 if (0 != fFilterLevelIndex) { 501 paint->setFilterLevel(gFilterLevelStates[fFilterLevelIndex].fLevel); 502 } 503 if (SkOSMenu::kMixedState != fSubpixelState) { 504 paint->setSubpixelText(SkOSMenu::kOnState == fSubpixelState); 505 } 506 if (0 != fHintingState && fHintingState < (int)SK_ARRAY_COUNT(gHintingStates)) { 507 paint->setHinting(gHintingStates[fHintingState].hinting); 508 } 509 return true; 510 } 511 512private: 513 SkOSMenu::TriState fLCDState; 514 SkOSMenu::TriState fAAState; 515 SkOSMenu::TriState fSubpixelState; 516 int fHintingState; 517 int fFilterLevelIndex; 518}; 519 520////////////////////////////////////////////////////////////////////////////// 521 522#define MAX_ZOOM_LEVEL 8 523#define MIN_ZOOM_LEVEL -8 524 525static const char gCharEvtName[] = "SampleCode_Char_Event"; 526static const char gKeyEvtName[] = "SampleCode_Key_Event"; 527static const char gTitleEvtName[] = "SampleCode_Title_Event"; 528static const char gPrefSizeEvtName[] = "SampleCode_PrefSize_Event"; 529static const char gFastTextEvtName[] = "SampleCode_FastText_Event"; 530static const char gUpdateWindowTitleEvtName[] = "SampleCode_UpdateWindowTitle"; 531 532bool SampleCode::CharQ(const SkEvent& evt, SkUnichar* outUni) { 533 if (evt.isType(gCharEvtName, sizeof(gCharEvtName) - 1)) { 534 if (outUni) { 535 *outUni = evt.getFast32(); 536 } 537 return true; 538 } 539 return false; 540} 541 542bool SampleCode::KeyQ(const SkEvent& evt, SkKey* outKey) { 543 if (evt.isType(gKeyEvtName, sizeof(gKeyEvtName) - 1)) { 544 if (outKey) { 545 *outKey = (SkKey)evt.getFast32(); 546 } 547 return true; 548 } 549 return false; 550} 551 552bool SampleCode::TitleQ(const SkEvent& evt) { 553 return evt.isType(gTitleEvtName, sizeof(gTitleEvtName) - 1); 554} 555 556void SampleCode::TitleR(SkEvent* evt, const char title[]) { 557 SkASSERT(evt && TitleQ(*evt)); 558 evt->setString(gTitleEvtName, title); 559} 560 561bool SampleCode::RequestTitle(SkView* view, SkString* title) { 562 SkEvent evt(gTitleEvtName); 563 if (view->doQuery(&evt)) { 564 title->set(evt.findString(gTitleEvtName)); 565 return true; 566 } 567 return false; 568} 569 570bool SampleCode::PrefSizeQ(const SkEvent& evt) { 571 return evt.isType(gPrefSizeEvtName, sizeof(gPrefSizeEvtName) - 1); 572} 573 574void SampleCode::PrefSizeR(SkEvent* evt, SkScalar width, SkScalar height) { 575 SkASSERT(evt && PrefSizeQ(*evt)); 576 SkScalar size[2]; 577 size[0] = width; 578 size[1] = height; 579 evt->setScalars(gPrefSizeEvtName, 2, size); 580} 581 582bool SampleCode::FastTextQ(const SkEvent& evt) { 583 return evt.isType(gFastTextEvtName, sizeof(gFastTextEvtName) - 1); 584} 585 586/////////////////////////////////////////////////////////////////////////////// 587 588static SkMSec gAnimTime; 589static SkMSec gAnimTimePrev; 590 591SkMSec SampleCode::GetAnimTime() { return gAnimTime; } 592SkMSec SampleCode::GetAnimTimeDelta() { return gAnimTime - gAnimTimePrev; } 593SkScalar SampleCode::GetAnimSecondsDelta() { 594 return SkDoubleToScalar(GetAnimTimeDelta() / 1000.0); 595} 596 597SkScalar SampleCode::GetAnimScalar(SkScalar speed, SkScalar period) { 598 // since gAnimTime can be up to 32 bits, we can't convert it to a float 599 // or we'll lose the low bits. Hence we use doubles for the intermediate 600 // calculations 601 double seconds = (double)gAnimTime / 1000.0; 602 double value = SkScalarToDouble(speed) * seconds; 603 if (period) { 604 value = ::fmod(value, SkScalarToDouble(period)); 605 } 606 return SkDoubleToScalar(value); 607} 608 609SkScalar SampleCode::GetAnimSinScalar(SkScalar amplitude, 610 SkScalar periodInSec, 611 SkScalar phaseInSec) { 612 if (!periodInSec) { 613 return 0; 614 } 615 double t = (double)gAnimTime / 1000.0 + phaseInSec; 616 t *= SkScalarToFloat(2 * SK_ScalarPI) / periodInSec; 617 amplitude = SK_ScalarHalf * amplitude; 618 return SkScalarMul(amplitude, SkDoubleToScalar(sin(t))) + amplitude; 619} 620 621enum TilingMode { 622 kNo_Tiling, 623 kAbs_128x128_Tiling, 624 kAbs_256x256_Tiling, 625 kRel_4x4_Tiling, 626 kRel_1x16_Tiling, 627 kRel_16x1_Tiling, 628 629 kLast_TilingMode_Enum 630}; 631 632struct TilingInfo { 633 const char* label; 634 SkScalar w, h; 635}; 636 637static const struct TilingInfo gTilingInfo[] = { 638 { "No tiling", SK_Scalar1 , SK_Scalar1 }, // kNo_Tiling 639 { "128x128" , SkIntToScalar(128), SkIntToScalar(128) }, // kAbs_128x128_Tiling 640 { "256x256" , SkIntToScalar(256), SkIntToScalar(256) }, // kAbs_256x256_Tiling 641 { "1/4x1/4" , SK_Scalar1 / 4 , SK_Scalar1 / 4 }, // kRel_4x4_Tiling 642 { "1/1x1/16" , SK_Scalar1 , SK_Scalar1 / 16 }, // kRel_1x16_Tiling 643 { "1/16x1/1" , SK_Scalar1 / 16 , SK_Scalar1 }, // kRel_16x1_Tiling 644}; 645SK_COMPILE_ASSERT((SK_ARRAY_COUNT(gTilingInfo) == kLast_TilingMode_Enum), 646 Incomplete_tiling_labels); 647 648SkSize SampleWindow::tileSize() const { 649 SkASSERT((TilingMode)fTilingMode < kLast_TilingMode_Enum); 650 const struct TilingInfo* info = gTilingInfo + fTilingMode; 651 return SkSize::Make(info->w > SK_Scalar1 ? info->w : this->width() * info->w, 652 info->h > SK_Scalar1 ? info->h : this->height() * info->h); 653} 654////////////////////////////////////////////////////////////////////////////// 655 656static SkView* curr_view(SkWindow* wind) { 657 SkView::F2BIter iter(wind); 658 return iter.next(); 659} 660 661static bool curr_title(SkWindow* wind, SkString* title) { 662 SkView* view = curr_view(wind); 663 if (view) { 664 SkEvent evt(gTitleEvtName); 665 if (view->doQuery(&evt)) { 666 title->set(evt.findString(gTitleEvtName)); 667 return true; 668 } 669 } 670 return false; 671} 672 673void SampleWindow::setZoomCenter(float x, float y) 674{ 675 fZoomCenterX = x; 676 fZoomCenterY = y; 677} 678 679bool SampleWindow::zoomIn() 680{ 681 // Arbitrarily decided 682 if (fFatBitsScale == 25) return false; 683 fFatBitsScale++; 684 this->inval(NULL); 685 return true; 686} 687 688bool SampleWindow::zoomOut() 689{ 690 if (fFatBitsScale == 1) return false; 691 fFatBitsScale--; 692 this->inval(NULL); 693 return true; 694} 695 696void SampleWindow::updatePointer(int x, int y) 697{ 698 fMouseX = x; 699 fMouseY = y; 700 if (fShowZoomer) { 701 this->inval(NULL); 702 } 703} 704 705static inline SampleWindow::DeviceType cycle_devicetype(SampleWindow::DeviceType ct) { 706 static const SampleWindow::DeviceType gCT[] = { 707 SampleWindow::kPicture_DeviceType, 708#if SK_SUPPORT_GPU 709 SampleWindow::kGPU_DeviceType, 710#if SK_ANGLE 711 SampleWindow::kANGLE_DeviceType, 712#endif // SK_ANGLE 713 SampleWindow::kRaster_DeviceType, // skip the null gpu device in normal cycling 714#endif // SK_SUPPORT_GPU 715 SampleWindow::kRaster_DeviceType 716 }; 717 SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gCT) == SampleWindow::kDeviceTypeCnt, array_size_mismatch); 718 return gCT[ct]; 719} 720 721static void usage(const char * argv0) { 722 SkDebugf("%s [--slide sampleName] [-i resourcePath] [--msaa sampleCount] [--pictureDir dirPath] [--picture path] [--sort]\n", argv0); 723#ifdef SAMPLE_PDF_FILE_VIEWER 724 SkDebugf(" [--pdfDir pdfPath]\n"); 725 SkDebugf(" pdfPath: path to directory pdf files are read from\n"); 726#endif // SAMPLE_PDF_FILE_VIEWER 727 SkDebugf(" sampleName: sample at which to start.\n"); 728 SkDebugf(" resourcePath: directory that stores image resources.\n"); 729 SkDebugf(" msaa: request multisampling with the given sample count.\n"); 730 SkDebugf(" dirPath: path to directory skia pictures are read from\n"); 731 SkDebugf(" path: path to skia picture\n"); 732 SkDebugf(" --sort: sort samples by title, this would help to compare pdf rendering (P:foo.pdf) with skp rendering (P:foo.pdf)\n"); 733} 734 735static SkString getSampleTitle(const SkViewFactory* sampleFactory) { 736 SkView* view = (*sampleFactory)(); 737 SkString title; 738 SampleCode::RequestTitle(view, &title); 739 view->unref(); 740 return title; 741} 742 743static bool compareSampleTitle(const SkViewFactory* first, const SkViewFactory* second) { 744 return strcmp(getSampleTitle(first).c_str(), getSampleTitle(second).c_str()) < 0; 745} 746 747SampleWindow::SampleWindow(void* hwnd, int argc, char** argv, DeviceManager* devManager) 748 : INHERITED(hwnd) 749 , fDevManager(NULL) { 750 751 fCurrIndex = -1; 752 753 this->registerPictFileSamples(argv, argc); 754 this->registerPictFileSample(argv, argc); 755#ifdef SAMPLE_PDF_FILE_VIEWER 756 this->registerPdfFileViewerSamples(argv, argc); 757#endif // SAMPLE_PDF_FILE_VIEWER 758 SkGMRegistyToSampleRegistry(); 759 { 760 const SkViewRegister* reg = SkViewRegister::Head(); 761 while (reg) { 762 *fSamples.append() = reg->factory(); 763 reg = reg->next(); 764 } 765 } 766 767 bool sort = false; 768 for (int i = 0; i < argc; ++i) { 769 if (!strcmp(argv[i], "--sort")) { 770 sort = true; 771 break; 772 } 773 } 774 775 if (sort) { 776 // Sort samples, so foo.skp and foo.pdf are consecutive and we can quickly spot where 777 // skp -> pdf -> png fails. 778 SkTQSort(fSamples.begin(), fSamples.end() ? fSamples.end() - 1 : NULL, compareSampleTitle); 779 } 780 781 const char* resourcePath = "resources"; // same default as tests 782 fMSAASampleCount = 0; 783 784 const char* const commandName = argv[0]; 785 char* const* stop = argv + argc; 786 for (++argv; argv < stop; ++argv) { 787 if (!strcmp(*argv, "-i") || !strcmp(*argv, "--resourcePath")) { 788 argv++; 789 if (argv < stop && **argv) { 790 resourcePath = *argv; 791 } 792 } else if (strcmp(*argv, "--slide") == 0) { 793 argv++; 794 if (argv < stop && **argv) { 795 fCurrIndex = findByTitle(*argv); 796 if (fCurrIndex < 0) { 797 fprintf(stderr, "Unknown sample \"%s\"\n", *argv); 798 listTitles(); 799 } 800 } 801 } else if (strcmp(*argv, "--msaa") == 0) { 802 ++argv; 803 if (argv < stop && **argv) { 804 fMSAASampleCount = atoi(*argv); 805 } 806 } else if (strcmp(*argv, "--list") == 0) { 807 listTitles(); 808 } else if (strcmp(*argv, "--pictureDir") == 0) { 809 ++argv; // This case is dealt with in registerPictFileSamples(). 810 } else if (strcmp(*argv, "--picture") == 0) { 811 ++argv; // This case is dealt with in registerPictFileSample(). 812 } 813 else { 814 usage(commandName); 815 } 816 } 817 818 if (fCurrIndex < 0) { 819 SkString title; 820 if (readTitleFromPrefs(&title)) { 821 fCurrIndex = findByTitle(title.c_str()); 822 } 823 } 824 825 if (fCurrIndex < 0) { 826 fCurrIndex = 0; 827 } 828 829 gSampleWindow = this; 830 831#ifdef PIPE_FILE 832 //Clear existing file or create file if it doesn't exist 833 FILE* f = fopen(FILE_PATH, "wb"); 834 fclose(f); 835#endif 836 837 fPicture = NULL; 838 839 fDeviceType = kRaster_DeviceType; 840 841#if DEFAULT_TO_GPU 842 fDeviceType = kGPU_DeviceType; 843#endif 844#if SK_ANGLE && DEFAULT_TO_ANGLE 845 fDeviceType = kANGLE_DeviceType; 846#endif 847 848 fUseClip = false; 849 fNClip = false; 850 fAnimating = false; 851 fRotate = false; 852 fRotateAnimTime = 0; 853 fPerspAnim = false; 854 fPerspAnimTime = 0; 855 fRequestGrabImage = false; 856 fPipeState = SkOSMenu::kOffState; 857 fTilingMode = kNo_Tiling; 858 fMeasureFPS = false; 859 fLCDState = SkOSMenu::kMixedState; 860 fAAState = SkOSMenu::kMixedState; 861 fSubpixelState = SkOSMenu::kMixedState; 862 fHintingState = 0; 863 fFilterLevelIndex = 0; 864 fFlipAxis = 0; 865 fScrollTestX = fScrollTestY = 0; 866 867 fMouseX = fMouseY = 0; 868 fFatBitsScale = 8; 869 fTypeface = SkTypeface::CreateFromTypeface(NULL, SkTypeface::kBold); 870 fShowZoomer = false; 871 872 fZoomLevel = 0; 873 fZoomScale = SK_Scalar1; 874 875 fMagnify = false; 876 877 fSaveToPdf = false; 878 fPdfCanvas = NULL; 879 880 fTransitionNext = 6; 881 fTransitionPrev = 2; 882 883 int sinkID = this->getSinkID(); 884 fAppMenu = new SkOSMenu; 885 fAppMenu->setTitle("Global Settings"); 886 int itemID; 887 888 itemID =fAppMenu->appendList("Device Type", "Device Type", sinkID, 0, 889 "Raster", "Picture", "OpenGL", 890#if SK_ANGLE 891 "ANGLE", 892#endif 893 NULL); 894 fAppMenu->assignKeyEquivalentToItem(itemID, 'd'); 895 itemID = fAppMenu->appendTriState("AA", "AA", sinkID, fAAState); 896 fAppMenu->assignKeyEquivalentToItem(itemID, 'b'); 897 itemID = fAppMenu->appendTriState("LCD", "LCD", sinkID, fLCDState); 898 fAppMenu->assignKeyEquivalentToItem(itemID, 'l'); 899 itemID = fAppMenu->appendList("FilterLevel", "FilterLevel", sinkID, fFilterLevelIndex, 900 gFilterLevelStates[0].fName, 901 gFilterLevelStates[1].fName, 902 gFilterLevelStates[2].fName, 903 gFilterLevelStates[3].fName, 904 gFilterLevelStates[4].fName, 905 NULL); 906 fAppMenu->assignKeyEquivalentToItem(itemID, 'n'); 907 itemID = fAppMenu->appendTriState("Subpixel", "Subpixel", sinkID, fSubpixelState); 908 fAppMenu->assignKeyEquivalentToItem(itemID, 's'); 909 itemID = fAppMenu->appendList("Hinting", "Hinting", sinkID, fHintingState, 910 gHintingStates[0].name, 911 gHintingStates[1].name, 912 gHintingStates[2].name, 913 gHintingStates[3].name, 914 gHintingStates[4].name, 915 NULL); 916 fAppMenu->assignKeyEquivalentToItem(itemID, 'h'); 917 918 fUsePipeMenuItemID = fAppMenu->appendTriState("Pipe", "Pipe" , sinkID, 919 fPipeState); 920 fAppMenu->assignKeyEquivalentToItem(fUsePipeMenuItemID, 'P'); 921 922 itemID =fAppMenu->appendList("Tiling", "Tiling", sinkID, fTilingMode, 923 gTilingInfo[kNo_Tiling].label, 924 gTilingInfo[kAbs_128x128_Tiling].label, 925 gTilingInfo[kAbs_256x256_Tiling].label, 926 gTilingInfo[kRel_4x4_Tiling].label, 927 gTilingInfo[kRel_1x16_Tiling].label, 928 gTilingInfo[kRel_16x1_Tiling].label, 929 NULL); 930 fAppMenu->assignKeyEquivalentToItem(itemID, 't'); 931 932 itemID = fAppMenu->appendSwitch("Slide Show", "Slide Show" , sinkID, false); 933 fAppMenu->assignKeyEquivalentToItem(itemID, 'a'); 934 itemID = fAppMenu->appendSwitch("Clip", "Clip" , sinkID, fUseClip); 935 fAppMenu->assignKeyEquivalentToItem(itemID, 'c'); 936 itemID = fAppMenu->appendSwitch("Flip X", "Flip X" , sinkID, false); 937 fAppMenu->assignKeyEquivalentToItem(itemID, 'x'); 938 itemID = fAppMenu->appendSwitch("Flip Y", "Flip Y" , sinkID, false); 939 fAppMenu->assignKeyEquivalentToItem(itemID, 'y'); 940 itemID = fAppMenu->appendSwitch("Zoomer", "Zoomer" , sinkID, fShowZoomer); 941 fAppMenu->assignKeyEquivalentToItem(itemID, 'z'); 942 itemID = fAppMenu->appendSwitch("Magnify", "Magnify" , sinkID, fMagnify); 943 fAppMenu->assignKeyEquivalentToItem(itemID, 'm'); 944 itemID =fAppMenu->appendList("Transition-Next", "Transition-Next", sinkID, 945 fTransitionNext, "Up", "Up and Right", "Right", 946 "Down and Right", "Down", "Down and Left", 947 "Left", "Up and Left", NULL); 948 fAppMenu->assignKeyEquivalentToItem(itemID, 'j'); 949 itemID =fAppMenu->appendList("Transition-Prev", "Transition-Prev", sinkID, 950 fTransitionPrev, "Up", "Up and Right", "Right", 951 "Down and Right", "Down", "Down and Left", 952 "Left", "Up and Left", NULL); 953 fAppMenu->assignKeyEquivalentToItem(itemID, 'k'); 954 itemID = fAppMenu->appendAction("Save to PDF", sinkID); 955 fAppMenu->assignKeyEquivalentToItem(itemID, 'e'); 956 957 this->addMenu(fAppMenu); 958 fSlideMenu = new SkOSMenu; 959 this->addMenu(fSlideMenu); 960 961 this->setColorType(kN32_SkColorType); 962 this->setVisibleP(true); 963 this->setClipToBounds(false); 964 965 skiagm::GM::SetResourcePath(resourcePath); 966 967 this->loadView((*fSamples[fCurrIndex])()); 968 969 fPDFData = NULL; 970 971 if (NULL == devManager) { 972 fDevManager = new DefaultDeviceManager(); 973 } else { 974 devManager->ref(); 975 fDevManager = devManager; 976 } 977 fDevManager->setUpBackend(this, fMSAASampleCount); 978 979 // If another constructor set our dimensions, ensure that our 980 // onSizeChange gets called. 981 if (this->height() && this->width()) { 982 this->onSizeChange(); 983 } 984 985 // can't call this synchronously, since it may require a subclass to 986 // to implement, or the caller may need us to have returned from the 987 // constructor first. Hence we post an event to ourselves. 988// this->updateTitle(); 989 post_event_to_sink(new SkEvent(gUpdateWindowTitleEvtName), this); 990} 991 992SampleWindow::~SampleWindow() { 993 delete fPicture; 994 delete fPdfCanvas; 995 fTypeface->unref(); 996 997 SkSafeUnref(fDevManager); 998} 999 1000static void make_filepath(SkString* path, const char* dir, const SkString& name) { 1001 size_t len = strlen(dir); 1002 path->set(dir); 1003 if (len > 0 && dir[len - 1] != '/') { 1004 path->append("/"); 1005 } 1006 path->append(name); 1007} 1008 1009void SampleWindow::registerPictFileSample(char** argv, int argc) { 1010 const char* pict = NULL; 1011 1012 for (int i = 0; i < argc; ++i) { 1013 if (!strcmp(argv[i], "--picture")) { 1014 i += 1; 1015 if (i < argc) { 1016 pict = argv[i]; 1017 break; 1018 } 1019 } 1020 } 1021 if (pict) { 1022 SkString path(pict); 1023 fCurrIndex = fSamples.count(); 1024 *fSamples.append() = new PictFileFactory(path); 1025 } 1026} 1027 1028void SampleWindow::registerPictFileSamples(char** argv, int argc) { 1029 const char* pictDir = NULL; 1030 1031 for (int i = 0; i < argc; ++i) { 1032 if (!strcmp(argv[i], "--pictureDir")) { 1033 i += 1; 1034 if (i < argc) { 1035 pictDir = argv[i]; 1036 break; 1037 } 1038 } 1039 } 1040 if (pictDir) { 1041 SkOSFile::Iter iter(pictDir, "skp"); 1042 SkString filename; 1043 while (iter.next(&filename)) { 1044 SkString path; 1045 make_filepath(&path, pictDir, filename); 1046 *fSamples.append() = new PictFileFactory(path); 1047 } 1048 } 1049} 1050 1051#ifdef SAMPLE_PDF_FILE_VIEWER 1052void SampleWindow::registerPdfFileViewerSamples(char** argv, int argc) { 1053 const char* pdfDir = NULL; 1054 1055 for (int i = 0; i < argc; ++i) { 1056 if (!strcmp(argv[i], "--pdfDir")) { 1057 i += 1; 1058 if (i < argc) { 1059 pdfDir = argv[i]; 1060 break; 1061 } 1062 } 1063 } 1064 if (pdfDir) { 1065 SkOSFile::Iter iter(pdfDir, "pdf"); 1066 SkString filename; 1067 while (iter.next(&filename)) { 1068 SkString path; 1069 make_filepath(&path, pdfDir, filename); 1070 *fSamples.append() = new PdfFileViewerFactory(path); 1071 } 1072 } 1073} 1074#endif // SAMPLE_PDF_FILE_VIEWER 1075 1076 1077int SampleWindow::findByTitle(const char title[]) { 1078 int i, count = fSamples.count(); 1079 for (i = 0; i < count; i++) { 1080 if (getSampleTitle(i).equals(title)) { 1081 return i; 1082 } 1083 } 1084 return -1; 1085} 1086 1087void SampleWindow::listTitles() { 1088 int count = fSamples.count(); 1089 SkDebugf("All Slides:\n"); 1090 for (int i = 0; i < count; i++) { 1091 SkDebugf(" %s\n", getSampleTitle(i).c_str()); 1092 } 1093} 1094 1095static SkBitmap capture_bitmap(SkCanvas* canvas) { 1096 SkBitmap bm; 1097 if (bm.allocPixels(canvas->imageInfo())) { 1098 canvas->readPixels(&bm, 0, 0); 1099 } 1100 return bm; 1101} 1102 1103static bool bitmap_diff(SkCanvas* canvas, const SkBitmap& orig, 1104 SkBitmap* diff) { 1105 const SkBitmap& src = canvas->getDevice()->accessBitmap(false); 1106 1107 SkAutoLockPixels alp0(src); 1108 SkAutoLockPixels alp1(orig); 1109 for (int y = 0; y < src.height(); y++) { 1110 const void* srcP = src.getAddr(0, y); 1111 const void* origP = orig.getAddr(0, y); 1112 size_t bytes = src.width() * src.bytesPerPixel(); 1113 if (memcmp(srcP, origP, bytes)) { 1114 SkDebugf("---------- difference on line %d\n", y); 1115 return true; 1116 } 1117 } 1118 return false; 1119} 1120 1121static void drawText(SkCanvas* canvas, SkString string, SkScalar left, SkScalar top, SkPaint& paint) 1122{ 1123 SkColor desiredColor = paint.getColor(); 1124 paint.setColor(SK_ColorWHITE); 1125 const char* c_str = string.c_str(); 1126 size_t size = string.size(); 1127 SkRect bounds; 1128 paint.measureText(c_str, size, &bounds); 1129 bounds.offset(left, top); 1130 SkScalar inset = SkIntToScalar(-2); 1131 bounds.inset(inset, inset); 1132 canvas->drawRect(bounds, paint); 1133 if (desiredColor != SK_ColorBLACK) { 1134 paint.setColor(SK_ColorBLACK); 1135 canvas->drawText(c_str, size, left + SK_Scalar1, top + SK_Scalar1, paint); 1136 } 1137 paint.setColor(desiredColor); 1138 canvas->drawText(c_str, size, left, top, paint); 1139} 1140 1141#define XCLIP_N 8 1142#define YCLIP_N 8 1143 1144void SampleWindow::draw(SkCanvas* canvas) { 1145 // update the animation time 1146 if (!gAnimTimePrev && !gAnimTime) { 1147 // first time make delta be 0 1148 gAnimTime = SkTime::GetMSecs(); 1149 gAnimTimePrev = gAnimTime; 1150 } else { 1151 gAnimTimePrev = gAnimTime; 1152 gAnimTime = SkTime::GetMSecs(); 1153 } 1154 1155 if (fGesture.isActive()) { 1156 this->updateMatrix(); 1157 } 1158 1159 if (fMeasureFPS) { 1160 fMeasureFPS_Time = 0; 1161 } 1162 1163 if (fNClip) { 1164 this->INHERITED::draw(canvas); 1165 SkBitmap orig = capture_bitmap(canvas); 1166 1167 const SkScalar w = this->width(); 1168 const SkScalar h = this->height(); 1169 const SkScalar cw = w / XCLIP_N; 1170 const SkScalar ch = h / YCLIP_N; 1171 for (int y = 0; y < YCLIP_N; y++) { 1172 SkRect r; 1173 r.fTop = y * ch; 1174 r.fBottom = (y + 1) * ch; 1175 if (y == YCLIP_N - 1) { 1176 r.fBottom = h; 1177 } 1178 for (int x = 0; x < XCLIP_N; x++) { 1179 SkAutoCanvasRestore acr(canvas, true); 1180 r.fLeft = x * cw; 1181 r.fRight = (x + 1) * cw; 1182 if (x == XCLIP_N - 1) { 1183 r.fRight = w; 1184 } 1185 canvas->clipRect(r); 1186 this->INHERITED::draw(canvas); 1187 } 1188 } 1189 1190 SkBitmap diff; 1191 if (bitmap_diff(canvas, orig, &diff)) { 1192 } 1193 } else { 1194 SkSize tile = this->tileSize(); 1195 1196 for (SkScalar y = 0; y < height(); y += tile.height()) { 1197 for (SkScalar x = 0; x < width(); x += tile.width()) { 1198 SkAutoCanvasRestore acr(canvas, true); 1199 canvas->clipRect(SkRect::MakeXYWH(x, y, 1200 tile.width(), 1201 tile.height())); 1202 this->INHERITED::draw(canvas); 1203 } 1204 } 1205 1206 if (fTilingMode != kNo_Tiling) { 1207 SkPaint paint; 1208 paint.setColor(0x60FF00FF); 1209 paint.setStyle(SkPaint::kStroke_Style); 1210 1211 for (SkScalar y = 0; y < height(); y += tile.height()) { 1212 for (SkScalar x = 0; x < width(); x += tile.width()) { 1213 canvas->drawRect(SkRect::MakeXYWH(x, y, 1214 tile.width(), 1215 tile.height()), 1216 paint); 1217 } 1218 } 1219 } 1220 } 1221 if (fShowZoomer && !fSaveToPdf) { 1222 showZoomer(canvas); 1223 } 1224 if (fMagnify && !fSaveToPdf) { 1225 magnify(canvas); 1226 } 1227 1228 if (fMeasureFPS && fMeasureFPS_Time) { 1229 this->updateTitle(); 1230 this->postInvalDelay(); 1231 } 1232 1233 // do this last 1234 fDevManager->publishCanvas(fDeviceType, canvas, this); 1235} 1236 1237static float clipW = 200; 1238static float clipH = 200; 1239void SampleWindow::magnify(SkCanvas* canvas) { 1240 SkRect r; 1241 int count = canvas->save(); 1242 1243 SkMatrix m = canvas->getTotalMatrix(); 1244 if (!m.invert(&m)) { 1245 return; 1246 } 1247 SkPoint offset, center; 1248 SkScalar mouseX = fMouseX * SK_Scalar1; 1249 SkScalar mouseY = fMouseY * SK_Scalar1; 1250 m.mapXY(mouseX - clipW/2, mouseY - clipH/2, &offset); 1251 m.mapXY(mouseX, mouseY, ¢er); 1252 1253 r.set(0, 0, clipW * m.getScaleX(), clipH * m.getScaleX()); 1254 r.offset(offset.fX, offset.fY); 1255 1256 SkPaint paint; 1257 paint.setColor(0xFF66AAEE); 1258 paint.setStyle(SkPaint::kStroke_Style); 1259 paint.setStrokeWidth(10.f * m.getScaleX()); 1260 //lense offset 1261 //canvas->translate(0, -250); 1262 canvas->drawRect(r, paint); 1263 canvas->clipRect(r); 1264 1265 m = canvas->getTotalMatrix(); 1266 m.setTranslate(-center.fX, -center.fY); 1267 m.postScale(0.5f * fFatBitsScale, 0.5f * fFatBitsScale); 1268 m.postTranslate(center.fX, center.fY); 1269 canvas->concat(m); 1270 1271 this->INHERITED::draw(canvas); 1272 1273 canvas->restoreToCount(count); 1274} 1275 1276void SampleWindow::showZoomer(SkCanvas* canvas) { 1277 int count = canvas->save(); 1278 canvas->resetMatrix(); 1279 // Ensure the mouse position is on screen. 1280 int width = SkScalarRoundToInt(this->width()); 1281 int height = SkScalarRoundToInt(this->height()); 1282 if (fMouseX >= width) fMouseX = width - 1; 1283 else if (fMouseX < 0) fMouseX = 0; 1284 if (fMouseY >= height) fMouseY = height - 1; 1285 else if (fMouseY < 0) fMouseY = 0; 1286 1287 SkBitmap bitmap = capture_bitmap(canvas); 1288 bitmap.lockPixels(); 1289 1290 // Find the size of the zoomed in view, forced to be odd, so the examined pixel is in the middle. 1291 int zoomedWidth = (width >> 1) | 1; 1292 int zoomedHeight = (height >> 1) | 1; 1293 SkIRect src; 1294 src.set(0, 0, zoomedWidth / fFatBitsScale, zoomedHeight / fFatBitsScale); 1295 src.offset(fMouseX - (src.width()>>1), fMouseY - (src.height()>>1)); 1296 SkRect dest; 1297 dest.set(0, 0, SkIntToScalar(zoomedWidth), SkIntToScalar(zoomedHeight)); 1298 dest.offset(SkIntToScalar(width - zoomedWidth), SkIntToScalar(height - zoomedHeight)); 1299 SkPaint paint; 1300 // Clear the background behind our zoomed in view 1301 paint.setColor(SK_ColorWHITE); 1302 canvas->drawRect(dest, paint); 1303 canvas->drawBitmapRect(bitmap, &src, dest); 1304 paint.setColor(SK_ColorBLACK); 1305 paint.setStyle(SkPaint::kStroke_Style); 1306 // Draw a border around the pixel in the middle 1307 SkRect originalPixel; 1308 originalPixel.set(SkIntToScalar(fMouseX), SkIntToScalar(fMouseY), SkIntToScalar(fMouseX + 1), SkIntToScalar(fMouseY + 1)); 1309 SkMatrix matrix; 1310 SkRect scalarSrc; 1311 scalarSrc.set(src); 1312 SkColor color = bitmap.getColor(fMouseX, fMouseY); 1313 if (matrix.setRectToRect(scalarSrc, dest, SkMatrix::kFill_ScaleToFit)) { 1314 SkRect pixel; 1315 matrix.mapRect(&pixel, originalPixel); 1316 // TODO Perhaps measure the values and make the outline white if it's "dark" 1317 if (color == SK_ColorBLACK) { 1318 paint.setColor(SK_ColorWHITE); 1319 } 1320 canvas->drawRect(pixel, paint); 1321 } 1322 paint.setColor(SK_ColorBLACK); 1323 // Draw a border around the destination rectangle 1324 canvas->drawRect(dest, paint); 1325 paint.setStyle(SkPaint::kStrokeAndFill_Style); 1326 // Identify the pixel and its color on screen 1327 paint.setTypeface(fTypeface); 1328 paint.setAntiAlias(true); 1329 SkScalar lineHeight = paint.getFontMetrics(NULL); 1330 SkString string; 1331 string.appendf("(%i, %i)", fMouseX, fMouseY); 1332 SkScalar left = dest.fLeft + SkIntToScalar(3); 1333 SkScalar i = SK_Scalar1; 1334 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1335 // Alpha 1336 i += SK_Scalar1; 1337 string.reset(); 1338 string.appendf("A: %X", SkColorGetA(color)); 1339 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1340 // Red 1341 i += SK_Scalar1; 1342 string.reset(); 1343 string.appendf("R: %X", SkColorGetR(color)); 1344 paint.setColor(SK_ColorRED); 1345 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1346 // Green 1347 i += SK_Scalar1; 1348 string.reset(); 1349 string.appendf("G: %X", SkColorGetG(color)); 1350 paint.setColor(SK_ColorGREEN); 1351 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1352 // Blue 1353 i += SK_Scalar1; 1354 string.reset(); 1355 string.appendf("B: %X", SkColorGetB(color)); 1356 paint.setColor(SK_ColorBLUE); 1357 drawText(canvas, string, left, SkScalarMulAdd(lineHeight, i, dest.fTop), paint); 1358 canvas->restoreToCount(count); 1359} 1360 1361void SampleWindow::onDraw(SkCanvas* canvas) { 1362} 1363 1364#include "SkColorPriv.h" 1365 1366void SampleWindow::saveToPdf() 1367{ 1368 fSaveToPdf = true; 1369 this->inval(NULL); 1370} 1371 1372SkCanvas* SampleWindow::beforeChildren(SkCanvas* canvas) { 1373 if (fSaveToPdf) { 1374 const SkBitmap& bmp = canvas->getDevice()->accessBitmap(false); 1375 SkISize size = SkISize::Make(bmp.width(), bmp.height()); 1376 SkPDFDevice* pdfDevice = new SkPDFDevice(size, size, 1377 canvas->getTotalMatrix()); 1378 fPdfCanvas = new SkCanvas(pdfDevice); 1379 pdfDevice->unref(); 1380 canvas = fPdfCanvas; 1381 } else if (kPicture_DeviceType == fDeviceType) { 1382 fPicture = new SkPicture; 1383 canvas = fPicture->beginRecording(9999, 9999); 1384 } else { 1385#if SK_SUPPORT_GPU 1386 if (kNullGPU_DeviceType != fDeviceType) 1387#endif 1388 { 1389 canvas = this->INHERITED::beforeChildren(canvas); 1390 } 1391 } 1392 1393 if (fUseClip) { 1394 canvas->drawColor(0xFFFF88FF); 1395 canvas->clipPath(fClipPath, SkRegion::kIntersect_Op, true); 1396 } 1397 1398 return canvas; 1399} 1400 1401static void paint_rgn(const SkBitmap& bm, const SkIRect& r, 1402 const SkRegion& rgn) { 1403 SkCanvas canvas(bm); 1404 SkRegion inval(rgn); 1405 1406 inval.translate(r.fLeft, r.fTop); 1407 canvas.clipRegion(inval); 1408 canvas.drawColor(0xFFFF8080); 1409} 1410#include "SkData.h" 1411void SampleWindow::afterChildren(SkCanvas* orig) { 1412 if (fSaveToPdf) { 1413 fSaveToPdf = false; 1414 if (fShowZoomer) { 1415 showZoomer(fPdfCanvas); 1416 } 1417 SkString name; 1418 name.printf("%s.pdf", this->getTitle()); 1419 SkPDFDocument doc; 1420 SkPDFDevice* device = static_cast<SkPDFDevice*>(fPdfCanvas->getDevice()); 1421 doc.appendPage(device); 1422#ifdef SK_BUILD_FOR_ANDROID 1423 name.prepend("/sdcard/"); 1424#endif 1425 1426#ifdef SK_BUILD_FOR_IOS 1427 SkDynamicMemoryWStream mstream; 1428 doc.emitPDF(&mstream); 1429 fPDFData = mstream.copyToData(); 1430#endif 1431 SkFILEWStream stream(name.c_str()); 1432 if (stream.isValid()) { 1433 doc.emitPDF(&stream); 1434 const char* desc = "File saved from Skia SampleApp"; 1435 this->onPDFSaved(this->getTitle(), desc, name.c_str()); 1436 } 1437 1438 delete fPdfCanvas; 1439 fPdfCanvas = NULL; 1440 1441 // We took over the draw calls in order to create the PDF, so we need 1442 // to redraw. 1443 this->inval(NULL); 1444 return; 1445 } 1446 1447 if (fRequestGrabImage) { 1448 fRequestGrabImage = false; 1449 1450 SkBaseDevice* device = orig->getDevice(); 1451 SkBitmap bmp; 1452 if (device->accessBitmap(false).copyTo(&bmp, kN32_SkColorType)) { 1453 static int gSampleGrabCounter; 1454 SkString name; 1455 name.printf("sample_grab_%d.png", gSampleGrabCounter++); 1456 SkImageEncoder::EncodeFile(name.c_str(), bmp, 1457 SkImageEncoder::kPNG_Type, 100); 1458 } 1459 } 1460 1461 if (kPicture_DeviceType == fDeviceType) { 1462 if (true) { 1463 SkPicture* pict = new SkPicture(*fPicture); 1464 fPicture->unref(); 1465 this->installDrawFilter(orig); 1466 orig->drawPicture(*pict); 1467 pict->unref(); 1468 } else if (true) { 1469 SkDynamicMemoryWStream ostream; 1470 fPicture->serialize(&ostream); 1471 fPicture->unref(); 1472 1473 SkAutoDataUnref data(ostream.copyToData()); 1474 SkMemoryStream istream(data->data(), data->size()); 1475 SkAutoTUnref<SkPicture> pict(SkPicture::CreateFromStream(&istream)); 1476 if (pict.get() != NULL) { 1477 orig->drawPicture(*pict.get()); 1478 } 1479 } else { 1480 fPicture->draw(orig); 1481 fPicture->unref(); 1482 } 1483 fPicture = NULL; 1484 } 1485 1486 // Do this after presentGL and other finishing, rather than in afterChild 1487 if (fMeasureFPS && fMeasureFPS_StartTime) { 1488 fMeasureFPS_Time += SkTime::GetMSecs() - fMeasureFPS_StartTime; 1489 } 1490 1491 // if ((fScrollTestX | fScrollTestY) != 0) 1492 if (false) { 1493 const SkBitmap& bm = orig->getDevice()->accessBitmap(true); 1494 int dx = fScrollTestX * 7; 1495 int dy = fScrollTestY * 7; 1496 SkIRect r; 1497 SkRegion inval; 1498 1499 r.set(50, 50, 50+100, 50+100); 1500 bm.scrollRect(&r, dx, dy, &inval); 1501 paint_rgn(bm, r, inval); 1502 } 1503} 1504 1505void SampleWindow::beforeChild(SkView* child, SkCanvas* canvas) { 1506 if (fRotate) { 1507 fRotateAnimTime += SampleCode::GetAnimSecondsDelta(); 1508 1509 SkScalar cx = this->width() / 2; 1510 SkScalar cy = this->height() / 2; 1511 canvas->translate(cx, cy); 1512 canvas->rotate(fRotateAnimTime * 10); 1513 canvas->translate(-cx, -cy); 1514 } 1515 1516 if (fPerspAnim) { 1517 fPerspAnimTime += SampleCode::GetAnimSecondsDelta(); 1518 1519 static const SkScalar gAnimPeriod = 10 * SK_Scalar1; 1520 static const SkScalar gAnimMag = SK_Scalar1 / 1000; 1521 SkScalar t = SkScalarMod(fPerspAnimTime, gAnimPeriod); 1522 if (SkScalarFloorToInt(SkScalarDiv(fPerspAnimTime, gAnimPeriod)) & 0x1) { 1523 t = gAnimPeriod - t; 1524 } 1525 t = 2 * t - gAnimPeriod; 1526 t = SkScalarMul(SkScalarDiv(t, gAnimPeriod), gAnimMag); 1527 SkMatrix m; 1528 m.reset(); 1529 m.setPerspY(t); 1530 canvas->concat(m); 1531 } 1532 1533 this->installDrawFilter(canvas); 1534 1535 if (fMeasureFPS) { 1536 if (SampleView::SetRepeatDraw(child, FPS_REPEAT_COUNT)) { 1537 fMeasureFPS_StartTime = SkTime::GetMSecs(); 1538 } 1539 } else { 1540 (void)SampleView::SetRepeatDraw(child, 1); 1541 } 1542 if (fPerspAnim || fRotate) { 1543 this->inval(NULL); 1544 } 1545} 1546 1547void SampleWindow::afterChild(SkView* child, SkCanvas* canvas) { 1548 canvas->setDrawFilter(NULL); 1549} 1550 1551static SkColorType gColorTypeCycle[] = { 1552 kUnknown_SkColorType, // none -> none 1553 kUnknown_SkColorType, // a8 -> none 1554 kARGB_4444_SkColorType, // 565 -> 4444 1555 kN32_SkColorType, // 4444 -> 8888 1556 kRGB_565_SkColorType, // 8888 -> 565 1557 kRGB_565_SkColorType, // 8888 -> 565 1558 kUnknown_SkColorType, // index8 -> none 1559}; 1560 1561static SkColorType cycle_colortypes(SkColorType c) { 1562 return gColorTypeCycle[c]; 1563} 1564 1565void SampleWindow::changeZoomLevel(float delta) { 1566 fZoomLevel += delta; 1567 if (fZoomLevel > 0) { 1568 fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL); 1569 fZoomScale = fZoomLevel + SK_Scalar1; 1570 } else if (fZoomLevel < 0) { 1571 fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL); 1572 fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel); 1573 } else { 1574 fZoomScale = SK_Scalar1; 1575 } 1576 this->updateMatrix(); 1577} 1578 1579void SampleWindow::updateMatrix(){ 1580 SkMatrix m; 1581 m.reset(); 1582 if (fZoomLevel) { 1583 SkPoint center; 1584 //m = this->getLocalMatrix();//.invert(&m); 1585 m.mapXY(fZoomCenterX, fZoomCenterY, ¢er); 1586 SkScalar cx = center.fX; 1587 SkScalar cy = center.fY; 1588 1589 m.setTranslate(-cx, -cy); 1590 m.postScale(fZoomScale, fZoomScale); 1591 m.postTranslate(cx, cy); 1592 } 1593 1594 if (fFlipAxis) { 1595 m.preTranslate(fZoomCenterX, fZoomCenterY); 1596 if (fFlipAxis & kFlipAxis_X) { 1597 m.preScale(-SK_Scalar1, SK_Scalar1); 1598 } 1599 if (fFlipAxis & kFlipAxis_Y) { 1600 m.preScale(SK_Scalar1, -SK_Scalar1); 1601 } 1602 m.preTranslate(-fZoomCenterX, -fZoomCenterY); 1603 //canvas->concat(m); 1604 } 1605 // Apply any gesture matrix 1606 m.preConcat(fGesture.localM()); 1607 m.preConcat(fGesture.globalM()); 1608 1609 this->setLocalMatrix(m); 1610 1611 this->updateTitle(); 1612 this->inval(NULL); 1613} 1614bool SampleWindow::previousSample() { 1615 fCurrIndex = (fCurrIndex - 1 + fSamples.count()) % fSamples.count(); 1616 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(), 1617 fTransitionPrev)); 1618 return true; 1619} 1620 1621bool SampleWindow::nextSample() { 1622 fCurrIndex = (fCurrIndex + 1) % fSamples.count(); 1623 this->loadView(create_transition(curr_view(this), (*fSamples[fCurrIndex])(), 1624 fTransitionNext)); 1625 return true; 1626} 1627 1628bool SampleWindow::goToSample(int i) { 1629 fCurrIndex = (i) % fSamples.count(); 1630 this->loadView(create_transition(curr_view(this),(*fSamples[fCurrIndex])(), 6)); 1631 return true; 1632} 1633 1634SkString SampleWindow::getSampleTitle(int i) { 1635 return ::getSampleTitle(fSamples[i]); 1636} 1637 1638int SampleWindow::sampleCount() { 1639 return fSamples.count(); 1640} 1641 1642void SampleWindow::showOverview() { 1643 this->loadView(create_transition(curr_view(this), 1644 create_overview(fSamples.count(), fSamples.begin()), 1645 4)); 1646} 1647 1648void SampleWindow::installDrawFilter(SkCanvas* canvas) { 1649 canvas->setDrawFilter(new FlagsDrawFilter(fLCDState, fAAState, fSubpixelState, 1650 fHintingState, fFilterLevelIndex))->unref(); 1651} 1652 1653void SampleWindow::postAnimatingEvent() { 1654 if (fAnimating) { 1655 (new SkEvent(ANIMATING_EVENTTYPE, this->getSinkID()))->postDelay(ANIMATING_DELAY); 1656 } 1657} 1658 1659bool SampleWindow::onEvent(const SkEvent& evt) { 1660 if (evt.isType(gUpdateWindowTitleEvtName)) { 1661 this->updateTitle(); 1662 return true; 1663 } 1664 if (evt.isType(ANIMATING_EVENTTYPE)) { 1665 if (fAnimating) { 1666 this->nextSample(); 1667 this->postAnimatingEvent(); 1668 } 1669 return true; 1670 } 1671 if (evt.isType("replace-transition-view")) { 1672 this->loadView((SkView*)SkEventSink::FindSink(evt.getFast32())); 1673 return true; 1674 } 1675 if (evt.isType("set-curr-index")) { 1676 this->goToSample(evt.getFast32()); 1677 return true; 1678 } 1679 if (isInvalEvent(evt)) { 1680 this->inval(NULL); 1681 return true; 1682 } 1683 int selected = -1; 1684 if (SkOSMenu::FindListIndex(evt, "Device Type", &selected)) { 1685 this->setDeviceType((DeviceType)selected); 1686 return true; 1687 } 1688 if (SkOSMenu::FindTriState(evt, "Pipe", &fPipeState)) { 1689#ifdef PIPE_NET 1690 if (!fPipeState != SkOSMenu::kOnState) 1691 gServer.disconnectAll(); 1692#endif 1693 (void)SampleView::SetUsePipe(curr_view(this), fPipeState); 1694 this->updateTitle(); 1695 this->inval(NULL); 1696 return true; 1697 } 1698 if (SkOSMenu::FindSwitchState(evt, "Slide Show", NULL)) { 1699 this->toggleSlideshow(); 1700 return true; 1701 } 1702 if (SkOSMenu::FindTriState(evt, "AA", &fAAState) || 1703 SkOSMenu::FindTriState(evt, "LCD", &fLCDState) || 1704 SkOSMenu::FindListIndex(evt, "FilterLevel", &fFilterLevelIndex) || 1705 SkOSMenu::FindTriState(evt, "Subpixel", &fSubpixelState) || 1706 SkOSMenu::FindListIndex(evt, "Hinting", &fHintingState) || 1707 SkOSMenu::FindSwitchState(evt, "Clip", &fUseClip) || 1708 SkOSMenu::FindSwitchState(evt, "Zoomer", &fShowZoomer) || 1709 SkOSMenu::FindSwitchState(evt, "Magnify", &fMagnify) || 1710 SkOSMenu::FindListIndex(evt, "Transition-Next", &fTransitionNext) || 1711 SkOSMenu::FindListIndex(evt, "Transition-Prev", &fTransitionPrev)) { 1712 this->inval(NULL); 1713 this->updateTitle(); 1714 return true; 1715 } 1716 if (SkOSMenu::FindListIndex(evt, "Tiling", &fTilingMode)) { 1717 if (SampleView::IsSampleView(curr_view(this))) { 1718 ((SampleView*)curr_view(this))->onTileSizeChanged(this->tileSize()); 1719 } 1720 this->inval(NULL); 1721 this->updateTitle(); 1722 return true; 1723 } 1724 if (SkOSMenu::FindSwitchState(evt, "Flip X", NULL)) { 1725 fFlipAxis ^= kFlipAxis_X; 1726 this->updateMatrix(); 1727 return true; 1728 } 1729 if (SkOSMenu::FindSwitchState(evt, "Flip Y", NULL)) { 1730 fFlipAxis ^= kFlipAxis_Y; 1731 this->updateMatrix(); 1732 return true; 1733 } 1734 if (SkOSMenu::FindAction(evt,"Save to PDF")) { 1735 this->saveToPdf(); 1736 return true; 1737 } 1738 return this->INHERITED::onEvent(evt); 1739} 1740 1741bool SampleWindow::onQuery(SkEvent* query) { 1742 if (query->isType("get-slide-count")) { 1743 query->setFast32(fSamples.count()); 1744 return true; 1745 } 1746 if (query->isType("get-slide-title")) { 1747 SkView* view = (*fSamples[query->getFast32()])(); 1748 SkEvent evt(gTitleEvtName); 1749 if (view->doQuery(&evt)) { 1750 query->setString("title", evt.findString(gTitleEvtName)); 1751 } 1752 SkSafeUnref(view); 1753 return true; 1754 } 1755 if (query->isType("use-fast-text")) { 1756 SkEvent evt(gFastTextEvtName); 1757 return curr_view(this)->doQuery(&evt); 1758 } 1759 if (query->isType("ignore-window-bitmap")) { 1760 query->setFast32(this->getGrContext() != NULL); 1761 return true; 1762 } 1763 return this->INHERITED::onQuery(query); 1764} 1765 1766#if 0 // UNUSED 1767static void cleanup_for_filename(SkString* name) { 1768 char* str = name->writable_str(); 1769 for (size_t i = 0; i < name->size(); i++) { 1770 switch (str[i]) { 1771 case ':': str[i] = '-'; break; 1772 case '/': str[i] = '-'; break; 1773 case ' ': str[i] = '_'; break; 1774 default: break; 1775 } 1776 } 1777} 1778#endif 1779 1780bool SampleWindow::onHandleChar(SkUnichar uni) { 1781 { 1782 SkView* view = curr_view(this); 1783 if (view) { 1784 SkEvent evt(gCharEvtName); 1785 evt.setFast32(uni); 1786 if (view->doQuery(&evt)) { 1787 return true; 1788 } 1789 } 1790 } 1791 1792 int dx = 0xFF; 1793 int dy = 0xFF; 1794 1795 switch (uni) { 1796 case '5': dx = 0; dy = 0; break; 1797 case '8': dx = 0; dy = -1; break; 1798 case '6': dx = 1; dy = 0; break; 1799 case '2': dx = 0; dy = 1; break; 1800 case '4': dx = -1; dy = 0; break; 1801 case '7': dx = -1; dy = -1; break; 1802 case '9': dx = 1; dy = -1; break; 1803 case '3': dx = 1; dy = 1; break; 1804 case '1': dx = -1; dy = 1; break; 1805 1806 default: 1807 break; 1808 } 1809 1810 if (0xFF != dx && 0xFF != dy) { 1811 if ((dx | dy) == 0) { 1812 fScrollTestX = fScrollTestY = 0; 1813 } else { 1814 fScrollTestX += dx; 1815 fScrollTestY += dy; 1816 } 1817 this->inval(NULL); 1818 return true; 1819 } 1820 1821 switch (uni) { 1822 case 'B': 1823 post_event_to_sink(SkNEW_ARGS(SkEvent, ("PictFileView::toggleBBox")), curr_view(this)); 1824 // Cannot call updateTitle() synchronously, because the toggleBBox event is still in 1825 // the queue. 1826 post_event_to_sink(SkNEW_ARGS(SkEvent, (gUpdateWindowTitleEvtName)), this); 1827 this->inval(NULL); 1828 break; 1829 case 'f': 1830 // only 1831 toggleFPS(); 1832 break; 1833 case 'g': 1834 fRequestGrabImage = true; 1835 this->inval(NULL); 1836 break; 1837 case 'G': 1838 gShowGMBounds = !gShowGMBounds; 1839 post_event_to_sink(GMSampleView::NewShowSizeEvt(gShowGMBounds), 1840 curr_view(this)); 1841 this->inval(NULL); 1842 break; 1843 case 'i': 1844 this->zoomIn(); 1845 break; 1846 case 'o': 1847 this->zoomOut(); 1848 break; 1849 case 'r': 1850 fRotate = !fRotate; 1851 fRotateAnimTime = 0; 1852 this->inval(NULL); 1853 this->updateTitle(); 1854 return true; 1855 case 'k': 1856 fPerspAnim = !fPerspAnim; 1857 this->inval(NULL); 1858 this->updateTitle(); 1859 return true; 1860#if SK_SUPPORT_GPU 1861 case '\\': 1862 this->setDeviceType(kNullGPU_DeviceType); 1863 this->inval(NULL); 1864 this->updateTitle(); 1865 return true; 1866 case 'p': 1867 { 1868 GrContext* grContext = this->getGrContext(); 1869 if (grContext) { 1870 size_t cacheBytes = grContext->getGpuTextureCacheBytes(); 1871 grContext->freeGpuResources(); 1872 SkDebugf("Purged %d bytes from the GPU resource cache.\n", 1873 cacheBytes); 1874 } 1875 } 1876 return true; 1877#endif 1878 default: 1879 break; 1880 } 1881 1882 if (fAppMenu->handleKeyEquivalent(uni)|| fSlideMenu->handleKeyEquivalent(uni)) { 1883 this->onUpdateMenu(fAppMenu); 1884 this->onUpdateMenu(fSlideMenu); 1885 return true; 1886 } 1887 return this->INHERITED::onHandleChar(uni); 1888} 1889 1890void SampleWindow::setDeviceType(DeviceType type) { 1891 if (type == fDeviceType) 1892 return; 1893 1894 fDevManager->tearDownBackend(this); 1895 1896 fDeviceType = type; 1897 1898 fDevManager->setUpBackend(this, fMSAASampleCount); 1899 1900 this->updateTitle(); 1901 this->inval(NULL); 1902} 1903 1904void SampleWindow::toggleSlideshow() { 1905 fAnimating = !fAnimating; 1906 this->postAnimatingEvent(); 1907 this->updateTitle(); 1908} 1909 1910void SampleWindow::toggleRendering() { 1911 this->setDeviceType(cycle_devicetype(fDeviceType)); 1912 this->updateTitle(); 1913 this->inval(NULL); 1914} 1915 1916void SampleWindow::toggleFPS() { 1917 fMeasureFPS = !fMeasureFPS; 1918 this->updateTitle(); 1919 this->inval(NULL); 1920} 1921 1922#include "SkDumpCanvas.h" 1923 1924bool SampleWindow::onHandleKey(SkKey key) { 1925 { 1926 SkView* view = curr_view(this); 1927 if (view) { 1928 SkEvent evt(gKeyEvtName); 1929 evt.setFast32(key); 1930 if (view->doQuery(&evt)) { 1931 return true; 1932 } 1933 } 1934 } 1935 switch (key) { 1936 case kRight_SkKey: 1937 if (this->nextSample()) { 1938 return true; 1939 } 1940 break; 1941 case kLeft_SkKey: 1942 if (this->previousSample()) { 1943 return true; 1944 } 1945 return true; 1946 case kUp_SkKey: 1947 if (USE_ARROWS_FOR_ZOOM) { 1948 this->changeZoomLevel(1.f / 32.f); 1949 } else { 1950 fNClip = !fNClip; 1951 this->inval(NULL); 1952 this->updateTitle(); 1953 } 1954 return true; 1955 case kDown_SkKey: 1956 if (USE_ARROWS_FOR_ZOOM) { 1957 this->changeZoomLevel(-1.f / 32.f); 1958 } else { 1959 this->setColorType(cycle_colortypes(this->getBitmap().colorType())); 1960 this->updateTitle(); 1961 } 1962 return true; 1963 case kOK_SkKey: { 1964 SkString title; 1965 if (curr_title(this, &title)) { 1966 writeTitleToPrefs(title.c_str()); 1967 } 1968 return true; 1969 } 1970 case kBack_SkKey: 1971 this->showOverview(); 1972 return true; 1973 default: 1974 break; 1975 } 1976 return this->INHERITED::onHandleKey(key); 1977} 1978 1979/////////////////////////////////////////////////////////////////////////////// 1980 1981static const char gGestureClickType[] = "GestureClickType"; 1982 1983bool SampleWindow::onDispatchClick(int x, int y, Click::State state, 1984 void* owner, unsigned modi) { 1985 if (Click::kMoved_State == state) { 1986 updatePointer(x, y); 1987 } 1988 int w = SkScalarRoundToInt(this->width()); 1989 int h = SkScalarRoundToInt(this->height()); 1990 1991 // check for the resize-box 1992 if (w - x < 16 && h - y < 16) { 1993 return false; // let the OS handle the click 1994 } 1995 else if (fMagnify) { 1996 //it's only necessary to update the drawing if there's a click 1997 this->inval(NULL); 1998 return false; //prevent dragging while magnify is enabled 1999 } else { 2000 // capture control+option, and trigger debugger 2001 if ((modi & kControl_SkModifierKey) && (modi & kOption_SkModifierKey)) { 2002 if (Click::kDown_State == state) { 2003 SkEvent evt("debug-hit-test"); 2004 evt.setS32("debug-hit-test-x", x); 2005 evt.setS32("debug-hit-test-y", y); 2006 curr_view(this)->doEvent(evt); 2007 } 2008 return true; 2009 } else { 2010 return this->INHERITED::onDispatchClick(x, y, state, owner, modi); 2011 } 2012 } 2013} 2014 2015class GestureClick : public SkView::Click { 2016public: 2017 GestureClick(SkView* target) : SkView::Click(target) { 2018 this->setType(gGestureClickType); 2019 } 2020 2021 static bool IsGesture(Click* click) { 2022 return click->isType(gGestureClickType); 2023 } 2024}; 2025 2026SkView::Click* SampleWindow::onFindClickHandler(SkScalar x, SkScalar y, 2027 unsigned modi) { 2028 return new GestureClick(this); 2029} 2030 2031bool SampleWindow::onClick(Click* click) { 2032 if (GestureClick::IsGesture(click)) { 2033 float x = static_cast<float>(click->fICurr.fX); 2034 float y = static_cast<float>(click->fICurr.fY); 2035 2036 switch (click->fState) { 2037 case SkView::Click::kDown_State: 2038 fGesture.touchBegin(click->fOwner, x, y); 2039 break; 2040 case SkView::Click::kMoved_State: 2041 fGesture.touchMoved(click->fOwner, x, y); 2042 this->updateMatrix(); 2043 break; 2044 case SkView::Click::kUp_State: 2045 fGesture.touchEnd(click->fOwner); 2046 this->updateMatrix(); 2047 break; 2048 } 2049 return true; 2050 } 2051 return false; 2052} 2053 2054/////////////////////////////////////////////////////////////////////////////// 2055 2056void SampleWindow::loadView(SkView* view) { 2057 SkView::F2BIter iter(this); 2058 SkView* prev = iter.next(); 2059 if (prev) { 2060 prev->detachFromParent(); 2061 } 2062 2063 view->setVisibleP(true); 2064 view->setClipToBounds(false); 2065 this->attachChildToFront(view)->unref(); 2066 view->setSize(this->width(), this->height()); 2067 2068 //repopulate the slide menu when a view is loaded 2069 fSlideMenu->reset(); 2070 2071 (void)SampleView::SetUsePipe(view, fPipeState); 2072 if (SampleView::IsSampleView(view)) { 2073 SampleView* sampleView = (SampleView*)view; 2074 sampleView->requestMenu(fSlideMenu); 2075 sampleView->onTileSizeChanged(this->tileSize()); 2076 } 2077 this->onUpdateMenu(fSlideMenu); 2078 this->updateTitle(); 2079} 2080 2081static const char* gConfigNames[] = { 2082 "unknown config", 2083 "A8", 2084 "Index8", 2085 "565", 2086 "4444", 2087 "8888" 2088}; 2089 2090static const char* configToString(SkBitmap::Config c) { 2091 return gConfigNames[c]; 2092} 2093 2094static const char* gDeviceTypePrefix[] = { 2095 "raster: ", 2096 "picture: ", 2097#if SK_SUPPORT_GPU 2098 "opengl: ", 2099#if SK_ANGLE 2100 "angle: ", 2101#endif // SK_ANGLE 2102 "null-gl: " 2103#endif // SK_SUPPORT_GPU 2104}; 2105SK_COMPILE_ASSERT(SK_ARRAY_COUNT(gDeviceTypePrefix) == SampleWindow::kDeviceTypeCnt, 2106 array_size_mismatch); 2107 2108static const char* trystate_str(SkOSMenu::TriState state, 2109 const char trueStr[], const char falseStr[]) { 2110 if (SkOSMenu::kOnState == state) { 2111 return trueStr; 2112 } else if (SkOSMenu::kOffState == state) { 2113 return falseStr; 2114 } 2115 return NULL; 2116} 2117 2118void SampleWindow::updateTitle() { 2119 SkView* view = curr_view(this); 2120 2121 SkString title; 2122 if (!curr_title(this, &title)) { 2123 title.set("<unknown>"); 2124 } 2125 2126 title.prepend(gDeviceTypePrefix[fDeviceType]); 2127 2128 title.prepend(" "); 2129 title.prepend(configToString(this->getBitmap().config())); 2130 2131 if (fTilingMode != kNo_Tiling) { 2132 title.prependf("<T: %s> ", gTilingInfo[fTilingMode].label); 2133 } 2134 if (fAnimating) { 2135 title.prepend("<A> "); 2136 } 2137 if (fRotate) { 2138 title.prepend("<R> "); 2139 } 2140 if (fNClip) { 2141 title.prepend("<C> "); 2142 } 2143 if (fPerspAnim) { 2144 title.prepend("<K> "); 2145 } 2146 2147 title.prepend(trystate_str(fLCDState, "LCD ", "lcd ")); 2148 title.prepend(trystate_str(fAAState, "AA ", "aa ")); 2149 title.prepend(gFilterLevelStates[fFilterLevelIndex].fLabel); 2150 title.prepend(trystate_str(fSubpixelState, "S ", "s ")); 2151 title.prepend(fFlipAxis & kFlipAxis_X ? "X " : NULL); 2152 title.prepend(fFlipAxis & kFlipAxis_Y ? "Y " : NULL); 2153 title.prepend(gHintingStates[fHintingState].label); 2154 2155 if (fZoomLevel) { 2156 title.prependf("{%.2f} ", SkScalarToFloat(fZoomLevel)); 2157 } 2158 2159 if (fMeasureFPS) { 2160 title.appendf(" %8.3f ms", fMeasureFPS_Time / (float)FPS_REPEAT_COUNT); 2161 } 2162 if (SampleView::IsSampleView(view)) { 2163 switch (fPipeState) { 2164 case SkOSMenu::kOnState: 2165 title.prepend("<Pipe> "); 2166 break; 2167 case SkOSMenu::kMixedState: 2168 title.prepend("<Tiled Pipe> "); 2169 break; 2170 2171 default: 2172 break; 2173 } 2174 title.prepend("! "); 2175 } 2176 2177#if SK_SUPPORT_GPU 2178 if (IsGpuDeviceType(fDeviceType) && 2179 NULL != fDevManager && 2180 fDevManager->getGrRenderTarget() && 2181 fDevManager->getGrRenderTarget()->numSamples() > 0) { 2182 title.appendf(" [MSAA: %d]", 2183 fDevManager->getGrRenderTarget()->numSamples()); 2184 } 2185#endif 2186 2187 this->setTitle(title.c_str()); 2188} 2189 2190void SampleWindow::onSizeChange() { 2191 this->INHERITED::onSizeChange(); 2192 2193 SkView::F2BIter iter(this); 2194 SkView* view = iter.next(); 2195 view->setSize(this->width(), this->height()); 2196 2197 // rebuild our clippath 2198 { 2199 const SkScalar W = this->width(); 2200 const SkScalar H = this->height(); 2201 2202 fClipPath.reset(); 2203#if 0 2204 for (SkScalar y = SK_Scalar1; y < H; y += SkIntToScalar(32)) { 2205 SkRect r; 2206 r.set(SK_Scalar1, y, SkIntToScalar(30), y + SkIntToScalar(30)); 2207 for (; r.fLeft < W; r.offset(SkIntToScalar(32), 0)) 2208 fClipPath.addRect(r); 2209 } 2210#else 2211 SkRect r; 2212 r.set(0, 0, W, H); 2213 fClipPath.addRect(r, SkPath::kCCW_Direction); 2214 r.set(W/4, H/4, W*3/4, H*3/4); 2215 fClipPath.addRect(r, SkPath::kCW_Direction); 2216#endif 2217 } 2218 2219 fZoomCenterX = SkScalarHalf(this->width()); 2220 fZoomCenterY = SkScalarHalf(this->height()); 2221 2222#ifdef SK_BUILD_FOR_ANDROID 2223 // FIXME: The first draw after a size change does not work on Android, so 2224 // we post an invalidate. 2225 this->postInvalDelay(); 2226#endif 2227 this->updateTitle(); // to refresh our config 2228 fDevManager->windowSizeChanged(this); 2229 2230 if (fTilingMode != kNo_Tiling && SampleView::IsSampleView(view)) { 2231 ((SampleView*)view)->onTileSizeChanged(this->tileSize()); 2232 } 2233} 2234 2235/////////////////////////////////////////////////////////////////////////////// 2236 2237static const char is_sample_view_tag[] = "sample-is-sample-view"; 2238static const char repeat_count_tag[] = "sample-set-repeat-count"; 2239static const char set_use_pipe_tag[] = "sample-set-use-pipe"; 2240 2241bool SampleView::IsSampleView(SkView* view) { 2242 SkEvent evt(is_sample_view_tag); 2243 return view->doQuery(&evt); 2244} 2245 2246bool SampleView::SetRepeatDraw(SkView* view, int count) { 2247 SkEvent evt(repeat_count_tag); 2248 evt.setFast32(count); 2249 return view->doEvent(evt); 2250} 2251 2252bool SampleView::SetUsePipe(SkView* view, SkOSMenu::TriState state) { 2253 SkEvent evt; 2254 evt.setS32(set_use_pipe_tag, state); 2255 return view->doEvent(evt); 2256} 2257 2258bool SampleView::onEvent(const SkEvent& evt) { 2259 if (evt.isType(repeat_count_tag)) { 2260 fRepeatCount = evt.getFast32(); 2261 return true; 2262 } 2263 2264 int32_t pipeHolder; 2265 if (evt.findS32(set_use_pipe_tag, &pipeHolder)) { 2266 fPipeState = static_cast<SkOSMenu::TriState>(pipeHolder); 2267 return true; 2268 } 2269 2270 if (evt.isType("debug-hit-test")) { 2271 fDebugHitTest = true; 2272 evt.findS32("debug-hit-test-x", &fDebugHitTestLoc.fX); 2273 evt.findS32("debug-hit-test-y", &fDebugHitTestLoc.fY); 2274 this->inval(NULL); 2275 return true; 2276 } 2277 2278 return this->INHERITED::onEvent(evt); 2279} 2280 2281bool SampleView::onQuery(SkEvent* evt) { 2282 if (evt->isType(is_sample_view_tag)) { 2283 return true; 2284 } 2285 return this->INHERITED::onQuery(evt); 2286} 2287 2288 2289class SimplePC : public SkGPipeController { 2290public: 2291 SimplePC(SkCanvas* target); 2292 ~SimplePC(); 2293 2294 virtual void* requestBlock(size_t minRequest, size_t* actual); 2295 virtual void notifyWritten(size_t bytes); 2296 2297private: 2298 SkGPipeReader fReader; 2299 void* fBlock; 2300 size_t fBlockSize; 2301 size_t fBytesWritten; 2302 int fAtomsWritten; 2303 SkGPipeReader::Status fStatus; 2304 2305 size_t fTotalWritten; 2306}; 2307 2308SimplePC::SimplePC(SkCanvas* target) : fReader(target) { 2309 fBlock = NULL; 2310 fBlockSize = fBytesWritten = 0; 2311 fStatus = SkGPipeReader::kDone_Status; 2312 fTotalWritten = 0; 2313 fAtomsWritten = 0; 2314 fReader.setBitmapDecoder(&SkImageDecoder::DecodeMemory); 2315} 2316 2317SimplePC::~SimplePC() { 2318// SkASSERT(SkGPipeReader::kDone_Status == fStatus); 2319 if (fTotalWritten) { 2320 SkDebugf("--- %d bytes %d atoms, status %d\n", fTotalWritten, 2321 fAtomsWritten, fStatus); 2322#ifdef PIPE_FILE 2323 //File is open in append mode 2324 FILE* f = fopen(FILE_PATH, "ab"); 2325 SkASSERT(f != NULL); 2326 fwrite((const char*)fBlock + fBytesWritten, 1, bytes, f); 2327 fclose(f); 2328#endif 2329#ifdef PIPE_NET 2330 if (fAtomsWritten > 1 && fTotalWritten > 4) { //ignore done 2331 gServer.acceptConnections(); 2332 gServer.writePacket(fBlock, fTotalWritten); 2333 } 2334#endif 2335 } 2336 sk_free(fBlock); 2337} 2338 2339void* SimplePC::requestBlock(size_t minRequest, size_t* actual) { 2340 sk_free(fBlock); 2341 2342 fBlockSize = minRequest * 4; 2343 fBlock = sk_malloc_throw(fBlockSize); 2344 fBytesWritten = 0; 2345 *actual = fBlockSize; 2346 return fBlock; 2347} 2348 2349void SimplePC::notifyWritten(size_t bytes) { 2350 SkASSERT(fBytesWritten + bytes <= fBlockSize); 2351 fStatus = fReader.playback((const char*)fBlock + fBytesWritten, bytes); 2352 SkASSERT(SkGPipeReader::kError_Status != fStatus); 2353 fBytesWritten += bytes; 2354 fTotalWritten += bytes; 2355 2356 fAtomsWritten += 1; 2357} 2358 2359void SampleView::draw(SkCanvas* canvas) { 2360 if (SkOSMenu::kOffState == fPipeState) { 2361 this->INHERITED::draw(canvas); 2362 } else { 2363 SkGPipeWriter writer; 2364 SimplePC controller(canvas); 2365 TiledPipeController tc(canvas->getDevice()->accessBitmap(false), 2366 &SkImageDecoder::DecodeMemory, 2367 &canvas->getTotalMatrix()); 2368 SkGPipeController* pc; 2369 if (SkOSMenu::kMixedState == fPipeState) { 2370 pc = &tc; 2371 } else { 2372 pc = &controller; 2373 } 2374 uint32_t flags = SkGPipeWriter::kCrossProcess_Flag; 2375 2376 canvas = writer.startRecording(pc, flags); 2377 //Must draw before controller goes out of scope and sends data 2378 this->INHERITED::draw(canvas); 2379 //explicitly end recording to ensure writer is flushed before the memory 2380 //is freed in the deconstructor of the controller 2381 writer.endRecording(); 2382 } 2383} 2384 2385#include "SkBounder.h" 2386 2387class DebugHitTestBounder : public SkBounder { 2388public: 2389 DebugHitTestBounder(int x, int y) { 2390 fLoc.set(x, y); 2391 } 2392 2393 virtual bool onIRect(const SkIRect& bounds) SK_OVERRIDE { 2394 if (bounds.contains(fLoc.x(), fLoc.y())) { 2395 // 2396 // Set a break-point here to see what was being drawn under 2397 // the click point (just needed a line of code to stop the debugger) 2398 // 2399 bounds.centerX(); 2400 } 2401 return true; 2402 } 2403 2404private: 2405 SkIPoint fLoc; 2406 typedef SkBounder INHERITED; 2407}; 2408 2409void SampleView::onDraw(SkCanvas* canvas) { 2410 this->onDrawBackground(canvas); 2411 2412 DebugHitTestBounder bounder(fDebugHitTestLoc.x(), fDebugHitTestLoc.y()); 2413 if (fDebugHitTest) { 2414 canvas->setBounder(&bounder); 2415 } 2416 2417 for (int i = 0; i < fRepeatCount; i++) { 2418 SkAutoCanvasRestore acr(canvas, true); 2419 this->onDrawContent(canvas); 2420 } 2421 2422 fDebugHitTest = false; 2423 canvas->setBounder(NULL); 2424} 2425 2426void SampleView::onDrawBackground(SkCanvas* canvas) { 2427 canvas->drawColor(fBGColor); 2428} 2429 2430/////////////////////////////////////////////////////////////////////////////// 2431 2432template <typename T> void SkTBSort(T array[], int count) { 2433 for (int i = 1; i < count - 1; i++) { 2434 bool didSwap = false; 2435 for (int j = count - 1; j > i; --j) { 2436 if (array[j] < array[j-1]) { 2437 T tmp(array[j-1]); 2438 array[j-1] = array[j]; 2439 array[j] = tmp; 2440 didSwap = true; 2441 } 2442 } 2443 if (!didSwap) { 2444 break; 2445 } 2446 } 2447 2448 for (int k = 0; k < count - 1; k++) { 2449 SkASSERT(!(array[k+1] < array[k])); 2450 } 2451} 2452 2453#include "SkRandom.h" 2454 2455static void rand_rect(SkIRect* rect, SkRandom& rand) { 2456 int bits = 8; 2457 int shift = 32 - bits; 2458 rect->set(rand.nextU() >> shift, rand.nextU() >> shift, 2459 rand.nextU() >> shift, rand.nextU() >> shift); 2460 rect->sort(); 2461} 2462 2463static void dumpRect(const SkIRect& r) { 2464 SkDebugf(" { %d, %d, %d, %d },\n", 2465 r.fLeft, r.fTop, 2466 r.fRight, r.fBottom); 2467} 2468 2469static void test_rects(const SkIRect rect[], int count) { 2470 SkRegion rgn0, rgn1; 2471 2472 for (int i = 0; i < count; i++) { 2473 rgn0.op(rect[i], SkRegion::kUnion_Op); 2474 // dumpRect(rect[i]); 2475 } 2476 rgn1.setRects(rect, count); 2477 2478 if (rgn0 != rgn1) { 2479 SkDebugf("\n"); 2480 for (int i = 0; i < count; i++) { 2481 dumpRect(rect[i]); 2482 } 2483 SkDebugf("\n"); 2484 } 2485} 2486 2487static void test() { 2488 size_t i; 2489 2490 const SkIRect r0[] = { 2491 { 0, 0, 1, 1 }, 2492 { 2, 2, 3, 3 }, 2493 }; 2494 const SkIRect r1[] = { 2495 { 0, 0, 1, 3 }, 2496 { 1, 1, 2, 2 }, 2497 { 2, 0, 3, 3 }, 2498 }; 2499 const SkIRect r2[] = { 2500 { 0, 0, 1, 2 }, 2501 { 2, 1, 3, 3 }, 2502 { 4, 0, 5, 1 }, 2503 { 6, 0, 7, 4 }, 2504 }; 2505 2506 static const struct { 2507 const SkIRect* fRects; 2508 int fCount; 2509 } gRecs[] = { 2510 { r0, SK_ARRAY_COUNT(r0) }, 2511 { r1, SK_ARRAY_COUNT(r1) }, 2512 { r2, SK_ARRAY_COUNT(r2) }, 2513 }; 2514 2515 for (i = 0; i < SK_ARRAY_COUNT(gRecs); i++) { 2516 test_rects(gRecs[i].fRects, gRecs[i].fCount); 2517 } 2518 2519 SkRandom rand; 2520 for (i = 0; i < 10000; i++) { 2521 SkRegion rgn0, rgn1; 2522 2523 const int N = 8; 2524 SkIRect rect[N]; 2525 for (int j = 0; j < N; j++) { 2526 rand_rect(&rect[j], rand); 2527 } 2528 test_rects(rect, N); 2529 } 2530} 2531 2532// FIXME: this should be in a header 2533SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv); 2534SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) { 2535 if (false) { // avoid bit rot, suppress warning 2536 test(); 2537 } 2538 return new SampleWindow(hwnd, argc, argv, NULL); 2539} 2540 2541// FIXME: this should be in a header 2542void get_preferred_size(int* x, int* y, int* width, int* height); 2543void get_preferred_size(int* x, int* y, int* width, int* height) { 2544 *x = 10; 2545 *y = 50; 2546 *width = 640; 2547 *height = 480; 2548} 2549 2550#ifdef SK_BUILD_FOR_IOS 2551void save_args(int argc, char *argv[]) { 2552} 2553#endif 2554 2555// FIXME: this should be in a header 2556void application_init(); 2557void application_init() { 2558// setenv("ANDROID_ROOT", "../../../data", 0); 2559#ifdef SK_BUILD_FOR_MAC 2560 setenv("ANDROID_ROOT", "/android/device/data", 0); 2561#endif 2562 SkGraphics::Init(); 2563 SkEvent::Init(); 2564} 2565 2566// FIXME: this should be in a header 2567void application_term(); 2568void application_term() { 2569 SkEvent::Term(); 2570 SkGraphics::Term(); 2571} 2572