├── .gitignore ├── README.rst ├── android ├── .project ├── AndroidManifest.xml ├── jni │ ├── Android.mk │ ├── Application.mk │ └── libseg.cc ├── project.properties └── src │ └── net │ └── fhtagn │ └── libseg │ └── SimpleMatter.java ├── include ├── api.h ├── geodesic.h ├── kde.h ├── matting.h └── utils.h ├── screenshot.png ├── src ├── api.cc ├── geodesic.cc ├── geodesic_test.cc ├── kde.cc ├── kde_test.cc ├── matting.cc └── third_party │ └── miniglog │ ├── README.rst │ └── glog │ ├── logging.cc │ └── logging.h └── unix ├── build.sh ├── clean.sh ├── gdb.sh ├── gen_ninja.sh ├── plot_densities.py ├── project.gyp ├── run.sh ├── samples ├── cvutils.cc ├── cvutils.h ├── interactive.cc ├── main.cc └── simple_interactive.cc ├── third_party └── gmock-1.7.0 │ ├── CHANGES │ ├── CONTRIBUTORS │ ├── LICENSE │ ├── README │ ├── gtest │ ├── CHANGES │ ├── CONTRIBUTORS │ ├── LICENSE │ ├── README │ ├── include │ │ └── gtest │ │ │ ├── gtest-death-test.h │ │ │ ├── gtest-message.h │ │ │ ├── gtest-param-test.h │ │ │ ├── gtest-param-test.h.pump │ │ │ ├── gtest-printers.h │ │ │ ├── gtest-spi.h │ │ │ ├── gtest-test-part.h │ │ │ ├── gtest-typed-test.h │ │ │ ├── gtest.h │ │ │ ├── gtest_pred_impl.h │ │ │ ├── gtest_prod.h │ │ │ └── internal │ │ │ ├── gtest-death-test-internal.h │ │ │ ├── gtest-filepath.h │ │ │ ├── gtest-internal.h │ │ │ ├── gtest-linked_ptr.h │ │ │ ├── gtest-param-util-generated.h │ │ │ ├── gtest-param-util-generated.h.pump │ │ │ ├── gtest-param-util.h │ │ │ ├── gtest-port.h │ │ │ ├── gtest-string.h │ │ │ ├── gtest-tuple.h │ │ │ ├── gtest-tuple.h.pump │ │ │ ├── gtest-type-util.h │ │ │ └── gtest-type-util.h.pump │ └── src │ │ ├── gtest-all.cc │ │ ├── gtest-death-test.cc │ │ ├── gtest-filepath.cc │ │ ├── gtest-internal-inl.h │ │ ├── gtest-port.cc │ │ ├── gtest-printers.cc │ │ ├── gtest-test-part.cc │ │ ├── gtest-typed-test.cc │ │ ├── gtest.cc │ │ └── gtest_main.cc │ ├── include │ └── gmock │ │ ├── gmock-actions.h │ │ ├── gmock-cardinalities.h │ │ ├── gmock-generated-actions.h │ │ ├── gmock-generated-actions.h.pump │ │ ├── gmock-generated-function-mockers.h │ │ ├── gmock-generated-function-mockers.h.pump │ │ ├── gmock-generated-matchers.h │ │ ├── gmock-generated-matchers.h.pump │ │ ├── gmock-generated-nice-strict.h │ │ ├── gmock-generated-nice-strict.h.pump │ │ ├── gmock-matchers.h │ │ ├── gmock-more-actions.h │ │ ├── gmock-more-matchers.h │ │ ├── gmock-spec-builders.h │ │ ├── gmock.h │ │ └── internal │ │ ├── gmock-generated-internal-utils.h │ │ ├── gmock-generated-internal-utils.h.pump │ │ ├── gmock-internal-utils.h │ │ └── gmock-port.h │ └── src │ ├── gmock-all.cc │ ├── gmock-cardinalities.cc │ ├── gmock-internal-utils.cc │ ├── gmock-matchers.cc │ ├── gmock-spec-builders.cc │ ├── gmock.cc │ └── gmock_main.cc └── valgrind.sh /.gitignore: -------------------------------------------------------------------------------- 1 | third_party/figtree-0.9.3* 2 | third_party/gmock-1.7.0* 3 | third_party/glog-0.3.3* 4 | third_party/_install 5 | third_party/opencv* 6 | *.txt 7 | core 8 | data 9 | out 10 | unix/env.sh 11 | unix/third_party/gmock-1.7.0/Makefile 12 | unix/third_party/gmock-1.7.0/build-aux/* 13 | unix/third_party/gmock-1.7.0/config.log 14 | unix/third_party/gmock-1.7.0/config.status 15 | unix/third_party/gmock-1.7.0/libtool 16 | unix/third_party/gmock-1.7.0/scripts/gmock-config 17 | unix/third_party/gmock-1.7.0/gtest/Makefile 18 | unix/third_party/gmock-1.7.0/gtest/build-aux/* 19 | unix/third_party/gmock-1.7.0/gtest/config.log 20 | unix/third_party/gmock-1.7.0/gtest/config.status 21 | unix/third_party/gmock-1.7.0/gtest/libtool 22 | unix/third_party/gmock-1.7.0/gtest/scripts/gtest-config 23 | unix/third_party/opencv-2.4.8/ 24 | *.deps 25 | android/bin 26 | android/gen 27 | android/libs 28 | android/obj 29 | 30 | # built application files 31 | *.apk 32 | *.ap_ 33 | 34 | # files for the dex VM 35 | *.dex 36 | 37 | # Java class files 38 | *.class 39 | 40 | local.properties 41 | android/.classpath 42 | android/.settings 43 | android/.cproject 44 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | libseg 2 | ====== 3 | 4 | This is an *UNFINISHED* implementation and it is still quite buggy. 5 | 6 | An interactive image foreground/background segmentation library. 7 | 8 | For now, this is an implementation of geodesic matting of [Bai09]. It doesn't 9 | implement the alpha matting part and just stops at the foreground/background 10 | segmentation stage. 11 | 12 | This library can be build for the Linux/OSX and for android. 13 | 14 | Its only dependency is the FIGTree library[1]. A version adapted for android 15 | (and still working on the desktop) is available here : 16 | TODO: include figtree-android 17 | 18 | .. image:: screenshot.png 19 | :width: 90% 20 | 21 | 22 | Linux/OSX 23 | --------- 24 | Linux/OSX build files and scripts are under unix/. Gyp (generate your project) 25 | and ninja are used to build the projects. 26 | 27 | Example programs are under unix/samples 28 | 29 | Note that the Linux/OSX example programs require OpenCV. libseg itself 30 | doesn't depend on OpenCV. 31 | 32 | Build instruction : 33 | 34 | cd third_party/gmock-1.7.0 35 | ./configure 36 | make 37 | 38 | cd unix 39 | # Point FIGTREE to figtree-android 40 | export FIGTREE=../../figtree-android ./gen_ninja.sh 41 | ./build.sh 42 | 43 | Android 44 | ------- 45 | Android build files are under jni/. 46 | 47 | Build instructions 48 | ------------------ 49 | 50 | Use the run script to run a binary (it sets up the correct LD_LIBRARY_PATH) : 51 | 52 | ./run.sh out/Default/tests 53 | ./run.sh out/Default/interactive 54 | 55 | References 56 | ========== 57 | [1] http://www.umiacs.umd.edu/~morariu/figtree/ 58 | 59 | [Bai09] "Geodesic Matting: A Framework for Fast Interactive Image 60 | and Video Segmentation and Matting", Int J Comput Vis'09 61 | -------------------------------------------------------------------------------- /android/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | net.fhtagn.libseg 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.cdt.managedbuilder.core.genmakebuilder 10 | clean,full,incremental, 11 | 12 | 13 | 14 | 15 | com.android.ide.eclipse.adt.ResourceManagerBuilder 16 | 17 | 18 | 19 | 20 | com.android.ide.eclipse.adt.PreCompilerBuilder 21 | 22 | 23 | 24 | 25 | org.eclipse.jdt.core.javabuilder 26 | 27 | 28 | 29 | 30 | com.android.ide.eclipse.adt.ApkBuilder 31 | 32 | 33 | 34 | 35 | org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder 36 | full,incremental, 37 | 38 | 39 | 40 | 41 | 42 | com.android.ide.eclipse.adt.AndroidNature 43 | org.eclipse.jdt.core.javanature 44 | org.eclipse.cdt.core.cnature 45 | org.eclipse.cdt.core.ccnature 46 | org.eclipse.cdt.managedbuilder.core.managedBuildNature 47 | org.eclipse.cdt.managedbuilder.core.ScannerConfigNature 48 | 49 | 50 | -------------------------------------------------------------------------------- /android/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /android/jni/Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH := $(call my-dir) 2 | 3 | # libseg.a 4 | include $(CLEAR_VARS) 5 | LOCAL_MODULE := libseg 6 | LOCAL_SHARED_LIBRARIES += libfigtree 7 | LOCAL_DEFAULT_CPP_EXTENSION := cc 8 | LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../include $(LOCAL_PATH)/../../src/third_party/miniglog/ 9 | LOCAL_CPPFLAGS := -std=c++11 10 | LOCAL_CFLAGS := -D__GXX_EXPERIMENTAL_CXX0X__ 11 | LOCAL_LDLIBS := -llog -ljnigraphics 12 | LOCAL_SRC_FILES := libseg.cc \ 13 | ../../src/api.cc \ 14 | ../../src/geodesic.cc \ 15 | ../../src/kde.cc \ 16 | ../../src/matting.cc \ 17 | ../../src/third_party/miniglog/glog/logging.cc 18 | include $(BUILD_SHARED_LIBRARY) 19 | 20 | $(call import-module,figtree-android/jni) 21 | -------------------------------------------------------------------------------- /android/jni/Application.mk: -------------------------------------------------------------------------------- 1 | #APP_ABI := all 2 | APP_ABI := armeabi-v7a 3 | APP_STL := gnustl_shared 4 | APP_MODULES := libseg 5 | APP_PLATFORM := android-8 6 | NDK_TOOLCHAIN_VERSION := 4.8 7 | -------------------------------------------------------------------------------- /android/jni/libseg.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | #include 6 | #include "api.h" 7 | 8 | extern "C" JNIEXPORT jstring JNICALL 9 | Java_net_fhtagn_libseg_SimpleMatter_hello(JNIEnv* env, jclass) { 10 | return env->NewStringUTF("Hello from JNI"); 11 | } 12 | 13 | extern "C" JNIEXPORT jlong JNICALL 14 | Java_net_fhtagn_libseg_SimpleMatter_nativeNew( 15 | JNIEnv* env, 16 | jclass, 17 | jobject bitmap_image) { 18 | // TODO RGB => Lab conversion 19 | // http://www.easyrgb.com/index.php?X=MATH 20 | AndroidBitmapInfo bm_info; 21 | AndroidBitmap_getInfo(env, bitmap_image, &bm_info); 22 | CHECK_EQ(bm_info.format, ANDROID_BITMAP_FORMAT_RGBA_8888) 23 | << "Need ARGB_8888 format"; 24 | 25 | char* pixels; 26 | AndroidBitmap_lockPixels(env, bitmap_image, (void**)&pixels); 27 | 28 | // TODO: SimpleMatter shouldn't make an internal copy 29 | const int W = bm_info.width; 30 | const int H = bm_info.height; 31 | std::unique_ptr r(new uint8_t[W*H]); 32 | std::unique_ptr g(new uint8_t[W*H]); 33 | std::unique_ptr b(new uint8_t[W*H]); 34 | 35 | for (int i = 0; i < H; ++i) { 36 | for (int j = 0; j < W; ++j) { 37 | r[i*W + j] = pixels[i*W*4 + j*4]; 38 | g[i*W + j] = pixels[i*W*4 + j*4 + 1]; 39 | b[i*W + j] = pixels[i*W*4 + j*4 + 2]; 40 | } 41 | } 42 | 43 | SimpleMatter* m = new SimpleMatter(r.get(), g.get(), b.get(), W, H); 44 | 45 | AndroidBitmap_unlockPixels(env, bitmap_image); 46 | 47 | LOG(INFO) << "Created native matter : " << m; 48 | return (jlong)m; 49 | } 50 | 51 | 52 | extern "C" JNIEXPORT void JNICALL 53 | Java_net_fhtagn_libseg_SimpleMatter_nativeDestroy( 54 | JNIEnv* env, 55 | jclass, 56 | jlong obj) { 57 | SimpleMatter* m = (SimpleMatter*)obj; 58 | LOG(INFO) << "Destroying native matter : " << m; 59 | delete m; 60 | } 61 | 62 | void CheckMaskBitmap(JNIEnv* env, jobject bitmap, int expectedW, int expectedH, 63 | AndroidBitmapFormat fmt=ANDROID_BITMAP_FORMAT_RGBA_8888) { 64 | AndroidBitmapInfo bm_info; 65 | AndroidBitmap_getInfo(env, bitmap, &bm_info); 66 | CHECK_EQ(bm_info.format, fmt) << "Wrong format"; 67 | CHECK_EQ(bm_info.width, expectedW); 68 | CHECK_EQ(bm_info.height, expectedH); 69 | } 70 | 71 | extern "C" JNIEXPORT void JNICALL 72 | Java_net_fhtagn_libseg_SimpleMatter_nativeUpdateMasks( 73 | JNIEnv* env, 74 | jclass, 75 | jlong obj, 76 | jobject bitmap_bgmask, 77 | jobject bitmap_fgmask) { 78 | SimpleMatter* m = (SimpleMatter*)obj; 79 | CheckMaskBitmap(env, bitmap_fgmask, m->GetWidth(), m->GetHeight()); 80 | CheckMaskBitmap(env, bitmap_bgmask, m->GetWidth(), m->GetHeight()); 81 | 82 | uint8_t* bg_pix; 83 | uint8_t* fg_pix; 84 | AndroidBitmap_lockPixels(env, bitmap_fgmask, (void**)&fg_pix); 85 | AndroidBitmap_lockPixels(env, bitmap_bgmask, (void**)&bg_pix); 86 | 87 | const int W = m->GetWidth(); 88 | const int H = m->GetHeight(); 89 | 90 | // TODO: Avoid copy 91 | std::unique_ptr fg(new uint8_t[W*H]); 92 | std::unique_ptr bg(new uint8_t[W*H]); 93 | for (int i = 0; i < H; ++i) { 94 | for (int j = 0; j < W; ++j) { 95 | // Only consider alpha 96 | fg[i*W + j] = fg_pix[i*W*4 + j*4 + 3]; 97 | bg[i*W + j] = bg_pix[i*W*4 + j*4 + 3]; 98 | } 99 | } 100 | 101 | m->UpdateMasks(bg.get(), fg.get()); 102 | 103 | AndroidBitmap_unlockPixels(env, bitmap_bgmask); 104 | AndroidBitmap_unlockPixels(env, bitmap_fgmask); 105 | } 106 | 107 | extern "C" JNIEXPORT void JNICALL 108 | Java_net_fhtagn_libseg_SimpleMatter_nativeGetForegroundMask( 109 | JNIEnv* env, 110 | jclass, 111 | jlong obj, 112 | jobject bitmap_mask) { 113 | SimpleMatter* m = (SimpleMatter*)obj; 114 | CheckMaskBitmap(env, bitmap_mask, m->GetWidth(), m->GetHeight(), 115 | ANDROID_BITMAP_FORMAT_A_8); 116 | uint8_t* pixels; 117 | AndroidBitmap_lockPixels(env, bitmap_mask, (void**)&pixels); 118 | 119 | m->GetForegroundMask(pixels); 120 | 121 | AndroidBitmap_unlockPixels(env, bitmap_mask); 122 | } 123 | -------------------------------------------------------------------------------- /android/project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-19 15 | android.library=true 16 | -------------------------------------------------------------------------------- /android/src/net/fhtagn/libseg/SimpleMatter.java: -------------------------------------------------------------------------------- 1 | package net.fhtagn.libseg; 2 | 3 | import android.graphics.Bitmap; 4 | import android.util.Log; 5 | 6 | // Java interface to C++ SimpleMatter 7 | public class SimpleMatter { 8 | private final static String TAG = SimpleMatter.class.getName(); 9 | // The image being matted. Do NOT modify this directly 10 | public Bitmap image; 11 | 12 | // TODO: We need to handle locking somewhat 13 | 14 | // The client application should directly modify the bitmaps here and then 15 | // call updateMatter() to redo the matting 16 | public Bitmap fgScribbles; 17 | public Bitmap bgScribbles; 18 | 19 | public Bitmap finalMask; 20 | 21 | private long nativeMatter = 0; 22 | 23 | public SimpleMatter(Bitmap image) { 24 | this.image = image; 25 | this.fgScribbles = Bitmap.createBitmap(image.getWidth(), 26 | image.getHeight(), 27 | Bitmap.Config.ARGB_8888); 28 | this.bgScribbles = Bitmap.createBitmap(image.getWidth(), 29 | image.getHeight(), 30 | Bitmap.Config.ARGB_8888); 31 | this.finalMask = Bitmap.createBitmap(image.getWidth(), 32 | image.getHeight(), 33 | Bitmap.Config.ALPHA_8); 34 | Log.i(TAG, "Hello jni : " + hello()); 35 | nativeMatter = nativeNew(image); 36 | } 37 | 38 | @Override 39 | protected void finalize() throws Throwable { 40 | nativeDestroy(nativeMatter); 41 | } 42 | 43 | public synchronized void updateMatter() { 44 | nativeUpdateMasks(nativeMatter, bgScribbles, fgScribbles); 45 | nativeGetForegroundMask(nativeMatter, finalMask); 46 | } 47 | 48 | // TODO: JNI methods have to be private ? 49 | static native String hello(); 50 | 51 | // Create a new SimpleMatter on the C++ side, returning an identifier 52 | static native long nativeNew(Bitmap image); 53 | static native void nativeDestroy(long obj); 54 | static native void nativeUpdateMasks(long obj, Bitmap bgmask, Bitmap fgmask); 55 | // Get the foreground mask resulting from the matting 56 | static native void nativeGetForegroundMask(long obj, Bitmap mask); 57 | 58 | static { 59 | System.loadLibrary("gnustl_shared"); 60 | System.loadLibrary("figtree"); 61 | System.loadLibrary("seg"); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /include/api.h: -------------------------------------------------------------------------------- 1 | #ifndef _LIBMATTING_API_H_ 2 | #define _LIBMATTING_API_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include "utils.h" 9 | 10 | class Matter { 11 | public: 12 | Matter(uint8_t* lab_l, uint8_t* lab_a, 13 | uint8_t* lab_b, int W, int H); 14 | virtual ~Matter(); 15 | 16 | // Fill mask with the foreground mask resulting from the matting. 17 | // 255 indicates foreground pixels, 0 background. 18 | void GetForegroundMask(uint8_t* mask); 19 | 20 | void GetForegroundLikelihood(double* out); 21 | void GetBackgroundLikelihood(double* out); 22 | 23 | void GetForegroundDist(double* out); 24 | void GetBackgroundDist(double* out); 25 | 26 | int GetWidth() { return W; } 27 | int GetHeight() { return H; } 28 | 29 | protected: 30 | int W, H; 31 | std::unique_ptr lab_l, lab_a, lab_b; 32 | // TODO: We do not actually need the pdf for each pixel of the image. Use 33 | // a simple lookup table of pixel intensity to pdf instead 34 | std::unique_ptr fg_pdf, bg_pdf; 35 | std::unique_ptr fg_likelihood, bg_likelihood; 36 | std::unique_ptr fg_dist, bg_dist; 37 | std::unique_ptr final_mask; 38 | 39 | uint8_t* channels[3]; 40 | }; 41 | 42 | // A simpler API that doesn't have the notion of scribbles ordering, but just 43 | // use one mask for background scribbles and one mask for foreground 44 | class SimpleMatter : public Matter { 45 | public: 46 | // The image is given in the lab colorspace. Each of lab_l, lab_a, lab_b is 47 | // a W*H array stored in row-major order 48 | // Matter makes an internal copy of the image 49 | SimpleMatter(uint8_t* lab_l, uint8_t* lab_a, uint8_t* lab_b, int W, int H); 50 | virtual ~SimpleMatter(); 51 | 52 | void UpdateMasks(uint8_t* bg_mask, uint8_t* fg_mask); 53 | }; 54 | 55 | // Contains the current state of the matting 56 | // This is an API that implements section 3.1.3 of [Bai09] regarding user 57 | // interaction. Basically, scribbles ordering matters and a new background 58 | // scribble will only interfer with what's current foreground and inversely. 59 | class InteractiveMatter : public Matter { 60 | public: 61 | // The image is given in the lab colorspace. Each of lab_l, lab_a, lab_b is 62 | // a W*H array stored in row-major order 63 | // Matter makes an internal copy of the image 64 | InteractiveMatter(uint8_t* lab_l, uint8_t* lab_a, 65 | uint8_t* lab_b, int W, int H); 66 | virtual ~InteractiveMatter(); 67 | 68 | 69 | // Add a scribble. Note that empty scribbles (0 pixels) will be ignored 70 | // 71 | // We do not store all scribbles as a simple boolean mask because 72 | // of the way user interaction is handled (see Bai09). Scribbles ordering is 73 | // important to let user do local corrections that do not influence 74 | // the whole image. In other words, doing the matting with the same set of 75 | // scribbles but in different order might result in different result. 76 | void AddScribble(const Scribble& s); 77 | 78 | int NumScribbles() { 79 | return scribbles.size(); 80 | } 81 | 82 | private: 83 | // Initially false, true when at least one scribble has been added to bg/fg 84 | bool bg_scribbled_, fg_scribbled_; 85 | 86 | std::vector scribbles; 87 | }; 88 | 89 | #endif 90 | -------------------------------------------------------------------------------- /include/geodesic.h: -------------------------------------------------------------------------------- 1 | #ifndef _GEODESIC_H_ 2 | #define _GEODESIC_H_ 3 | 4 | #include 5 | #include "utils.h" 6 | 7 | // Functions to compute geodesic distance between image pixels and user 8 | // scribbles as per section 3.1.2 (fig.5) of Bai09 9 | 10 | // For a W*H image (4-connected graph) given as a heightmap, compute, for each 11 | // pixel, the minimum geodesic distance to the closest source 12 | // This is described in section 3.1.2 (fig. 5) of Bai09 13 | void GeodesicDistanceMap(const std::vector& sources, 14 | const double* height, 15 | int W, 16 | int H, 17 | double* dists); 18 | 19 | void GeodesicDistanceMap(const uint8_t* source_mask, 20 | const double* height, 21 | int W, 22 | int H, 23 | double* dists); 24 | 25 | void GeodesicDistanceMap(const std::vector& scribbles, 26 | bool background, 27 | const double* height, 28 | int W, 29 | int H, 30 | double* dists); 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /include/kde.h: -------------------------------------------------------------------------------- 1 | #ifndef _LIBMATTING_KDE_H_ 2 | #define _LIBMATTING_KDE_H_ 3 | 4 | // Implement Kernel Density Estimation (KDE) to estimate the color PDF 5 | // Pr(color | foreground) 6 | // This is described in section 3.1.1 (and fig.3) of Bai09. Note that like 7 | // in Bai, we perform one univariate KDE on each axis of the colorspace instead 8 | // of a multivariate 3D KDE 9 | #include 10 | #include 11 | 12 | #include "utils.h" 13 | 14 | // Use kernel density estimation to compute the probability of each point 15 | // int targets (storing the probability in target_prob) given the data points 16 | // in xis and their corresponding weights 17 | // 18 | // p = \sum_i w_i K(t - xi) 19 | // 20 | // Where K is a gaussian kernel and t is the target. w_i is the weight 21 | // 22 | // The KDE bandwidth is estimated automatically using a rule-of-thumb 23 | void UnivariateKDE(const std::vector& xis, 24 | const std::vector& weights, 25 | const std::vector& targets, 26 | std::vector* target_prob); 27 | 28 | // Uses the figtree library to compute fast KDE with the help of the 29 | // Gauss transform 30 | // epsilon is the desired maximum absolute error after normalizing output 31 | // by sum of weights. 32 | // If the weights, q_i (see below), add up to 1, then this is will be the 33 | // maximum absolute error. 34 | void FastUnivariateKDE(const std::vector& xis, 35 | const std::vector& weights, 36 | const std::vector& targets, 37 | std::vector* target_prob, 38 | double epsilon=1e-2); 39 | 40 | // Helper function to compute KDE on a single color channel for values of 41 | // x in the [0, 255] interval. 42 | // So, target_prob will have 256 entries containing the probability for each 43 | // 8bit color value. 44 | // (Optionally) A median filter is also applied to smooth the probabilities 45 | void ColorChannelKDE(const uint8_t* data, 46 | const uint8_t* mask, 47 | int W, 48 | int H, 49 | bool median_filter, 50 | std::vector* target_prob); 51 | 52 | // Same as above, but uses a list of scribbles instead of a mask. Only 53 | // scribbles with s.background == background are considered. 54 | void ColorChannelKDE(const uint8_t* data, 55 | const std::vector& scribbles, 56 | bool background, 57 | int W, 58 | int H, 59 | bool median_filter, 60 | std::vector* target_prob); 61 | 62 | void ColorChannelKDE(const std::vector& xi, 63 | bool median_filter, 64 | std::vector* target_prob); 65 | 66 | #endif 67 | -------------------------------------------------------------------------------- /include/matting.h: -------------------------------------------------------------------------------- 1 | #ifndef _LIBMATTING_MATTING_H_ 2 | #define _LIBMATTING_MATTING_H_ 3 | 4 | #include 5 | #include "utils.h" 6 | 7 | // Computes P(c_x | M) where M is background/foreground estimated by KDE from 8 | // the mask. c_x is a pixel. 9 | // 10 | // outimg should be a user-allocated W*H image 11 | void ImageColorPDF(const uint8_t* const* channels, 12 | const uint8_t* mask, 13 | int W, 14 | int H, 15 | double* outimg); 16 | 17 | void ImageColorPDF(uint8_t const* const* channels, 18 | const std::vector& scribbles, 19 | bool background, 20 | int W, 21 | int H, 22 | double* outimg); 23 | 24 | void ImageColorPDF(uint8_t const* const* channels, 25 | const std::vector>& probs, 26 | int W, 27 | int H, 28 | double* outimg); 29 | 30 | 31 | // Equation 1. of Bai09 : 32 | // P_F(cx) = P(cx|F) / (P(cx|F) + P(cx|B)) 33 | // 34 | // likelihood should be a user-allocated W*H image 35 | void ForegroundLikelihood(const double* P_cx_F, 36 | const double* P_cx_B, 37 | int W, 38 | int H, 39 | double* likelihood); 40 | 41 | // Compute final foreground mask 42 | // outmask is allocated by the caller as a W*H row-major array 43 | void FinalForegroundMask(const double* fg_dist, 44 | const double* bg_dist, 45 | int W, 46 | int H, 47 | uint8_t* outmask); 48 | 49 | #endif 50 | -------------------------------------------------------------------------------- /include/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef _LIBMATTING_UTILS_H_ 2 | #define _LIBMATTING_UTILS_H_ 3 | 4 | #include 5 | 6 | struct Point2i { 7 | Point2i(int x, int y) : x(x), y(y) {} 8 | int x, y; 9 | }; 10 | 11 | // A user-provided drawing that is either foreground or background 12 | struct Scribble { 13 | bool background; 14 | std::vector pixels; 15 | }; 16 | 17 | 18 | template 19 | bool IsNaN(T t) { 20 | return t != t; 21 | } 22 | 23 | // Copy src[i] to dst[i] if mask[i] == true_val 24 | template 25 | void MaskedCopy(const T* src, 26 | const M* mask, 27 | M true_val, 28 | const int len, 29 | T* dst) { 30 | for (int i = 0; i < len; ++i) { 31 | if (mask[i] == true_val) { 32 | dst[i] = src[i]; 33 | } 34 | } 35 | } 36 | 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/julienr/libseg/597b0073eb1dd0531868168654ba28e64729f8e5/screenshot.png -------------------------------------------------------------------------------- /src/api.cc: -------------------------------------------------------------------------------- 1 | #include "api.h" 2 | 3 | #include "kde.h" 4 | #include "geodesic.h" 5 | #include "matting.h" 6 | 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | Matter::Matter(uint8_t* l, uint8_t* a, uint8_t* b, int W, int H) 13 | : W(W), H(H), 14 | lab_l(new uint8_t[W*H]), 15 | lab_a(new uint8_t[W*H]), 16 | lab_b(new uint8_t[W*H]), 17 | fg_pdf(new double[W*H]), 18 | bg_pdf(new double[W*H]), 19 | fg_likelihood(new double[W*H]), 20 | bg_likelihood(new double[W*H]), 21 | fg_dist(new double[W*H]), 22 | bg_dist(new double[W*H]), 23 | final_mask(new uint8_t[W*H]) { 24 | memcpy(lab_l.get(), l, sizeof(uint8_t)*W*H); 25 | memcpy(lab_a.get(), a, sizeof(uint8_t)*W*H); 26 | memcpy(lab_b.get(), b, sizeof(uint8_t)*W*H); 27 | 28 | for (int i = 0; i < W*H; ++i) { 29 | final_mask[i] = 0; 30 | fg_dist[i] = numeric_limits::max(); 31 | bg_dist[i] = numeric_limits::max(); 32 | } 33 | 34 | channels[0] = lab_l.get(); 35 | channels[1] = lab_a.get(); 36 | channels[2] = lab_b.get(); 37 | } 38 | 39 | Matter::~Matter() {} 40 | 41 | void Matter::GetForegroundLikelihood(double* out) { 42 | memcpy(out, fg_likelihood.get(), sizeof(double)*W*H); 43 | } 44 | 45 | void Matter::GetBackgroundLikelihood(double* out) { 46 | memcpy(out, bg_likelihood.get(), sizeof(double)*W*H); 47 | } 48 | 49 | void Matter::GetForegroundDist(double* out) { 50 | memcpy(out, fg_dist.get(), sizeof(double)*W*H); 51 | } 52 | 53 | void Matter::GetBackgroundDist(double* out) { 54 | memcpy(out, bg_dist.get(), sizeof(double)*W*H); 55 | } 56 | 57 | void Matter::GetForegroundMask(uint8_t* outmask) { 58 | memcpy(outmask, final_mask.get(), sizeof(uint8_t)*W*H); 59 | } 60 | 61 | SimpleMatter::SimpleMatter(uint8_t* l, uint8_t* a, uint8_t* b, 62 | int W, int H) 63 | : Matter(l, a, b, W, H) { 64 | } 65 | 66 | SimpleMatter::~SimpleMatter() {} 67 | 68 | void SimpleMatter::UpdateMasks(uint8_t* bg_mask, uint8_t* fg_mask) { 69 | // Update PDFs 70 | ImageColorPDF(channels, bg_mask, W, H, bg_pdf.get()); 71 | ImageColorPDF(channels, fg_mask, W, H, fg_pdf.get()); 72 | 73 | // Update likelihoods 74 | ForegroundLikelihood(fg_pdf.get(), bg_pdf.get(), H, W, fg_likelihood.get()); 75 | ForegroundLikelihood(bg_pdf.get(), fg_pdf.get(), H, W, bg_likelihood.get()); 76 | 77 | // Update distance maps 78 | GeodesicDistanceMap(bg_mask, bg_likelihood.get(), W, H, bg_dist.get()); 79 | GeodesicDistanceMap(fg_mask, fg_likelihood.get(), W, H, fg_dist.get()); 80 | 81 | // Compute final mask 82 | FinalForegroundMask(fg_dist.get(), bg_dist.get(), W, H, final_mask.get()); 83 | } 84 | 85 | InteractiveMatter::InteractiveMatter(uint8_t* l, uint8_t* a, uint8_t* b, 86 | int W, int H) 87 | : Matter(l, a, b, W, H), 88 | bg_scribbled_(false), 89 | fg_scribbled_(false) { 90 | } 91 | 92 | InteractiveMatter::~InteractiveMatter() {} 93 | 94 | void InteractiveMatter::AddScribble(const Scribble& s) { 95 | if (s.pixels.size() == 0) { 96 | LOG(WARNING) << "Ignoring empty scribble"; 97 | return; 98 | } 99 | scribbles.push_back(s); 100 | 101 | // 1. Update bg or fg pdf (depending on scribble's background attribute) 102 | if (s.background) { 103 | //cout << "Updating bg pdf" << endl; 104 | ImageColorPDF(channels, scribbles, true, W, H, bg_pdf.get()); 105 | } else { 106 | //cout << "Updating fg pdf" << endl; 107 | ImageColorPDF(channels, scribbles, false, W, H, fg_pdf.get()); 108 | } 109 | 110 | // 2. Update fg AND bg likelihood 111 | ForegroundLikelihood(fg_pdf.get(), bg_pdf.get(), H, W, fg_likelihood.get()); 112 | ForegroundLikelihood(bg_pdf.get(), fg_pdf.get(), H, W, bg_likelihood.get()); 113 | 114 | #if 1 115 | // 3. Update fg or bg distance map, but only for pixels within the 116 | // fg (if bg scribble) or bg (if fg scribble). 117 | unique_ptr newdist(new double[W*H]); 118 | if (s.background) { 119 | GeodesicDistanceMap(scribbles, true, bg_likelihood.get(), W, H, 120 | newdist.get()); 121 | if (!bg_scribbled_) { // special case for first scribble 122 | memcpy(bg_dist.get(), newdist.get(), sizeof(double)*W*H); 123 | bg_scribbled_ = true; 124 | } else { 125 | MaskedCopy(newdist.get(), final_mask.get(), 255, 126 | W*H, bg_dist.get()); 127 | } 128 | } else { 129 | GeodesicDistanceMap(scribbles, false, fg_likelihood.get(), W, H, 130 | newdist.get()); 131 | if (!fg_scribbled_) { // special case for first scribble 132 | memcpy(fg_dist.get(), newdist.get(), sizeof(double)*W*H); 133 | fg_scribbled_ = true; 134 | } else { 135 | MaskedCopy(newdist.get(), final_mask.get(), 0, 136 | W*H, fg_dist.get()); 137 | 138 | } 139 | } 140 | #else 141 | // 3. (alternative) Update everything 142 | GeodesicDistanceMap(scribbles, true, bg_likelihood.get(), W, H, 143 | bg_dist.get()); 144 | GeodesicDistanceMap(scribbles, false, fg_likelihood.get(), W, H, 145 | fg_dist.get()); 146 | #endif 147 | 148 | // 4. Compute final mask 149 | FinalForegroundMask(fg_dist.get(), bg_dist.get(), W, H, final_mask.get()); 150 | } 151 | -------------------------------------------------------------------------------- /src/geodesic.cc: -------------------------------------------------------------------------------- 1 | #include "geodesic.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | void GeodesicDistanceMap(const uint8_t* source_mask, 13 | const double* height, 14 | int W, int H, 15 | double* dists) { 16 | vector points; 17 | for (int x = 0; x < W; ++x) { 18 | for (int y = 0; y < H; ++y) { 19 | if (source_mask[W*y + x]) { 20 | points.push_back(Point2i(x, y)); 21 | } 22 | } 23 | } 24 | GeodesicDistanceMap(points, height, W, H, dists); 25 | } 26 | 27 | void GeodesicDistanceMap(const std::vector& scribbles, 28 | bool background, 29 | const double* height, 30 | int W, int H, 31 | double* dists) { 32 | vector points; 33 | for (const Scribble& s : scribbles) { 34 | if (s.background == background) { 35 | points.insert(points.end(), s.pixels.begin(), s.pixels.end()); 36 | } 37 | } 38 | GeodesicDistanceMap(points, height, W, H, dists); 39 | } 40 | 41 | void GeodesicDistanceMap(const std::vector& sources, 42 | const double* height, 43 | int W, 44 | int H, 45 | double* dists) { 46 | // The algorithm is actually equivalent to running Dijkstra once for each 47 | // source and then keeping the minimum distance. 48 | // This is similar to "SHORTEST-PATH FOREST WITH TOPOLOGICAL ORDERING" 49 | // 50 | // But we do it all at once so it should be faster. It works as follow : 51 | // 1. assign a distance of 0 to all source nodes, infinity to others 52 | // 2. create a list of unvisited nodes consisting of the source nodes 53 | // 3. visit neighbors of the current node 54 | // - if the current node allows a shortest path to the neighbor 55 | // - update the neighbor dist 56 | // - add the neighbor to the unvisited nodes 57 | // 4. remove current node from visited 58 | // 5. pick the node with the smallest distance from the unvisited node as 59 | // the new current 60 | const int N = W*H; 61 | // priority queue 62 | typedef pair PriorityEntry; 63 | auto comp = [](const PriorityEntry& e1, const PriorityEntry& e2) { 64 | return e1.second > e2.second; 65 | }; 66 | priority_queue, decltype(comp)> Q(comp); 67 | 68 | for (int i = 0; i < N; ++i) { 69 | dists[i] = numeric_limits::max(); 70 | } 71 | 72 | for (const Point2i& p : sources) { 73 | const int i = W*p.y + p.x; 74 | dists[i] = 0; 75 | Q.push(make_pair(i, 0)); 76 | } 77 | 78 | //dx dy pairs for neighborhood exploration 79 | const int dx[4] = {-1, 0, 1, 0}; 80 | const int dy[4] = { 0, 1, 0, -1}; 81 | 82 | // main loop 83 | while(!Q.empty()) { 84 | int u = Q.top().first; 85 | const int ux = u % W; 86 | const int uy = u / W; 87 | Q.pop(); 88 | // explore neighbors 89 | for (int i = 0; i < 4; ++i) { 90 | const int vx = ux + dx[i]; 91 | const int vy = uy + dy[i]; 92 | if ((vx < 0 || vx >= W) || (vy < 0 || vy >= H)) { 93 | continue; 94 | } 95 | const int v = vy*W + vx; 96 | const double w = fabs(height[v] - height[u]); 97 | 98 | if ((dists[u] + w) < dists[v]) { // we found a shortest path to v 99 | dists[v] = dists[u] + w; 100 | // TODO: should UPDATE existing v (instead of duplicating) 101 | Q.push(make_pair(v, dists[v])); 102 | } 103 | } 104 | } 105 | } 106 | 107 | -------------------------------------------------------------------------------- /src/geodesic_test.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "geodesic.h" 6 | 7 | using namespace std; 8 | using ::testing::DoubleNear; 9 | 10 | namespace { 11 | 12 | TEST(GeodesicDistanceMap, Simple) { 13 | double height[] = { 14 | 0, 1, 2, 1, 15 | 0, 2, 1, 2, 16 | 0, 1, 0, 1 17 | }; 18 | uint8_t sources[] = { 19 | 1, 0, 0, 0, 20 | 0, 0, 0, 0, 21 | 0, 0, 1, 0 22 | }; 23 | const int W = 4; 24 | const int H = 3; 25 | double dists[W*H]; 26 | GeodesicDistanceMap(sources, height, W, H, dists); 27 | 28 | uint8_t expected_dists[] = { 29 | 0, 1, 2, 3, 30 | 0, 2, 1, 2, 31 | 0, 1, 0, 1, 32 | }; 33 | 34 | //cout << "dists" << endl; 35 | for (int i = 0; i < 3; ++i) { 36 | for (int j = 0; j < 4; ++j) { 37 | ASSERT_EQ(dists[i*W + j], expected_dists[i*W + j]) 38 | << "difference at (" << i << ", " << j << ") : " << dists[i*W+j] 39 | << " != " << expected_dists[i*W + j]; 40 | //cout << "\t" << dists[i*4 + j]; 41 | } 42 | //cout << endl; 43 | } 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/kde.cc: -------------------------------------------------------------------------------- 1 | #include "kde.h" 2 | #include 3 | #include 4 | #include 5 | 6 | #include 7 | 8 | #include 9 | 10 | using namespace std; 11 | 12 | const double NORMAL_FACTOR = 1/(double)sqrt(2*M_PI); 13 | 14 | double GaussianKernel(double t, double xi, double h, bool verbose=false) { 15 | const double x = (t - xi) / h; 16 | // TODO: We have to remove NORMAL_FACTOR so that is sums to 1 17 | // (see plot_densities.py). Is that normal ? 18 | if (verbose) { 19 | LOG(INFO) << "xi : " << xi << ", t : " << t << ", h : " << h 20 | << " => x = " << x << " => x*x = " << x*x; 21 | } 22 | 23 | //return NORMAL_FACTOR * exp(-0.5 * x * x); 24 | return exp(-0.5 * x * x); 25 | } 26 | 27 | // Use Scott's Rule, like scipy : 28 | // h = n**(-1./(d+4)) 29 | // where n is the number of data points, d the number of dimensions 30 | // http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html 31 | double EstimateBandwidth(int ndata, int ndims) { 32 | //return pow(ndata, -1.0/(double)(ndims + 4)); 33 | // TODO: Hardcoded 0.1 value works better than estimator 34 | return 0.1; 35 | } 36 | 37 | void UnivariateKDE(const vector& xis, 38 | const vector& weights, 39 | const vector& targets, 40 | vector* target_prob) { 41 | CHECK_EQ(xis.size(), weights.size()); 42 | const double h = EstimateBandwidth(xis.size(), 1); 43 | //LOG(INFO) << "h : " << h; 44 | for (size_t ti = 0; ti < targets.size(); ++ti) { 45 | double prob = 0; 46 | for (size_t i = 0; i < xis.size(); ++i) { 47 | prob += weights[i] * GaussianKernel(targets[ti], xis[i], h); 48 | } 49 | //if (prob == 0) { 50 | //for (size_t i = 0; i < xis.size(); ++i) { 51 | //LOG(INFO) << "i : " << i << ", " << weights[i] << ", " 52 | //<< GaussianKernel(targets[ti], xis[i], h, true); 53 | //} 54 | //} 55 | target_prob->push_back(prob); 56 | } 57 | } 58 | 59 | void FastUnivariateKDE(const std::vector& xis, 60 | const std::vector& weights, 61 | const std::vector& targets, 62 | std::vector* target_prob, 63 | double epsilon) { 64 | // libfigtree doesn't like empty xis 65 | if (xis.size() == 0) { 66 | // Uniform distribution 67 | target_prob->resize(targets.size(), 1.0/(double)targets.size()); 68 | return; 69 | } 70 | 71 | // Figtree's h is not exactly the same as standard deviation : 72 | // (from figtree sample.cpp) 73 | // The bandwidth. NOTE: this is not the same as standard deviation since 74 | // the Gauss Transform sums terms exp( -||x_i - y_j||^2 / h^2 ) as opposed 75 | // to exp( -||x_i - y_j||^2 / (2*sigma^2) ). Thus, if sigma is known, 76 | // bandwidth can be set to h = sqrt(2)*sigma. 77 | const double h = sqrt(2) * EstimateBandwidth(xis.size(), 1); 78 | //const double h = sqrt(2) * 30; 79 | //LOG(INFO) << "h : " << h; 80 | const int d = 1; 81 | const int N = xis.size(); 82 | const int M = targets.size(); 83 | const int W = 1; 84 | 85 | target_prob->resize(M); 86 | 87 | figtree(d, N, M, W, 88 | const_cast(xis.data()), 89 | h, 90 | const_cast(weights.data()), 91 | const_cast(targets.data()), 92 | epsilon, 93 | target_prob->data()); 94 | } 95 | 96 | // Return the median of the elements in v. Note that v WILL be modified 97 | template 98 | T Median(vector* v) { 99 | // TODO: This is not completely correct. If v has an even number of elements, 100 | // the median should be the average of the middle two 101 | // http://stackoverflow.com/questions/1719070/what-is-the-right-approach-when-using-stl-container-for-median-calculation 102 | size_t n = v->size() / 2; 103 | std::nth_element(v->begin(), v->begin() + n, v->end()); 104 | return v->at(n); 105 | } 106 | 107 | void MedianFilter(const vector& v, 108 | size_t hwsize, // half window size 109 | vector* vfilt) { 110 | for (size_t i = 0; i < v.size(); ++i) { 111 | const int wstart = max(0, i - hwsize); 112 | const int wend = min(v.size() - 1, i + hwsize); 113 | vector window(v.begin() + wstart, v.begin() + wend); 114 | vfilt->push_back(Median(&window)); 115 | } 116 | } 117 | 118 | void ColorChannelKDE(const uint8_t* data, 119 | const uint8_t* mask, 120 | int W, 121 | int H, 122 | bool median_filter, 123 | std::vector* target_prob) { 124 | vector xis; 125 | for (int i = 0; i < W*H; ++i) { 126 | if (mask[i]) { 127 | xis.push_back(data[i]); 128 | } 129 | } 130 | 131 | ColorChannelKDE(xis, median_filter, target_prob); 132 | } 133 | 134 | void ColorChannelKDE(const uint8_t* data, 135 | const vector& scribbles, 136 | bool background, 137 | int W, 138 | int H, 139 | bool median_filter, 140 | std::vector* target_prob) { 141 | vector xis; 142 | for (const Scribble& s : scribbles) { 143 | if (s.background == background) { 144 | for (const Point2i& p : s.pixels) { 145 | xis.push_back(data[W*p.y + p.x]); 146 | } 147 | } 148 | } 149 | ColorChannelKDE(xis, median_filter, target_prob); 150 | } 151 | 152 | void ColorChannelKDE(const std::vector& xis, 153 | bool median_filter, 154 | std::vector* target_prob) { 155 | vector weights(xis.size(), 1/(double)xis.size()); 156 | vector targets; 157 | //for (int i = 0; i < 255; ++i) { 158 | //targets.push_back(i); 159 | //} 160 | 161 | // z-score normalize xis and targets to the [-1,1] range 162 | // Otherwise, the standard gaussian kernel (e^(-0.5*(x-t)**2)) will blow up 163 | // because x-t will be too large 164 | vector nx(xis.size(), 0); 165 | for (size_t i = 0; i < xis.size(); ++i) { 166 | nx[i] = (xis[i] - 128) / 128.0; 167 | } 168 | for (int i = 0; i < 255; ++i) { 169 | targets.push_back((i - 128)/128.0); 170 | } 171 | //UnivariateKDE(nx, weights, targets, target_prob); 172 | FastUnivariateKDE(nx, weights, targets, target_prob); 173 | 174 | // TODO: Median filtering is useless (look at plot_densities) 175 | if (median_filter) { 176 | vector medfilt; 177 | MedianFilter(*target_prob, 5, &medfilt); 178 | *target_prob = medfilt; 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/kde_test.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "kde.h" 6 | 7 | using namespace std; 8 | using ::testing::DoubleNear; 9 | 10 | namespace { 11 | 12 | TEST(FastUnivariateKDE, FastSlow) { 13 | // Ensure UnivariateKDE and FastUnivariateKDE produce the same results 14 | 15 | // Source 16 | vector x{0.7165, 0.5113, 0.7764, 0.4893, 0.1859}; 17 | 18 | // source weights 19 | vector w{0.2280, 0.4496, 0.1722, 0.9688, 0.3557}; 20 | 21 | // Targets 22 | vector y{0.9561, 0.5955, 0.0287, 0.8121, 0.6101, 0.7015, 0.0922, 23 | 0.4249, 0.3756, 0.1662, 0.8332, 0.8386, 0.4516, 0.9566, 24 | 0.1472, 0.8699, 0.7694, 0.4442, 0.6206}; 25 | 26 | const double epsilon = 1e-2; 27 | 28 | vector slow_prob; 29 | vector fast_prob; 30 | UnivariateKDE(x, w, y, &slow_prob); 31 | FastUnivariateKDE(x, w, y, &fast_prob, epsilon); 32 | 33 | ASSERT_EQ(slow_prob.size(), fast_prob.size()); 34 | for (size_t i = 0; i < slow_prob.size(); ++i) { 35 | ASSERT_THAT(slow_prob[i], DoubleNear(fast_prob[i], 1e-2)) 36 | << "At index " << i << " : " << slow_prob[i] << " != " << fast_prob[i]; 37 | } 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/matting.cc: -------------------------------------------------------------------------------- 1 | #include "matting.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include "kde.h" 10 | #include "geodesic.h" 11 | 12 | using namespace std; 13 | 14 | void ImageColorPDF(uint8_t const* const* channels, 15 | const uint8_t* mask, 16 | int W, 17 | int H, 18 | double* outimg) { 19 | vector> probs(3); 20 | for (int i = 0; i < 3; ++i) { 21 | ColorChannelKDE(channels[i], mask, W, H, true, &probs[i]); 22 | } 23 | 24 | ImageColorPDF(channels, probs, W, H, outimg); 25 | } 26 | 27 | void ImageColorPDF(uint8_t const* const* channels, 28 | const std::vector& scribbles, 29 | bool background, 30 | int W, 31 | int H, 32 | double* outimg) { 33 | vector> probs(3); 34 | for (int i = 0; i < 3; ++i) { 35 | ColorChannelKDE(channels[i], scribbles, background, W, H, true, &probs[i]); 36 | } 37 | 38 | ImageColorPDF(channels, probs, W, H, outimg); 39 | } 40 | 41 | void ImageColorPDF(uint8_t const* const* channels, 42 | const vector>& probs, 43 | int W, 44 | int H, 45 | double* outimg) { 46 | double prob_max = numeric_limits::min(); 47 | for (int i = 0; i < W*H; ++i) { 48 | // The probabilities at a given value are very low (< 0.030), which is 49 | // mathematically correct (we have 255 such values and they sum to 1), but 50 | // can be problematic numerically. So we scale them by a factor of 10 51 | // TODO: Check that has no other incidence 52 | const double prob = probs[0][channels[0][i]] 53 | * probs[1][channels[1][i]] 54 | * probs[2][channels[2][i]]; 55 | outimg[i] = prob; 56 | if (prob > prob_max) { 57 | prob_max = prob; 58 | } 59 | } 60 | } 61 | 62 | void ForegroundLikelihood(const double* P_cx_F, 63 | const double* P_cx_B, 64 | int W, 65 | int H, 66 | double* likelihood) { 67 | for (int i = 0; i < W*H; ++i) { 68 | // Avoid division by zero 69 | if (P_cx_F[i] == 0 && P_cx_B[i] == 0) { 70 | // If P(cx|B) = 0, we have P(cx|F) / (P(cx|F), so set to 1 71 | likelihood[i] = 1; 72 | } else { 73 | likelihood[i] = P_cx_F[i] / (P_cx_F[i] + P_cx_B[i]); 74 | } 75 | } 76 | } 77 | 78 | void FinalForegroundMask(const double* fg_dist, 79 | const double* bg_dist, 80 | int W, 81 | int H, 82 | uint8_t* outmask) { 83 | const int N = W*H; 84 | for (int i = 0; i < N; ++i) { 85 | outmask[i] = (fg_dist[i] < bg_dist[i]) ? 255 : 0; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/third_party/miniglog/README.rst: -------------------------------------------------------------------------------- 1 | This is the miniglog (a minimal version of Google logging library) library from ceres-solver : 2 | https://code.google.com/p/ceres-solver/source/browse/internal/ceres/miniglog/#miniglog%2Fglog 3 | 4 | This is BSD licensed. 5 | -------------------------------------------------------------------------------- /src/third_party/miniglog/glog/logging.cc: -------------------------------------------------------------------------------- 1 | // Ceres Solver - A fast non-linear least squares minimizer 2 | // Copyright 2012 Google Inc. All rights reserved. 3 | // http://code.google.com/p/ceres-solver/ 4 | // 5 | // Redistribution and use in source and binary forms, with or without 6 | // modification, are permitted provided that the following conditions are met: 7 | // 8 | // * Redistributions of source code must retain the above copyright notice, 9 | // this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above copyright notice, 11 | // this list of conditions and the following disclaimer in the documentation 12 | // and/or other materials provided with the distribution. 13 | // * Neither the name of Google Inc. nor the names of its contributors may be 14 | // used to endorse or promote products derived from this software without 15 | // specific prior written permission. 16 | // 17 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 21 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 24 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 25 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 27 | // POSSIBILITY OF SUCH DAMAGE. 28 | // 29 | // Author: keir@google.com (Keir Mierle) 30 | 31 | #include "glog/logging.h" 32 | 33 | namespace google { 34 | 35 | // This is the set of log sinks. This must be in a separate library to ensure 36 | // that there is only one instance of this across the entire program. 37 | std::set log_sinks_global; 38 | 39 | } // namespace ceres 40 | -------------------------------------------------------------------------------- /unix/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | CCACHE_SLOPPINESS=time_macros ninja -C out/Default $@ 3 | -------------------------------------------------------------------------------- /unix/clean.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | CCACHE_SLOPPINESS=time_macros ninja -C out/Default -t clean 3 | -------------------------------------------------------------------------------- /unix/gdb.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | LIB_PATH=out/Default/lib:$FIGTREE/unix/:third_party/_install/lib:$LD_LIBRARY_PATH 3 | DYLD_LIBRARY_PATH=$LIB_PATH LD_LIBRARY_PATH=$LIB_PATH gdb --ex run --args $@ 4 | -------------------------------------------------------------------------------- /unix/gen_ninja.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #COMP=g++ 3 | #COMP="clang++" 4 | COMP="ccache g++" 5 | export CXX=$COMP 6 | export CC=$COMP 7 | 8 | gyp project.gyp --depth=. -f ninja -G output_dir=$PWD/out -D ROOTDIR=${PWD} \ 9 | -D SRCDIR=../src -D INCDIR=../include -D FIGTREE=$FIGTREE 10 | -------------------------------------------------------------------------------- /unix/plot_densities.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pylab as pl 3 | 4 | #densities = np.genfromtxt('densities.txt') 5 | #print densities.shape 6 | 7 | for densfile in ['densities_nomedfilter.txt', 'densities_medfilter.txt']: 8 | densities = np.genfromtxt(densfile) 9 | pl.figure() 10 | pl.suptitle(densfile) 11 | for c in xrange(3): 12 | print '--- Channel %d' % c 13 | pl.subplot(3, 1, c + 1) 14 | pl.title('Channel %d' % c) 15 | p_fg = densities[2*c] 16 | p_bg = densities[2*c + 1] 17 | print "count(p_fg == 0) : ", np.sum(p_fg == 0) 18 | print "count(p_bg == 0) : ", np.sum(p_bg == 0) 19 | pl.plot(np.arange(255), p_fg, c='b', label='fg') 20 | pl.plot(np.arange(255), p_bg, c='g', label='bg') 21 | pl.legend() 22 | print 'sum(p_fg) : ', np.sum(p_fg) 23 | print 'sum(p_bg) : ', np.sum(p_bg) 24 | pl.show() 25 | -------------------------------------------------------------------------------- /unix/project.gyp: -------------------------------------------------------------------------------- 1 | # gyp --toplevel-dir option doesn't seem to work as we want when the .gyp 2 | # file is also out of the source tree. 3 | # So instead, use SRCDIR environment variable set by gen_ninja.sh to locate 4 | # source files 5 | { 6 | 'variables': { 7 | 'pkg-config' : 'pkg-config', 8 | 9 | }, 10 | 11 | 'target_defaults': { 12 | 'cflags':[ 13 | '-Wall', '-Wextra', '-Wno-unused-parameter', '-Werror', '-std=c++11', 14 | '-Wno-unused-variable', 15 | '-Wno-unused-but-set-variable', 16 | #'-O2', 17 | '-ggdb', 18 | ], 19 | 'include_dirs': [ 20 | '<(INCDIR)', 21 | ] 22 | }, 23 | 24 | 'targets': [ 25 | { 26 | 'target_name' : 'miniglog', 27 | 'type': 'static_library', 28 | 'cflags': [], 29 | 'sources': [ 30 | '<(SRCDIR)/third_party/miniglog/glog/logging.cc' 31 | ], 32 | 'include_dirs': [ 33 | '<(SRCDIR)/third_party/miniglog/' 34 | ], 35 | 'direct_dependent_settings': { 36 | 'include_dirs': [ 37 | '<(SRCDIR)/third_party/miniglog/', 38 | ], 39 | } 40 | }, 41 | { 42 | # See gmock README 43 | 'target_name' : 'gtest_mock', 44 | 'type': 'static_library', 45 | 'cflags': [ 46 | '-Wno-missing-field-initializers', 47 | '-isystem <(ROOTDIR)/third_party/gmock-1.7.0/include', 48 | '-isystem <(ROOTDIR)/third_party/gmock-1.7.0/gtest/include', 49 | ], 50 | 'sources':[ 51 | 'third_party/gmock-1.7.0/src/gmock-all.cc', 52 | 'third_party/gmock-1.7.0/src/gmock_main.cc', 53 | 'third_party/gmock-1.7.0/gtest/src/gtest-all.cc', 54 | ], 55 | 'include_dirs': [ 56 | 'third_party/gmock-1.7.0/', 57 | 'third_party/gmock-1.7.0/gtest/', 58 | ], 59 | 'libraries': [ 60 | '-pthread', 61 | ], 62 | 'direct_dependent_settings': { 63 | 'include_dirs': [ 64 | 'third_party/gmock-1.7.0/include', 65 | 'third_party/gmock-1.7.0/gtest/include', 66 | ], 67 | 'libraries': [ 68 | '-lpthread', 69 | ] 70 | }, 71 | }, 72 | { 73 | 'target_name' : 'libmatting', 74 | 'type': 'static_library', 75 | 'sources':[ 76 | '<(SRCDIR)/api.cc', 77 | '<(SRCDIR)/kde.cc', 78 | '<(SRCDIR)/geodesic.cc', 79 | '<(SRCDIR)/matting.cc', 80 | ], 81 | 'include_dirs':[ 82 | '<(FIGTREE)/include/figtree/', 83 | ], 84 | 'direct_dependent_settings': { 85 | 'libraries': [ 86 | '-L<(FIGTREE)/unix/', 87 | '-lfigtree', 88 | ] 89 | }, 90 | 'export_dependent_settings': [ 91 | 'miniglog', 92 | ], 93 | 'dependencies' : [ 94 | 'miniglog', 95 | ] 96 | }, 97 | { 98 | 'target_name' : 'main', 99 | 'type' : 'executable', 100 | 'sources':[ 101 | 'samples/cvutils.cc', 102 | 'samples/main.cc', 103 | ], 104 | 'include_dirs': [ 105 | 'samples', 106 | ], 107 | 'libraries':[ 108 | ' 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "utils.h" 14 | 15 | void WaitForEsc(); 16 | 17 | void ShowImage(const cv::Mat& img, 18 | const std::string& window_name, 19 | bool wait_for_esc=true); 20 | 21 | // Similar to matlab's imagesc 22 | template 23 | void ImageSC(const cv::Mat& img, 24 | const std::string& window_name, 25 | bool wait_for_esc=true, 26 | bool verbose=true, 27 | float Amin=NAN, 28 | float Amax=NAN, 29 | bool colormap=true) { 30 | using namespace std; 31 | if (IsNaN(Amin) || IsNaN(Amax)) { 32 | Amin = *min_element(img.begin(), img.end()); 33 | Amax = *max_element(img.begin(), img.end()); 34 | } 35 | 36 | if (verbose) { 37 | cout << "[ImageSC " << window_name << "] min = " << Amin 38 | << ", max = " << Amax << endl; 39 | } 40 | cv::Mat A_scaled = (img - Amin)/(Amax - Amin); 41 | //LOG(INFO) << "A_scaled max : " << *max_element(A_scaled.begin(), A_scaled.end()); 42 | cv::Mat display; 43 | A_scaled.convertTo(display, CV_8UC1, 255.0, 0); 44 | if (colormap) { 45 | cv::applyColorMap(display, display, cv::COLORMAP_JET); 46 | } 47 | 48 | ShowImage(display, window_name, wait_for_esc); 49 | } 50 | 51 | 52 | 53 | #endif 54 | -------------------------------------------------------------------------------- /unix/samples/interactive.cc: -------------------------------------------------------------------------------- 1 | // InteractiveMatter demo 2 | #include 3 | 4 | #include 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | #include "cvutils.h" 12 | 13 | #include "api.h" 14 | 15 | using boost::scoped_ptr; 16 | using boost::scoped_array; 17 | using namespace std; 18 | using namespace cv; 19 | using namespace std::chrono; 20 | 21 | Mat fg_layer, bg_layer; 22 | enum DrawMode { 23 | DRAW_BG, 24 | DRAW_FG 25 | }; 26 | DrawMode draw_mode = DRAW_BG; 27 | bool drawing = false; 28 | scoped_ptr current_scribble; 29 | scoped_ptr matter; 30 | 31 | // Used to track cursor movements between two MOUSEMOVE events. For example 32 | // on OSX, it seems the MOUSEMOVE events have a somewhat important interval 33 | // between them 34 | int x_prev = -1, y_prev = -1; 35 | 36 | const int SCRIBLE_RADIUS = 5; 37 | 38 | static void DrawScribbleCircle(int x, int y) { 39 | const int radius = SCRIBLE_RADIUS; 40 | const int rr = radius*radius; 41 | for (int dx = -radius; dx <=radius; ++dx) { 42 | for (int dy = -radius; dy <=radius; ++dy) { 43 | if ((dx*dx + dy*dy) <= rr) { 44 | current_scribble->pixels.push_back(::Point2i(x + dx, y + dy)); 45 | if (draw_mode == DRAW_FG) { 46 | fg_layer.at(y + dy, x + dx) = 255; 47 | } else { 48 | bg_layer.at(y + dy, x + dx) = 255; 49 | } 50 | } 51 | } 52 | } 53 | } 54 | 55 | static float Length(const int* vec) { 56 | return sqrt(vec[0]*vec[0] + vec[1]*vec[1]); 57 | } 58 | 59 | static void OnMouse(int event, int x, int y, int, void*) { 60 | if (event == EVENT_LBUTTONDOWN) { 61 | drawing = true; 62 | draw_mode = DRAW_FG; 63 | current_scribble.reset(new Scribble); 64 | current_scribble->background = false; 65 | x_prev = x; 66 | y_prev = y; 67 | } else if (event == EVENT_RBUTTONDOWN) { 68 | drawing = true; 69 | draw_mode = DRAW_BG; 70 | current_scribble.reset(new Scribble); 71 | current_scribble->background = true; 72 | x_prev = x; 73 | y_prev = y; 74 | } else if (event == EVENT_MOUSEMOVE && drawing) { 75 | if (x_prev != -1 && y_prev != -1) { 76 | // Draw scribbles on a line between (x_prev, y_prev) and (x,y), spaced 77 | // by SCRIBBLE_RADIUS 78 | const int d[2] = { x - x_prev, y - y_prev }; 79 | const float len = Length(d); 80 | const float nsteps = len / (float)SCRIBLE_RADIUS; 81 | if (nsteps > 0) { 82 | const float tstep = 1.0f / nsteps; 83 | for (float t = 0; t < 1.0f; t += tstep) { 84 | const int curr_x = (int)(x_prev + t * d[0]); 85 | const int curr_y = (int)(y_prev + t * d[1]); 86 | DrawScribbleCircle(curr_x, curr_y); 87 | } 88 | } 89 | x_prev = x; 90 | y_prev = y; 91 | } 92 | } else if (event == EVENT_LBUTTONUP || event == EVENT_RBUTTONUP) { 93 | if (current_scribble->pixels.size() > 0) { 94 | LOG(INFO) << "-- Adding scribble"; 95 | matter->AddScribble(*current_scribble); 96 | LOG(INFO) << "-- done"; 97 | } else { 98 | LOG(INFO) << "-- Ignoring empty scribble"; 99 | } 100 | current_scribble.reset(); 101 | drawing = false; 102 | x_prev = -1; 103 | y_prev = -1; 104 | } 105 | } 106 | 107 | int main(int argc, char** argv) { 108 | string imgname = "data/default_img.jpg"; 109 | if (argc > 1) { 110 | imgname = argv[1]; 111 | } 112 | 113 | Mat img = imread(imgname, CV_LOAD_IMAGE_COLOR); 114 | CHECK(img.data); 115 | 116 | fg_layer = Mat::zeros(img.rows, img.cols, CV_8UC1); 117 | bg_layer = Mat::zeros(img.rows, img.cols, CV_8UC1); 118 | 119 | namedWindow("img", 0); 120 | setMouseCallback("img", OnMouse, 0); 121 | imshow("img", img); 122 | 123 | //namedWindow("matted", 0); 124 | 125 | cout << "Instructions : " << endl; 126 | cout << "- left click to draw foreground scribbles" << endl; 127 | cout << "- right click to draw background scribbles" << endl; 128 | 129 | const int W = img.cols; 130 | const int H = img.rows; 131 | 132 | // RGB -> lab 133 | cv::Mat img_lab; 134 | cv::cvtColor(img, img_lab, CV_BGR2Lab); 135 | vector lab; 136 | scoped_array lab_l(new uint8_t[W*H]); 137 | lab.push_back(cv::Mat(H, W, CV_8U, lab_l.get())); 138 | scoped_array lab_a(new uint8_t[W*H]); 139 | lab.push_back(cv::Mat(H, W, CV_8U, lab_a.get())); 140 | scoped_array lab_b(new uint8_t[W*H]); 141 | lab.push_back(cv::Mat(H, W, CV_8U, lab_b.get())); 142 | cv::split(img_lab, lab); 143 | 144 | matter.reset(new InteractiveMatter(lab_l.get(), lab_a.get(), lab_b.get(), 145 | W, H)); 146 | 147 | scoped_array fg_likelihood(new double[W*H]); 148 | cv::Mat fg_likelihood_mat(H, W, CV_64F, fg_likelihood.get()); 149 | fg_likelihood_mat.setTo(0); 150 | scoped_array bg_likelihood(new double[W*H]); 151 | cv::Mat bg_likelihood_mat(H, W, CV_64F, bg_likelihood.get()); 152 | bg_likelihood_mat.setTo(0); 153 | 154 | scoped_array fg_dist(new double[W*H]); 155 | Mat fg_dist_mat(H, W, CV_64F, fg_dist.get()); 156 | fg_dist_mat.setTo(0); 157 | scoped_array bg_dist(new double[W*H]); 158 | Mat bg_dist_mat(H, W, CV_64F, bg_dist.get()); 159 | bg_dist_mat.setTo(0); 160 | 161 | scoped_array final_mask(new uint8_t[W*H]); 162 | cv::Mat final_mask_mat(H, W, CV_8UC1, final_mask.get()); 163 | final_mask_mat.setTo(0); 164 | 165 | int nscribbles = matter->NumScribbles(); 166 | 167 | Mat result(img.rows, img.cols, img.type(), Scalar::all(0)); 168 | 169 | while (true) { 170 | auto start = high_resolution_clock::now(); 171 | // http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_core/py_image_arithmetics/py_image_arithmetics.html 172 | // Display scribbles on top of images : 173 | // - fg scribbles are green 174 | // - bg scribbles are red 175 | // - fg and bg scribbles intersections (bad) are pink 176 | Mat disp_img; 177 | img.copyTo(disp_img); 178 | CHECK_EQ(disp_img.type(), CV_8UC3); 179 | 180 | disp_img.setTo(Scalar(0, 255, 0), fg_layer); 181 | disp_img.setTo(Scalar(0, 0, 255), bg_layer); 182 | { 183 | Mat layer_overlap; 184 | bitwise_and(fg_layer, bg_layer, layer_overlap); 185 | disp_img.setTo(Scalar(255, 105, 180), layer_overlap); 186 | } 187 | imshow("img", disp_img); 188 | 189 | // Refresh images from matter if something has changed 190 | if (matter->NumScribbles() != nscribbles) { 191 | LOG(INFO) << "Refreshing from matter"; 192 | matter->GetForegroundLikelihood(fg_likelihood.get()); 193 | matter->GetBackgroundLikelihood(bg_likelihood.get()); 194 | matter->GetForegroundDist(fg_dist.get()); 195 | matter->GetBackgroundDist(bg_dist.get()); 196 | matter->GetForegroundMask(final_mask.get()); 197 | nscribbles = matter->NumScribbles(); 198 | } 199 | ImageSC(fg_likelihood_mat, "fg_likelihood", false, false); 200 | ImageSC(bg_likelihood_mat, "bg_likelihood", false, false); 201 | 202 | ImageSC(fg_dist_mat, "fg_dist", false, false); 203 | ImageSC(bg_dist_mat, "bg_dist", false, false); 204 | 205 | ImageSC(final_mask_mat, "final_mask", false, false); 206 | 207 | result.setTo(0); 208 | img.copyTo(result, final_mask_mat); 209 | ShowImage(result, "result", false); 210 | 211 | auto end = high_resolution_clock::now(); 212 | //LOG(INFO) << "time to display : " 213 | //<< duration_cast(end - start).count() / 1000.0; 214 | //LOG(INFO) << "waitKey"; 215 | const int key = cv::waitKey(30); 216 | if (key == 27 || key == 'q') { 217 | break; 218 | } else if (key == (int)'r') { 219 | // TODO: This is not working 100% correctly 220 | LOG(INFO) << "Reset"; 221 | fg_layer.setTo(0); 222 | bg_layer.setTo(0); 223 | matter.reset(new InteractiveMatter(lab_l.get(), lab_a.get(), 224 | lab_b.get(), W, H)); 225 | } 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /unix/samples/main.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | 16 | #include "utils.h" 17 | #include "kde.h" 18 | #include "geodesic.h" 19 | #include "matting.h" 20 | 21 | #include "cvutils.h" 22 | 23 | using boost::scoped_ptr; 24 | using boost::scoped_array; 25 | using namespace std; 26 | 27 | void SaveVector(const string& filename, const vector& v) { 28 | fstream f(filename.c_str(), fstream::out); 29 | for (size_t i = 0; i < v.size(); ++i) { 30 | f << v[i] << "\t"; 31 | } 32 | f.close(); 33 | } 34 | 35 | // Saves foreground and background density estimation to fname 36 | // channels should be an array of 3 uint8_t W*H array containing channel data 37 | // Those can then be displayed using the plot_densities.py script 38 | void SaveForegroundBackgroundDensities(const uint8_t** channels, 39 | const uint8_t* fg, 40 | const uint8_t* bg, 41 | int W, 42 | int H, 43 | bool median_filter, 44 | const string& fname) { 45 | // For each channel, foreground and background probabilities 46 | vector> fg_prob(3), bg_prob(3); 47 | for (int i = 0; i < 3; ++i) { 48 | ColorChannelKDE(channels[i], fg, W, H, median_filter, &fg_prob[i]); 49 | ColorChannelKDE(channels[i], bg, W, H, median_filter, &bg_prob[i]); 50 | } 51 | 52 | fstream f(fname.c_str(), fstream::out); 53 | for (int c = 0; c < 3; ++c) { 54 | for (int k = 0; k < 2; ++k) { // k == 0 => fg, k == 1 => bg 55 | const vector& v = (k == 0) ? fg_prob[c] : bg_prob[c]; 56 | for (size_t i = 0; i < v.size(); ++i) { 57 | f << v[i] << "\t"; 58 | } 59 | f << endl; 60 | } 61 | } 62 | f.close(); 63 | } 64 | 65 | int main(int argc, char** argv) { 66 | //const string imgname = "data/alphamatting.com/GT18"; 67 | const string imgname = "data/front"; 68 | //const string imgname = "data/cat"; 69 | 70 | // Load input image 71 | cv::Mat img = cv::imread(imgname + ".png", CV_LOAD_IMAGE_COLOR); 72 | CHECK(img.data); 73 | 74 | // Load scribbles and binarize them such that pixels drawn by the user 75 | // have a value of 255 76 | cv::Mat scribble_fg = cv::imread(imgname + "_FG.png", 77 | CV_LOAD_IMAGE_GRAYSCALE); 78 | CHECK(scribble_fg.data); 79 | cv::threshold(scribble_fg, scribble_fg, 1, 255, cv::THRESH_BINARY_INV); 80 | 81 | cv::Mat scribble_bg = cv::imread(imgname + "_BG.png", 82 | CV_LOAD_IMAGE_GRAYSCALE); 83 | CHECK(scribble_bg.data); 84 | cv::threshold(scribble_bg, scribble_bg, 1, 255, cv::THRESH_BINARY_INV); 85 | 86 | cv::Mat img_lab; 87 | // TODO: HSV seems to work much better 88 | //cv::cvtColor(img, img_lab, CV_BGR2HSV); 89 | cv::cvtColor(img, img_lab, CV_BGR2Lab); 90 | CHECK_EQ(img_lab.type(), CV_8UC3); 91 | 92 | // Split the image channels, getting a direct pointer to memory 93 | const int W = img.cols; 94 | const int H = img.rows; 95 | CHECK_EQ(scribble_fg.cols, W); 96 | CHECK_EQ(scribble_fg.rows, H); 97 | CHECK_EQ(scribble_bg.cols, W); 98 | CHECK_EQ(scribble_bg.rows, H); 99 | 100 | LOG(INFO) << "W = " << W << ", H = " << H; 101 | 102 | // Note: OpenCV's Mat uses row major storage 103 | vector lab; 104 | scoped_array lab_l(new uint8_t[W*H]); 105 | lab.push_back(cv::Mat(H, W, CV_8U, lab_l.get())); 106 | scoped_array lab_a(new uint8_t[W*H]); 107 | lab.push_back(cv::Mat(H, W, CV_8U, lab_a.get())); 108 | scoped_array lab_b(new uint8_t[W*H]); 109 | lab.push_back(cv::Mat(H, W, CV_8U, lab_b.get())); 110 | cv::split(img_lab, lab); 111 | 112 | scoped_array fg(new uint8_t[W*H]); 113 | { 114 | cv::Mat fg_mat(H, W, CV_8U, fg.get()); 115 | scribble_fg.copyTo(fg_mat); 116 | } 117 | scoped_array bg(new uint8_t[W*H]); 118 | { 119 | cv::Mat bg_mat(H, W, CV_8U, bg.get()); 120 | scribble_bg.copyTo(bg_mat); 121 | } 122 | 123 | const uint8_t* channels[3] = {lab_l.get(), lab_a.get(), lab_b.get()}; 124 | // Export densities for plot_densities.py script 125 | if (true) { 126 | SaveForegroundBackgroundDensities(channels, fg.get(), bg.get(), W, H, 127 | false, "densities_nomedfilter.txt"); 128 | SaveForegroundBackgroundDensities(channels, fg.get(), bg.get(), W, H, 129 | true, "densities_medfilter.txt"); 130 | LOG(INFO) << "Saved per-channel PDF to .txt"; 131 | } 132 | 133 | ShowImage(scribble_fg, "scribble fg", false); 134 | ShowImage(scribble_bg, "scribble bg", false); 135 | 136 | // Color PDF 137 | scoped_array fg_pdf(new double[W*H]); 138 | scoped_array bg_pdf(new double[W*H]); 139 | ImageColorPDF(channels, fg.get(), W, H, fg_pdf.get()); 140 | // Caution : at first, it might seem bg_pdf = 1 - fg_pdf, but this is not 141 | // the case 142 | ImageColorPDF(channels, bg.get(), W, H, bg_pdf.get()); 143 | 144 | cv::Mat fg_pdf_mat(H, W, CV_64F, fg_pdf.get()); 145 | cv::Mat bg_pdf_mat(H, W, CV_64F, bg_pdf.get()); 146 | ImageSC(fg_pdf_mat, "fg_pdf", false); 147 | ImageSC(bg_pdf_mat, "bg_pdf", false); 148 | //WaitForEsc(); 149 | //return EXIT_SUCCESS; 150 | 151 | // Foreground/Background likelihood 152 | scoped_array fg_like(new double[W*H]); 153 | scoped_array bg_like(new double[W*H]); 154 | cv::Mat fg_like_mat(H, W, CV_64F, fg_like.get()); 155 | cv::Mat bg_like_mat(H, W, CV_64F, bg_like.get()); 156 | ForegroundLikelihood(fg_pdf.get(), bg_pdf.get(), H, W, fg_like.get()); 157 | ForegroundLikelihood(bg_pdf.get(), fg_pdf.get(), H, W, bg_like.get()); 158 | 159 | ImageSC(fg_like_mat, "fg_likelihood", false); 160 | ImageSC(bg_like_mat, "bg_likelihood", false); 161 | 162 | // Distance maps 163 | scoped_array fg_dist(new double[W*H]); 164 | scoped_array bg_dist(new double[W*H]); 165 | cv::Mat fg_dist_mat(H, W, CV_64F, fg_dist.get()); 166 | cv::Mat bg_dist_mat(H, W, CV_64F, bg_dist.get()); 167 | CHECK(scribble_fg.isContinuous()); 168 | CHECK(scribble_bg.isContinuous()); 169 | GeodesicDistanceMap(scribble_fg.ptr(0), fg_like.get(), W, H, 170 | fg_dist.get()); 171 | GeodesicDistanceMap(scribble_bg.ptr(0), bg_like.get(), W, H, 172 | bg_dist.get()); 173 | 174 | // Show both distance maps with the same range 175 | double min1, min2, max1, max2; 176 | minMaxIdx(fg_dist_mat, &min1, &max1, NULL, NULL); 177 | minMaxIdx(bg_dist_mat, &min2, &max2, NULL, NULL); 178 | const double Amin = min(min1, min2); 179 | const double Amax = max(max1, max2); 180 | 181 | ImageSC(fg_dist_mat, "fg_dist", false, true, Amin, Amax); 182 | ImageSC(bg_dist_mat, "bg_dist", false, true, Amin, Amax); 183 | 184 | // Segmentation 185 | cv::Mat fgmask = fg_dist_mat < bg_dist_mat; 186 | CHECK_EQ(fgmask.type(), CV_8U); 187 | ImageSC(fgmask, "fgmask", false); 188 | 189 | //ShowImage(lab[0], "lab[0]", true); 190 | 191 | cv::Mat result; 192 | img.copyTo(result, fgmask); 193 | result.setTo(cv::Scalar(255,255,255), ~fgmask); 194 | ShowImage(result, "result", false); 195 | ShowImage(img, "image", true); 196 | return 0; 197 | } 198 | -------------------------------------------------------------------------------- /unix/samples/simple_interactive.cc: -------------------------------------------------------------------------------- 1 | // SimpleMatter demo 2 | #include 3 | 4 | #include 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | #include "cvutils.h" 12 | 13 | #include "api.h" 14 | 15 | using boost::scoped_ptr; 16 | using boost::scoped_array; 17 | using namespace std; 18 | using namespace cv; 19 | using namespace std::chrono; 20 | 21 | Mat fg_layer, bg_layer; 22 | 23 | enum DrawMode { 24 | DRAW_BG, 25 | DRAW_FG 26 | }; 27 | 28 | DrawMode draw_mode = DRAW_BG; 29 | bool drawing = false; 30 | scoped_ptr matter; 31 | 32 | bool changed = true; 33 | 34 | // Used to track cursor movements between two MOUSEMOVE events. For example 35 | // on OSX, it seems the MOUSEMOVE events have a somewhat important interval 36 | // between them 37 | int x_prev = -1, y_prev = -1; 38 | 39 | const int SCRIBLE_RADIUS = 5; 40 | 41 | static void DrawScribbleCircle(int x, int y) { 42 | const int radius = SCRIBLE_RADIUS; 43 | const int rr = radius*radius; 44 | for (int dx = -radius; dx <=radius; ++dx) { 45 | for (int dy = -radius; dy <=radius; ++dy) { 46 | if ((dx*dx + dy*dy) <= rr) { 47 | if (draw_mode == DRAW_FG) { 48 | fg_layer.at(y + dy, x + dx) = 255; 49 | } else { 50 | bg_layer.at(y + dy, x + dx) = 255; 51 | } 52 | } 53 | } 54 | } 55 | } 56 | 57 | static float Length(const int* vec) { 58 | return sqrt(vec[0]*vec[0] + vec[1]*vec[1]); 59 | } 60 | 61 | static void UpdateMatter() { 62 | LOG(INFO) << "-- Updating masks"; 63 | // Opencv uses row-major like libseg 64 | CHECK(fg_layer.isContinuous()); 65 | CHECK(bg_layer.isContinuous()); 66 | matter->UpdateMasks(bg_layer.ptr(), fg_layer.ptr()); 67 | changed = true; 68 | LOG(INFO) << "-- done"; 69 | } 70 | 71 | static void OnMouse(int event, int x, int y, int, void*) { 72 | if (event == EVENT_LBUTTONDOWN) { 73 | drawing = true; 74 | draw_mode = DRAW_FG; 75 | x_prev = x; 76 | y_prev = y; 77 | } else if (event == EVENT_RBUTTONDOWN) { 78 | drawing = true; 79 | draw_mode = DRAW_BG; 80 | x_prev = x; 81 | y_prev = y; 82 | } else if (event == EVENT_MOUSEMOVE && drawing) { 83 | if (x_prev != -1 && y_prev != -1) { 84 | // Draw scribbles on a line between (x_prev, y_prev) and (x,y), spaced 85 | // by SCRIBBLE_RADIUS 86 | const int d[2] = { x - x_prev, y - y_prev }; 87 | const float len = Length(d); 88 | const float nsteps = len / (float)SCRIBLE_RADIUS; 89 | if (nsteps > 0) { 90 | const float tstep = 1.0f / nsteps; 91 | for (float t = 0; t < 1.0f; t += tstep) { 92 | const int curr_x = (int)(x_prev + t * d[0]); 93 | const int curr_y = (int)(y_prev + t * d[1]); 94 | DrawScribbleCircle(curr_x, curr_y); 95 | } 96 | } 97 | x_prev = x; 98 | y_prev = y; 99 | } 100 | } else if (event == EVENT_LBUTTONUP || event == EVENT_RBUTTONUP) { 101 | UpdateMatter(); 102 | drawing = false; 103 | x_prev = -1; 104 | y_prev = -1; 105 | } 106 | } 107 | 108 | int main(int argc, char** argv) { 109 | string imgname = "data/default_img.jpg"; 110 | if (argc > 1) { 111 | imgname = argv[1]; 112 | } 113 | 114 | Mat img = imread(imgname, CV_LOAD_IMAGE_COLOR); 115 | CHECK(img.data); 116 | 117 | fg_layer = Mat::zeros(img.rows, img.cols, CV_8UC1); 118 | bg_layer = Mat::zeros(img.rows, img.cols, CV_8UC1); 119 | 120 | namedWindow("img", 0); 121 | setMouseCallback("img", OnMouse, 0); 122 | imshow("img", img); 123 | 124 | //namedWindow("matted", 0); 125 | 126 | cout << "Instructions : " << endl; 127 | cout << "- left click to draw foreground scribbles" << endl; 128 | cout << "- right click to draw background scribbles" << endl; 129 | 130 | const int W = img.cols; 131 | const int H = img.rows; 132 | 133 | // RGB -> lab 134 | cv::Mat img_lab; 135 | cv::cvtColor(img, img_lab, CV_BGR2Lab); 136 | vector lab; 137 | scoped_array lab_l(new uint8_t[W*H]); 138 | lab.push_back(cv::Mat(H, W, CV_8U, lab_l.get())); 139 | scoped_array lab_a(new uint8_t[W*H]); 140 | lab.push_back(cv::Mat(H, W, CV_8U, lab_a.get())); 141 | scoped_array lab_b(new uint8_t[W*H]); 142 | lab.push_back(cv::Mat(H, W, CV_8U, lab_b.get())); 143 | cv::split(img_lab, lab); 144 | 145 | matter.reset(new SimpleMatter(lab_l.get(), lab_a.get(), lab_b.get(), 146 | W, H)); 147 | 148 | scoped_array fg_likelihood(new double[W*H]); 149 | cv::Mat fg_likelihood_mat(H, W, CV_64F, fg_likelihood.get()); 150 | fg_likelihood_mat.setTo(0); 151 | scoped_array bg_likelihood(new double[W*H]); 152 | cv::Mat bg_likelihood_mat(H, W, CV_64F, bg_likelihood.get()); 153 | bg_likelihood_mat.setTo(0); 154 | 155 | scoped_array fg_dist(new double[W*H]); 156 | Mat fg_dist_mat(H, W, CV_64F, fg_dist.get()); 157 | fg_dist_mat.setTo(0); 158 | scoped_array bg_dist(new double[W*H]); 159 | Mat bg_dist_mat(H, W, CV_64F, bg_dist.get()); 160 | bg_dist_mat.setTo(0); 161 | 162 | scoped_array final_mask(new uint8_t[W*H]); 163 | cv::Mat final_mask_mat(H, W, CV_8UC1, final_mask.get()); 164 | final_mask_mat.setTo(0); 165 | 166 | Mat result(img.rows, img.cols, img.type(), Scalar::all(0)); 167 | 168 | while (true) { 169 | auto start = high_resolution_clock::now(); 170 | // http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_core/py_image_arithmetics/py_image_arithmetics.html 171 | // Display scribbles on top of images : 172 | // - fg scribbles are green 173 | // - bg scribbles are red 174 | // - fg and bg scribbles intersections (bad) are pink 175 | Mat disp_img; 176 | img.copyTo(disp_img); 177 | CHECK_EQ(disp_img.type(), CV_8UC3); 178 | 179 | disp_img.setTo(Scalar(0, 255, 0), fg_layer); 180 | disp_img.setTo(Scalar(0, 0, 255), bg_layer); 181 | { 182 | Mat layer_overlap; 183 | bitwise_and(fg_layer, bg_layer, layer_overlap); 184 | disp_img.setTo(Scalar(255, 105, 180), layer_overlap); 185 | } 186 | imshow("img", disp_img); 187 | 188 | // Refresh images from matter if something has changed 189 | if (changed) { 190 | LOG(INFO) << "Refreshing from matter"; 191 | matter->GetForegroundLikelihood(fg_likelihood.get()); 192 | matter->GetBackgroundLikelihood(bg_likelihood.get()); 193 | matter->GetForegroundDist(fg_dist.get()); 194 | matter->GetBackgroundDist(bg_dist.get()); 195 | matter->GetForegroundMask(final_mask.get()); 196 | changed = false; 197 | } 198 | ImageSC(fg_likelihood_mat, "fg_likelihood", false, false); 199 | ImageSC(bg_likelihood_mat, "bg_likelihood", false, false); 200 | 201 | ImageSC(fg_dist_mat, "fg_dist", false, false); 202 | ImageSC(bg_dist_mat, "bg_dist", false, false); 203 | 204 | ImageSC(final_mask_mat, "final_mask", false, false); 205 | 206 | result.setTo(0); 207 | img.copyTo(result, final_mask_mat); 208 | ShowImage(result, "result", false); 209 | 210 | auto end = high_resolution_clock::now(); 211 | //LOG(INFO) << "time to display : " 212 | //<< duration_cast(end - start).count() / 1000.0; 213 | //LOG(INFO) << "waitKey"; 214 | const int key = cv::waitKey(30); 215 | if (key == 27 || key == 'q') { 216 | break; 217 | } else if (key == (int)'r') { 218 | LOG(INFO) << "Reset"; 219 | fg_layer.setTo(0); 220 | bg_layer.setTo(0); 221 | matter.reset(new SimpleMatter(lab_l.get(), lab_a.get(), 222 | lab_b.get(), W, H)); 223 | UpdateMatter(); 224 | } 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/CHANGES: -------------------------------------------------------------------------------- 1 | Changes for 1.7.0: 2 | 3 | * All new improvements in Google Test 1.7.0. 4 | * New feature: matchers DoubleNear(), FloatNear(), 5 | NanSensitiveDoubleNear(), NanSensitiveFloatNear(), 6 | UnorderedElementsAre(), UnorderedElementsAreArray(), WhenSorted(), 7 | WhenSortedBy(), IsEmpty(), and SizeIs(). 8 | * Improvement: Google Mock can now be built as a DLL. 9 | * Improvement: when compiled by a C++11 compiler, matchers AllOf() 10 | and AnyOf() can accept an arbitrary number of matchers. 11 | * Improvement: when compiled by a C++11 compiler, matchers 12 | ElementsAreArray() can accept an initializer list. 13 | * Improvement: when exceptions are enabled, a mock method with no 14 | default action now throws instead crashing the test. 15 | * Improvement: added class testing::StringMatchResultListener to aid 16 | definition of composite matchers. 17 | * Improvement: function return types used in MOCK_METHOD*() macros can 18 | now contain unprotected commas. 19 | * Improvement (potentially breaking): EXPECT_THAT() and ASSERT_THAT() 20 | are now more strict in ensuring that the value type and the matcher 21 | type are compatible, catching potential bugs in tests. 22 | * Improvement: Pointee() now works on an optional. 23 | * Improvement: the ElementsAreArray() matcher can now take a vector or 24 | iterator range as input, and makes a copy of its input elements 25 | before the conversion to a Matcher. 26 | * Improvement: the Google Mock Generator can now generate mocks for 27 | some class templates. 28 | * Bug fix: mock object destruction triggerred by another mock object's 29 | destruction no longer hangs. 30 | * Improvement: Google Mock Doctor works better with newer Clang and 31 | GCC now. 32 | * Compatibility fixes. 33 | * Bug/warning fixes. 34 | 35 | Changes for 1.6.0: 36 | 37 | * Compilation is much faster and uses much less memory, especially 38 | when the constructor and destructor of a mock class are moved out of 39 | the class body. 40 | * New matchers: Pointwise(), Each(). 41 | * New actions: ReturnPointee() and ReturnRefOfCopy(). 42 | * CMake support. 43 | * Project files for Visual Studio 2010. 44 | * AllOf() and AnyOf() can handle up-to 10 arguments now. 45 | * Google Mock doctor understands Clang error messages now. 46 | * SetArgPointee<> now accepts string literals. 47 | * gmock_gen.py handles storage specifier macros and template return 48 | types now. 49 | * Compatibility fixes. 50 | * Bug fixes and implementation clean-ups. 51 | * Potentially incompatible changes: disables the harmful 'make install' 52 | command in autotools. 53 | 54 | Potentially breaking changes: 55 | 56 | * The description string for MATCHER*() changes from Python-style 57 | interpolation to an ordinary C++ string expression. 58 | * SetArgumentPointee is deprecated in favor of SetArgPointee. 59 | * Some non-essential project files for Visual Studio 2005 are removed. 60 | 61 | Changes for 1.5.0: 62 | 63 | * New feature: Google Mock can be safely used in multi-threaded tests 64 | on platforms having pthreads. 65 | * New feature: function for printing a value of arbitrary type. 66 | * New feature: function ExplainMatchResult() for easy definition of 67 | composite matchers. 68 | * The new matcher API lets user-defined matchers generate custom 69 | explanations more directly and efficiently. 70 | * Better failure messages all around. 71 | * NotNull() and IsNull() now work with smart pointers. 72 | * Field() and Property() now work when the matcher argument is a pointer 73 | passed by reference. 74 | * Regular expression matchers on all platforms. 75 | * Added GCC 4.0 support for Google Mock Doctor. 76 | * Added gmock_all_test.cc for compiling most Google Mock tests 77 | in a single file. 78 | * Significantly cleaned up compiler warnings. 79 | * Bug fixes, better test coverage, and implementation clean-ups. 80 | 81 | Potentially breaking changes: 82 | 83 | * Custom matchers defined using MatcherInterface or MakePolymorphicMatcher() 84 | need to be updated after upgrading to Google Mock 1.5.0; matchers defined 85 | using MATCHER or MATCHER_P* aren't affected. 86 | * Dropped support for 'make install'. 87 | 88 | Changes for 1.4.0 (we skipped 1.2.* and 1.3.* to match the version of 89 | Google Test): 90 | 91 | * Works in more environments: Symbian and minGW, Visual C++ 7.1. 92 | * Lighter weight: comes with our own implementation of TR1 tuple (no 93 | more dependency on Boost!). 94 | * New feature: --gmock_catch_leaked_mocks for detecting leaked mocks. 95 | * New feature: ACTION_TEMPLATE for defining templatized actions. 96 | * New feature: the .After() clause for specifying expectation order. 97 | * New feature: the .With() clause for for specifying inter-argument 98 | constraints. 99 | * New feature: actions ReturnArg(), ReturnNew(...), and 100 | DeleteArg(). 101 | * New feature: matchers Key(), Pair(), Args<...>(), AllArgs(), IsNull(), 102 | and Contains(). 103 | * New feature: utility class MockFunction, useful for checkpoints, etc. 104 | * New feature: functions Value(x, m) and SafeMatcherCast(m). 105 | * New feature: copying a mock object is rejected at compile time. 106 | * New feature: a script for fusing all Google Mock and Google Test 107 | source files for easy deployment. 108 | * Improved the Google Mock doctor to diagnose more diseases. 109 | * Improved the Google Mock generator script. 110 | * Compatibility fixes for Mac OS X and gcc. 111 | * Bug fixes and implementation clean-ups. 112 | 113 | Changes for 1.1.0: 114 | 115 | * New feature: ability to use Google Mock with any testing framework. 116 | * New feature: macros for easily defining new matchers 117 | * New feature: macros for easily defining new actions. 118 | * New feature: more container matchers. 119 | * New feature: actions for accessing function arguments and throwing 120 | exceptions. 121 | * Improved the Google Mock doctor script for diagnosing compiler errors. 122 | * Bug fixes and implementation clean-ups. 123 | 124 | Changes for 1.0.0: 125 | 126 | * Initial Open Source release of Google Mock 127 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This file contains a list of people who've made non-trivial 2 | # contribution to the Google C++ Mocking Framework project. People 3 | # who commit code to the project are encouraged to add their names 4 | # here. Please keep the list sorted by first names. 5 | 6 | Benoit Sigoure 7 | Bogdan Piloca 8 | Chandler Carruth 9 | Dave MacLachlan 10 | David Anderson 11 | Dean Sturtevant 12 | Gene Volovich 13 | Hal Burch 14 | Jeffrey Yasskin 15 | Jim Keller 16 | Joe Walnes 17 | Jon Wray 18 | Keir Mierle 19 | Keith Ray 20 | Kostya Serebryany 21 | Lev Makhlis 22 | Manuel Klimek 23 | Mario Tanev 24 | Mark Paskin 25 | Markus Heule 26 | Matthew Simmons 27 | Mike Bland 28 | Neal Norwitz 29 | Nermin Ozkiranartli 30 | Owen Carlsen 31 | Paneendra Ba 32 | Paul Menage 33 | Piotr Kaminski 34 | Russ Rufer 35 | Sverre Sundsdal 36 | Takeshi Yoshino 37 | Vadim Berman 38 | Vlad Losev 39 | Wolfgang Klier 40 | Zhanyong Wan 41 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2008, Google Inc. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above 11 | copyright notice, this list of conditions and the following disclaimer 12 | in the documentation and/or other materials provided with the 13 | distribution. 14 | * Neither the name of Google Inc. nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/CHANGES: -------------------------------------------------------------------------------- 1 | Changes for 1.7.0: 2 | 3 | * New feature: death tests are supported on OpenBSD and in iOS 4 | simulator now. 5 | * New feature: Google Test now implements a protocol to allow 6 | a test runner to detect that a test program has exited 7 | prematurely and report it as a failure (before it would be 8 | falsely reported as a success if the exit code is 0). 9 | * New feature: Test::RecordProperty() can now be used outside of the 10 | lifespan of a test method, in which case it will be attributed to 11 | the current test case or the test program in the XML report. 12 | * New feature (potentially breaking): --gtest_list_tests now prints 13 | the type parameters and value parameters for each test. 14 | * Improvement: char pointers and char arrays are now escaped properly 15 | in failure messages. 16 | * Improvement: failure summary in XML reports now includes file and 17 | line information. 18 | * Improvement: the XML element now has a timestamp attribute. 19 | * Improvement: When --gtest_filter is specified, XML report now doesn't 20 | contain information about tests that are filtered out. 21 | * Fixed the bug where long --gtest_filter flag values are truncated in 22 | death tests. 23 | * Potentially breaking change: RUN_ALL_TESTS() is now implemented as a 24 | function instead of a macro in order to work better with Clang. 25 | * Compatibility fixes with C++ 11 and various platforms. 26 | * Bug/warning fixes. 27 | 28 | Changes for 1.6.0: 29 | 30 | * New feature: ADD_FAILURE_AT() for reporting a test failure at the 31 | given source location -- useful for writing testing utilities. 32 | * New feature: the universal value printer is moved from Google Mock 33 | to Google Test. 34 | * New feature: type parameters and value parameters are reported in 35 | the XML report now. 36 | * A gtest_disable_pthreads CMake option. 37 | * Colored output works in GNU Screen sessions now. 38 | * Parameters of value-parameterized tests are now printed in the 39 | textual output. 40 | * Failures from ad hoc test assertions run before RUN_ALL_TESTS() are 41 | now correctly reported. 42 | * Arguments of ASSERT_XY and EXPECT_XY no longer need to support << to 43 | ostream. 44 | * More complete handling of exceptions. 45 | * GTEST_ASSERT_XY can be used instead of ASSERT_XY in case the latter 46 | name is already used by another library. 47 | * --gtest_catch_exceptions is now true by default, allowing a test 48 | program to continue after an exception is thrown. 49 | * Value-parameterized test fixtures can now derive from Test and 50 | WithParamInterface separately, easing conversion of legacy tests. 51 | * Death test messages are clearly marked to make them more 52 | distinguishable from other messages. 53 | * Compatibility fixes for Android, Google Native Client, MinGW, HP UX, 54 | PowerPC, Lucid autotools, libCStd, Sun C++, Borland C++ Builder (Code Gear), 55 | IBM XL C++ (Visual Age C++), and C++0x. 56 | * Bug fixes and implementation clean-ups. 57 | * Potentially incompatible changes: disables the harmful 'make install' 58 | command in autotools. 59 | 60 | Changes for 1.5.0: 61 | 62 | * New feature: assertions can be safely called in multiple threads 63 | where the pthreads library is available. 64 | * New feature: predicates used inside EXPECT_TRUE() and friends 65 | can now generate custom failure messages. 66 | * New feature: Google Test can now be compiled as a DLL. 67 | * New feature: fused source files are included. 68 | * New feature: prints help when encountering unrecognized Google Test flags. 69 | * Experimental feature: CMake build script (requires CMake 2.6.4+). 70 | * Experimental feature: the Pump script for meta programming. 71 | * double values streamed to an assertion are printed with enough precision 72 | to differentiate any two different values. 73 | * Google Test now works on Solaris and AIX. 74 | * Build and test script improvements. 75 | * Bug fixes and implementation clean-ups. 76 | 77 | Potentially breaking changes: 78 | 79 | * Stopped supporting VC++ 7.1 with exceptions disabled. 80 | * Dropped support for 'make install'. 81 | 82 | Changes for 1.4.0: 83 | 84 | * New feature: the event listener API 85 | * New feature: test shuffling 86 | * New feature: the XML report format is closer to junitreport and can 87 | be parsed by Hudson now. 88 | * New feature: when a test runs under Visual Studio, its failures are 89 | integrated in the IDE. 90 | * New feature: /MD(d) versions of VC++ projects. 91 | * New feature: elapsed time for the tests is printed by default. 92 | * New feature: comes with a TR1 tuple implementation such that Boost 93 | is no longer needed for Combine(). 94 | * New feature: EXPECT_DEATH_IF_SUPPORTED macro and friends. 95 | * New feature: the Xcode project can now produce static gtest 96 | libraries in addition to a framework. 97 | * Compatibility fixes for Solaris, Cygwin, minGW, Windows Mobile, 98 | Symbian, gcc, and C++Builder. 99 | * Bug fixes and implementation clean-ups. 100 | 101 | Changes for 1.3.0: 102 | 103 | * New feature: death tests on Windows, Cygwin, and Mac. 104 | * New feature: ability to use Google Test assertions in other testing 105 | frameworks. 106 | * New feature: ability to run disabled test via 107 | --gtest_also_run_disabled_tests. 108 | * New feature: the --help flag for printing the usage. 109 | * New feature: access to Google Test flag values in user code. 110 | * New feature: a script that packs Google Test into one .h and one 111 | .cc file for easy deployment. 112 | * New feature: support for distributing test functions to multiple 113 | machines (requires support from the test runner). 114 | * Bug fixes and implementation clean-ups. 115 | 116 | Changes for 1.2.1: 117 | 118 | * Compatibility fixes for Linux IA-64 and IBM z/OS. 119 | * Added support for using Boost and other TR1 implementations. 120 | * Changes to the build scripts to support upcoming release of Google C++ 121 | Mocking Framework. 122 | * Added Makefile to the distribution package. 123 | * Improved build instructions in README. 124 | 125 | Changes for 1.2.0: 126 | 127 | * New feature: value-parameterized tests. 128 | * New feature: the ASSERT/EXPECT_(NON)FATAL_FAILURE(_ON_ALL_THREADS) 129 | macros. 130 | * Changed the XML report format to match JUnit/Ant's. 131 | * Added tests to the Xcode project. 132 | * Added scons/SConscript for building with SCons. 133 | * Added src/gtest-all.cc for building Google Test from a single file. 134 | * Fixed compatibility with Solaris and z/OS. 135 | * Enabled running Python tests on systems with python 2.3 installed, 136 | e.g. Mac OS X 10.4. 137 | * Bug fixes. 138 | 139 | Changes for 1.1.0: 140 | 141 | * New feature: type-parameterized tests. 142 | * New feature: exception assertions. 143 | * New feature: printing elapsed time of tests. 144 | * Improved the robustness of death tests. 145 | * Added an Xcode project and samples. 146 | * Adjusted the output format on Windows to be understandable by Visual Studio. 147 | * Minor bug fixes. 148 | 149 | Changes for 1.0.1: 150 | 151 | * Added project files for Visual Studio 7.1. 152 | * Fixed issues with compiling on Mac OS X. 153 | * Fixed issues with compiling on Cygwin. 154 | 155 | Changes for 1.0.0: 156 | 157 | * Initial Open Source release of Google Test 158 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This file contains a list of people who've made non-trivial 2 | # contribution to the Google C++ Testing Framework project. People 3 | # who commit code to the project are encouraged to add their names 4 | # here. Please keep the list sorted by first names. 5 | 6 | Ajay Joshi 7 | Balázs Dán 8 | Bharat Mediratta 9 | Chandler Carruth 10 | Chris Prince 11 | Chris Taylor 12 | Dan Egnor 13 | Eric Roman 14 | Hady Zalek 15 | Jeffrey Yasskin 16 | Jói Sigurðsson 17 | Keir Mierle 18 | Keith Ray 19 | Kenton Varda 20 | Manuel Klimek 21 | Markus Heule 22 | Mika Raento 23 | Miklós Fazekas 24 | Pasi Valminen 25 | Patrick Hanna 26 | Patrick Riley 27 | Peter Kaminski 28 | Preston Jackson 29 | Rainer Klaffenboeck 30 | Russ Cox 31 | Russ Rufer 32 | Sean Mcafee 33 | Sigurður Ásgeirsson 34 | Tracy Bialik 35 | Vadim Berman 36 | Vlad Losev 37 | Zhanyong Wan 38 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2008, Google Inc. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above 11 | copyright notice, this list of conditions and the following disclaimer 12 | in the documentation and/or other materials provided with the 13 | distribution. 14 | * Neither the name of Google Inc. nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/include/gtest/gtest-message.h: -------------------------------------------------------------------------------- 1 | // Copyright 2005, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | // 32 | // The Google C++ Testing Framework (Google Test) 33 | // 34 | // This header file defines the Message class. 35 | // 36 | // IMPORTANT NOTE: Due to limitation of the C++ language, we have to 37 | // leave some internal implementation details in this header file. 38 | // They are clearly marked by comments like this: 39 | // 40 | // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 41 | // 42 | // Such code is NOT meant to be used by a user directly, and is subject 43 | // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user 44 | // program! 45 | 46 | #ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ 47 | #define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ 48 | 49 | #include 50 | 51 | #include "gtest/internal/gtest-port.h" 52 | 53 | // Ensures that there is at least one operator<< in the global namespace. 54 | // See Message& operator<<(...) below for why. 55 | void operator<<(const testing::internal::Secret&, int); 56 | 57 | namespace testing { 58 | 59 | // The Message class works like an ostream repeater. 60 | // 61 | // Typical usage: 62 | // 63 | // 1. You stream a bunch of values to a Message object. 64 | // It will remember the text in a stringstream. 65 | // 2. Then you stream the Message object to an ostream. 66 | // This causes the text in the Message to be streamed 67 | // to the ostream. 68 | // 69 | // For example; 70 | // 71 | // testing::Message foo; 72 | // foo << 1 << " != " << 2; 73 | // std::cout << foo; 74 | // 75 | // will print "1 != 2". 76 | // 77 | // Message is not intended to be inherited from. In particular, its 78 | // destructor is not virtual. 79 | // 80 | // Note that stringstream behaves differently in gcc and in MSVC. You 81 | // can stream a NULL char pointer to it in the former, but not in the 82 | // latter (it causes an access violation if you do). The Message 83 | // class hides this difference by treating a NULL char pointer as 84 | // "(null)". 85 | class GTEST_API_ Message { 86 | private: 87 | // The type of basic IO manipulators (endl, ends, and flush) for 88 | // narrow streams. 89 | typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); 90 | 91 | public: 92 | // Constructs an empty Message. 93 | Message(); 94 | 95 | // Copy constructor. 96 | Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT 97 | *ss_ << msg.GetString(); 98 | } 99 | 100 | // Constructs a Message from a C-string. 101 | explicit Message(const char* str) : ss_(new ::std::stringstream) { 102 | *ss_ << str; 103 | } 104 | 105 | #if GTEST_OS_SYMBIAN 106 | // Streams a value (either a pointer or not) to this object. 107 | template 108 | inline Message& operator <<(const T& value) { 109 | StreamHelper(typename internal::is_pointer::type(), value); 110 | return *this; 111 | } 112 | #else 113 | // Streams a non-pointer value to this object. 114 | template 115 | inline Message& operator <<(const T& val) { 116 | // Some libraries overload << for STL containers. These 117 | // overloads are defined in the global namespace instead of ::std. 118 | // 119 | // C++'s symbol lookup rule (i.e. Koenig lookup) says that these 120 | // overloads are visible in either the std namespace or the global 121 | // namespace, but not other namespaces, including the testing 122 | // namespace which Google Test's Message class is in. 123 | // 124 | // To allow STL containers (and other types that has a << operator 125 | // defined in the global namespace) to be used in Google Test 126 | // assertions, testing::Message must access the custom << operator 127 | // from the global namespace. With this using declaration, 128 | // overloads of << defined in the global namespace and those 129 | // visible via Koenig lookup are both exposed in this function. 130 | using ::operator <<; 131 | *ss_ << val; 132 | return *this; 133 | } 134 | 135 | // Streams a pointer value to this object. 136 | // 137 | // This function is an overload of the previous one. When you 138 | // stream a pointer to a Message, this definition will be used as it 139 | // is more specialized. (The C++ Standard, section 140 | // [temp.func.order].) If you stream a non-pointer, then the 141 | // previous definition will be used. 142 | // 143 | // The reason for this overload is that streaming a NULL pointer to 144 | // ostream is undefined behavior. Depending on the compiler, you 145 | // may get "0", "(nil)", "(null)", or an access violation. To 146 | // ensure consistent result across compilers, we always treat NULL 147 | // as "(null)". 148 | template 149 | inline Message& operator <<(T* const& pointer) { // NOLINT 150 | if (pointer == NULL) { 151 | *ss_ << "(null)"; 152 | } else { 153 | *ss_ << pointer; 154 | } 155 | return *this; 156 | } 157 | #endif // GTEST_OS_SYMBIAN 158 | 159 | // Since the basic IO manipulators are overloaded for both narrow 160 | // and wide streams, we have to provide this specialized definition 161 | // of operator <<, even though its body is the same as the 162 | // templatized version above. Without this definition, streaming 163 | // endl or other basic IO manipulators to Message will confuse the 164 | // compiler. 165 | Message& operator <<(BasicNarrowIoManip val) { 166 | *ss_ << val; 167 | return *this; 168 | } 169 | 170 | // Instead of 1/0, we want to see true/false for bool values. 171 | Message& operator <<(bool b) { 172 | return *this << (b ? "true" : "false"); 173 | } 174 | 175 | // These two overloads allow streaming a wide C string to a Message 176 | // using the UTF-8 encoding. 177 | Message& operator <<(const wchar_t* wide_c_str); 178 | Message& operator <<(wchar_t* wide_c_str); 179 | 180 | #if GTEST_HAS_STD_WSTRING 181 | // Converts the given wide string to a narrow string using the UTF-8 182 | // encoding, and streams the result to this Message object. 183 | Message& operator <<(const ::std::wstring& wstr); 184 | #endif // GTEST_HAS_STD_WSTRING 185 | 186 | #if GTEST_HAS_GLOBAL_WSTRING 187 | // Converts the given wide string to a narrow string using the UTF-8 188 | // encoding, and streams the result to this Message object. 189 | Message& operator <<(const ::wstring& wstr); 190 | #endif // GTEST_HAS_GLOBAL_WSTRING 191 | 192 | // Gets the text streamed to this object so far as an std::string. 193 | // Each '\0' character in the buffer is replaced with "\\0". 194 | // 195 | // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 196 | std::string GetString() const; 197 | 198 | private: 199 | 200 | #if GTEST_OS_SYMBIAN 201 | // These are needed as the Nokia Symbian Compiler cannot decide between 202 | // const T& and const T* in a function template. The Nokia compiler _can_ 203 | // decide between class template specializations for T and T*, so a 204 | // tr1::type_traits-like is_pointer works, and we can overload on that. 205 | template 206 | inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) { 207 | if (pointer == NULL) { 208 | *ss_ << "(null)"; 209 | } else { 210 | *ss_ << pointer; 211 | } 212 | } 213 | template 214 | inline void StreamHelper(internal::false_type /*is_pointer*/, 215 | const T& value) { 216 | // See the comments in Message& operator <<(const T&) above for why 217 | // we need this using statement. 218 | using ::operator <<; 219 | *ss_ << value; 220 | } 221 | #endif // GTEST_OS_SYMBIAN 222 | 223 | // We'll hold the text streamed to this object here. 224 | const internal::scoped_ptr< ::std::stringstream> ss_; 225 | 226 | // We declare (but don't implement) this to prevent the compiler 227 | // from implementing the assignment operator. 228 | void operator=(const Message&); 229 | }; 230 | 231 | // Streams a Message to an ostream. 232 | inline std::ostream& operator <<(std::ostream& os, const Message& sb) { 233 | return os << sb.GetString(); 234 | } 235 | 236 | namespace internal { 237 | 238 | // Converts a streamable value to an std::string. A NULL pointer is 239 | // converted to "(null)". When the input value is a ::string, 240 | // ::std::string, ::wstring, or ::std::wstring object, each NUL 241 | // character in it is replaced with "\\0". 242 | template 243 | std::string StreamableToString(const T& streamable) { 244 | return (Message() << streamable).GetString(); 245 | } 246 | 247 | } // namespace internal 248 | } // namespace testing 249 | 250 | #endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ 251 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/include/gtest/gtest-test-part.h: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: mheule@google.com (Markus Heule) 31 | // 32 | 33 | #ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ 34 | #define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ 35 | 36 | #include 37 | #include 38 | #include "gtest/internal/gtest-internal.h" 39 | #include "gtest/internal/gtest-string.h" 40 | 41 | namespace testing { 42 | 43 | // A copyable object representing the result of a test part (i.e. an 44 | // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). 45 | // 46 | // Don't inherit from TestPartResult as its destructor is not virtual. 47 | class GTEST_API_ TestPartResult { 48 | public: 49 | // The possible outcomes of a test part (i.e. an assertion or an 50 | // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). 51 | enum Type { 52 | kSuccess, // Succeeded. 53 | kNonFatalFailure, // Failed but the test can continue. 54 | kFatalFailure // Failed and the test should be terminated. 55 | }; 56 | 57 | // C'tor. TestPartResult does NOT have a default constructor. 58 | // Always use this constructor (with parameters) to create a 59 | // TestPartResult object. 60 | TestPartResult(Type a_type, 61 | const char* a_file_name, 62 | int a_line_number, 63 | const char* a_message) 64 | : type_(a_type), 65 | file_name_(a_file_name == NULL ? "" : a_file_name), 66 | line_number_(a_line_number), 67 | summary_(ExtractSummary(a_message)), 68 | message_(a_message) { 69 | } 70 | 71 | // Gets the outcome of the test part. 72 | Type type() const { return type_; } 73 | 74 | // Gets the name of the source file where the test part took place, or 75 | // NULL if it's unknown. 76 | const char* file_name() const { 77 | return file_name_.empty() ? NULL : file_name_.c_str(); 78 | } 79 | 80 | // Gets the line in the source file where the test part took place, 81 | // or -1 if it's unknown. 82 | int line_number() const { return line_number_; } 83 | 84 | // Gets the summary of the failure message. 85 | const char* summary() const { return summary_.c_str(); } 86 | 87 | // Gets the message associated with the test part. 88 | const char* message() const { return message_.c_str(); } 89 | 90 | // Returns true iff the test part passed. 91 | bool passed() const { return type_ == kSuccess; } 92 | 93 | // Returns true iff the test part failed. 94 | bool failed() const { return type_ != kSuccess; } 95 | 96 | // Returns true iff the test part non-fatally failed. 97 | bool nonfatally_failed() const { return type_ == kNonFatalFailure; } 98 | 99 | // Returns true iff the test part fatally failed. 100 | bool fatally_failed() const { return type_ == kFatalFailure; } 101 | 102 | private: 103 | Type type_; 104 | 105 | // Gets the summary of the failure message by omitting the stack 106 | // trace in it. 107 | static std::string ExtractSummary(const char* message); 108 | 109 | // The name of the source file where the test part took place, or 110 | // "" if the source file is unknown. 111 | std::string file_name_; 112 | // The line in the source file where the test part took place, or -1 113 | // if the line number is unknown. 114 | int line_number_; 115 | std::string summary_; // The test failure summary. 116 | std::string message_; // The test failure message. 117 | }; 118 | 119 | // Prints a TestPartResult object. 120 | std::ostream& operator<<(std::ostream& os, const TestPartResult& result); 121 | 122 | // An array of TestPartResult objects. 123 | // 124 | // Don't inherit from TestPartResultArray as its destructor is not 125 | // virtual. 126 | class GTEST_API_ TestPartResultArray { 127 | public: 128 | TestPartResultArray() {} 129 | 130 | // Appends the given TestPartResult to the array. 131 | void Append(const TestPartResult& result); 132 | 133 | // Returns the TestPartResult at the given index (0-based). 134 | const TestPartResult& GetTestPartResult(int index) const; 135 | 136 | // Returns the number of TestPartResult objects in the array. 137 | int size() const; 138 | 139 | private: 140 | std::vector array_; 141 | 142 | GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); 143 | }; 144 | 145 | // This interface knows how to report a test part result. 146 | class TestPartResultReporterInterface { 147 | public: 148 | virtual ~TestPartResultReporterInterface() {} 149 | 150 | virtual void ReportTestPartResult(const TestPartResult& result) = 0; 151 | }; 152 | 153 | namespace internal { 154 | 155 | // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a 156 | // statement generates new fatal failures. To do so it registers itself as the 157 | // current test part result reporter. Besides checking if fatal failures were 158 | // reported, it only delegates the reporting to the former result reporter. 159 | // The original result reporter is restored in the destructor. 160 | // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 161 | class GTEST_API_ HasNewFatalFailureHelper 162 | : public TestPartResultReporterInterface { 163 | public: 164 | HasNewFatalFailureHelper(); 165 | virtual ~HasNewFatalFailureHelper(); 166 | virtual void ReportTestPartResult(const TestPartResult& result); 167 | bool has_new_fatal_failure() const { return has_new_fatal_failure_; } 168 | private: 169 | bool has_new_fatal_failure_; 170 | TestPartResultReporterInterface* original_reporter_; 171 | 172 | GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); 173 | }; 174 | 175 | } // namespace internal 176 | 177 | } // namespace testing 178 | 179 | #endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ 180 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/include/gtest/gtest_prod.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | // 32 | // Google C++ Testing Framework definitions useful in production code. 33 | 34 | #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ 35 | #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ 36 | 37 | // When you need to test the private or protected members of a class, 38 | // use the FRIEND_TEST macro to declare your tests as friends of the 39 | // class. For example: 40 | // 41 | // class MyClass { 42 | // private: 43 | // void MyMethod(); 44 | // FRIEND_TEST(MyClassTest, MyMethod); 45 | // }; 46 | // 47 | // class MyClassTest : public testing::Test { 48 | // // ... 49 | // }; 50 | // 51 | // TEST_F(MyClassTest, MyMethod) { 52 | // // Can call MyClass::MyMethod() here. 53 | // } 54 | 55 | #define FRIEND_TEST(test_case_name, test_name)\ 56 | friend class test_case_name##_##test_name##_Test 57 | 58 | #endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_ 59 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/include/gtest/internal/gtest-linked_ptr.h: -------------------------------------------------------------------------------- 1 | // Copyright 2003 Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Authors: Dan Egnor (egnor@google.com) 31 | // 32 | // A "smart" pointer type with reference tracking. Every pointer to a 33 | // particular object is kept on a circular linked list. When the last pointer 34 | // to an object is destroyed or reassigned, the object is deleted. 35 | // 36 | // Used properly, this deletes the object when the last reference goes away. 37 | // There are several caveats: 38 | // - Like all reference counting schemes, cycles lead to leaks. 39 | // - Each smart pointer is actually two pointers (8 bytes instead of 4). 40 | // - Every time a pointer is assigned, the entire list of pointers to that 41 | // object is traversed. This class is therefore NOT SUITABLE when there 42 | // will often be more than two or three pointers to a particular object. 43 | // - References are only tracked as long as linked_ptr<> objects are copied. 44 | // If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS 45 | // will happen (double deletion). 46 | // 47 | // A good use of this class is storing object references in STL containers. 48 | // You can safely put linked_ptr<> in a vector<>. 49 | // Other uses may not be as good. 50 | // 51 | // Note: If you use an incomplete type with linked_ptr<>, the class 52 | // *containing* linked_ptr<> must have a constructor and destructor (even 53 | // if they do nothing!). 54 | // 55 | // Bill Gibbons suggested we use something like this. 56 | // 57 | // Thread Safety: 58 | // Unlike other linked_ptr implementations, in this implementation 59 | // a linked_ptr object is thread-safe in the sense that: 60 | // - it's safe to copy linked_ptr objects concurrently, 61 | // - it's safe to copy *from* a linked_ptr and read its underlying 62 | // raw pointer (e.g. via get()) concurrently, and 63 | // - it's safe to write to two linked_ptrs that point to the same 64 | // shared object concurrently. 65 | // TODO(wan@google.com): rename this to safe_linked_ptr to avoid 66 | // confusion with normal linked_ptr. 67 | 68 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ 69 | #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ 70 | 71 | #include 72 | #include 73 | 74 | #include "gtest/internal/gtest-port.h" 75 | 76 | namespace testing { 77 | namespace internal { 78 | 79 | // Protects copying of all linked_ptr objects. 80 | GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); 81 | 82 | // This is used internally by all instances of linked_ptr<>. It needs to be 83 | // a non-template class because different types of linked_ptr<> can refer to 84 | // the same object (linked_ptr(obj) vs linked_ptr(obj)). 85 | // So, it needs to be possible for different types of linked_ptr to participate 86 | // in the same circular linked list, so we need a single class type here. 87 | // 88 | // DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr. 89 | class linked_ptr_internal { 90 | public: 91 | // Create a new circle that includes only this instance. 92 | void join_new() { 93 | next_ = this; 94 | } 95 | 96 | // Many linked_ptr operations may change p.link_ for some linked_ptr 97 | // variable p in the same circle as this object. Therefore we need 98 | // to prevent two such operations from occurring concurrently. 99 | // 100 | // Note that different types of linked_ptr objects can coexist in a 101 | // circle (e.g. linked_ptr, linked_ptr, and 102 | // linked_ptr). Therefore we must use a single mutex to 103 | // protect all linked_ptr objects. This can create serious 104 | // contention in production code, but is acceptable in a testing 105 | // framework. 106 | 107 | // Join an existing circle. 108 | void join(linked_ptr_internal const* ptr) 109 | GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { 110 | MutexLock lock(&g_linked_ptr_mutex); 111 | 112 | linked_ptr_internal const* p = ptr; 113 | while (p->next_ != ptr) p = p->next_; 114 | p->next_ = this; 115 | next_ = ptr; 116 | } 117 | 118 | // Leave whatever circle we're part of. Returns true if we were the 119 | // last member of the circle. Once this is done, you can join() another. 120 | bool depart() 121 | GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { 122 | MutexLock lock(&g_linked_ptr_mutex); 123 | 124 | if (next_ == this) return true; 125 | linked_ptr_internal const* p = next_; 126 | while (p->next_ != this) p = p->next_; 127 | p->next_ = next_; 128 | return false; 129 | } 130 | 131 | private: 132 | mutable linked_ptr_internal const* next_; 133 | }; 134 | 135 | template 136 | class linked_ptr { 137 | public: 138 | typedef T element_type; 139 | 140 | // Take over ownership of a raw pointer. This should happen as soon as 141 | // possible after the object is created. 142 | explicit linked_ptr(T* ptr = NULL) { capture(ptr); } 143 | ~linked_ptr() { depart(); } 144 | 145 | // Copy an existing linked_ptr<>, adding ourselves to the list of references. 146 | template linked_ptr(linked_ptr const& ptr) { copy(&ptr); } 147 | linked_ptr(linked_ptr const& ptr) { // NOLINT 148 | assert(&ptr != this); 149 | copy(&ptr); 150 | } 151 | 152 | // Assignment releases the old value and acquires the new. 153 | template linked_ptr& operator=(linked_ptr const& ptr) { 154 | depart(); 155 | copy(&ptr); 156 | return *this; 157 | } 158 | 159 | linked_ptr& operator=(linked_ptr const& ptr) { 160 | if (&ptr != this) { 161 | depart(); 162 | copy(&ptr); 163 | } 164 | return *this; 165 | } 166 | 167 | // Smart pointer members. 168 | void reset(T* ptr = NULL) { 169 | depart(); 170 | capture(ptr); 171 | } 172 | T* get() const { return value_; } 173 | T* operator->() const { return value_; } 174 | T& operator*() const { return *value_; } 175 | 176 | bool operator==(T* p) const { return value_ == p; } 177 | bool operator!=(T* p) const { return value_ != p; } 178 | template 179 | bool operator==(linked_ptr const& ptr) const { 180 | return value_ == ptr.get(); 181 | } 182 | template 183 | bool operator!=(linked_ptr const& ptr) const { 184 | return value_ != ptr.get(); 185 | } 186 | 187 | private: 188 | template 189 | friend class linked_ptr; 190 | 191 | T* value_; 192 | linked_ptr_internal link_; 193 | 194 | void depart() { 195 | if (link_.depart()) delete value_; 196 | } 197 | 198 | void capture(T* ptr) { 199 | value_ = ptr; 200 | link_.join_new(); 201 | } 202 | 203 | template void copy(linked_ptr const* ptr) { 204 | value_ = ptr->get(); 205 | if (value_) 206 | link_.join(&ptr->link_); 207 | else 208 | link_.join_new(); 209 | } 210 | }; 211 | 212 | template inline 213 | bool operator==(T* ptr, const linked_ptr& x) { 214 | return ptr == x.get(); 215 | } 216 | 217 | template inline 218 | bool operator!=(T* ptr, const linked_ptr& x) { 219 | return ptr != x.get(); 220 | } 221 | 222 | // A function to convert T* into linked_ptr 223 | // Doing e.g. make_linked_ptr(new FooBarBaz(arg)) is a shorter notation 224 | // for linked_ptr >(new FooBarBaz(arg)) 225 | template 226 | linked_ptr make_linked_ptr(T* ptr) { 227 | return linked_ptr(ptr); 228 | } 229 | 230 | } // namespace internal 231 | } // namespace testing 232 | 233 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ 234 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/include/gtest/internal/gtest-string.h: -------------------------------------------------------------------------------- 1 | // Copyright 2005, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) 31 | // 32 | // The Google C++ Testing Framework (Google Test) 33 | // 34 | // This header file declares the String class and functions used internally by 35 | // Google Test. They are subject to change without notice. They should not used 36 | // by code external to Google Test. 37 | // 38 | // This header file is #included by . 39 | // It should not be #included by other files. 40 | 41 | #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ 42 | #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ 43 | 44 | #ifdef __BORLANDC__ 45 | // string.h is not guaranteed to provide strcpy on C++ Builder. 46 | # include 47 | #endif 48 | 49 | #include 50 | #include 51 | 52 | #include "gtest/internal/gtest-port.h" 53 | 54 | namespace testing { 55 | namespace internal { 56 | 57 | // String - an abstract class holding static string utilities. 58 | class GTEST_API_ String { 59 | public: 60 | // Static utility methods 61 | 62 | // Clones a 0-terminated C string, allocating memory using new. The 63 | // caller is responsible for deleting the return value using 64 | // delete[]. Returns the cloned string, or NULL if the input is 65 | // NULL. 66 | // 67 | // This is different from strdup() in string.h, which allocates 68 | // memory using malloc(). 69 | static const char* CloneCString(const char* c_str); 70 | 71 | #if GTEST_OS_WINDOWS_MOBILE 72 | // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be 73 | // able to pass strings to Win32 APIs on CE we need to convert them 74 | // to 'Unicode', UTF-16. 75 | 76 | // Creates a UTF-16 wide string from the given ANSI string, allocating 77 | // memory using new. The caller is responsible for deleting the return 78 | // value using delete[]. Returns the wide string, or NULL if the 79 | // input is NULL. 80 | // 81 | // The wide string is created using the ANSI codepage (CP_ACP) to 82 | // match the behaviour of the ANSI versions of Win32 calls and the 83 | // C runtime. 84 | static LPCWSTR AnsiToUtf16(const char* c_str); 85 | 86 | // Creates an ANSI string from the given wide string, allocating 87 | // memory using new. The caller is responsible for deleting the return 88 | // value using delete[]. Returns the ANSI string, or NULL if the 89 | // input is NULL. 90 | // 91 | // The returned string is created using the ANSI codepage (CP_ACP) to 92 | // match the behaviour of the ANSI versions of Win32 calls and the 93 | // C runtime. 94 | static const char* Utf16ToAnsi(LPCWSTR utf16_str); 95 | #endif 96 | 97 | // Compares two C strings. Returns true iff they have the same content. 98 | // 99 | // Unlike strcmp(), this function can handle NULL argument(s). A 100 | // NULL C string is considered different to any non-NULL C string, 101 | // including the empty string. 102 | static bool CStringEquals(const char* lhs, const char* rhs); 103 | 104 | // Converts a wide C string to a String using the UTF-8 encoding. 105 | // NULL will be converted to "(null)". If an error occurred during 106 | // the conversion, "(failed to convert from wide string)" is 107 | // returned. 108 | static std::string ShowWideCString(const wchar_t* wide_c_str); 109 | 110 | // Compares two wide C strings. Returns true iff they have the same 111 | // content. 112 | // 113 | // Unlike wcscmp(), this function can handle NULL argument(s). A 114 | // NULL C string is considered different to any non-NULL C string, 115 | // including the empty string. 116 | static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); 117 | 118 | // Compares two C strings, ignoring case. Returns true iff they 119 | // have the same content. 120 | // 121 | // Unlike strcasecmp(), this function can handle NULL argument(s). 122 | // A NULL C string is considered different to any non-NULL C string, 123 | // including the empty string. 124 | static bool CaseInsensitiveCStringEquals(const char* lhs, 125 | const char* rhs); 126 | 127 | // Compares two wide C strings, ignoring case. Returns true iff they 128 | // have the same content. 129 | // 130 | // Unlike wcscasecmp(), this function can handle NULL argument(s). 131 | // A NULL C string is considered different to any non-NULL wide C string, 132 | // including the empty string. 133 | // NB: The implementations on different platforms slightly differ. 134 | // On windows, this method uses _wcsicmp which compares according to LC_CTYPE 135 | // environment variable. On GNU platform this method uses wcscasecmp 136 | // which compares according to LC_CTYPE category of the current locale. 137 | // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the 138 | // current locale. 139 | static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, 140 | const wchar_t* rhs); 141 | 142 | // Returns true iff the given string ends with the given suffix, ignoring 143 | // case. Any string is considered to end with an empty suffix. 144 | static bool EndsWithCaseInsensitive( 145 | const std::string& str, const std::string& suffix); 146 | 147 | // Formats an int value as "%02d". 148 | static std::string FormatIntWidth2(int value); // "%02d" for width == 2 149 | 150 | // Formats an int value as "%X". 151 | static std::string FormatHexInt(int value); 152 | 153 | // Formats a byte as "%02X". 154 | static std::string FormatByte(unsigned char value); 155 | 156 | private: 157 | String(); // Not meant to be instantiated. 158 | }; // class String 159 | 160 | // Gets the content of the stringstream's buffer as an std::string. Each '\0' 161 | // character in the buffer is replaced with "\\0". 162 | GTEST_API_ std::string StringStreamToString(::std::stringstream* stream); 163 | 164 | } // namespace internal 165 | } // namespace testing 166 | 167 | #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ 168 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/src/gtest-all.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: mheule@google.com (Markus Heule) 31 | // 32 | // Google C++ Testing Framework (Google Test) 33 | // 34 | // Sometimes it's desirable to build Google Test by compiling a single file. 35 | // This file serves this purpose. 36 | 37 | // This line ensures that gtest.h can be compiled on its own, even 38 | // when it's fused. 39 | #include "gtest/gtest.h" 40 | 41 | // The following lines pull in the real gtest *.cc files. 42 | #include "src/gtest.cc" 43 | #include "src/gtest-death-test.cc" 44 | #include "src/gtest-filepath.cc" 45 | #include "src/gtest-port.cc" 46 | #include "src/gtest-printers.cc" 47 | #include "src/gtest-test-part.cc" 48 | #include "src/gtest-typed-test.cc" 49 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/src/gtest-test-part.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: mheule@google.com (Markus Heule) 31 | // 32 | // The Google C++ Testing Framework (Google Test) 33 | 34 | #include "gtest/gtest-test-part.h" 35 | 36 | // Indicates that this translation unit is part of Google Test's 37 | // implementation. It must come before gtest-internal-inl.h is 38 | // included, or there will be a compiler error. This trick is to 39 | // prevent a user from accidentally including gtest-internal-inl.h in 40 | // his code. 41 | #define GTEST_IMPLEMENTATION_ 1 42 | #include "src/gtest-internal-inl.h" 43 | #undef GTEST_IMPLEMENTATION_ 44 | 45 | namespace testing { 46 | 47 | using internal::GetUnitTestImpl; 48 | 49 | // Gets the summary of the failure message by omitting the stack trace 50 | // in it. 51 | std::string TestPartResult::ExtractSummary(const char* message) { 52 | const char* const stack_trace = strstr(message, internal::kStackTraceMarker); 53 | return stack_trace == NULL ? message : 54 | std::string(message, stack_trace); 55 | } 56 | 57 | // Prints a TestPartResult object. 58 | std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { 59 | return os 60 | << result.file_name() << ":" << result.line_number() << ": " 61 | << (result.type() == TestPartResult::kSuccess ? "Success" : 62 | result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : 63 | "Non-fatal failure") << ":\n" 64 | << result.message() << std::endl; 65 | } 66 | 67 | // Appends a TestPartResult to the array. 68 | void TestPartResultArray::Append(const TestPartResult& result) { 69 | array_.push_back(result); 70 | } 71 | 72 | // Returns the TestPartResult at the given index (0-based). 73 | const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { 74 | if (index < 0 || index >= size()) { 75 | printf("\nInvalid index (%d) into TestPartResultArray.\n", index); 76 | internal::posix::Abort(); 77 | } 78 | 79 | return array_[index]; 80 | } 81 | 82 | // Returns the number of TestPartResult objects in the array. 83 | int TestPartResultArray::size() const { 84 | return static_cast(array_.size()); 85 | } 86 | 87 | namespace internal { 88 | 89 | HasNewFatalFailureHelper::HasNewFatalFailureHelper() 90 | : has_new_fatal_failure_(false), 91 | original_reporter_(GetUnitTestImpl()-> 92 | GetTestPartResultReporterForCurrentThread()) { 93 | GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); 94 | } 95 | 96 | HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { 97 | GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( 98 | original_reporter_); 99 | } 100 | 101 | void HasNewFatalFailureHelper::ReportTestPartResult( 102 | const TestPartResult& result) { 103 | if (result.fatally_failed()) 104 | has_new_fatal_failure_ = true; 105 | original_reporter_->ReportTestPartResult(result); 106 | } 107 | 108 | } // namespace internal 109 | 110 | } // namespace testing 111 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/src/gtest-typed-test.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008 Google Inc. 2 | // All Rights Reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | #include "gtest/gtest-typed-test.h" 33 | #include "gtest/gtest.h" 34 | 35 | namespace testing { 36 | namespace internal { 37 | 38 | #if GTEST_HAS_TYPED_TEST_P 39 | 40 | // Skips to the first non-space char in str. Returns an empty string if str 41 | // contains only whitespace characters. 42 | static const char* SkipSpaces(const char* str) { 43 | while (IsSpace(*str)) 44 | str++; 45 | return str; 46 | } 47 | 48 | // Verifies that registered_tests match the test names in 49 | // defined_test_names_; returns registered_tests if successful, or 50 | // aborts the program otherwise. 51 | const char* TypedTestCasePState::VerifyRegisteredTestNames( 52 | const char* file, int line, const char* registered_tests) { 53 | typedef ::std::set::const_iterator DefinedTestIter; 54 | registered_ = true; 55 | 56 | // Skip initial whitespace in registered_tests since some 57 | // preprocessors prefix stringizied literals with whitespace. 58 | registered_tests = SkipSpaces(registered_tests); 59 | 60 | Message errors; 61 | ::std::set tests; 62 | for (const char* names = registered_tests; names != NULL; 63 | names = SkipComma(names)) { 64 | const std::string name = GetPrefixUntilComma(names); 65 | if (tests.count(name) != 0) { 66 | errors << "Test " << name << " is listed more than once.\n"; 67 | continue; 68 | } 69 | 70 | bool found = false; 71 | for (DefinedTestIter it = defined_test_names_.begin(); 72 | it != defined_test_names_.end(); 73 | ++it) { 74 | if (name == *it) { 75 | found = true; 76 | break; 77 | } 78 | } 79 | 80 | if (found) { 81 | tests.insert(name); 82 | } else { 83 | errors << "No test named " << name 84 | << " can be found in this test case.\n"; 85 | } 86 | } 87 | 88 | for (DefinedTestIter it = defined_test_names_.begin(); 89 | it != defined_test_names_.end(); 90 | ++it) { 91 | if (tests.count(*it) == 0) { 92 | errors << "You forgot to list test " << *it << ".\n"; 93 | } 94 | } 95 | 96 | const std::string& errors_str = errors.GetString(); 97 | if (errors_str != "") { 98 | fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), 99 | errors_str.c_str()); 100 | fflush(stderr); 101 | posix::Abort(); 102 | } 103 | 104 | return registered_tests; 105 | } 106 | 107 | #endif // GTEST_HAS_TYPED_TEST_P 108 | 109 | } // namespace internal 110 | } // namespace testing 111 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/gtest/src/gtest_main.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2006, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | 30 | #include 31 | 32 | #include "gtest/gtest.h" 33 | 34 | GTEST_API_ int main(int argc, char **argv) { 35 | printf("Running main() from gtest_main.cc\n"); 36 | testing::InitGoogleTest(&argc, argv); 37 | return RUN_ALL_TESTS(); 38 | } 39 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/include/gmock/gmock-cardinalities.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | // Google Mock - a framework for writing C++ mock classes. 33 | // 34 | // This file implements some commonly used cardinalities. More 35 | // cardinalities can be defined by the user implementing the 36 | // CardinalityInterface interface if necessary. 37 | 38 | #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ 39 | #define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ 40 | 41 | #include 42 | #include // NOLINT 43 | #include "gmock/internal/gmock-port.h" 44 | #include "gtest/gtest.h" 45 | 46 | namespace testing { 47 | 48 | // To implement a cardinality Foo, define: 49 | // 1. a class FooCardinality that implements the 50 | // CardinalityInterface interface, and 51 | // 2. a factory function that creates a Cardinality object from a 52 | // const FooCardinality*. 53 | // 54 | // The two-level delegation design follows that of Matcher, providing 55 | // consistency for extension developers. It also eases ownership 56 | // management as Cardinality objects can now be copied like plain values. 57 | 58 | // The implementation of a cardinality. 59 | class CardinalityInterface { 60 | public: 61 | virtual ~CardinalityInterface() {} 62 | 63 | // Conservative estimate on the lower/upper bound of the number of 64 | // calls allowed. 65 | virtual int ConservativeLowerBound() const { return 0; } 66 | virtual int ConservativeUpperBound() const { return INT_MAX; } 67 | 68 | // Returns true iff call_count calls will satisfy this cardinality. 69 | virtual bool IsSatisfiedByCallCount(int call_count) const = 0; 70 | 71 | // Returns true iff call_count calls will saturate this cardinality. 72 | virtual bool IsSaturatedByCallCount(int call_count) const = 0; 73 | 74 | // Describes self to an ostream. 75 | virtual void DescribeTo(::std::ostream* os) const = 0; 76 | }; 77 | 78 | // A Cardinality is a copyable and IMMUTABLE (except by assignment) 79 | // object that specifies how many times a mock function is expected to 80 | // be called. The implementation of Cardinality is just a linked_ptr 81 | // to const CardinalityInterface, so copying is fairly cheap. 82 | // Don't inherit from Cardinality! 83 | class GTEST_API_ Cardinality { 84 | public: 85 | // Constructs a null cardinality. Needed for storing Cardinality 86 | // objects in STL containers. 87 | Cardinality() {} 88 | 89 | // Constructs a Cardinality from its implementation. 90 | explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} 91 | 92 | // Conservative estimate on the lower/upper bound of the number of 93 | // calls allowed. 94 | int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); } 95 | int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } 96 | 97 | // Returns true iff call_count calls will satisfy this cardinality. 98 | bool IsSatisfiedByCallCount(int call_count) const { 99 | return impl_->IsSatisfiedByCallCount(call_count); 100 | } 101 | 102 | // Returns true iff call_count calls will saturate this cardinality. 103 | bool IsSaturatedByCallCount(int call_count) const { 104 | return impl_->IsSaturatedByCallCount(call_count); 105 | } 106 | 107 | // Returns true iff call_count calls will over-saturate this 108 | // cardinality, i.e. exceed the maximum number of allowed calls. 109 | bool IsOverSaturatedByCallCount(int call_count) const { 110 | return impl_->IsSaturatedByCallCount(call_count) && 111 | !impl_->IsSatisfiedByCallCount(call_count); 112 | } 113 | 114 | // Describes self to an ostream 115 | void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } 116 | 117 | // Describes the given actual call count to an ostream. 118 | static void DescribeActualCallCountTo(int actual_call_count, 119 | ::std::ostream* os); 120 | 121 | private: 122 | internal::linked_ptr impl_; 123 | }; 124 | 125 | // Creates a cardinality that allows at least n calls. 126 | GTEST_API_ Cardinality AtLeast(int n); 127 | 128 | // Creates a cardinality that allows at most n calls. 129 | GTEST_API_ Cardinality AtMost(int n); 130 | 131 | // Creates a cardinality that allows any number of calls. 132 | GTEST_API_ Cardinality AnyNumber(); 133 | 134 | // Creates a cardinality that allows between min and max calls. 135 | GTEST_API_ Cardinality Between(int min, int max); 136 | 137 | // Creates a cardinality that allows exactly n calls. 138 | GTEST_API_ Cardinality Exactly(int n); 139 | 140 | // Creates a cardinality from its implementation. 141 | inline Cardinality MakeCardinality(const CardinalityInterface* c) { 142 | return Cardinality(c); 143 | } 144 | 145 | } // namespace testing 146 | 147 | #endif // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ 148 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h.pump: -------------------------------------------------------------------------------- 1 | $$ -*- mode: c++; -*- 2 | $$ This is a Pump source file. Please use Pump to convert it to 3 | $$ gmock-generated-function-mockers.h. 4 | $$ 5 | $var n = 10 $$ The maximum arity we support. 6 | // Copyright 2007, Google Inc. 7 | // All rights reserved. 8 | // 9 | // Redistribution and use in source and binary forms, with or without 10 | // modification, are permitted provided that the following conditions are 11 | // met: 12 | // 13 | // * Redistributions of source code must retain the above copyright 14 | // notice, this list of conditions and the following disclaimer. 15 | // * Redistributions in binary form must reproduce the above 16 | // copyright notice, this list of conditions and the following disclaimer 17 | // in the documentation and/or other materials provided with the 18 | // distribution. 19 | // * Neither the name of Google Inc. nor the names of its 20 | // contributors may be used to endorse or promote products derived from 21 | // this software without specific prior written permission. 22 | // 23 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 24 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 25 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 26 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 27 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 28 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 29 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 30 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 31 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 33 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | // 35 | // Author: wan@google.com (Zhanyong Wan) 36 | 37 | // Google Mock - a framework for writing C++ mock classes. 38 | // 39 | // This file implements function mockers of various arities. 40 | 41 | #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ 42 | #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ 43 | 44 | #include "gmock/gmock-spec-builders.h" 45 | #include "gmock/internal/gmock-internal-utils.h" 46 | 47 | namespace testing { 48 | namespace internal { 49 | 50 | template 51 | class FunctionMockerBase; 52 | 53 | // Note: class FunctionMocker really belongs to the ::testing 54 | // namespace. However if we define it in ::testing, MSVC will 55 | // complain when classes in ::testing::internal declare it as a 56 | // friend class template. To workaround this compiler bug, we define 57 | // FunctionMocker in ::testing::internal and import it into ::testing. 58 | template 59 | class FunctionMocker; 60 | 61 | 62 | $range i 0..n 63 | $for i [[ 64 | $range j 1..i 65 | $var typename_As = [[$for j [[, typename A$j]]]] 66 | $var As = [[$for j, [[A$j]]]] 67 | $var as = [[$for j, [[a$j]]]] 68 | $var Aas = [[$for j, [[A$j a$j]]]] 69 | $var ms = [[$for j, [[m$j]]]] 70 | $var matchers = [[$for j, [[const Matcher& m$j]]]] 71 | template 72 | class FunctionMocker : public 73 | internal::FunctionMockerBase { 74 | public: 75 | typedef R F($As); 76 | typedef typename internal::Function::ArgumentTuple ArgumentTuple; 77 | 78 | MockSpec& With($matchers) { 79 | 80 | $if i >= 1 [[ 81 | this->current_spec().SetMatchers(::std::tr1::make_tuple($ms)); 82 | 83 | ]] 84 | return this->current_spec(); 85 | } 86 | 87 | R Invoke($Aas) { 88 | // Even though gcc and MSVC don't enforce it, 'this->' is required 89 | // by the C++ standard [14.6.4] here, as the base class type is 90 | // dependent on the template argument (and thus shouldn't be 91 | // looked into when resolving InvokeWith). 92 | return this->InvokeWith(ArgumentTuple($as)); 93 | } 94 | }; 95 | 96 | 97 | ]] 98 | } // namespace internal 99 | 100 | // The style guide prohibits "using" statements in a namespace scope 101 | // inside a header file. However, the FunctionMocker class template 102 | // is meant to be defined in the ::testing namespace. The following 103 | // line is just a trick for working around a bug in MSVC 8.0, which 104 | // cannot handle it if we define FunctionMocker in ::testing. 105 | using internal::FunctionMocker; 106 | 107 | // GMOCK_RESULT_(tn, F) expands to the result type of function type F. 108 | // We define this as a variadic macro in case F contains unprotected 109 | // commas (the same reason that we use variadic macros in other places 110 | // in this file). 111 | // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! 112 | #define GMOCK_RESULT_(tn, ...) \ 113 | tn ::testing::internal::Function<__VA_ARGS__>::Result 114 | 115 | // The type of argument N of the given function type. 116 | // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! 117 | #define GMOCK_ARG_(tn, N, ...) \ 118 | tn ::testing::internal::Function<__VA_ARGS__>::Argument##N 119 | 120 | // The matcher type for argument N of the given function type. 121 | // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! 122 | #define GMOCK_MATCHER_(tn, N, ...) \ 123 | const ::testing::Matcher& 124 | 125 | // The variable for mocking the given method. 126 | // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! 127 | #define GMOCK_MOCKER_(arity, constness, Method) \ 128 | GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) 129 | 130 | 131 | $for i [[ 132 | $range j 1..i 133 | $var arg_as = [[$for j, \ 134 | [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]] 135 | $var as = [[$for j, [[gmock_a$j]]]] 136 | $var matcher_as = [[$for j, \ 137 | [[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]] 138 | // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! 139 | #define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \ 140 | GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ 141 | $arg_as) constness { \ 142 | GTEST_COMPILE_ASSERT_((::std::tr1::tuple_size< \ 143 | tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value == $i), \ 144 | this_method_does_not_take_$i[[]]_argument[[$if i != 1 [[s]]]]); \ 145 | GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \ 146 | return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \ 147 | } \ 148 | ::testing::MockSpec<__VA_ARGS__>& \ 149 | gmock_##Method($matcher_as) constness { \ 150 | GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \ 151 | return GMOCK_MOCKER_($i, constness, Method).With($as); \ 152 | } \ 153 | mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method) 154 | 155 | 156 | ]] 157 | $for i [[ 158 | #define MOCK_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, , , m, __VA_ARGS__) 159 | 160 | ]] 161 | 162 | 163 | $for i [[ 164 | #define MOCK_CONST_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, const, , m, __VA_ARGS__) 165 | 166 | ]] 167 | 168 | 169 | $for i [[ 170 | #define MOCK_METHOD$i[[]]_T(m, ...) GMOCK_METHOD$i[[]]_(typename, , , m, __VA_ARGS__) 171 | 172 | ]] 173 | 174 | 175 | $for i [[ 176 | #define MOCK_CONST_METHOD$i[[]]_T(m, ...) \ 177 | GMOCK_METHOD$i[[]]_(typename, const, , m, __VA_ARGS__) 178 | 179 | ]] 180 | 181 | 182 | $for i [[ 183 | #define MOCK_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \ 184 | GMOCK_METHOD$i[[]]_(, , ct, m, __VA_ARGS__) 185 | 186 | ]] 187 | 188 | 189 | $for i [[ 190 | #define MOCK_CONST_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \ 191 | GMOCK_METHOD$i[[]]_(, const, ct, m, __VA_ARGS__) 192 | 193 | ]] 194 | 195 | 196 | $for i [[ 197 | #define MOCK_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \ 198 | GMOCK_METHOD$i[[]]_(typename, , ct, m, __VA_ARGS__) 199 | 200 | ]] 201 | 202 | 203 | $for i [[ 204 | #define MOCK_CONST_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \ 205 | GMOCK_METHOD$i[[]]_(typename, const, ct, m, __VA_ARGS__) 206 | 207 | ]] 208 | 209 | // A MockFunction class has one mock method whose type is F. It is 210 | // useful when you just want your test code to emit some messages and 211 | // have Google Mock verify the right messages are sent (and perhaps at 212 | // the right times). For example, if you are exercising code: 213 | // 214 | // Foo(1); 215 | // Foo(2); 216 | // Foo(3); 217 | // 218 | // and want to verify that Foo(1) and Foo(3) both invoke 219 | // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write: 220 | // 221 | // TEST(FooTest, InvokesBarCorrectly) { 222 | // MyMock mock; 223 | // MockFunction check; 224 | // { 225 | // InSequence s; 226 | // 227 | // EXPECT_CALL(mock, Bar("a")); 228 | // EXPECT_CALL(check, Call("1")); 229 | // EXPECT_CALL(check, Call("2")); 230 | // EXPECT_CALL(mock, Bar("a")); 231 | // } 232 | // Foo(1); 233 | // check.Call("1"); 234 | // Foo(2); 235 | // check.Call("2"); 236 | // Foo(3); 237 | // } 238 | // 239 | // The expectation spec says that the first Bar("a") must happen 240 | // before check point "1", the second Bar("a") must happen after check 241 | // point "2", and nothing should happen between the two check 242 | // points. The explicit check points make it easy to tell which 243 | // Bar("a") is called by which call to Foo(). 244 | template 245 | class MockFunction; 246 | 247 | 248 | $for i [[ 249 | $range j 0..i-1 250 | template 251 | class MockFunction { 252 | public: 253 | MockFunction() {} 254 | 255 | MOCK_METHOD$i[[]]_T(Call, R($for j, [[A$j]])); 256 | 257 | private: 258 | GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); 259 | }; 260 | 261 | 262 | ]] 263 | } // namespace testing 264 | 265 | #endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ 266 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h.pump: -------------------------------------------------------------------------------- 1 | $$ -*- mode: c++; -*- 2 | $$ This is a Pump source file. Please use Pump to convert it to 3 | $$ gmock-generated-nice-strict.h. 4 | $$ 5 | $var n = 10 $$ The maximum arity we support. 6 | // Copyright 2008, Google Inc. 7 | // All rights reserved. 8 | // 9 | // Redistribution and use in source and binary forms, with or without 10 | // modification, are permitted provided that the following conditions are 11 | // met: 12 | // 13 | // * Redistributions of source code must retain the above copyright 14 | // notice, this list of conditions and the following disclaimer. 15 | // * Redistributions in binary form must reproduce the above 16 | // copyright notice, this list of conditions and the following disclaimer 17 | // in the documentation and/or other materials provided with the 18 | // distribution. 19 | // * Neither the name of Google Inc. nor the names of its 20 | // contributors may be used to endorse or promote products derived from 21 | // this software without specific prior written permission. 22 | // 23 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 24 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 25 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 26 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 27 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 28 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 29 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 30 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 31 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 33 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | // 35 | // Author: wan@google.com (Zhanyong Wan) 36 | 37 | // Implements class templates NiceMock, NaggyMock, and StrictMock. 38 | // 39 | // Given a mock class MockFoo that is created using Google Mock, 40 | // NiceMock is a subclass of MockFoo that allows 41 | // uninteresting calls (i.e. calls to mock methods that have no 42 | // EXPECT_CALL specs), NaggyMock is a subclass of MockFoo 43 | // that prints a warning when an uninteresting call occurs, and 44 | // StrictMock is a subclass of MockFoo that treats all 45 | // uninteresting calls as errors. 46 | // 47 | // Currently a mock is naggy by default, so MockFoo and 48 | // NaggyMock behave like the same. However, we will soon 49 | // switch the default behavior of mocks to be nice, as that in general 50 | // leads to more maintainable tests. When that happens, MockFoo will 51 | // stop behaving like NaggyMock and start behaving like 52 | // NiceMock. 53 | // 54 | // NiceMock, NaggyMock, and StrictMock "inherit" the constructors of 55 | // their respective base class, with up-to $n arguments. Therefore 56 | // you can write NiceMock(5, "a") to construct a nice mock 57 | // where MockFoo has a constructor that accepts (int, const char*), 58 | // for example. 59 | // 60 | // A known limitation is that NiceMock, NaggyMock, 61 | // and StrictMock only works for mock methods defined using 62 | // the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class. 63 | // If a mock method is defined in a base class of MockFoo, the "nice" 64 | // or "strict" modifier may not affect it, depending on the compiler. 65 | // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT 66 | // supported. 67 | // 68 | // Another known limitation is that the constructors of the base mock 69 | // cannot have arguments passed by non-const reference, which are 70 | // banned by the Google C++ style guide anyway. 71 | 72 | #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ 73 | #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ 74 | 75 | #include "gmock/gmock-spec-builders.h" 76 | #include "gmock/internal/gmock-port.h" 77 | 78 | namespace testing { 79 | 80 | $range kind 0..2 81 | $for kind [[ 82 | 83 | $var clazz=[[$if kind==0 [[NiceMock]] 84 | $elif kind==1 [[NaggyMock]] 85 | $else [[StrictMock]]]] 86 | 87 | $var method=[[$if kind==0 [[AllowUninterestingCalls]] 88 | $elif kind==1 [[WarnUninterestingCalls]] 89 | $else [[FailUninterestingCalls]]]] 90 | 91 | template 92 | class $clazz : public MockClass { 93 | public: 94 | // We don't factor out the constructor body to a common method, as 95 | // we have to avoid a possible clash with members of MockClass. 96 | $clazz() { 97 | ::testing::Mock::$method( 98 | internal::ImplicitCast_(this)); 99 | } 100 | 101 | // C++ doesn't (yet) allow inheritance of constructors, so we have 102 | // to define it for each arity. 103 | template 104 | explicit $clazz(const A1& a1) : MockClass(a1) { 105 | ::testing::Mock::$method( 106 | internal::ImplicitCast_(this)); 107 | } 108 | 109 | $range i 2..n 110 | $for i [[ 111 | $range j 1..i 112 | template <$for j, [[typename A$j]]> 113 | $clazz($for j, [[const A$j& a$j]]) : MockClass($for j, [[a$j]]) { 114 | ::testing::Mock::$method( 115 | internal::ImplicitCast_(this)); 116 | } 117 | 118 | 119 | ]] 120 | virtual ~$clazz() { 121 | ::testing::Mock::UnregisterCallReaction( 122 | internal::ImplicitCast_(this)); 123 | } 124 | 125 | private: 126 | GTEST_DISALLOW_COPY_AND_ASSIGN_($clazz); 127 | }; 128 | 129 | ]] 130 | 131 | // The following specializations catch some (relatively more common) 132 | // user errors of nesting nice and strict mocks. They do NOT catch 133 | // all possible errors. 134 | 135 | // These specializations are declared but not defined, as NiceMock, 136 | // NaggyMock, and StrictMock cannot be nested. 137 | 138 | template 139 | class NiceMock >; 140 | template 141 | class NiceMock >; 142 | template 143 | class NiceMock >; 144 | 145 | template 146 | class NaggyMock >; 147 | template 148 | class NaggyMock >; 149 | template 150 | class NaggyMock >; 151 | 152 | template 153 | class StrictMock >; 154 | template 155 | class StrictMock >; 156 | template 157 | class StrictMock >; 158 | 159 | } // namespace testing 160 | 161 | #endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ 162 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/include/gmock/gmock-more-actions.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | // Google Mock - a framework for writing C++ mock classes. 33 | // 34 | // This file implements some actions that depend on gmock-generated-actions.h. 35 | 36 | #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ 37 | #define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ 38 | 39 | #include 40 | 41 | #include "gmock/gmock-generated-actions.h" 42 | 43 | namespace testing { 44 | namespace internal { 45 | 46 | // Implements the Invoke(f) action. The template argument 47 | // FunctionImpl is the implementation type of f, which can be either a 48 | // function pointer or a functor. Invoke(f) can be used as an 49 | // Action as long as f's type is compatible with F (i.e. f can be 50 | // assigned to a tr1::function). 51 | template 52 | class InvokeAction { 53 | public: 54 | // The c'tor makes a copy of function_impl (either a function 55 | // pointer or a functor). 56 | explicit InvokeAction(FunctionImpl function_impl) 57 | : function_impl_(function_impl) {} 58 | 59 | template 60 | Result Perform(const ArgumentTuple& args) { 61 | return InvokeHelper::Invoke(function_impl_, args); 62 | } 63 | 64 | private: 65 | FunctionImpl function_impl_; 66 | 67 | GTEST_DISALLOW_ASSIGN_(InvokeAction); 68 | }; 69 | 70 | // Implements the Invoke(object_ptr, &Class::Method) action. 71 | template 72 | class InvokeMethodAction { 73 | public: 74 | InvokeMethodAction(Class* obj_ptr, MethodPtr method_ptr) 75 | : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {} 76 | 77 | template 78 | Result Perform(const ArgumentTuple& args) const { 79 | return InvokeHelper::InvokeMethod( 80 | obj_ptr_, method_ptr_, args); 81 | } 82 | 83 | private: 84 | Class* const obj_ptr_; 85 | const MethodPtr method_ptr_; 86 | 87 | GTEST_DISALLOW_ASSIGN_(InvokeMethodAction); 88 | }; 89 | 90 | } // namespace internal 91 | 92 | // Various overloads for Invoke(). 93 | 94 | // Creates an action that invokes 'function_impl' with the mock 95 | // function's arguments. 96 | template 97 | PolymorphicAction > Invoke( 98 | FunctionImpl function_impl) { 99 | return MakePolymorphicAction( 100 | internal::InvokeAction(function_impl)); 101 | } 102 | 103 | // Creates an action that invokes the given method on the given object 104 | // with the mock function's arguments. 105 | template 106 | PolymorphicAction > Invoke( 107 | Class* obj_ptr, MethodPtr method_ptr) { 108 | return MakePolymorphicAction( 109 | internal::InvokeMethodAction(obj_ptr, method_ptr)); 110 | } 111 | 112 | // WithoutArgs(inner_action) can be used in a mock function with a 113 | // non-empty argument list to perform inner_action, which takes no 114 | // argument. In other words, it adapts an action accepting no 115 | // argument to one that accepts (and ignores) arguments. 116 | template 117 | inline internal::WithArgsAction 118 | WithoutArgs(const InnerAction& action) { 119 | return internal::WithArgsAction(action); 120 | } 121 | 122 | // WithArg(an_action) creates an action that passes the k-th 123 | // (0-based) argument of the mock function to an_action and performs 124 | // it. It adapts an action accepting one argument to one that accepts 125 | // multiple arguments. For convenience, we also provide 126 | // WithArgs(an_action) (defined below) as a synonym. 127 | template 128 | inline internal::WithArgsAction 129 | WithArg(const InnerAction& action) { 130 | return internal::WithArgsAction(action); 131 | } 132 | 133 | // The ACTION*() macros trigger warning C4100 (unreferenced formal 134 | // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in 135 | // the macro definition, as the warnings are generated when the macro 136 | // is expanded and macro expansion cannot contain #pragma. Therefore 137 | // we suppress them here. 138 | #ifdef _MSC_VER 139 | # pragma warning(push) 140 | # pragma warning(disable:4100) 141 | #endif 142 | 143 | // Action ReturnArg() returns the k-th argument of the mock function. 144 | ACTION_TEMPLATE(ReturnArg, 145 | HAS_1_TEMPLATE_PARAMS(int, k), 146 | AND_0_VALUE_PARAMS()) { 147 | return std::tr1::get(args); 148 | } 149 | 150 | // Action SaveArg(pointer) saves the k-th (0-based) argument of the 151 | // mock function to *pointer. 152 | ACTION_TEMPLATE(SaveArg, 153 | HAS_1_TEMPLATE_PARAMS(int, k), 154 | AND_1_VALUE_PARAMS(pointer)) { 155 | *pointer = ::std::tr1::get(args); 156 | } 157 | 158 | // Action SaveArgPointee(pointer) saves the value pointed to 159 | // by the k-th (0-based) argument of the mock function to *pointer. 160 | ACTION_TEMPLATE(SaveArgPointee, 161 | HAS_1_TEMPLATE_PARAMS(int, k), 162 | AND_1_VALUE_PARAMS(pointer)) { 163 | *pointer = *::std::tr1::get(args); 164 | } 165 | 166 | // Action SetArgReferee(value) assigns 'value' to the variable 167 | // referenced by the k-th (0-based) argument of the mock function. 168 | ACTION_TEMPLATE(SetArgReferee, 169 | HAS_1_TEMPLATE_PARAMS(int, k), 170 | AND_1_VALUE_PARAMS(value)) { 171 | typedef typename ::std::tr1::tuple_element::type argk_type; 172 | // Ensures that argument #k is a reference. If you get a compiler 173 | // error on the next line, you are using SetArgReferee(value) in 174 | // a mock function whose k-th (0-based) argument is not a reference. 175 | GTEST_COMPILE_ASSERT_(internal::is_reference::value, 176 | SetArgReferee_must_be_used_with_a_reference_argument); 177 | ::std::tr1::get(args) = value; 178 | } 179 | 180 | // Action SetArrayArgument(first, last) copies the elements in 181 | // source range [first, last) to the array pointed to by the k-th 182 | // (0-based) argument, which can be either a pointer or an 183 | // iterator. The action does not take ownership of the elements in the 184 | // source range. 185 | ACTION_TEMPLATE(SetArrayArgument, 186 | HAS_1_TEMPLATE_PARAMS(int, k), 187 | AND_2_VALUE_PARAMS(first, last)) { 188 | // Microsoft compiler deprecates ::std::copy, so we want to suppress warning 189 | // 4996 (Function call with parameters that may be unsafe) there. 190 | #ifdef _MSC_VER 191 | # pragma warning(push) // Saves the current warning state. 192 | # pragma warning(disable:4996) // Temporarily disables warning 4996. 193 | #endif 194 | ::std::copy(first, last, ::std::tr1::get(args)); 195 | #ifdef _MSC_VER 196 | # pragma warning(pop) // Restores the warning state. 197 | #endif 198 | } 199 | 200 | // Action DeleteArg() deletes the k-th (0-based) argument of the mock 201 | // function. 202 | ACTION_TEMPLATE(DeleteArg, 203 | HAS_1_TEMPLATE_PARAMS(int, k), 204 | AND_0_VALUE_PARAMS()) { 205 | delete ::std::tr1::get(args); 206 | } 207 | 208 | // This action returns the value pointed to by 'pointer'. 209 | ACTION_P(ReturnPointee, pointer) { return *pointer; } 210 | 211 | // Action Throw(exception) can be used in a mock function of any type 212 | // to throw the given exception. Any copyable value can be thrown. 213 | #if GTEST_HAS_EXCEPTIONS 214 | 215 | // Suppresses the 'unreachable code' warning that VC generates in opt modes. 216 | # ifdef _MSC_VER 217 | # pragma warning(push) // Saves the current warning state. 218 | # pragma warning(disable:4702) // Temporarily disables warning 4702. 219 | # endif 220 | ACTION_P(Throw, exception) { throw exception; } 221 | # ifdef _MSC_VER 222 | # pragma warning(pop) // Restores the warning state. 223 | # endif 224 | 225 | #endif // GTEST_HAS_EXCEPTIONS 226 | 227 | #ifdef _MSC_VER 228 | # pragma warning(pop) 229 | #endif 230 | 231 | } // namespace testing 232 | 233 | #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ 234 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/include/gmock/gmock-more-matchers.h: -------------------------------------------------------------------------------- 1 | // Copyright 2013, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: marcus.boerger@google.com (Marcus Boerger) 31 | 32 | // Google Mock - a framework for writing C++ mock classes. 33 | // 34 | // This file implements some matchers that depend on gmock-generated-matchers.h. 35 | // 36 | // Note that tests are implemented in gmock-matchers_test.cc rather than 37 | // gmock-more-matchers-test.cc. 38 | 39 | #ifndef GMOCK_GMOCK_MORE_MATCHERS_H_ 40 | #define GMOCK_GMOCK_MORE_MATCHERS_H_ 41 | 42 | #include "gmock/gmock-generated-matchers.h" 43 | 44 | namespace testing { 45 | 46 | // Defines a matcher that matches an empty container. The container must 47 | // support both size() and empty(), which all STL-like containers provide. 48 | MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") { 49 | if (arg.empty()) { 50 | return true; 51 | } 52 | *result_listener << "whose size is " << arg.size(); 53 | return false; 54 | } 55 | 56 | } // namespace testing 57 | 58 | #endif // GMOCK_GMOCK_MORE_MATCHERS_H_ 59 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/include/gmock/gmock.h: -------------------------------------------------------------------------------- 1 | // Copyright 2007, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | // Google Mock - a framework for writing C++ mock classes. 33 | // 34 | // This is the main header file a user should include. 35 | 36 | #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_ 37 | #define GMOCK_INCLUDE_GMOCK_GMOCK_H_ 38 | 39 | // This file implements the following syntax: 40 | // 41 | // ON_CALL(mock_object.Method(...)) 42 | // .With(...) ? 43 | // .WillByDefault(...); 44 | // 45 | // where With() is optional and WillByDefault() must appear exactly 46 | // once. 47 | // 48 | // EXPECT_CALL(mock_object.Method(...)) 49 | // .With(...) ? 50 | // .Times(...) ? 51 | // .InSequence(...) * 52 | // .WillOnce(...) * 53 | // .WillRepeatedly(...) ? 54 | // .RetiresOnSaturation() ? ; 55 | // 56 | // where all clauses are optional and WillOnce() can be repeated. 57 | 58 | #include "gmock/gmock-actions.h" 59 | #include "gmock/gmock-cardinalities.h" 60 | #include "gmock/gmock-generated-actions.h" 61 | #include "gmock/gmock-generated-function-mockers.h" 62 | #include "gmock/gmock-generated-nice-strict.h" 63 | #include "gmock/gmock-generated-matchers.h" 64 | #include "gmock/gmock-matchers.h" 65 | #include "gmock/gmock-more-actions.h" 66 | #include "gmock/gmock-more-matchers.h" 67 | #include "gmock/internal/gmock-internal-utils.h" 68 | 69 | namespace testing { 70 | 71 | // Declares Google Mock flags that we want a user to use programmatically. 72 | GMOCK_DECLARE_bool_(catch_leaked_mocks); 73 | GMOCK_DECLARE_string_(verbose); 74 | 75 | // Initializes Google Mock. This must be called before running the 76 | // tests. In particular, it parses the command line for the flags 77 | // that Google Mock recognizes. Whenever a Google Mock flag is seen, 78 | // it is removed from argv, and *argc is decremented. 79 | // 80 | // No value is returned. Instead, the Google Mock flag variables are 81 | // updated. 82 | // 83 | // Since Google Test is needed for Google Mock to work, this function 84 | // also initializes Google Test and parses its flags, if that hasn't 85 | // been done. 86 | GTEST_API_ void InitGoogleMock(int* argc, char** argv); 87 | 88 | // This overloaded version can be used in Windows programs compiled in 89 | // UNICODE mode. 90 | GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv); 91 | 92 | } // namespace testing 93 | 94 | #endif // GMOCK_INCLUDE_GMOCK_GMOCK_H_ 95 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h.pump: -------------------------------------------------------------------------------- 1 | $$ -*- mode: c++; -*- 2 | $$ This is a Pump source file. Please use Pump to convert it to 3 | $$ gmock-generated-function-mockers.h. 4 | $$ 5 | $var n = 10 $$ The maximum arity we support. 6 | // Copyright 2007, Google Inc. 7 | // All rights reserved. 8 | // 9 | // Redistribution and use in source and binary forms, with or without 10 | // modification, are permitted provided that the following conditions are 11 | // met: 12 | // 13 | // * Redistributions of source code must retain the above copyright 14 | // notice, this list of conditions and the following disclaimer. 15 | // * Redistributions in binary form must reproduce the above 16 | // copyright notice, this list of conditions and the following disclaimer 17 | // in the documentation and/or other materials provided with the 18 | // distribution. 19 | // * Neither the name of Google Inc. nor the names of its 20 | // contributors may be used to endorse or promote products derived from 21 | // this software without specific prior written permission. 22 | // 23 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 24 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 25 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 26 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 27 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 28 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 29 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 30 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 31 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 33 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | // 35 | // Author: wan@google.com (Zhanyong Wan) 36 | 37 | // Google Mock - a framework for writing C++ mock classes. 38 | // 39 | // This file contains template meta-programming utility classes needed 40 | // for implementing Google Mock. 41 | 42 | #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ 43 | #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ 44 | 45 | #include "gmock/internal/gmock-port.h" 46 | 47 | namespace testing { 48 | 49 | template 50 | class Matcher; 51 | 52 | namespace internal { 53 | 54 | // An IgnoredValue object can be implicitly constructed from ANY value. 55 | // This is used in implementing the IgnoreResult(a) action. 56 | class IgnoredValue { 57 | public: 58 | // This constructor template allows any value to be implicitly 59 | // converted to IgnoredValue. The object has no data member and 60 | // doesn't try to remember anything about the argument. We 61 | // deliberately omit the 'explicit' keyword in order to allow the 62 | // conversion to be implicit. 63 | template 64 | IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit) 65 | }; 66 | 67 | // MatcherTuple::type is a tuple type where each field is a Matcher 68 | // for the corresponding field in tuple type T. 69 | template 70 | struct MatcherTuple; 71 | 72 | 73 | $range i 0..n 74 | $for i [[ 75 | $range j 1..i 76 | $var typename_As = [[$for j, [[typename A$j]]]] 77 | $var As = [[$for j, [[A$j]]]] 78 | $var matcher_As = [[$for j, [[Matcher]]]] 79 | template <$typename_As> 80 | struct MatcherTuple< ::std::tr1::tuple<$As> > { 81 | typedef ::std::tr1::tuple<$matcher_As > type; 82 | }; 83 | 84 | 85 | ]] 86 | // Template struct Function, where F must be a function type, contains 87 | // the following typedefs: 88 | // 89 | // Result: the function's return type. 90 | // ArgumentN: the type of the N-th argument, where N starts with 1. 91 | // ArgumentTuple: the tuple type consisting of all parameters of F. 92 | // ArgumentMatcherTuple: the tuple type consisting of Matchers for all 93 | // parameters of F. 94 | // MakeResultVoid: the function type obtained by substituting void 95 | // for the return type of F. 96 | // MakeResultIgnoredValue: 97 | // the function type obtained by substituting Something 98 | // for the return type of F. 99 | template 100 | struct Function; 101 | 102 | template 103 | struct Function { 104 | typedef R Result; 105 | typedef ::std::tr1::tuple<> ArgumentTuple; 106 | typedef typename MatcherTuple::type ArgumentMatcherTuple; 107 | typedef void MakeResultVoid(); 108 | typedef IgnoredValue MakeResultIgnoredValue(); 109 | }; 110 | 111 | 112 | $range i 1..n 113 | $for i [[ 114 | $range j 1..i 115 | $var typename_As = [[$for j [[, typename A$j]]]] 116 | $var As = [[$for j, [[A$j]]]] 117 | $var matcher_As = [[$for j, [[Matcher]]]] 118 | $range k 1..i-1 119 | $var prev_As = [[$for k, [[A$k]]]] 120 | template 121 | struct Function 122 | : Function { 123 | typedef A$i Argument$i; 124 | typedef ::std::tr1::tuple<$As> ArgumentTuple; 125 | typedef typename MatcherTuple::type ArgumentMatcherTuple; 126 | typedef void MakeResultVoid($As); 127 | typedef IgnoredValue MakeResultIgnoredValue($As); 128 | }; 129 | 130 | 131 | ]] 132 | } // namespace internal 133 | 134 | } // namespace testing 135 | 136 | #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ 137 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/include/gmock/internal/gmock-port.h: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: vadimb@google.com (Vadim Berman) 31 | // 32 | // Low-level types and utilities for porting Google Mock to various 33 | // platforms. They are subject to change without notice. DO NOT USE 34 | // THEM IN USER CODE. 35 | 36 | #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ 37 | #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ 38 | 39 | #include 40 | #include 41 | #include 42 | 43 | // Most of the types needed for porting Google Mock are also required 44 | // for Google Test and are defined in gtest-port.h. 45 | #include "gtest/internal/gtest-linked_ptr.h" 46 | #include "gtest/internal/gtest-port.h" 47 | 48 | // To avoid conditional compilation everywhere, we make it 49 | // gmock-port.h's responsibility to #include the header implementing 50 | // tr1/tuple. gmock-port.h does this via gtest-port.h, which is 51 | // guaranteed to pull in the tuple header. 52 | 53 | // For MS Visual C++, check the compiler version. At least VS 2003 is 54 | // required to compile Google Mock. 55 | #if defined(_MSC_VER) && _MSC_VER < 1310 56 | # error "At least Visual C++ 2003 (7.1) is required to compile Google Mock." 57 | #endif 58 | 59 | // Macro for referencing flags. This is public as we want the user to 60 | // use this syntax to reference Google Mock flags. 61 | #define GMOCK_FLAG(name) FLAGS_gmock_##name 62 | 63 | // Macros for declaring flags. 64 | #define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) 65 | #define GMOCK_DECLARE_int32_(name) \ 66 | extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) 67 | #define GMOCK_DECLARE_string_(name) \ 68 | extern GTEST_API_ ::std::string GMOCK_FLAG(name) 69 | 70 | // Macros for defining flags. 71 | #define GMOCK_DEFINE_bool_(name, default_val, doc) \ 72 | GTEST_API_ bool GMOCK_FLAG(name) = (default_val) 73 | #define GMOCK_DEFINE_int32_(name, default_val, doc) \ 74 | GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val) 75 | #define GMOCK_DEFINE_string_(name, default_val, doc) \ 76 | GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val) 77 | 78 | #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ 79 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/src/gmock-all.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | // 32 | // Google C++ Mocking Framework (Google Mock) 33 | // 34 | // This file #includes all Google Mock implementation .cc files. The 35 | // purpose is to allow a user to build Google Mock by compiling this 36 | // file alone. 37 | 38 | // This line ensures that gmock.h can be compiled on its own, even 39 | // when it's fused. 40 | #include "gmock/gmock.h" 41 | 42 | // The following lines pull in the real gmock *.cc files. 43 | #include "src/gmock-cardinalities.cc" 44 | #include "src/gmock-internal-utils.cc" 45 | #include "src/gmock-matchers.cc" 46 | #include "src/gmock-spec-builders.cc" 47 | #include "src/gmock.cc" 48 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/src/gmock-cardinalities.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2007, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | // Google Mock - a framework for writing C++ mock classes. 33 | // 34 | // This file implements cardinalities. 35 | 36 | #include "gmock/gmock-cardinalities.h" 37 | 38 | #include 39 | #include // NOLINT 40 | #include 41 | #include 42 | #include "gmock/internal/gmock-internal-utils.h" 43 | #include "gtest/gtest.h" 44 | 45 | namespace testing { 46 | 47 | namespace { 48 | 49 | // Implements the Between(m, n) cardinality. 50 | class BetweenCardinalityImpl : public CardinalityInterface { 51 | public: 52 | BetweenCardinalityImpl(int min, int max) 53 | : min_(min >= 0 ? min : 0), 54 | max_(max >= min_ ? max : min_) { 55 | std::stringstream ss; 56 | if (min < 0) { 57 | ss << "The invocation lower bound must be >= 0, " 58 | << "but is actually " << min << "."; 59 | internal::Expect(false, __FILE__, __LINE__, ss.str()); 60 | } else if (max < 0) { 61 | ss << "The invocation upper bound must be >= 0, " 62 | << "but is actually " << max << "."; 63 | internal::Expect(false, __FILE__, __LINE__, ss.str()); 64 | } else if (min > max) { 65 | ss << "The invocation upper bound (" << max 66 | << ") must be >= the invocation lower bound (" << min 67 | << ")."; 68 | internal::Expect(false, __FILE__, __LINE__, ss.str()); 69 | } 70 | } 71 | 72 | // Conservative estimate on the lower/upper bound of the number of 73 | // calls allowed. 74 | virtual int ConservativeLowerBound() const { return min_; } 75 | virtual int ConservativeUpperBound() const { return max_; } 76 | 77 | virtual bool IsSatisfiedByCallCount(int call_count) const { 78 | return min_ <= call_count && call_count <= max_; 79 | } 80 | 81 | virtual bool IsSaturatedByCallCount(int call_count) const { 82 | return call_count >= max_; 83 | } 84 | 85 | virtual void DescribeTo(::std::ostream* os) const; 86 | 87 | private: 88 | const int min_; 89 | const int max_; 90 | 91 | GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl); 92 | }; 93 | 94 | // Formats "n times" in a human-friendly way. 95 | inline internal::string FormatTimes(int n) { 96 | if (n == 1) { 97 | return "once"; 98 | } else if (n == 2) { 99 | return "twice"; 100 | } else { 101 | std::stringstream ss; 102 | ss << n << " times"; 103 | return ss.str(); 104 | } 105 | } 106 | 107 | // Describes the Between(m, n) cardinality in human-friendly text. 108 | void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const { 109 | if (min_ == 0) { 110 | if (max_ == 0) { 111 | *os << "never called"; 112 | } else if (max_ == INT_MAX) { 113 | *os << "called any number of times"; 114 | } else { 115 | *os << "called at most " << FormatTimes(max_); 116 | } 117 | } else if (min_ == max_) { 118 | *os << "called " << FormatTimes(min_); 119 | } else if (max_ == INT_MAX) { 120 | *os << "called at least " << FormatTimes(min_); 121 | } else { 122 | // 0 < min_ < max_ < INT_MAX 123 | *os << "called between " << min_ << " and " << max_ << " times"; 124 | } 125 | } 126 | 127 | } // Unnamed namespace 128 | 129 | // Describes the given call count to an ostream. 130 | void Cardinality::DescribeActualCallCountTo(int actual_call_count, 131 | ::std::ostream* os) { 132 | if (actual_call_count > 0) { 133 | *os << "called " << FormatTimes(actual_call_count); 134 | } else { 135 | *os << "never called"; 136 | } 137 | } 138 | 139 | // Creates a cardinality that allows at least n calls. 140 | GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); } 141 | 142 | // Creates a cardinality that allows at most n calls. 143 | GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); } 144 | 145 | // Creates a cardinality that allows any number of calls. 146 | GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); } 147 | 148 | // Creates a cardinality that allows between min and max calls. 149 | GTEST_API_ Cardinality Between(int min, int max) { 150 | return Cardinality(new BetweenCardinalityImpl(min, max)); 151 | } 152 | 153 | // Creates a cardinality that allows exactly n calls. 154 | GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); } 155 | 156 | } // namespace testing 157 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/src/gmock-internal-utils.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2007, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | // Google Mock - a framework for writing C++ mock classes. 33 | // 34 | // This file defines some utilities useful for implementing Google 35 | // Mock. They are subject to change without notice, so please DO NOT 36 | // USE THEM IN USER CODE. 37 | 38 | #include "gmock/internal/gmock-internal-utils.h" 39 | 40 | #include 41 | #include // NOLINT 42 | #include 43 | #include "gmock/gmock.h" 44 | #include "gmock/internal/gmock-port.h" 45 | #include "gtest/gtest.h" 46 | 47 | namespace testing { 48 | namespace internal { 49 | 50 | // Converts an identifier name to a space-separated list of lower-case 51 | // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is 52 | // treated as one word. For example, both "FooBar123" and 53 | // "foo_bar_123" are converted to "foo bar 123". 54 | GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) { 55 | string result; 56 | char prev_char = '\0'; 57 | for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) { 58 | // We don't care about the current locale as the input is 59 | // guaranteed to be a valid C++ identifier name. 60 | const bool starts_new_word = IsUpper(*p) || 61 | (!IsAlpha(prev_char) && IsLower(*p)) || 62 | (!IsDigit(prev_char) && IsDigit(*p)); 63 | 64 | if (IsAlNum(*p)) { 65 | if (starts_new_word && result != "") 66 | result += ' '; 67 | result += ToLower(*p); 68 | } 69 | } 70 | return result; 71 | } 72 | 73 | // This class reports Google Mock failures as Google Test failures. A 74 | // user can define another class in a similar fashion if he intends to 75 | // use Google Mock with a testing framework other than Google Test. 76 | class GoogleTestFailureReporter : public FailureReporterInterface { 77 | public: 78 | virtual void ReportFailure(FailureType type, const char* file, int line, 79 | const string& message) { 80 | AssertHelper(type == kFatal ? 81 | TestPartResult::kFatalFailure : 82 | TestPartResult::kNonFatalFailure, 83 | file, 84 | line, 85 | message.c_str()) = Message(); 86 | if (type == kFatal) { 87 | posix::Abort(); 88 | } 89 | } 90 | }; 91 | 92 | // Returns the global failure reporter. Will create a 93 | // GoogleTestFailureReporter and return it the first time called. 94 | GTEST_API_ FailureReporterInterface* GetFailureReporter() { 95 | // Points to the global failure reporter used by Google Mock. gcc 96 | // guarantees that the following use of failure_reporter is 97 | // thread-safe. We may need to add additional synchronization to 98 | // protect failure_reporter if we port Google Mock to other 99 | // compilers. 100 | static FailureReporterInterface* const failure_reporter = 101 | new GoogleTestFailureReporter(); 102 | return failure_reporter; 103 | } 104 | 105 | // Protects global resources (stdout in particular) used by Log(). 106 | static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex); 107 | 108 | // Returns true iff a log with the given severity is visible according 109 | // to the --gmock_verbose flag. 110 | GTEST_API_ bool LogIsVisible(LogSeverity severity) { 111 | if (GMOCK_FLAG(verbose) == kInfoVerbosity) { 112 | // Always show the log if --gmock_verbose=info. 113 | return true; 114 | } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) { 115 | // Always hide it if --gmock_verbose=error. 116 | return false; 117 | } else { 118 | // If --gmock_verbose is neither "info" nor "error", we treat it 119 | // as "warning" (its default value). 120 | return severity == kWarning; 121 | } 122 | } 123 | 124 | // Prints the given message to stdout iff 'severity' >= the level 125 | // specified by the --gmock_verbose flag. If stack_frames_to_skip >= 126 | // 0, also prints the stack trace excluding the top 127 | // stack_frames_to_skip frames. In opt mode, any positive 128 | // stack_frames_to_skip is treated as 0, since we don't know which 129 | // function calls will be inlined by the compiler and need to be 130 | // conservative. 131 | GTEST_API_ void Log(LogSeverity severity, 132 | const string& message, 133 | int stack_frames_to_skip) { 134 | if (!LogIsVisible(severity)) 135 | return; 136 | 137 | // Ensures that logs from different threads don't interleave. 138 | MutexLock l(&g_log_mutex); 139 | 140 | // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a 141 | // macro. 142 | 143 | if (severity == kWarning) { 144 | // Prints a GMOCK WARNING marker to make the warnings easily searchable. 145 | std::cout << "\nGMOCK WARNING:"; 146 | } 147 | // Pre-pends a new-line to message if it doesn't start with one. 148 | if (message.empty() || message[0] != '\n') { 149 | std::cout << "\n"; 150 | } 151 | std::cout << message; 152 | if (stack_frames_to_skip >= 0) { 153 | #ifdef NDEBUG 154 | // In opt mode, we have to be conservative and skip no stack frame. 155 | const int actual_to_skip = 0; 156 | #else 157 | // In dbg mode, we can do what the caller tell us to do (plus one 158 | // for skipping this function's stack frame). 159 | const int actual_to_skip = stack_frames_to_skip + 1; 160 | #endif // NDEBUG 161 | 162 | // Appends a new-line to message if it doesn't end with one. 163 | if (!message.empty() && *message.rbegin() != '\n') { 164 | std::cout << "\n"; 165 | } 166 | std::cout << "Stack trace:\n" 167 | << ::testing::internal::GetCurrentOsStackTraceExceptTop( 168 | ::testing::UnitTest::GetInstance(), actual_to_skip); 169 | } 170 | std::cout << ::std::flush; 171 | } 172 | 173 | } // namespace internal 174 | } // namespace testing 175 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/src/gmock.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | #include "gmock/gmock.h" 33 | #include "gmock/internal/gmock-port.h" 34 | 35 | namespace testing { 36 | 37 | // TODO(wan@google.com): support using environment variables to 38 | // control the flag values, like what Google Test does. 39 | 40 | GMOCK_DEFINE_bool_(catch_leaked_mocks, true, 41 | "true iff Google Mock should report leaked mock objects " 42 | "as failures."); 43 | 44 | GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity, 45 | "Controls how verbose Google Mock's output is." 46 | " Valid values:\n" 47 | " info - prints all messages.\n" 48 | " warning - prints warnings and errors.\n" 49 | " error - prints errors only."); 50 | 51 | namespace internal { 52 | 53 | // Parses a string as a command line flag. The string should have the 54 | // format "--gmock_flag=value". When def_optional is true, the 55 | // "=value" part can be omitted. 56 | // 57 | // Returns the value of the flag, or NULL if the parsing failed. 58 | static const char* ParseGoogleMockFlagValue(const char* str, 59 | const char* flag, 60 | bool def_optional) { 61 | // str and flag must not be NULL. 62 | if (str == NULL || flag == NULL) return NULL; 63 | 64 | // The flag must start with "--gmock_". 65 | const std::string flag_str = std::string("--gmock_") + flag; 66 | const size_t flag_len = flag_str.length(); 67 | if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; 68 | 69 | // Skips the flag name. 70 | const char* flag_end = str + flag_len; 71 | 72 | // When def_optional is true, it's OK to not have a "=value" part. 73 | if (def_optional && (flag_end[0] == '\0')) { 74 | return flag_end; 75 | } 76 | 77 | // If def_optional is true and there are more characters after the 78 | // flag name, or if def_optional is false, there must be a '=' after 79 | // the flag name. 80 | if (flag_end[0] != '=') return NULL; 81 | 82 | // Returns the string after "=". 83 | return flag_end + 1; 84 | } 85 | 86 | // Parses a string for a Google Mock bool flag, in the form of 87 | // "--gmock_flag=value". 88 | // 89 | // On success, stores the value of the flag in *value, and returns 90 | // true. On failure, returns false without changing *value. 91 | static bool ParseGoogleMockBoolFlag(const char* str, const char* flag, 92 | bool* value) { 93 | // Gets the value of the flag as a string. 94 | const char* const value_str = ParseGoogleMockFlagValue(str, flag, true); 95 | 96 | // Aborts if the parsing failed. 97 | if (value_str == NULL) return false; 98 | 99 | // Converts the string value to a bool. 100 | *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); 101 | return true; 102 | } 103 | 104 | // Parses a string for a Google Mock string flag, in the form of 105 | // "--gmock_flag=value". 106 | // 107 | // On success, stores the value of the flag in *value, and returns 108 | // true. On failure, returns false without changing *value. 109 | static bool ParseGoogleMockStringFlag(const char* str, const char* flag, 110 | std::string* value) { 111 | // Gets the value of the flag as a string. 112 | const char* const value_str = ParseGoogleMockFlagValue(str, flag, false); 113 | 114 | // Aborts if the parsing failed. 115 | if (value_str == NULL) return false; 116 | 117 | // Sets *value to the value of the flag. 118 | *value = value_str; 119 | return true; 120 | } 121 | 122 | // The internal implementation of InitGoogleMock(). 123 | // 124 | // The type parameter CharType can be instantiated to either char or 125 | // wchar_t. 126 | template 127 | void InitGoogleMockImpl(int* argc, CharType** argv) { 128 | // Makes sure Google Test is initialized. InitGoogleTest() is 129 | // idempotent, so it's fine if the user has already called it. 130 | InitGoogleTest(argc, argv); 131 | if (*argc <= 0) return; 132 | 133 | for (int i = 1; i != *argc; i++) { 134 | const std::string arg_string = StreamableToString(argv[i]); 135 | const char* const arg = arg_string.c_str(); 136 | 137 | // Do we see a Google Mock flag? 138 | if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks", 139 | &GMOCK_FLAG(catch_leaked_mocks)) || 140 | ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) { 141 | // Yes. Shift the remainder of the argv list left by one. Note 142 | // that argv has (*argc + 1) elements, the last one always being 143 | // NULL. The following loop moves the trailing NULL element as 144 | // well. 145 | for (int j = i; j != *argc; j++) { 146 | argv[j] = argv[j + 1]; 147 | } 148 | 149 | // Decrements the argument count. 150 | (*argc)--; 151 | 152 | // We also need to decrement the iterator as we just removed 153 | // an element. 154 | i--; 155 | } 156 | } 157 | } 158 | 159 | } // namespace internal 160 | 161 | // Initializes Google Mock. This must be called before running the 162 | // tests. In particular, it parses a command line for the flags that 163 | // Google Mock recognizes. Whenever a Google Mock flag is seen, it is 164 | // removed from argv, and *argc is decremented. 165 | // 166 | // No value is returned. Instead, the Google Mock flag variables are 167 | // updated. 168 | // 169 | // Since Google Test is needed for Google Mock to work, this function 170 | // also initializes Google Test and parses its flags, if that hasn't 171 | // been done. 172 | GTEST_API_ void InitGoogleMock(int* argc, char** argv) { 173 | internal::InitGoogleMockImpl(argc, argv); 174 | } 175 | 176 | // This overloaded version can be used in Windows programs compiled in 177 | // UNICODE mode. 178 | GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) { 179 | internal::InitGoogleMockImpl(argc, argv); 180 | } 181 | 182 | } // namespace testing 183 | -------------------------------------------------------------------------------- /unix/third_party/gmock-1.7.0/src/gmock_main.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // Author: wan@google.com (Zhanyong Wan) 31 | 32 | #include 33 | #include "gmock/gmock.h" 34 | #include "gtest/gtest.h" 35 | 36 | // MS C++ compiler/linker has a bug on Windows (not on Windows CE), which 37 | // causes a link error when _tmain is defined in a static library and UNICODE 38 | // is enabled. For this reason instead of _tmain, main function is used on 39 | // Windows. See the following link to track the current status of this bug: 40 | // http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=394464 // NOLINT 41 | #if GTEST_OS_WINDOWS_MOBILE 42 | # include // NOLINT 43 | 44 | GTEST_API_ int _tmain(int argc, TCHAR** argv) { 45 | #else 46 | GTEST_API_ int main(int argc, char** argv) { 47 | #endif // GTEST_OS_WINDOWS_MOBILE 48 | std::cout << "Running main() from gmock_main.cc\n"; 49 | // Since Google Mock depends on Google Test, InitGoogleMock() is 50 | // also responsible for initializing Google Test. Therefore there's 51 | // no need for calling testing::InitGoogleTest() separately. 52 | testing::InitGoogleMock(&argc, argv); 53 | return RUN_ALL_TESTS(); 54 | } 55 | -------------------------------------------------------------------------------- /unix/valgrind.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | LIB_PATH=out/Default/lib:$FIGTREE/unix/:third_party/_install/lib:$LD_LIBRARY_PATH 3 | DYLD_LIBRARY_PATH=$LIB_PATH LD_LIBRARY_PATH=$LIB_PATH valgrind --tool=memcheck --leak-check=yes $@ 4 | --------------------------------------------------------------------------------