<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrGLInterface.h"

#include <OpenGL/gl.h>
#include <OpenGL/glext.h>

#include <mach-o/dyld.h>

// This uses deprecated functions, should rewrite using dlopen, dlsym, dlclose
void* GetProcAddress(const char* name) {
    NSSymbol symbol = NULL;
    if (NSIsSymbolNameDefined(name)) {
        symbol = NSLookupAndBindSymbol(name);
    }
    return NULL == symbol ? NULL : NSAddressOfSymbol(symbol);
}

#define GET_PROC(name) ((GrGL ## name ## Proc) GetProcAddress("_gl" #name))
#define GET_PROC_SUFFIX(name, suffix) ((GrGL ## name ## Proc) GetProcAddress("_gl" #name #suffix))

const GrGLInterface* GrGLCreateNativeInterface() {
    // The gl functions are not context-specific so we create one global
    // interface
    static SkAutoTUnref<GrGLInterface> glInterface;
    if (!glInterface.get()) {
        GrGLInterface* interface = new GrGLInterface;
        glInterface.reset(interface);
        const char* verStr = (const char*) glGetString(GL_VERSION);
        GrGLVersion ver = GrGLGetVersionFromString(verStr);
        const char* extStr = (const char*) glGetString(GL_EXTENSIONS);

        interface->fBindingsExported = kDesktop_GrGLBinding;
        interface->fActiveTexture = glActiveTexture;
        interface->fAttachShader = glAttachShader;
        interface->fBeginQuery = glBeginQuery;
        interface->fBindAttribLocation = glBindAttribLocation;
        interface->fBindBuffer = glBindBuffer;
        if (ver >= GR_GL_VER(3,0)) {
            #if GL_VERSION_3_0
                interface->fBindFragDataLocation = glBindFragDataLocation;
            #else
                interface->fBindFragDataLocation = GET_PROC(BindFragDataLocation);
            #endif
        }
        interface->fBindTexture = glBindTexture;
        interface->fBlendColor = glBlendColor;
        interface->fBlendFunc = glBlendFunc;
        interface->fBufferData = glBufferData;
        interface->fBufferSubData = glBufferSubData;
        interface->fClear = glClear;
        interface->fClearColor = glClearColor;
        interface->fClearStencil = glClearStencil;
        interface->fColorMask = glColorMask;
        interface->fColorPointer = glColorPointer;
        interface->fCompileShader = glCompileShader;
        interface->fCompressedTexImage2D = glCompressedTexImage2D;
        interface->fCreateProgram = glCreateProgram;
        interface->fCreateShader = glCreateShader;
        interface->fCullFace = glCullFace;
        interface->fDeleteBuffers = glDeleteBuffers;
        interface->fDeleteProgram = glDeleteProgram;
        interface->fDeleteQueries = glDeleteQueries;
        interface->fDeleteShader = glDeleteShader;
        interface->fDeleteTextures = glDeleteTextures;
        interface->fDepthMask = glDepthMask;
        interface->fDisable = glDisable;
        interface->fDisableVertexAttribArray =
                                            glDisableVertexAttribArray;
        interface->fDrawArrays = glDrawArrays;
        interface->fDrawBuffer = glDrawBuffer;
        interface->fDrawBuffers = glDrawBuffers;
        interface->fDrawElements = glDrawElements;
        interface->fEnable = glEnable;
        interface->fEnableVertexAttribArray = glEnableVertexAttribArray;
        interface->fEndQuery = glEndQuery;
        interface->fFinish = glFinish;
        interface->fFlush = glFlush;
        interface->fFrontFace = glFrontFace;
        interface->fGenBuffers = glGenBuffers;
        interface->fGenQueries = glGenQueries;
        interface->fGetBufferParameteriv = glGetBufferParameteriv;
        interface->fGetError = glGetError;
        interface->fGetIntegerv = glGetIntegerv;
        interface->fGetProgramInfoLog = glGetProgramInfoLog;
        interface->fGetProgramiv = glGetProgramiv;
        interface->fGetQueryiv = glGetQueryiv;
        interface->fGetQueryObjectiv = glGetQueryObjectiv;
        interface->fGetQueryObjectuiv = glGetQueryObjectuiv;
        interface->fGetShaderInfoLog = glGetShaderInfoLog;
        interface->fGetShaderiv = glGetShaderiv;
        interface->fGetString = glGetString;
        interface->fGetTexLevelParameteriv = glGetTexLevelParameteriv;
        interface->fGenTextures = glGenTextures;
        interface->fGetUniformLocation = glGetUniformLocation;
        interface->fLineWidth = glLineWidth;
        interface->fLinkProgram = glLinkProgram;
        interface->fMapBuffer = glMapBuffer;
        interface->fPixelStorei = glPixelStorei;
        interface->fReadBuffer = glReadBuffer;
        interface->fReadPixels = glReadPixels;
        interface->fScissor = glScissor;
        interface->fShaderSource = glShaderSource;
        interface->fStencilFunc = glStencilFunc;
        interface->fStencilFuncSeparate = glStencilFuncSeparate;
        interface->fStencilMask = glStencilMask;
        interface->fStencilMaskSeparate = glStencilMaskSeparate;
        interface->fStencilOp = glStencilOp;
        interface->fStencilOpSeparate = glStencilOpSeparate;
        // mac uses GLenum for internalFormat param (non-standard)
        // amounts to int vs. uint.
        interface->fTexImage2D = (GrGLTexImage2DProc)glTexImage2D;
        interface->fTexParameteri = glTexParameteri;
    #if GL_ARB_texture_storage || GL_VERSION_4_2
        interface->fTexStorage2D = glTexStorage2D
    #elif GL_EXT_texture_storage
        interface->fTexStorage2D = glTexStorage2DEXT;
    #else
        if (glVer >= GR_GL_VER(4,2) ||
            GrGLHasExtensionFromString("GL_ARB_texture_storage", extString)) {
            GR_GL_GET_PROC(TexStorage2D);
        } else if (GrGLHasExtensionFromString("GL_EXT_texture_storage", extString)) {
            GR_GL_GET_PROC_SUFFIX(TexStorage2D, EXT);
        }
    #endif
        interface->fTexSubImage2D = glTexSubImage2D;
        interface->fUniform1f = glUniform1f;
        interface->fUniform1i = glUniform1i;
        interface->fUniform1fv = glUniform1fv;
        interface->fUniform1iv = glUniform1iv;
        interface->fUniform2f = glUniform2f;
        interface->fUniform2i = glUniform2i;
        interface->fUniform2fv = glUniform2fv;
        interface->fUniform2iv = glUniform2iv;
        interface->fUniform3f = glUniform3f;
        interface->fUniform3i = glUniform3i;
        interface->fUniform3fv = glUniform3fv;
        interface->fUniform3iv = glUniform3iv;
        interface->fUniform4f = glUniform4f;
        interface->fUniform4i = glUniform4i;
        interface->fUniform4fv = glUniform4fv;
        interface->fUniform4iv = glUniform4iv;
        interface->fUniform4fv = glUniform4fv;
        interface->fUniformMatrix2fv = glUniformMatrix2fv;
        interface->fUniformMatrix3fv = glUniformMatrix3fv;
        interface->fUniformMatrix4fv = glUniformMatrix4fv;
        interface->fUnmapBuffer = glUnmapBuffer;
        interface->fUseProgram = glUseProgram;
        interface->fVertexAttrib4fv = glVertexAttrib4fv;
        interface->fVertexAttribPointer = glVertexAttribPointer;
        interface->fViewport = glViewport;

        if (ver >= GR_GL_VER(3,3) || GrGLHasExtensionFromString("GL_ARB_timer_query", extStr)) {
            // ARB extension doesn't use the ARB suffix on the function name
            #if GL_ARB_timer_query || GL_VERSION_3_3
                interface->fQueryCounter = glQueryCounter;
                interface->fGetQueryObjecti64v = glGetQueryObjecti64v;
                interface->fGetQueryObjectui64v = glGetQueryObjectui64v;
            #else
                interface->fQueryCounter = GET_PROC(QueryCounter);
                interface->fGetQueryObjecti64v = GET_PROC(GetQueryObjecti64v);
                interface->fGetQueryObjectui64v = GET_PROC(GetQueryObjectui64v);
            #endif
        } else if (GrGLHasExtensionFromString("GL_EXT_timer_query", extStr)) {
            #if GL_EXT_timer_query
                interface->fGetQueryObjecti64v = glGetQueryObjecti64vEXT;
                interface->fGetQueryObjectui64v = glGetQueryObjectui64vEXT;
            #else
                interface->fGetQueryObjecti64v = GET_PROC_SUFFIX(GetQueryObjecti64v, EXT);
                interface->fGetQueryObjectui64v = GET_PROC_SUFFIX(GetQueryObjectui64v, EXT);
            #endif
        }

        if (ver >= GR_GL_VER(3,0) || GrGLHasExtensionFromString("GL_ARB_framebuffer_object", extStr)) {
            // ARB extension doesn't use the ARB suffix on the function names
            #if GL_VERSION_3_0 || GL_ARB_framebuffer_object
                interface->fGenFramebuffers = glGenFramebuffers;
                interface->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameteriv;
                interface->fGetRenderbufferParameteriv = glGetRenderbufferParameteriv;
                interface->fBindFramebuffer = glBindFramebuffer;
                interface->fFramebufferTexture2D = glFramebufferTexture2D;
                interface->fCheckFramebufferStatus = glCheckFramebufferStatus;
                interface->fDeleteFramebuffers = glDeleteFramebuffers;
                interface->fRenderbufferStorage = glRenderbufferStorage;
                interface->fGenRenderbuffers = glGenRenderbuffers;
                interface->fDeleteRenderbuffers = glDeleteRenderbuffers;
                interface->fFramebufferRenderbuffer = glFramebufferRenderbuffer;
                interface->fBindRenderbuffer = glBindRenderbuffer;
                interface->fRenderbufferStorageMultisample = glRenderbufferStorageMultisample;
                interface->fBlitFramebuffer = glBlitFramebuffer;
            #else
                interface->fGenFramebuffers = GET_PROC(GenFramebuffers);
                interface->fGetFramebufferAttachmentParameteriv = GET_PROC(GetFramebufferAttachmentParameteriv);
                interface->fGetRenderbufferParameteriv = GET_PROC(GetRenderbufferParameteriv);
                interface->fBindFramebuffer = GET_PROC(BindFramebuffer);
                interface->fFramebufferTexture2D = GET_PROC(FramebufferTexture2D);
                interface->fCheckFramebufferStatus = GET_PROC(CheckFramebufferStatus);
                interface->fDeleteFramebuffers = GET_PROC(DeleteFramebuffers);
                interface->fRenderbufferStorage = GET_PROC(RenderbufferStorage);
                interface->fGenRenderbuffers = GET_PROC(GenRenderbuffers);
                interface->fDeleteRenderbuffers = GET_PROC(DeleteRenderbuffers);
                interface->fFramebufferRenderbuffer = GET_PROC(FramebufferRenderbuffer);
                interface->fBindRenderbuffer = GET_PROC(BindRenderbuffer);
                interface->fRenderbufferStorageMultisample = GET_PROC(RenderbufferStorageMultisample);
                interface->fBlitFramebuffer = GET_PROC(BlitFramebuffer);
            #endif
        } else {
            if (GrGLHasExtensionFromString("GL_EXT_framebuffer_object", extStr)) {
                #if GL_EXT_framebuffer_object
                    interface->fGenFramebuffers = glGenFramebuffersEXT;
                    interface->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameterivEXT;
                    interface->fGetRenderbufferParameteriv = glGetRenderbufferParameterivEXT;
                    interface->fBindFramebuffer = glBindFramebufferEXT;
                    interface->fFramebufferTexture2D = glFramebufferTexture2DEXT;
                    interface->fCheckFramebufferStatus = glCheckFramebufferStatusEXT;
                    interface->fDeleteFramebuffers = glDeleteFramebuffersEXT;
                    interface->fRenderbufferStorage = glRenderbufferStorageEXT;
                    interface->fGenRenderbuffers = glGenRenderbuffersEXT;
                    interface->fDeleteRenderbuffers = glDeleteRenderbuffersEXT;
                    interface->fFramebufferRenderbuffer = glFramebufferRenderbufferEXT;
                    interface->fBindRenderbuffer = glBindRenderbufferEXT;
                #else
                    interface->fGenFramebuffers = GET_PROC_SUFFIX(GenFramebuffers, EXT);
                    interface->fGetFramebufferAttachmentParameteriv = GET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT);
                    interface->fGetRenderbufferParameteriv = GET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT);
                    interface->fBindFramebuffer = GET_PROC_SUFFIX(BindFramebuffer, EXT);
                    interface->fFramebufferTexture2D = GET_PROC_SUFFIX(FramebufferTexture2D, EXT);
                    interface->fCheckFramebufferStatus = GET_PROC_SUFFIX(CheckFramebufferStatus, EXT);
                    interface->fDeleteFramebuffers = GET_PROC_SUFFIX(DeleteFramebuffers, EXT);
                    interface->fRenderbufferStorage = GET_PROC_SUFFIX(RenderbufferStorage, EXT);
                    interface->fGenRenderbuffers = GET_PROC_SUFFIX(GenRenderbuffers, EXT);
                    interface->fDeleteRenderbuffers = GET_PROC_SUFFIX(DeleteRenderbuffers, EXT);
                    interface->fFramebufferRenderbuffer = GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT);
                    interface->fBindRenderbuffer = GET_PROC_SUFFIX(BindRenderbuffer, EXT);
                #endif
            }
            if (GrGLHasExtensionFromString("GL_EXT_framebuffer_multisample", extStr)) {
                #if GL_EXT_framebuffer_multisample
                    interface->fRenderbufferStorageMultisample = glRenderbufferStorageMultisampleEXT;
                #else
                    interface->fRenderbufferStorageMultisample = GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT);
                #endif
            }
            if (GrGLHasExtensionFromString("", extStr)) {
                #if GL_EXT_framebuffer_blit
                    interface->fBlitFramebuffer = glBlitFramebufferEXT;
                #else
                    interface->fBlitFramebuffer = GET_PROC_SUFFIX(BlitFramebuffer, EXT);
                #endif
            }
        }
        if (ver >= GR_GL_VER(3,3) || GrGLHasExtensionFromString("GL_ARB_blend_func_extended", extStr)) {
            // ARB extension doesn't use the ARB suffix on the function name
            #if GL_VERSION_3_3 || GL_ARB_blend_func_extended
                interface->fBindFragDataLocationIndexed = glBindFragDataLocationIndexed;
            #else
                interface->fBindFragDataLocationIndexed = GET_PROC(BindFragDataLocationIndexed);
            #endif
        }

        interface->fBindingsExported = kDesktop_GrGLBinding;
    }
    glInterface.get()->ref();
    return glInterface.get();
}
<commit_msg>Fix Mac build<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrGLInterface.h"

#include <OpenGL/gl.h>
#include <OpenGL/glext.h>

#include <mach-o/dyld.h>

// This uses deprecated functions, should rewrite using dlopen, dlsym, dlclose
void* GetProcAddress(const char* name) {
    NSSymbol symbol = NULL;
    if (NSIsSymbolNameDefined(name)) {
        symbol = NSLookupAndBindSymbol(name);
    }
    return NULL == symbol ? NULL : NSAddressOfSymbol(symbol);
}

#define GET_PROC(name) ((GrGL ## name ## Proc) GetProcAddress("_gl" #name))
#define GET_PROC_SUFFIX(name, suffix) ((GrGL ## name ## Proc) GetProcAddress("_gl" #name #suffix))

const GrGLInterface* GrGLCreateNativeInterface() {
    // The gl functions are not context-specific so we create one global
    // interface
    static SkAutoTUnref<GrGLInterface> glInterface;
    if (!glInterface.get()) {
        GrGLInterface* interface = new GrGLInterface;
        glInterface.reset(interface);
        const char* verStr = (const char*) glGetString(GL_VERSION);
        GrGLVersion ver = GrGLGetVersionFromString(verStr);
        const char* extStr = (const char*) glGetString(GL_EXTENSIONS);

        interface->fBindingsExported = kDesktop_GrGLBinding;
        interface->fActiveTexture = glActiveTexture;
        interface->fAttachShader = glAttachShader;
        interface->fBeginQuery = glBeginQuery;
        interface->fBindAttribLocation = glBindAttribLocation;
        interface->fBindBuffer = glBindBuffer;
        if (ver >= GR_GL_VER(3,0)) {
            #if GL_VERSION_3_0
                interface->fBindFragDataLocation = glBindFragDataLocation;
            #else
                interface->fBindFragDataLocation = GET_PROC(BindFragDataLocation);
            #endif
        }
        interface->fBindTexture = glBindTexture;
        interface->fBlendColor = glBlendColor;
        interface->fBlendFunc = glBlendFunc;
        interface->fBufferData = glBufferData;
        interface->fBufferSubData = glBufferSubData;
        interface->fClear = glClear;
        interface->fClearColor = glClearColor;
        interface->fClearStencil = glClearStencil;
        interface->fColorMask = glColorMask;
        interface->fColorPointer = glColorPointer;
        interface->fCompileShader = glCompileShader;
        interface->fCompressedTexImage2D = glCompressedTexImage2D;
        interface->fCreateProgram = glCreateProgram;
        interface->fCreateShader = glCreateShader;
        interface->fCullFace = glCullFace;
        interface->fDeleteBuffers = glDeleteBuffers;
        interface->fDeleteProgram = glDeleteProgram;
        interface->fDeleteQueries = glDeleteQueries;
        interface->fDeleteShader = glDeleteShader;
        interface->fDeleteTextures = glDeleteTextures;
        interface->fDepthMask = glDepthMask;
        interface->fDisable = glDisable;
        interface->fDisableVertexAttribArray =
                                            glDisableVertexAttribArray;
        interface->fDrawArrays = glDrawArrays;
        interface->fDrawBuffer = glDrawBuffer;
        interface->fDrawBuffers = glDrawBuffers;
        interface->fDrawElements = glDrawElements;
        interface->fEnable = glEnable;
        interface->fEnableVertexAttribArray = glEnableVertexAttribArray;
        interface->fEndQuery = glEndQuery;
        interface->fFinish = glFinish;
        interface->fFlush = glFlush;
        interface->fFrontFace = glFrontFace;
        interface->fGenBuffers = glGenBuffers;
        interface->fGenQueries = glGenQueries;
        interface->fGetBufferParameteriv = glGetBufferParameteriv;
        interface->fGetError = glGetError;
        interface->fGetIntegerv = glGetIntegerv;
        interface->fGetProgramInfoLog = glGetProgramInfoLog;
        interface->fGetProgramiv = glGetProgramiv;
        interface->fGetQueryiv = glGetQueryiv;
        interface->fGetQueryObjectiv = glGetQueryObjectiv;
        interface->fGetQueryObjectuiv = glGetQueryObjectuiv;
        interface->fGetShaderInfoLog = glGetShaderInfoLog;
        interface->fGetShaderiv = glGetShaderiv;
        interface->fGetString = glGetString;
        interface->fGetTexLevelParameteriv = glGetTexLevelParameteriv;
        interface->fGenTextures = glGenTextures;
        interface->fGetUniformLocation = glGetUniformLocation;
        interface->fLineWidth = glLineWidth;
        interface->fLinkProgram = glLinkProgram;
        interface->fMapBuffer = glMapBuffer;
        interface->fPixelStorei = glPixelStorei;
        interface->fReadBuffer = glReadBuffer;
        interface->fReadPixels = glReadPixels;
        interface->fScissor = glScissor;
        interface->fShaderSource = glShaderSource;
        interface->fStencilFunc = glStencilFunc;
        interface->fStencilFuncSeparate = glStencilFuncSeparate;
        interface->fStencilMask = glStencilMask;
        interface->fStencilMaskSeparate = glStencilMaskSeparate;
        interface->fStencilOp = glStencilOp;
        interface->fStencilOpSeparate = glStencilOpSeparate;
        // mac uses GLenum for internalFormat param (non-standard)
        // amounts to int vs. uint.
        interface->fTexImage2D = (GrGLTexImage2DProc)glTexImage2D;
        interface->fTexParameteri = glTexParameteri;
    #if GL_ARB_texture_storage || GL_VERSION_4_2
        interface->fTexStorage2D = glTexStorage2D
    #elif GL_EXT_texture_storage
        interface->fTexStorage2D = glTexStorage2DEXT;
    #else
        if (ver >= GR_GL_VER(4,2) ||
            GrGLHasExtensionFromString("GL_ARB_texture_storage", extStr)) {
            GET_PROC(TexStorage2D);
        } else if (GrGLHasExtensionFromString("GL_EXT_texture_storage", extStr)) {
            GET_PROC_SUFFIX(TexStorage2D, EXT);
        }
    #endif
        interface->fTexSubImage2D = glTexSubImage2D;
        interface->fUniform1f = glUniform1f;
        interface->fUniform1i = glUniform1i;
        interface->fUniform1fv = glUniform1fv;
        interface->fUniform1iv = glUniform1iv;
        interface->fUniform2f = glUniform2f;
        interface->fUniform2i = glUniform2i;
        interface->fUniform2fv = glUniform2fv;
        interface->fUniform2iv = glUniform2iv;
        interface->fUniform3f = glUniform3f;
        interface->fUniform3i = glUniform3i;
        interface->fUniform3fv = glUniform3fv;
        interface->fUniform3iv = glUniform3iv;
        interface->fUniform4f = glUniform4f;
        interface->fUniform4i = glUniform4i;
        interface->fUniform4fv = glUniform4fv;
        interface->fUniform4iv = glUniform4iv;
        interface->fUniform4fv = glUniform4fv;
        interface->fUniformMatrix2fv = glUniformMatrix2fv;
        interface->fUniformMatrix3fv = glUniformMatrix3fv;
        interface->fUniformMatrix4fv = glUniformMatrix4fv;
        interface->fUnmapBuffer = glUnmapBuffer;
        interface->fUseProgram = glUseProgram;
        interface->fVertexAttrib4fv = glVertexAttrib4fv;
        interface->fVertexAttribPointer = glVertexAttribPointer;
        interface->fViewport = glViewport;

        if (ver >= GR_GL_VER(3,3) || GrGLHasExtensionFromString("GL_ARB_timer_query", extStr)) {
            // ARB extension doesn't use the ARB suffix on the function name
            #if GL_ARB_timer_query || GL_VERSION_3_3
                interface->fQueryCounter = glQueryCounter;
                interface->fGetQueryObjecti64v = glGetQueryObjecti64v;
                interface->fGetQueryObjectui64v = glGetQueryObjectui64v;
            #else
                interface->fQueryCounter = GET_PROC(QueryCounter);
                interface->fGetQueryObjecti64v = GET_PROC(GetQueryObjecti64v);
                interface->fGetQueryObjectui64v = GET_PROC(GetQueryObjectui64v);
            #endif
        } else if (GrGLHasExtensionFromString("GL_EXT_timer_query", extStr)) {
            #if GL_EXT_timer_query
                interface->fGetQueryObjecti64v = glGetQueryObjecti64vEXT;
                interface->fGetQueryObjectui64v = glGetQueryObjectui64vEXT;
            #else
                interface->fGetQueryObjecti64v = GET_PROC_SUFFIX(GetQueryObjecti64v, EXT);
                interface->fGetQueryObjectui64v = GET_PROC_SUFFIX(GetQueryObjectui64v, EXT);
            #endif
        }

        if (ver >= GR_GL_VER(3,0) || GrGLHasExtensionFromString("GL_ARB_framebuffer_object", extStr)) {
            // ARB extension doesn't use the ARB suffix on the function names
            #if GL_VERSION_3_0 || GL_ARB_framebuffer_object
                interface->fGenFramebuffers = glGenFramebuffers;
                interface->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameteriv;
                interface->fGetRenderbufferParameteriv = glGetRenderbufferParameteriv;
                interface->fBindFramebuffer = glBindFramebuffer;
                interface->fFramebufferTexture2D = glFramebufferTexture2D;
                interface->fCheckFramebufferStatus = glCheckFramebufferStatus;
                interface->fDeleteFramebuffers = glDeleteFramebuffers;
                interface->fRenderbufferStorage = glRenderbufferStorage;
                interface->fGenRenderbuffers = glGenRenderbuffers;
                interface->fDeleteRenderbuffers = glDeleteRenderbuffers;
                interface->fFramebufferRenderbuffer = glFramebufferRenderbuffer;
                interface->fBindRenderbuffer = glBindRenderbuffer;
                interface->fRenderbufferStorageMultisample = glRenderbufferStorageMultisample;
                interface->fBlitFramebuffer = glBlitFramebuffer;
            #else
                interface->fGenFramebuffers = GET_PROC(GenFramebuffers);
                interface->fGetFramebufferAttachmentParameteriv = GET_PROC(GetFramebufferAttachmentParameteriv);
                interface->fGetRenderbufferParameteriv = GET_PROC(GetRenderbufferParameteriv);
                interface->fBindFramebuffer = GET_PROC(BindFramebuffer);
                interface->fFramebufferTexture2D = GET_PROC(FramebufferTexture2D);
                interface->fCheckFramebufferStatus = GET_PROC(CheckFramebufferStatus);
                interface->fDeleteFramebuffers = GET_PROC(DeleteFramebuffers);
                interface->fRenderbufferStorage = GET_PROC(RenderbufferStorage);
                interface->fGenRenderbuffers = GET_PROC(GenRenderbuffers);
                interface->fDeleteRenderbuffers = GET_PROC(DeleteRenderbuffers);
                interface->fFramebufferRenderbuffer = GET_PROC(FramebufferRenderbuffer);
                interface->fBindRenderbuffer = GET_PROC(BindRenderbuffer);
                interface->fRenderbufferStorageMultisample = GET_PROC(RenderbufferStorageMultisample);
                interface->fBlitFramebuffer = GET_PROC(BlitFramebuffer);
            #endif
        } else {
            if (GrGLHasExtensionFromString("GL_EXT_framebuffer_object", extStr)) {
                #if GL_EXT_framebuffer_object
                    interface->fGenFramebuffers = glGenFramebuffersEXT;
                    interface->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameterivEXT;
                    interface->fGetRenderbufferParameteriv = glGetRenderbufferParameterivEXT;
                    interface->fBindFramebuffer = glBindFramebufferEXT;
                    interface->fFramebufferTexture2D = glFramebufferTexture2DEXT;
                    interface->fCheckFramebufferStatus = glCheckFramebufferStatusEXT;
                    interface->fDeleteFramebuffers = glDeleteFramebuffersEXT;
                    interface->fRenderbufferStorage = glRenderbufferStorageEXT;
                    interface->fGenRenderbuffers = glGenRenderbuffersEXT;
                    interface->fDeleteRenderbuffers = glDeleteRenderbuffersEXT;
                    interface->fFramebufferRenderbuffer = glFramebufferRenderbufferEXT;
                    interface->fBindRenderbuffer = glBindRenderbufferEXT;
                #else
                    interface->fGenFramebuffers = GET_PROC_SUFFIX(GenFramebuffers, EXT);
                    interface->fGetFramebufferAttachmentParameteriv = GET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT);
                    interface->fGetRenderbufferParameteriv = GET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT);
                    interface->fBindFramebuffer = GET_PROC_SUFFIX(BindFramebuffer, EXT);
                    interface->fFramebufferTexture2D = GET_PROC_SUFFIX(FramebufferTexture2D, EXT);
                    interface->fCheckFramebufferStatus = GET_PROC_SUFFIX(CheckFramebufferStatus, EXT);
                    interface->fDeleteFramebuffers = GET_PROC_SUFFIX(DeleteFramebuffers, EXT);
                    interface->fRenderbufferStorage = GET_PROC_SUFFIX(RenderbufferStorage, EXT);
                    interface->fGenRenderbuffers = GET_PROC_SUFFIX(GenRenderbuffers, EXT);
                    interface->fDeleteRenderbuffers = GET_PROC_SUFFIX(DeleteRenderbuffers, EXT);
                    interface->fFramebufferRenderbuffer = GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT);
                    interface->fBindRenderbuffer = GET_PROC_SUFFIX(BindRenderbuffer, EXT);
                #endif
            }
            if (GrGLHasExtensionFromString("GL_EXT_framebuffer_multisample", extStr)) {
                #if GL_EXT_framebuffer_multisample
                    interface->fRenderbufferStorageMultisample = glRenderbufferStorageMultisampleEXT;
                #else
                    interface->fRenderbufferStorageMultisample = GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT);
                #endif
            }
            if (GrGLHasExtensionFromString("", extStr)) {
                #if GL_EXT_framebuffer_blit
                    interface->fBlitFramebuffer = glBlitFramebufferEXT;
                #else
                    interface->fBlitFramebuffer = GET_PROC_SUFFIX(BlitFramebuffer, EXT);
                #endif
            }
        }
        if (ver >= GR_GL_VER(3,3) || GrGLHasExtensionFromString("GL_ARB_blend_func_extended", extStr)) {
            // ARB extension doesn't use the ARB suffix on the function name
            #if GL_VERSION_3_3 || GL_ARB_blend_func_extended
                interface->fBindFragDataLocationIndexed = glBindFragDataLocationIndexed;
            #else
                interface->fBindFragDataLocationIndexed = GET_PROC(BindFragDataLocationIndexed);
            #endif
        }

        interface->fBindingsExported = kDesktop_GrGLBinding;
    }
    glInterface.get()->ref();
    return glInterface.get();
}
<|endoftext|>


<commit_before>#include "Launcher.h"
#include "DirectX.h"
#include "Engine.h"

using namespace Core;
using namespace Device;

void Launcher::Run(const WinApp::Param& winParam, const Rect<uint>& viewport, bool useMSAA)
{
	WinApp win(winParam);
	DirectX dx;
	Engine engine(dx);

	// Init System
	{
		win.Initialize();
		dx.Initialize(win, viewport, useMSAA);
		engine.Initialize();
	}

	// Loop
	{
		MSG msg;
		ZeroMemory(&msg, sizeof(msg));

		while ((msg.message != WM_QUIT) && (_exit == false))
		{
			if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) == false)
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
			else
			{
				engine.RunScene();
			}
		}
	}

	// Destroy
	{
		dx.Destroy();
		win.Destroy();
		engine.Destroy();
	}
}<commit_msg>Lauuncher 불필요한 함수 제거<commit_after>#include "Launcher.h"
#include "DirectX.h"
#include "Engine.h"

using namespace Core;
using namespace Device;

void Launcher::Run(const WinApp::Param& winParam, const Rect<uint>& viewport, bool useMSAA)
{
	WinApp win(winParam);
	DirectX dx;
	Engine engine(dx);

	// Init System
	{
		win.Initialize();
		dx.Initialize(win, viewport, useMSAA);
		engine.Initialize();
	}

	// Loop
	{
		MSG msg;
		ZeroMemory(&msg, sizeof(msg));

		while ((msg.message != WM_QUIT) && (_exit == false))
		{
			if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) == false)
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
			else
			{
				engine.RunScene();
			}
		}
	}

	// Destroy
	{
		win.Destroy();
		engine.Destroy();
	}
}<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "formeditorgraphicsview.h"

#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>

#include <qmlanchors.h>

namespace QmlDesigner {

FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
    QGraphicsView(parent)
{
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorViewCenter);
    setAlignment(Qt::AlignCenter);
    setCacheMode(QGraphicsView::CacheNone);
    setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
    setOptimizationFlags(QGraphicsView::DontSavePainterState);
//    setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    setRenderHint(QPainter::Antialiasing, false);

    setFrameShape(QFrame::NoFrame);

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Window);

    const int checkerbordSize= 20;
    QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
    tilePixmap.fill(Qt::white);
    QPainter tilePainter(&tilePixmap);
    QColor color(220, 220, 220);
    tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
    tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
    tilePainter.end();

    setBackgroundBrush(tilePixmap);

    viewport()->setMouseTracking(true);
}

void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
    if (event->modifiers().testFlag(Qt::ControlModifier)) {
        event->ignore();
    } else {
        QGraphicsView::wheelEvent(event);
    }

}

void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    if (rect().contains(event->pos())) {
        QGraphicsView::mouseMoveEvent(event);
    } else {
        QPoint position = event->pos();
        QPoint topLeft = rect().topLeft();
        QPoint bottomRight = rect().bottomRight();
        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

        QGraphicsView::mouseMoveEvent(mouseEvent);
        delete mouseEvent;
    }

    // Keeps the feedback bubble within screen boundraries
    int tx = qMin(width() - 114,  qMax(16, event->pos().x() + 50));
    int ty = qMin(height() - 45, qMax(10, event->pos().y() - 70));
    m_feedbackOriginPoint = QPoint(tx, ty);
}

void FormEditorGraphicsView::keyPressEvent(QKeyEvent *event)
{
    m_feedbackOriginPoint = QPoint();
    QGraphicsView::keyPressEvent(event);
}

void FormEditorGraphicsView::setRootItemRect(const QRectF &rect)
{
    m_rootItemRect = rect;
    viewport()->update();
}

QRectF FormEditorGraphicsView::rootItemRect() const
{
    return m_rootItemRect;
}

void FormEditorGraphicsView::mousePressEvent(QMouseEvent *mouseEvent)
{
    QGraphicsView::mousePressEvent(mouseEvent);
}

void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    if (rect().contains(event->pos())) {
        QGraphicsView::mouseReleaseEvent(event);
    } else {
        QPoint position = event->pos();
        QPoint topLeft = rect().topLeft();
        QPoint bottomRight = rect().bottomRight();
        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

        QGraphicsView::mouseReleaseEvent(mouseEvent);
        delete mouseEvent;
    }

    m_feedbackOriginPoint = QPoint();
}

void FormEditorGraphicsView::leaveEvent(QEvent *event)
{
     m_feedbackOriginPoint = QPoint();
     QGraphicsView::leaveEvent(event);
 }

static QPixmap createBubblePixmap()
{
    QPixmap pixmap(124, 48);
    pixmap.fill(Qt::transparent);
    QPainter pmPainter(&pixmap);
    pmPainter.setRenderHint(QPainter::Antialiasing);
    pmPainter.setOpacity(0.85);
    pmPainter.translate(0.5, 0.5);
    pmPainter.setPen(Qt::NoPen);
    pmPainter.setBrush(QColor(0, 0, 0, 40));
    pmPainter.drawRoundedRect(QRect(0, 0, 124, 48), 8, 8);
    QLinearGradient gradient(QPoint(0, 0), QPoint(0, 44));
    gradient.setColorAt(0.0, QColor(70, 70, 70));
    gradient.setColorAt(1.0, QColor(10, 10, 10));
    pmPainter.setBrush(gradient);
    pmPainter.setPen(QColor(60, 60, 60));
    pmPainter.drawRoundedRect(QRect(2, 1, 120, 45), 5, 5);
    pmPainter.setBrush(Qt::NoBrush);
    pmPainter.setPen(QColor(255, 255, 255, 140));
    pmPainter.drawRoundedRect(QRect(3, 2, 118, 43), 5, 5);
    pmPainter.end();
    return pixmap;
}

void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
    if (!m_feedbackNode.isValid())
        return;

    if (m_feedbackOriginPoint.isNull())
        return;

    painter->save();
    painter->resetTransform();
    painter->translate(m_feedbackOriginPoint);

    QColor defaultColor(Qt::white);
    QColor changeColor("#9999ff");

    QFont font;
    font.setFamily("Helvetica");
    font.setPixelSize(12);
    painter->setFont(font);

    if (m_bubblePixmap.isNull())
        m_bubblePixmap = createBubblePixmap();
    painter->drawPixmap(-13, -7, m_bubblePixmap);

    if (m_beginXHasExpression) {
        if(m_feedbackNode.hasBindingProperty("x"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginX != m_feedbackNode.instanceValue("x"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(8.0, 13.0), QString("x:"));
    painter->drawText(QPoint(22.0, 13.0), m_feedbackNode.instanceValue("x").toString());

    if (m_beginYHasExpression) {
        if(m_feedbackNode.hasBindingProperty("y"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginY != m_feedbackNode.instanceValue("y"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(60.0, 13.0), QString("y:"));
    painter->drawText(QPoint(72.0, 13.0), m_feedbackNode.instanceValue("y").toString());

    if (m_beginWidthHasExpression) {
        if(m_feedbackNode.hasBindingProperty("width"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginWidth != m_feedbackNode.instanceValue("width"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(8.0, 29.0), QString("w:"));
    painter->drawText(QPoint(22.0, 29.0), m_feedbackNode.instanceValue("width").toString());

    if (m_beginHeightHasExpression) {
        if(m_feedbackNode.hasBindingProperty("height"))
            painter->setPen(defaultColor);
        else
            painter->setPen(Qt::red);
    } else {
        if (m_beginHeight != m_feedbackNode.instanceValue("height"))
            painter->setPen(changeColor);
        else
            painter->setPen(defaultColor);
    }

    painter->drawText(QPoint(60.0, 29.0), QString("h:"));
    painter->drawText(QPoint(72.0, 29.0), m_feedbackNode.instanceValue("height").toString());

    if (m_parentNode != m_feedbackNode.instanceParent()) {
        painter->setPen(changeColor);
        painter->drawText(QPoint(2.0, 39.0), QString("Parent changed"));

    }

    painter->restore();
}

void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
    if (node == m_feedbackNode)
        return;

    m_feedbackNode = node;

    if (m_feedbackNode.isValid()) {
        m_beginX = m_feedbackNode.instanceValue("x");
        m_beginY = m_feedbackNode.instanceValue("y");
        m_beginWidth = m_feedbackNode.instanceValue("width");
        m_beginHeight = m_feedbackNode.instanceValue("height");
        m_parentNode = m_feedbackNode.instanceParent();
        m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
        m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
        m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
        m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
        m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
        m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
        m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
        m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
    } else {
        m_beginX = QVariant();
        m_beginY = QVariant();
        m_beginWidth = QVariant();
        m_beginHeight = QVariant();
        m_parentNode = QmlObjectNode();
        m_beginLeftMargin = QVariant();
        m_beginRightMargin = QVariant();
        m_beginTopMargin = QVariant();
        m_beginBottomMargin = QVariant();
        m_beginXHasExpression = false;
        m_beginYHasExpression = false;
        m_beginWidthHasExpression = false;
        m_beginHeightHasExpression = false;
    }
}

void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rectangle)
{
    painter->save();
    painter->setBrushOrigin(0, 0);

    painter->fillRect(rectangle.intersected(rootItemRect()), backgroundBrush());
    // paint rect around editable area
    painter->setPen(Qt::black);
    painter->drawRect( rootItemRect());
    painter->restore();
}

} // namespace QmlDesigner
<commit_msg>QmlDesigner.FormEditor: Disable feedback pane<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "formeditorgraphicsview.h"

#include <QWheelEvent>
#include <QApplication>
#include <QtDebug>

#include <qmlanchors.h>

namespace QmlDesigner {

FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
    QGraphicsView(parent)
{
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorViewCenter);
    setAlignment(Qt::AlignCenter);
    setCacheMode(QGraphicsView::CacheNone);
    setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
    setOptimizationFlags(QGraphicsView::DontSavePainterState);
//    setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    setRenderHint(QPainter::Antialiasing, false);

    setFrameShape(QFrame::NoFrame);

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Window);

    const int checkerbordSize= 20;
    QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
    tilePixmap.fill(Qt::white);
    QPainter tilePainter(&tilePixmap);
    QColor color(220, 220, 220);
    tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
    tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
    tilePainter.end();

    setBackgroundBrush(tilePixmap);

    viewport()->setMouseTracking(true);
}

void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
    if (event->modifiers().testFlag(Qt::ControlModifier)) {
        event->ignore();
    } else {
        QGraphicsView::wheelEvent(event);
    }

}

void FormEditorGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    QGraphicsView::mouseMoveEvent(event);

//    if (rect().contains(event->pos())) {
//        QGraphicsView::mouseMoveEvent(event);
//    } else {
//        QPoint position = event->pos();
//        QPoint topLeft = rect().topLeft();
//        QPoint bottomRight = rect().bottomRight();
//        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
//        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
//        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

//        QGraphicsView::mouseMoveEvent(mouseEvent);
//        delete mouseEvent;
//    }

//    // Keeps the feedback bubble within screen boundraries
//    int tx = qMin(width() - 114,  qMax(16, event->pos().x() + 50));
//    int ty = qMin(height() - 45, qMax(10, event->pos().y() - 70));
//    m_feedbackOriginPoint = QPoint(tx, ty);
}

void FormEditorGraphicsView::keyPressEvent(QKeyEvent *event)
{
    m_feedbackOriginPoint = QPoint();
    QGraphicsView::keyPressEvent(event);
}

void FormEditorGraphicsView::setRootItemRect(const QRectF &rect)
{
    m_rootItemRect = rect;
    viewport()->update();
}

QRectF FormEditorGraphicsView::rootItemRect() const
{
    return m_rootItemRect;
}

void FormEditorGraphicsView::mousePressEvent(QMouseEvent *mouseEvent)
{
    QGraphicsView::mousePressEvent(mouseEvent);
}

void FormEditorGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    QGraphicsView::mouseReleaseEvent(event);
//    if (rect().contains(event->pos())) {
//        QGraphicsView::mouseReleaseEvent(event);
//    } else {
//        QPoint position = event->pos();
//        QPoint topLeft = rect().topLeft();
//        QPoint bottomRight = rect().bottomRight();
//        position.rx() = qMax(topLeft.x(), qMin(position.x(), bottomRight.x()));
//        position.ry() = qMax(topLeft.y(), qMin(position.y(), bottomRight.y()));
//        QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(event->type(), position, mapToGlobal(position), event->button(), event->buttons(), event->modifiers());

//        QGraphicsView::mouseReleaseEvent(mouseEvent);
//        delete mouseEvent;
//    }

//    m_feedbackOriginPoint = QPoint();
}

void FormEditorGraphicsView::leaveEvent(QEvent *event)
{
     m_feedbackOriginPoint = QPoint();
     QGraphicsView::leaveEvent(event);
 }

static QPixmap createBubblePixmap()
{
    QPixmap pixmap(124, 48);
    pixmap.fill(Qt::transparent);
    QPainter pmPainter(&pixmap);
    pmPainter.setRenderHint(QPainter::Antialiasing);
    pmPainter.setOpacity(0.85);
    pmPainter.translate(0.5, 0.5);
    pmPainter.setPen(Qt::NoPen);
    pmPainter.setBrush(QColor(0, 0, 0, 40));
    pmPainter.drawRoundedRect(QRect(0, 0, 124, 48), 8, 8);
    QLinearGradient gradient(QPoint(0, 0), QPoint(0, 44));
    gradient.setColorAt(0.0, QColor(70, 70, 70));
    gradient.setColorAt(1.0, QColor(10, 10, 10));
    pmPainter.setBrush(gradient);
    pmPainter.setPen(QColor(60, 60, 60));
    pmPainter.drawRoundedRect(QRect(2, 1, 120, 45), 5, 5);
    pmPainter.setBrush(Qt::NoBrush);
    pmPainter.setPen(QColor(255, 255, 255, 140));
    pmPainter.drawRoundedRect(QRect(3, 2, 118, 43), 5, 5);
    pmPainter.end();
    return pixmap;
}

void FormEditorGraphicsView::drawForeground(QPainter *painter, const QRectF &/*rect*/ )
{
//    if (!m_feedbackNode.isValid())
//        return;

//    if (m_feedbackOriginPoint.isNull())
//        return;

//    painter->save();
//    painter->resetTransform();
//    painter->translate(m_feedbackOriginPoint);

//    QColor defaultColor(Qt::white);
//    QColor changeColor("#9999ff");

//    QFont font;
//    font.setFamily("Helvetica");
//    font.setPixelSize(12);
//    painter->setFont(font);

//    if (m_bubblePixmap.isNull())
//        m_bubblePixmap = createBubblePixmap();
//    painter->drawPixmap(-13, -7, m_bubblePixmap);

//    if (m_beginXHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("x"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginX != m_feedbackNode.instanceValue("x"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(8.0, 13.0), QString("x:"));
//    painter->drawText(QPoint(22.0, 13.0), m_feedbackNode.instanceValue("x").toString());

//    if (m_beginYHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("y"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginY != m_feedbackNode.instanceValue("y"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(60.0, 13.0), QString("y:"));
//    painter->drawText(QPoint(72.0, 13.0), m_feedbackNode.instanceValue("y").toString());

//    if (m_beginWidthHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("width"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginWidth != m_feedbackNode.instanceValue("width"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(8.0, 29.0), QString("w:"));
//    painter->drawText(QPoint(22.0, 29.0), m_feedbackNode.instanceValue("width").toString());

//    if (m_beginHeightHasExpression) {
//        if(m_feedbackNode.hasBindingProperty("height"))
//            painter->setPen(defaultColor);
//        else
//            painter->setPen(Qt::red);
//    } else {
//        if (m_beginHeight != m_feedbackNode.instanceValue("height"))
//            painter->setPen(changeColor);
//        else
//            painter->setPen(defaultColor);
//    }

//    painter->drawText(QPoint(60.0, 29.0), QString("h:"));
//    painter->drawText(QPoint(72.0, 29.0), m_feedbackNode.instanceValue("height").toString());

//    if (m_parentNode != m_feedbackNode.instanceParent()) {
//        painter->setPen(changeColor);
//        painter->drawText(QPoint(2.0, 39.0), QString("Parent changed"));

//    }

//    painter->restore();
}

void FormEditorGraphicsView::setFeedbackNode(const QmlItemNode &node)
{
//    if (node == m_feedbackNode)
//        return;

//    m_feedbackNode = node;

//    if (m_feedbackNode.isValid()) {
//        m_beginX = m_feedbackNode.instanceValue("x");
//        m_beginY = m_feedbackNode.instanceValue("y");
//        m_beginWidth = m_feedbackNode.instanceValue("width");
//        m_beginHeight = m_feedbackNode.instanceValue("height");
//        m_parentNode = m_feedbackNode.instanceParent();
//        m_beginLeftMargin = m_feedbackNode.instanceValue("anchors.leftMargin");
//        m_beginRightMargin = m_feedbackNode.instanceValue("anchors.rightMargin");
//        m_beginTopMargin = m_feedbackNode.instanceValue("anchors.topMargin");
//        m_beginBottomMargin = m_feedbackNode.instanceValue("anchors.bottomMargin");
//        m_beginXHasExpression = m_feedbackNode.hasBindingProperty("x");
//        m_beginYHasExpression = m_feedbackNode.hasBindingProperty("y");
//        m_beginWidthHasExpression = m_feedbackNode.hasBindingProperty("width");
//        m_beginHeightHasExpression = m_feedbackNode.hasBindingProperty("height");
//    } else {
//        m_beginX = QVariant();
//        m_beginY = QVariant();
//        m_beginWidth = QVariant();
//        m_beginHeight = QVariant();
//        m_parentNode = QmlObjectNode();
//        m_beginLeftMargin = QVariant();
//        m_beginRightMargin = QVariant();
//        m_beginTopMargin = QVariant();
//        m_beginBottomMargin = QVariant();
//        m_beginXHasExpression = false;
//        m_beginYHasExpression = false;
//        m_beginWidthHasExpression = false;
//        m_beginHeightHasExpression = false;
//    }
}

void FormEditorGraphicsView::drawBackground(QPainter *painter, const QRectF &rectangle)
{
    painter->save();
    painter->setBrushOrigin(0, 0);

    painter->fillRect(rectangle.intersected(rootItemRect()), backgroundBrush());
    // paint rect around editable area
    painter->setPen(Qt::black);
    painter->drawRect( rootItemRect());
    painter->restore();
}

} // namespace QmlDesigner
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdint>
#include <string>
#include <memory>
#include <list>

#include "boost/format.hpp"

#include "packet.h"
#include "exceptions.h"
#include "parser.h"

namespace parse4880 {

PGPPacket::PGPPacket(std::string contents) : contents_(contents) {
}

std::shared_ptr<PGPPacket> PGPPacket::ParsePacket(uint8_t tag,
                                                  std::string packet) {
  try {
    switch (tag) {
      case 2:
        return std::shared_ptr<PGPPacket>(new SignaturePacket(packet));
        break;
      case 6:
        return std::shared_ptr<PGPPacket>(new PublicKeyPacket(packet));
        break;
      case 13:
        return std::shared_ptr<PGPPacket>(new UserIDPacket(packet));
        break;
      case 14:
        return std::shared_ptr<PGPPacket>(new PublicSubkeyPacket(packet));
        break;
      default:
        return std::shared_ptr<PGPPacket>(new UnknownPGPPacket(tag, packet));
    }
  } catch (parse4880_error e) {
    return std::shared_ptr<PGPPacket>(new UnknownPGPPacket(tag, packet));
  }
}

const std::list<std::shared_ptr<PGPPacket>>& PGPPacket::subpackets() const {
  return subpackets_;
}

const std::string& PGPPacket::contents() const {
  return contents_;
}

}
<commit_msg>Removed unnecessary break statements.<commit_after>#include <cstdio>
#include <cstdint>
#include <string>
#include <memory>
#include <list>

#include "boost/format.hpp"

#include "packet.h"
#include "exceptions.h"
#include "parser.h"

namespace parse4880 {

PGPPacket::PGPPacket(std::string contents) : contents_(contents) {
}

std::shared_ptr<PGPPacket> PGPPacket::ParsePacket(uint8_t tag,
                                                  std::string packet) {
  try {
    switch (tag) {
      case 2:
        return std::shared_ptr<PGPPacket>(new SignaturePacket(packet));
      case 6:
        return std::shared_ptr<PGPPacket>(new PublicKeyPacket(packet));
      case 13:
        return std::shared_ptr<PGPPacket>(new UserIDPacket(packet));
      case 14:
        return std::shared_ptr<PGPPacket>(new PublicSubkeyPacket(packet));
      default:
        return std::shared_ptr<PGPPacket>(new UnknownPGPPacket(tag, packet));
    }
  } catch (parse4880_error e) {
    return std::shared_ptr<PGPPacket>(new UnknownPGPPacket(tag, packet));
  }
}

const std::list<std::shared_ptr<PGPPacket>>& PGPPacket::subpackets() const {
  return subpackets_;
}

const std::string& PGPPacket::contents() const {
  return contents_;
}

}
<|endoftext|>


<commit_before>#include "helpers.hpp"
#include <count.hpp>

#include <vector>
#include <iterator>
#include <utility>

#include "catch.hpp"

using iter::count;

TEST_CASE("count: watch for 10 elements", "[count]") {
    std::vector<int> v{};
    for (auto i : count()) {
        v.push_back(i);
        if (i == 9) break;
    }

    const std::vector<int> vc{0,1,2,3,4,5,6,7,8,9};
    REQUIRE( v == vc );
}

TEST_CASE("count: start at 10", "[count]") {
    std::vector<int> v{};
    for (auto i : count(10)) {
        v.push_back(i);
        if (i == 14) break;
    }

    const std::vector<int> vc{10,11,12,13,14};
    REQUIRE( v == vc );
}

TEST_CASE("count with step", "[count]") {
    std::vector<int> v{};
    for (auto i : count(2, -1)) {
        v.push_back(i);
        if (i == -3) break;
    }

    const std::vector<int> vc{2,1,0,-1,-2,-3};
    REQUIRE( v == vc);
}
<commit_msg>adds count test with step >1<commit_after>#include "helpers.hpp"
#include <count.hpp>

#include <vector>
#include <iterator>
#include <utility>

#include "catch.hpp"

using iter::count;

TEST_CASE("count: watch for 10 elements", "[count]") {
    std::vector<int> v{};
    for (auto i : count()) {
        v.push_back(i);
        if (i == 9) break;
    }

    const std::vector<int> vc{0,1,2,3,4,5,6,7,8,9};
    REQUIRE( v == vc );
}

TEST_CASE("count: start at 10", "[count]") {
    std::vector<int> v{};
    for (auto i : count(10)) {
        v.push_back(i);
        if (i == 14) break;
    }

    const std::vector<int> vc{10,11,12,13,14};
    REQUIRE( v == vc );
}

TEST_CASE("count: with step", "[count]") {
    std::vector<int> v{};
    for (auto i : count(2, -1)) {
        v.push_back(i);
        if (i == -3) break;
    }

    const std::vector<int> vc{2,1,0,-1,-2,-3};
    REQUIRE( v == vc);
}

TEST_CASE("count: with step > 1", "[count]") {
    std::vector<int> v{};
    for (auto i : count(10, 2)) {
        v.push_back(i);
        if (i == 16) break;
    }

    const std::vector<int> vc{10, 12, 14, 16};
    REQUIRE( v == vc );
}
<|endoftext|>


<commit_before>// mixing different itertools, there is nothing called iter::mixed()

#include "imap.hpp"
#include "filter.hpp"

#include "catch.hpp"

#include <iostream>
#include <vector>

using iter::filter;
using iter::imap;

class MyUnMovable {
    int val;
public:
    constexpr MyUnMovable(int val)
        : val{val}
    { }

    MyUnMovable(const MyUnMovable&) = delete;
    MyUnMovable& operator=(const MyUnMovable&) = delete;

    MyUnMovable(MyUnMovable&& other)
        : val{other.val}
    { }

    constexpr int get_val() const {
        return val;
    }
    void set_val(int val) {
        this->val = val;
    }

    bool operator==(const MyUnMovable& other) const {
        return this->val == other.val;
    }

    bool operator!=(const MyUnMovable& other) const {
        return !(*this == other);
    }
};

TEST_CASE("imap and filter where imap Functor modifies its sequence",
    "[imap][filter]") {

    // source data
    std::array<MyUnMovable, 3> arr = {{{41}, {42}, {43}}};

    // some transformations
    auto inc_ten = [](MyUnMovable& el) -> MyUnMovable& {
        int va = el.get_val();
        el.set_val(va + 10);
        return el;
    };
    auto dec_ten = [](MyUnMovable& el) -> MyUnMovable& {
        int va = el.get_val();
        el.set_val(va - 10);
        return el;
    };

    auto transformed1 = imap(inc_ten, arr);
    auto filtered = filter([](const MyUnMovable& el) {
        return 52 != el.get_val();
    }, transformed1);
    auto transformed2 = imap(dec_ten, filtered);

    std::vector<int> v;
    for (auto&& el : transformed2) {
        // I would use imap again instead of the loop if this wasn't an imap
        // test
        v.push_back(el.get_val());
    }

    std::vector<int> vc = {41, 43};

    REQUIRE( v == vc);

    constexpr std::array<MyUnMovable, 3> arrc = {{{41}, {52}, {43}}};
    REQUIRE( arr == arrc );
}
<commit_msg>adds double-deref test for dropwhile<commit_after>// mixing different itertools, there is nothing called iter::mixed()

#include "itertools.hpp"

#include "catch.hpp"

#include <iostream>
#include <vector>

class MyUnMovable {
    int val;
public:
    constexpr MyUnMovable(int val)
        : val{val}
    { }

    MyUnMovable(const MyUnMovable&) = delete;
    MyUnMovable& operator=(const MyUnMovable&) = delete;

    MyUnMovable(MyUnMovable&& other)
        : val{other.val}
    { }

    constexpr int get_val() const {
        return val;
    }
    void set_val(int val) {
        this->val = val;
    }

    bool operator==(const MyUnMovable& other) const {
        return this->val == other.val;
    }

    bool operator!=(const MyUnMovable& other) const {
        return !(*this == other);
    }
};

namespace {
    auto inc_ten = [](MyUnMovable& el) -> MyUnMovable& {
        int va = el.get_val();
        el.set_val(va + 10);
        return el;
    };
    auto dec_ten = [](MyUnMovable& el) -> MyUnMovable& {
        int va = el.get_val();
        el.set_val(va - 10);
        return el;
    };
}

TEST_CASE("filtering doesn't dereference multiple times", "[imap][filter]") {
    using iter::filter;
    using iter::imap;

    // source data
    std::array<MyUnMovable, 3> arr = {{{41}, {42}, {43}}};

    auto transformed1 = imap(inc_ten, arr);
    auto filtered = filter([](const MyUnMovable& el) {
        return 52 != el.get_val();
    }, transformed1);
    auto transformed2 = imap(dec_ten, filtered);

    std::vector<int> v;
    for (auto&& el : transformed2) {
        // I would use imap again instead of the loop if this wasn't an imap
        // test
        v.push_back(el.get_val());
    }

    std::vector<int> vc = {41, 43};

    REQUIRE( v == vc);

    constexpr std::array<MyUnMovable, 3> arrc = {{{41}, {52}, {43}}};
    REQUIRE( arr == arrc );
}

TEST_CASE("dropwhile doesn't dereference multiple times", "[imap][dropwhile]"){
    using iter::imap;
    using iter::dropwhile;
    // source data
    std::array<MyUnMovable, 3> arr = {{{41}, {42}, {43}}};

    auto transformed1 = imap(inc_ten, arr);
    auto filtered = dropwhile([](const MyUnMovable& el) {
        return 52 != el.get_val();
    }, transformed1);
    auto transformed2 = imap(dec_ten, filtered);

    std::vector<int> v;
    for (auto&& el : transformed2) {
        v.push_back(el.get_val());
    }

    std::vector<int> vc = {42, 43};

    constexpr std::array<MyUnMovable, 3> arrc = {{{51}, {42}, {43}}};
    REQUIRE( arr == arrc );
}
<|endoftext|>


<commit_before>/*
    This file is part of cpp-ethereum.

    cpp-ethereum is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    cpp-ethereum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Scope - object that holds declaration of names.
 */

#include <libsolidity/DeclarationContainer.h>
#include <libsolidity/AST.h>
#include <libsolidity/Types.h>

using namespace std;
using namespace dev;
using namespace dev::solidity;

bool DeclarationContainer::registerDeclaration(Declaration const& _declaration, bool _invisible, bool _update)
{
	ASTString const& name(_declaration.getName());
	if (name.empty())
		return true;

	if (_update)
	{
		solAssert(!dynamic_cast<FunctionDefinition const*>(&_declaration), "Attempt to update function definition.");
		m_declarations[name].clear();
		m_invisibleDeclarations[name].clear();
	}
	else
	{
		if (dynamic_cast<FunctionDefinition const*>(&_declaration))
		{
			// check that all other declarations with the same name are functions
			for (auto&& declaration: m_invisibleDeclarations[name] + m_declarations[name])
				if (!dynamic_cast<FunctionDefinition const*>(declaration))
					return false;
		}
		else if (m_declarations.count(name) > 0 || m_invisibleDeclarations.count(name) > 0)
			return false;
	}

	if (_invisible)
		m_invisibleDeclarations[name].insert(&_declaration);
	else
		m_declarations[name].insert(&_declaration);

	return true;
}

set<Declaration const*> DeclarationContainer::resolveName(ASTString const& _name, bool _recursive) const
{
	solAssert(!_name.empty(), "Attempt to resolve empty name.");
	auto result = m_declarations.find(_name);
	if (result != m_declarations.end())
		return result->second;
	if (_recursive && m_enclosingContainer)
		return m_enclosingContainer->resolveName(_name, true);
	return set<Declaration const*>({});
}
<commit_msg>Fix for declarations.<commit_after>/*
    This file is part of cpp-ethereum.

    cpp-ethereum is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    cpp-ethereum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Scope - object that holds declaration of names.
 */

#include <libsolidity/DeclarationContainer.h>
#include <libsolidity/AST.h>
#include <libsolidity/Types.h>

using namespace std;
using namespace dev;
using namespace dev::solidity;

bool DeclarationContainer::registerDeclaration(Declaration const& _declaration, bool _invisible, bool _update)
{
	ASTString const& name(_declaration.getName());
	if (name.empty())
		return true;

	if (_update)
	{
		solAssert(!dynamic_cast<FunctionDefinition const*>(&_declaration), "Attempt to update function definition.");
		m_declarations.erase(name);
		m_invisibleDeclarations.erase(name);
	}
	else
	{
		vector<Declaration const*> declarations;
		if (m_declarations.count(name))
			declarations += m_declarations.at(name);
		if (m_invisibleDeclarations.count(name))
			declarations += m_invisibleDeclarations.at(name);
		if (dynamic_cast<FunctionDefinition const*>(&_declaration))
		{
			// check that all other declarations with the same name are functions

			for (Declaration const* declaration: declarations)
				if (!dynamic_cast<FunctionDefinition const*>(declaration))
					return false;
		}
		else if (!declarations.empty())
			return false;
	}

	if (_invisible)
		m_invisibleDeclarations[name].insert(&_declaration);
	else
		m_declarations[name].insert(&_declaration);

	return true;
}

set<Declaration const*> DeclarationContainer::resolveName(ASTString const& _name, bool _recursive) const
{
	solAssert(!_name.empty(), "Attempt to resolve empty name.");
	auto result = m_declarations.find(_name);
	if (result != m_declarations.end())
		return result->second;
	if (_recursive && m_enclosingContainer)
		return m_enclosingContainer->resolveName(_name, true);
	return set<Declaration const*>({});
}
<|endoftext|>


<commit_before>/*
	This file is part of solidity.

	solidity is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	solidity is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with solidity.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2016
 * Code-generating part of inline assembly.
 */

#include <libsolidity/inlineasm/AsmCodeGen.h>

#include <libsolidity/inlineasm/AsmParser.h>
#include <libsolidity/inlineasm/AsmData.h>
#include <libsolidity/inlineasm/AsmScope.h>
#include <libsolidity/inlineasm/AsmAnalysis.h>
#include <libsolidity/inlineasm/AsmAnalysisInfo.h>

#include <libevmasm/Assembly.h>
#include <libevmasm/SourceLocation.h>
#include <libevmasm/Instruction.h>

#include <libdevcore/CommonIO.h>

#include <boost/range/adaptor/reversed.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/algorithm/count_if.hpp>

#include <memory>
#include <functional>

using namespace std;
using namespace dev;
using namespace dev::solidity;
using namespace dev::solidity::assembly;

struct GeneratorState
{
	GeneratorState(ErrorList& _errors, AsmAnalysisInfo& _analysisInfo, eth::Assembly& _assembly):
		errors(_errors), info(_analysisInfo), assembly(_assembly) {}

	size_t newLabelId()
	{
		return assemblyTagToIdentifier(assembly.newTag());
	}

	size_t assemblyTagToIdentifier(eth::AssemblyItem const& _tag) const
	{
		u256 id = _tag.data();
		solAssert(id <= std::numeric_limits<size_t>::max(), "Tag id too large.");
		return size_t(id);
	}

	ErrorList& errors;
	AsmAnalysisInfo info;
	eth::Assembly& assembly;
};

class CodeTransform: public boost::static_visitor<>
{
public:
	/// Create the code transformer which appends assembly to _state.assembly when called
	/// with parsed assembly data.
	/// @param _identifierAccess used to resolve identifiers external to the inline assembly
	explicit CodeTransform(
		GeneratorState& _state,
		assembly::Block const& _block,
		assembly::ExternalIdentifierAccess const& _identifierAccess = assembly::ExternalIdentifierAccess()
	):
		m_state(_state),
		m_scope(*m_state.info.scopes.at(&_block)),
		m_initialDeposit(m_state.assembly.deposit()),
		m_identifierAccess(_identifierAccess)
	{
		std::for_each(_block.statements.begin(), _block.statements.end(), boost::apply_visitor(*this));

		m_state.assembly.setSourceLocation(_block.location);

		// pop variables
		for (auto const& identifier: m_scope.identifiers)
			if (identifier.second.type() == typeid(Scope::Variable))
				m_state.assembly.append(solidity::Instruction::POP);

		int deposit = m_state.assembly.deposit() - m_initialDeposit;

		solAssert(deposit == 0, "Invalid stack height at end of block.");
	}

	void operator()(assembly::Instruction const& _instruction)
	{
		m_state.assembly.setSourceLocation(_instruction.location);
		m_state.assembly.append(_instruction.instruction);
	}
	void operator()(assembly::Literal const& _literal)
	{
		m_state.assembly.setSourceLocation(_literal.location);
		if (_literal.isNumber)
			m_state.assembly.append(u256(_literal.value));
		else
		{
			solAssert(_literal.value.size() <= 32, "");
			m_state.assembly.append(u256(h256(_literal.value, h256::FromBinary, h256::AlignLeft)));
		}
	}
	void operator()(assembly::Identifier const& _identifier)
	{
		m_state.assembly.setSourceLocation(_identifier.location);
		// First search internals, then externals.
		if (m_scope.lookup(_identifier.name, Scope::NonconstVisitor(
			[=](Scope::Variable& _var)
			{
				if (int heightDiff = variableHeightDiff(_var, _identifier.location, false))
					m_state.assembly.append(solidity::dupInstruction(heightDiff));
				else
					// Store something to balance the stack
					m_state.assembly.append(u256(0));
			},
			[=](Scope::Label& _label)
			{
				assignLabelIdIfUnset(_label);
				m_state.assembly.append(eth::AssemblyItem(eth::PushTag, _label.id));
			},
			[=](Scope::Function&)
			{
				solAssert(false, "Function not removed during desugaring.");
			}
		)))
		{
			return;
		}
		solAssert(
			m_identifierAccess.generateCode,
			"Identifier not found and no external access available."
		);
		m_identifierAccess.generateCode(_identifier, IdentifierContext::RValue, m_state.assembly);
	}
	void operator()(FunctionalInstruction const& _instr)
	{
		for (auto it = _instr.arguments.rbegin(); it != _instr.arguments.rend(); ++it)
		{
			int height = m_state.assembly.deposit();
			boost::apply_visitor(*this, *it);
			expectDeposit(1, height);
		}
		(*this)(_instr.instruction);
	}
	void operator()(assembly::FunctionCall const&)
	{
		solAssert(false, "Function call not removed during desugaring phase.");
	}
	void operator()(Label const& _label)
	{
		m_state.assembly.setSourceLocation(_label.location);
		solAssert(m_scope.identifiers.count(_label.name), "");
		Scope::Label& label = boost::get<Scope::Label>(m_scope.identifiers.at(_label.name));
		assignLabelIdIfUnset(label);
		m_state.assembly.append(eth::AssemblyItem(eth::Tag, label.id));
	}
	void operator()(assembly::Assignment const& _assignment)
	{
		m_state.assembly.setSourceLocation(_assignment.location);
		generateAssignment(_assignment.variableName, _assignment.location);
	}
	void operator()(FunctionalAssignment const& _assignment)
	{
		int height = m_state.assembly.deposit();
		boost::apply_visitor(*this, *_assignment.value);
		expectDeposit(1, height);
		m_state.assembly.setSourceLocation(_assignment.location);
		generateAssignment(_assignment.variableName, _assignment.location);
	}
	void operator()(assembly::VariableDeclaration const& _varDecl)
	{
		int height = m_state.assembly.deposit();
		boost::apply_visitor(*this, *_varDecl.value);
		expectDeposit(1, height);
		auto& var = boost::get<Scope::Variable>(m_scope.identifiers.at(_varDecl.name));
		var.stackHeight = height;
		var.active = true;
	}
	void operator()(assembly::Block const& _block)
	{
		CodeTransform(m_state, _block, m_identifierAccess);
	}
	void operator()(assembly::FunctionDefinition const&)
	{
		solAssert(false, "Function definition not removed during desugaring phase.");
	}

private:
	void generateAssignment(assembly::Identifier const& _variableName, SourceLocation const& _location)
	{
		auto var = m_scope.lookup(_variableName.name);
		if (var)
		{
			Scope::Variable const& _var = boost::get<Scope::Variable>(*var);
			if (int heightDiff = variableHeightDiff(_var, _location, true))
				m_state.assembly.append(solidity::swapInstruction(heightDiff - 1));
			m_state.assembly.append(solidity::Instruction::POP);
		}
		else
		{
			solAssert(
				m_identifierAccess.generateCode,
				"Identifier not found and no external access available."
			);
			m_identifierAccess.generateCode(_variableName, IdentifierContext::LValue, m_state.assembly);
		}
	}

	/// Determines the stack height difference to the given variables. Automatically generates
	/// errors if it is not yet in scope or the height difference is too large. Returns 0 on
	/// errors and the (positive) stack height difference otherwise.
	int variableHeightDiff(Scope::Variable const& _var, SourceLocation const& _location, bool _forSwap)
	{
		int heightDiff = m_state.assembly.deposit() - _var.stackHeight;
		if (heightDiff <= (_forSwap ? 1 : 0) || heightDiff > (_forSwap ? 17 : 16))
		{
			//@TODO move this to analysis phase.
			m_state.errors.push_back(make_shared<Error>(
				Error::Type::TypeError,
				"Variable inaccessible, too deep inside stack (" + boost::lexical_cast<string>(heightDiff) + ")",
				_location
			));
			return 0;
		}
		else
			return heightDiff;
	}

	void expectDeposit(int _deposit, int _oldHeight)
	{
		solAssert(m_state.assembly.deposit() == _oldHeight + _deposit, "Invalid stack deposit.");
	}

	/// Assigns the label's id to a value taken from eth::Assembly if it has not yet been set.
	void assignLabelIdIfUnset(Scope::Label& _label)
	{
		if (_label.id == Scope::Label::unassignedLabelId)
			_label.id = m_state.newLabelId();
		else if (_label.id == Scope::Label::errorLabelId)
			_label.id = size_t(m_state.assembly.errorTag().data());
	}

	GeneratorState& m_state;
	Scope& m_scope;
	int const m_initialDeposit;
	ExternalIdentifierAccess m_identifierAccess;
};

eth::Assembly assembly::CodeGenerator::assemble(
	Block const& _parsedData,
	AsmAnalysisInfo& _analysisInfo,
	ExternalIdentifierAccess const& _identifierAccess
)
{
	eth::Assembly assembly;
	GeneratorState state(m_errors, _analysisInfo, assembly);
	CodeTransform(state, _parsedData, _identifierAccess);
	return assembly;
}

void assembly::CodeGenerator::assemble(
	Block const& _parsedData,
	AsmAnalysisInfo& _analysisInfo,
	eth::Assembly& _assembly,
	ExternalIdentifierAccess const& _identifierAccess
)
{
	GeneratorState state(m_errors, _analysisInfo, _assembly);
	CodeTransform(state, _parsedData, _identifierAccess);
}
<commit_msg>Check stack height during code generation.<commit_after>/*
	This file is part of solidity.

	solidity is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	solidity is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with solidity.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2016
 * Code-generating part of inline assembly.
 */

#include <libsolidity/inlineasm/AsmCodeGen.h>

#include <libsolidity/inlineasm/AsmParser.h>
#include <libsolidity/inlineasm/AsmData.h>
#include <libsolidity/inlineasm/AsmScope.h>
#include <libsolidity/inlineasm/AsmAnalysis.h>
#include <libsolidity/inlineasm/AsmAnalysisInfo.h>

#include <libevmasm/Assembly.h>
#include <libevmasm/SourceLocation.h>
#include <libevmasm/Instruction.h>

#include <libdevcore/CommonIO.h>

#include <boost/range/adaptor/reversed.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/algorithm/count_if.hpp>

#include <memory>
#include <functional>

using namespace std;
using namespace dev;
using namespace dev::solidity;
using namespace dev::solidity::assembly;

struct GeneratorState
{
	GeneratorState(ErrorList& _errors, AsmAnalysisInfo& _analysisInfo, eth::Assembly& _assembly):
		errors(_errors), info(_analysisInfo), assembly(_assembly) {}

	size_t newLabelId()
	{
		return assemblyTagToIdentifier(assembly.newTag());
	}

	size_t assemblyTagToIdentifier(eth::AssemblyItem const& _tag) const
	{
		u256 id = _tag.data();
		solAssert(id <= std::numeric_limits<size_t>::max(), "Tag id too large.");
		return size_t(id);
	}

	ErrorList& errors;
	AsmAnalysisInfo info;
	eth::Assembly& assembly;
};

class CodeTransform: public boost::static_visitor<>
{
public:
	/// Create the code transformer which appends assembly to _state.assembly when called
	/// with parsed assembly data.
	/// @param _identifierAccess used to resolve identifiers external to the inline assembly
	explicit CodeTransform(
		GeneratorState& _state,
		assembly::Block const& _block,
		assembly::ExternalIdentifierAccess const& _identifierAccess = assembly::ExternalIdentifierAccess()
	): CodeTransform(_state, _block, _identifierAccess, _state.assembly.deposit())
	{
	}

private:
	CodeTransform(
		GeneratorState& _state,
		assembly::Block const& _block,
		assembly::ExternalIdentifierAccess const& _identifierAccess,
		int _initialDeposit
	):
		m_state(_state),
		m_scope(*m_state.info.scopes.at(&_block)),
		m_identifierAccess(_identifierAccess),
		m_initialDeposit(_initialDeposit)
	{
		int blockStartDeposit = m_state.assembly.deposit();
		std::for_each(_block.statements.begin(), _block.statements.end(), boost::apply_visitor(*this));

		m_state.assembly.setSourceLocation(_block.location);

		// pop variables
		for (auto const& identifier: m_scope.identifiers)
			if (identifier.second.type() == typeid(Scope::Variable))
				m_state.assembly.append(solidity::Instruction::POP);

		int deposit = m_state.assembly.deposit() - blockStartDeposit;
		solAssert(deposit == 0, "Invalid stack height at end of block.");
	}

public:
	void operator()(assembly::Instruction const& _instruction)
	{
		m_state.assembly.setSourceLocation(_instruction.location);
		m_state.assembly.append(_instruction.instruction);
		checkStackHeight(&_instruction);
	}
	void operator()(assembly::Literal const& _literal)
	{
		m_state.assembly.setSourceLocation(_literal.location);
		if (_literal.isNumber)
			m_state.assembly.append(u256(_literal.value));
		else
		{
			solAssert(_literal.value.size() <= 32, "");
			m_state.assembly.append(u256(h256(_literal.value, h256::FromBinary, h256::AlignLeft)));
		}
		checkStackHeight(&_literal);
	}
	void operator()(assembly::Identifier const& _identifier)
	{
		m_state.assembly.setSourceLocation(_identifier.location);
		// First search internals, then externals.
		if (m_scope.lookup(_identifier.name, Scope::NonconstVisitor(
			[=](Scope::Variable& _var)
			{
				if (int heightDiff = variableHeightDiff(_var, _identifier.location, false))
					m_state.assembly.append(solidity::dupInstruction(heightDiff));
				else
					// Store something to balance the stack
					m_state.assembly.append(u256(0));
			},
			[=](Scope::Label& _label)
			{
				assignLabelIdIfUnset(_label);
				m_state.assembly.append(eth::AssemblyItem(eth::PushTag, _label.id));
			},
			[=](Scope::Function&)
			{
				solAssert(false, "Function not removed during desugaring.");
			}
		)))
		{
			return;
		}
		solAssert(
			m_identifierAccess.generateCode,
			"Identifier not found and no external access available."
		);
		m_identifierAccess.generateCode(_identifier, IdentifierContext::RValue, m_state.assembly);
		checkStackHeight(&_identifier);
	}
	void operator()(FunctionalInstruction const& _instr)
	{
		for (auto it = _instr.arguments.rbegin(); it != _instr.arguments.rend(); ++it)
		{
			int height = m_state.assembly.deposit();
			boost::apply_visitor(*this, *it);
			expectDeposit(1, height);
		}
		(*this)(_instr.instruction);
		checkStackHeight(&_instr);
	}
	void operator()(assembly::FunctionCall const&)
	{
		solAssert(false, "Function call not removed during desugaring phase.");
	}
	void operator()(Label const& _label)
	{
		m_state.assembly.setSourceLocation(_label.location);
		solAssert(m_scope.identifiers.count(_label.name), "");
		Scope::Label& label = boost::get<Scope::Label>(m_scope.identifiers.at(_label.name));
		assignLabelIdIfUnset(label);
		m_state.assembly.append(eth::AssemblyItem(eth::Tag, label.id));
		checkStackHeight(&_label);
	}
	void operator()(assembly::Assignment const& _assignment)
	{
		m_state.assembly.setSourceLocation(_assignment.location);
		generateAssignment(_assignment.variableName, _assignment.location);
		checkStackHeight(&_assignment);
	}
	void operator()(FunctionalAssignment const& _assignment)
	{
		int height = m_state.assembly.deposit();
		boost::apply_visitor(*this, *_assignment.value);
		expectDeposit(1, height);
		m_state.assembly.setSourceLocation(_assignment.location);
		generateAssignment(_assignment.variableName, _assignment.location);
		checkStackHeight(&_assignment);
	}
	void operator()(assembly::VariableDeclaration const& _varDecl)
	{
		int height = m_state.assembly.deposit();
		boost::apply_visitor(*this, *_varDecl.value);
		expectDeposit(1, height);
		auto& var = boost::get<Scope::Variable>(m_scope.identifiers.at(_varDecl.name));
		var.stackHeight = height;
		var.active = true;
	}
	void operator()(assembly::Block const& _block)
	{
		CodeTransform(m_state, _block, m_identifierAccess, m_initialDeposit);
		checkStackHeight(&_block);
	}
	void operator()(assembly::FunctionDefinition const&)
	{
		solAssert(false, "Function definition not removed during desugaring phase.");
	}

private:
	void generateAssignment(assembly::Identifier const& _variableName, SourceLocation const& _location)
	{
		auto var = m_scope.lookup(_variableName.name);
		if (var)
		{
			Scope::Variable const& _var = boost::get<Scope::Variable>(*var);
			if (int heightDiff = variableHeightDiff(_var, _location, true))
				m_state.assembly.append(solidity::swapInstruction(heightDiff - 1));
			m_state.assembly.append(solidity::Instruction::POP);
		}
		else
		{
			solAssert(
				m_identifierAccess.generateCode,
				"Identifier not found and no external access available."
			);
			m_identifierAccess.generateCode(_variableName, IdentifierContext::LValue, m_state.assembly);
		}
	}

	/// Determines the stack height difference to the given variables. Automatically generates
	/// errors if it is not yet in scope or the height difference is too large. Returns 0 on
	/// errors and the (positive) stack height difference otherwise.
	int variableHeightDiff(Scope::Variable const& _var, SourceLocation const& _location, bool _forSwap)
	{
		int heightDiff = m_state.assembly.deposit() - _var.stackHeight;
		if (heightDiff <= (_forSwap ? 1 : 0) || heightDiff > (_forSwap ? 17 : 16))
		{
			//@TODO move this to analysis phase.
			m_state.errors.push_back(make_shared<Error>(
				Error::Type::TypeError,
				"Variable inaccessible, too deep inside stack (" + boost::lexical_cast<string>(heightDiff) + ")",
				_location
			));
			return 0;
		}
		else
			return heightDiff;
	}

	void expectDeposit(int _deposit, int _oldHeight)
	{
		solAssert(m_state.assembly.deposit() == _oldHeight + _deposit, "Invalid stack deposit.");
	}

	void checkStackHeight(void const* _astElement)
	{
		solAssert(m_state.info.stackHeightInfo.count(_astElement), "Stack height for AST element not found.");
		solAssert(
			m_state.info.stackHeightInfo.at(_astElement) == m_state.assembly.deposit() - m_initialDeposit,
			"Stack height mismatch between analysis and code generation phase."
		);
	}

	/// Assigns the label's id to a value taken from eth::Assembly if it has not yet been set.
	void assignLabelIdIfUnset(Scope::Label& _label)
	{
		if (_label.id == Scope::Label::unassignedLabelId)
			_label.id = m_state.newLabelId();
		else if (_label.id == Scope::Label::errorLabelId)
			_label.id = size_t(m_state.assembly.errorTag().data());
	}

	GeneratorState& m_state;
	Scope& m_scope;
	ExternalIdentifierAccess m_identifierAccess;
	int const m_initialDeposit;
};

eth::Assembly assembly::CodeGenerator::assemble(
	Block const& _parsedData,
	AsmAnalysisInfo& _analysisInfo,
	ExternalIdentifierAccess const& _identifierAccess
)
{
	eth::Assembly assembly;
	GeneratorState state(m_errors, _analysisInfo, assembly);
	CodeTransform(state, _parsedData, _identifierAccess);
	return assembly;
}

void assembly::CodeGenerator::assemble(
	Block const& _parsedData,
	AsmAnalysisInfo& _analysisInfo,
	eth::Assembly& _assembly,
	ExternalIdentifierAccess const& _identifierAccess
)
{
	GeneratorState state(m_errors, _analysisInfo, _assembly);
	CodeTransform(state, _parsedData, _identifierAccess);
}
<|endoftext|>


<commit_before>#include "freud/freud.hpp"
#include <iostream>
#include <openssl/ssl.h>
#include <set>
#include <unistd.h>

class SSL_SESSION_Matcher : public freud::MemoryObject<SSL_SESSION> {
public:
    static bool verify(const freud::MemoryContext& ctx, const SSL_SESSION& e,
                       freud::address_t address) {
        bool res = e.ssl_version == 0x303 && e.master_key_length == 48 &&
                   e.session_id_length == 32;
        return res;
    }

    static void before_check() { usleep(1); }
};

int main(int argc, char** argv) {
    std::ofstream out("keys.log");
    std::set<freud::address_t> known_matches;

    freud::MemoryContext ctx(atoi(argv[1]), true);

    freud::MemoryContextIterator<SSL_SESSION_Matcher> iter =
        ctx.scan_forever<SSL_SESSION_Matcher>();

    for (;; ++iter) {
        if (!known_matches.count(iter.address())) {
            std::cout << "RSA Session-ID:"
                      << freud::format_as_hex(iter->session_id)
                      << " Master-Key:"
                      << freud::format_as_hex(iter->master_key) << std::endl;

            out << "RSA Session-ID:" << freud::format_as_hex(iter->session_id)
                << " Master-Key:" << freud::format_as_hex(iter->master_key)
                << "\n";
            known_matches.insert(iter.address());
        }
    }
}
<commit_msg>Fix bug where key log example didn't write to file quickly<commit_after>#include "freud/freud.hpp"
#include <iostream>
#include <openssl/ssl.h>
#include <set>
#include <unistd.h>

class SSL_SESSION_Matcher : public freud::MemoryObject<SSL_SESSION> {
public:
    static bool verify(const freud::MemoryContext& ctx, const SSL_SESSION& e,
                       freud::address_t address) {
        bool res = e.ssl_version == 0x303 && e.master_key_length == 48 &&
                   e.session_id_length == 32;
        return res;
    }

    static void before_check() { usleep(1); }
};

int main(int argc, char** argv) {
    std::ofstream out("keys.log");
    std::set<freud::address_t> known_matches;

    freud::MemoryContext ctx(atoi(argv[1]), true);

    freud::MemoryContextIterator<SSL_SESSION_Matcher> iter =
        ctx.scan_forever<SSL_SESSION_Matcher>();

    for (;; ++iter) {
        if (!known_matches.count(iter.address())) {
            std::cout << "RSA Session-ID:"
                      << freud::format_as_hex(iter->session_id)
                      << " Master-Key:"
                      << freud::format_as_hex(iter->master_key) << std::endl;

            out << "RSA Session-ID:" << freud::format_as_hex(iter->session_id)
                << " Master-Key:" << freud::format_as_hex(iter->master_key)
                << std::endl;
            known_matches.insert(iter.address());
        }
    }
}
<|endoftext|>


<commit_before>/***************************************************************************
*  @file       main.cpp
*  @author     Queequeg
*  @date       25  Nov 2014
*  @remark     This code is for the exercises from C++ Primer 5th Edition
*  @note
***************************************************************************/
//!
//! Exercise 17.17
//! Update your program so that it finds all the words in an input sequence
//! that violiate the "ei" grammar rule.

//!
//! Exercise 17.18
//! Revise your program to ignore words that contain "ei" but are not
//! misspellings, such as "albeit" and "neighbor".

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include<string>
using std::string;

#include <regex>
using std::regex;
using std::sregex_iterator;

int main()
{
	string s;
	cout << "Please input a sequence of words:" << endl;
	getline(cin, s);
	cout << endl;
	cout << "Word(s) that violiate the ei grammar rule:" << endl;
	string pattern("[^c]ei");
	pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
	regex r(pattern, regex::icase);
	for (sregex_iterator it(s.begin(), s.end(), r), end_it;
		it != end_it; ++it)
		cout << it->str() << endl;

	return 0;
}<commit_msg>fix stupid character mistake<commit_after>/***************************************************************************
*  @file       main.cpp
*  @author     Queequeg
*  @date       25  Nov 2014
*  @remark     This code is for the exercises from C++ Primer 5th Edition
*  @note
***************************************************************************/
//!
//! Exercise 17.17
//! Update your program so that it finds all the words in an input sequence
//! that violiate the "ei" grammar rule.

//!
//! Exercise 17.18
//! Revise your program to ignore words that contain "ei" but are not
//! misspellings, such as "albeit" and "neighbor."

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include<string>
using std::string;

#include <regex>
using std::regex;
using std::sregex_iterator;

int main()
{
	string s;
	cout << "Please input a sequence of words:" << endl;
	getline(cin, s);
	cout << endl;
	cout << "Word(s) that violiate the \"ei\" grammar rule:" << endl;
	string pattern("[^c]ei");
	pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
	regex r(pattern, regex::icase);
	for (sregex_iterator it(s.begin(), s.end(), r), end_it;
		it != end_it; ++it)
		cout << it->str() << endl;

	return 0;
}<|endoftext|>