<commit_before>//
//  GaussianBlurNode.cpp
//  Cinder-Pipeline
//
//  Created by Jean-Pierre Mouilleseaux on 22 Apr 2014.
//  Copyright 2014-2015 Chorded Constructions. All rights reserved.
//

#include "GaussianBlurNode.h"
#include <numeric>

using namespace ci;
using namespace Cinder::Pipeline;

static const std::string GaussianBlurNodeInputPortKeyDimension = "dimension";
static const float GaussianBlurNodeRadiusDefault = 2.0f; // NB: actually sigma like CIGaussianBlur's inputRadius

// Based on Brad Larson's GPUImage work at https://github.com/BradLarson/GPUImage/blob/master/framework/Source/GPUImageGaussianBlurFilter.h
//  https://github.com/BradLarson/GPUImage/blob/master/framework/Source/GPUImageGaussianBlurFilter.m
// and Daniel Rákos' work at http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/
const std::string FragmentShaderGaussianBlur = R"(
    #version 150
    uniform sampler2D image;
    uniform vec2 direction;
    uniform float dimension;
    uniform float mixAmount;

    in vec2 vTexCoord0;

    out vec4 oFragColor;

    #ifndef DEFAULT_OVERRIDE
        // defualt to blur radius 6, sigma 2
        #define SAMPLE_COUNT 7
        #define OFFSET_VALUES 0, 1, 2, 3, 4, 5, 6
        #define WEIGHT_VALUES 0.199675635, 0.17621313, 0.121109389, 0.0648251921, 0.027023159, 0.00877313502, 0.00221819594
    #endif

    const float offset[SAMPLE_COUNT] = float[](OFFSET_VALUES);
    const float weight[SAMPLE_COUNT] = float[](WEIGHT_VALUES);

    void main() {
        vec4 color = texture(image, vTexCoord0);

        vec4 sum = texture(image, vTexCoord0) * weight[0];
        for (int idx = 1; idx < SAMPLE_COUNT; idx++) {
            sum += texture(image, vTexCoord0 + direction * (offset[idx] / dimension)) * weight[idx];
            sum += texture(image, vTexCoord0 - direction * (offset[idx] / dimension)) * weight[idx];
        }

        oFragColor = mix(color, sum, mixAmount);
    }
)";

GaussianBlurNode::GaussianBlurNode() {
    std::vector<NodePortRef> inputPorts = {
        NodePort::create(NodeInputPortKeyImage, NodePortType::FBOImage),
        NodePort::create(GaussianBlurNodeInputPortKeyDirection, NodePortType::Index, "Direction", static_cast<int>(BlurDirection::Vertical), {static_cast<int>(BlurDirection::Vertical), static_cast<int>(BlurDirection::Horizontal)}, {"Vertical", "Horizontal"}),
        NodePort::create(GaussianBlurNodeInputPortKeyRadius, NodePortType::Float, "Radius", GaussianBlurNodeRadiusDefault, 0.0f, 8.0f),
        NodePort::create(GaussianBlurNodeInputPortKeyMixAmount, NodePortType::Float, "Mix", 1.0f, 0.0f, 1.0f),
    };
    setInputPorts(inputPorts);
    // NB - output port "image" of type NodePortType::FBOImage is already present

    // setup shader when radius changes
    connectValueForInputPortKeyChangedHandler(GaussianBlurNodeInputPortKeyRadius, [&](const std::string& key, const boost::any& newValue, const boost::any& oldValue) {
        float radius = roundf(boost::any_cast<float>(newValue));
        float oldRadius = roundf(boost::any_cast<float>(oldValue));
        if (radius != oldRadius) {
            setupShaderForRadius(radius);
        }
    });

    setupShader(sVertexShaderPassThrough, FragmentShaderGaussianBlur);
}

GaussianBlurNode::~GaussianBlurNode() {
}

void GaussianBlurNode::render(const FBOImageRef& outputFBOImage) {
    FBOImageRef inputFBOImage = getValueForInputPortKey<FBOImageRef>(NodeInputPortKeyImage);
    gl::TextureBaseRef inputTexture = inputFBOImage->getTexture();

    int index = getValueForInputPortKey<int>(GaussianBlurNodeInputPortKeyDirection);
    int value = getInputPortForKey(GaussianBlurNodeInputPortKeyDirection)->getValues().at(index);
    vec2 direction = value == static_cast<int>(BlurDirection::Vertical) ? vec2(0.0f, 1.0f) : vec2(1.0f, 0.0f);
    float dimension = value == static_cast<int>(BlurDirection::Vertical) ? inputTexture->getHeight() : inputTexture->getWidth();
    float mixAmount = getValueForInputPortKey<float>(GaussianBlurNodeInputPortKeyMixAmount);

    gl::ScopedTextureBind texture(inputTexture, 0);
    gl::ScopedGlslProg shader(mShader);

    mShader->uniform(NodeInputPortKeyImage, 0);
    mShader->uniform(GaussianBlurNodeInputPortKeyDirection, direction);
    mShader->uniform(GaussianBlurNodeInputPortKeyDimension, dimension);
    mShader->uniform(GaussianBlurNodeInputPortKeyMixAmount, mixAmount);
    gl::drawSolidRect(outputFBOImage->getFBO()->getBounds());
}

void GaussianBlurNode::setupShaderForRadius(const float radius) {
    float blurRadiusInPixels = radius;
    int calculatedSampleRadius = 0;
    if (blurRadiusInPixels > 0) {
        float minimumWeightToFindEdgeOfSamplingArea = 1.0f / 256.0f;
        calculatedSampleRadius = floor(sqrt(-2.0f * pow(blurRadiusInPixels, 2.0f) * log(minimumWeightToFindEdgeOfSamplingArea * sqrt(2.0f * M_PI * pow(blurRadiusInPixels, 2.0f))) ));
        calculatedSampleRadius += calculatedSampleRadius % 2;
    }

    int blurRadius = calculatedSampleRadius;
    float sigma = blurRadiusInPixels;

    std::vector<float> offsets(blurRadius + 1);
    for (size_t idx = 0; idx < offsets.size(); idx++) offsets[idx] = idx;

    // calculate weights
    std::vector<float> weights(blurRadius + 1);
    for (size_t idx = 0; idx < weights.size(); idx++) {
        float weight = (1.0f / sqrt(2.0f * M_PI * pow(sigma, 2.0f))) * exp(-pow(idx, 2.0f) / (2.0f * pow(sigma, 2.0f)));
        if (weight != weight) weight = 1.0f; // NaN check, occurs when blurRadius is 0
        weights[idx] = weight;
    }

    // normalize to prevent clamping
    float sumOfWeights = 2.0f * std::accumulate(weights.begin(), weights.end(), 0.0f);
    sumOfWeights -= weights[0];
    std::transform(weights.begin(), weights.end(), weights.begin(), [sumOfWeights](const float& val) { return val / sumOfWeights; });

    std::string offsetValuesString = toString(offsets[0]);
    for (size_t idx = 1; idx < offsets.size(); idx++) {
        offsetValuesString += ", " + toString(offsets[idx]);
    }

    std::string weightValuesString = toString(weights[0]);
    for (size_t idx = 1; idx < weights.size(); idx++) {
        weightValuesString += ", " + toString(weights[idx]);
    }

    auto format = gl::GlslProg::Format().vertex(sVertexShaderPassThrough).fragment(FragmentShaderGaussianBlur);
    format.define("DEFAULT_OVERRIDE");
    format.define("SAMPLE_COUNT", toString(weights.size()));
    format.define("OFFSET_VALUES", offsetValuesString);
    format.define("WEIGHT_VALUES", weightValuesString);
    try {
        mShader = gl::GlslProg::create(format);
    } catch (gl::GlslProgExc e) {
        throw e;
    }
}
<commit_msg>make blur radius an integer port<commit_after>//
//  GaussianBlurNode.cpp
//  Cinder-Pipeline
//
//  Created by Jean-Pierre Mouilleseaux on 22 Apr 2014.
//  Copyright 2014-2015 Chorded Constructions. All rights reserved.
//

#include "GaussianBlurNode.h"
#include <numeric>

using namespace ci;
using namespace Cinder::Pipeline;

static const std::string GaussianBlurNodeInputPortKeyDimension = "dimension";
static const int GaussianBlurNodeRadiusDefault = 2; // NB: actually sigma like CIGaussianBlur's inputRadius

// Based on Brad Larson's GPUImage work at https://github.com/BradLarson/GPUImage/blob/master/framework/Source/GPUImageGaussianBlurFilter.h
//  https://github.com/BradLarson/GPUImage/blob/master/framework/Source/GPUImageGaussianBlurFilter.m
// and Daniel Rákos' work at http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/
const std::string FragmentShaderGaussianBlur = R"(
    #version 150
    uniform sampler2D image;
    uniform vec2 direction;
    uniform float dimension;
    uniform float mixAmount;

    in vec2 vTexCoord0;

    out vec4 oFragColor;

    #ifndef DEFAULT_OVERRIDE
        // defualt to blur radius 6, sigma 2
        #define SAMPLE_COUNT 7
        #define OFFSET_VALUES 0, 1, 2, 3, 4, 5, 6
        #define WEIGHT_VALUES 0.199675635, 0.17621313, 0.121109389, 0.0648251921, 0.027023159, 0.00877313502, 0.00221819594
    #endif

    const float offset[SAMPLE_COUNT] = float[](OFFSET_VALUES);
    const float weight[SAMPLE_COUNT] = float[](WEIGHT_VALUES);

    void main() {
        vec4 color = texture(image, vTexCoord0);

        vec4 sum = texture(image, vTexCoord0) * weight[0];
        for (int idx = 1; idx < SAMPLE_COUNT; idx++) {
            sum += texture(image, vTexCoord0 + direction * (offset[idx] / dimension)) * weight[idx];
            sum += texture(image, vTexCoord0 - direction * (offset[idx] / dimension)) * weight[idx];
        }

        oFragColor = mix(color, sum, mixAmount);
    }
)";

GaussianBlurNode::GaussianBlurNode() {
    std::vector<NodePortRef> inputPorts = {
        NodePort::create(NodeInputPortKeyImage, NodePortType::FBOImage),
        NodePort::create(GaussianBlurNodeInputPortKeyDirection, NodePortType::Index, "Direction", static_cast<int>(BlurDirection::Vertical), {static_cast<int>(BlurDirection::Vertical), static_cast<int>(BlurDirection::Horizontal)}, {"Vertical", "Horizontal"}),
        NodePort::create(GaussianBlurNodeInputPortKeyRadius, NodePortType::Int, "Radius", GaussianBlurNodeRadiusDefault, 0, 10),
        NodePort::create(GaussianBlurNodeInputPortKeyMixAmount, NodePortType::Float, "Mix", 1.0f, 0.0f, 1.0f),
    };
    setInputPorts(inputPorts);
    // NB - output port "image" of type NodePortType::FBOImage is already present

    // setup shader when radius changes
    connectValueForInputPortKeyChangedHandler(GaussianBlurNodeInputPortKeyRadius, [&](const std::string& key, const boost::any& newValue, const boost::any& oldValue) {
        float radius = boost::any_cast<int>(newValue);
        setupShaderForRadius(radius);
    });

    setupShader(sVertexShaderPassThrough, FragmentShaderGaussianBlur);
}

GaussianBlurNode::~GaussianBlurNode() {
}

void GaussianBlurNode::render(const FBOImageRef& outputFBOImage) {
    FBOImageRef inputFBOImage = getValueForInputPortKey<FBOImageRef>(NodeInputPortKeyImage);
    gl::TextureBaseRef inputTexture = inputFBOImage->getTexture();

    int index = getValueForInputPortKey<int>(GaussianBlurNodeInputPortKeyDirection);
    int value = getInputPortForKey(GaussianBlurNodeInputPortKeyDirection)->getValues().at(index);
    vec2 direction = value == static_cast<int>(BlurDirection::Vertical) ? vec2(0.0f, 1.0f) : vec2(1.0f, 0.0f);
    float dimension = value == static_cast<int>(BlurDirection::Vertical) ? inputTexture->getHeight() : inputTexture->getWidth();
    float mixAmount = getValueForInputPortKey<float>(GaussianBlurNodeInputPortKeyMixAmount);

    gl::ScopedTextureBind texture(inputTexture, 0);
    gl::ScopedGlslProg shader(mShader);

    mShader->uniform(NodeInputPortKeyImage, 0);
    mShader->uniform(GaussianBlurNodeInputPortKeyDirection, direction);
    mShader->uniform(GaussianBlurNodeInputPortKeyDimension, dimension);
    mShader->uniform(GaussianBlurNodeInputPortKeyMixAmount, mixAmount);
    gl::drawSolidRect(outputFBOImage->getFBO()->getBounds());
}

void GaussianBlurNode::setupShaderForRadius(float radius) {
    float blurRadiusInPixels = radius;
    int calculatedSampleRadius = 0;
    if (blurRadiusInPixels > 0) {
        float minimumWeightToFindEdgeOfSamplingArea = 1.0f / 256.0f;
        calculatedSampleRadius = floor(sqrt(-2.0f * pow(blurRadiusInPixels, 2.0f) * log(minimumWeightToFindEdgeOfSamplingArea * sqrt(2.0f * M_PI * pow(blurRadiusInPixels, 2.0f))) ));
        calculatedSampleRadius += calculatedSampleRadius % 2;
    }

    int blurRadius = calculatedSampleRadius;
    float sigma = blurRadiusInPixels;

    std::vector<float> offsets(blurRadius + 1);
    for (size_t idx = 0; idx < offsets.size(); idx++) offsets[idx] = idx;

    // calculate weights
    std::vector<float> weights(blurRadius + 1);
    for (size_t idx = 0; idx < weights.size(); idx++) {
        float weight = (1.0f / sqrt(2.0f * M_PI * pow(sigma, 2.0f))) * exp(-pow(idx, 2.0f) / (2.0f * pow(sigma, 2.0f)));
        if (weight != weight) weight = 1.0f; // NaN check, occurs when blurRadius is 0
        weights[idx] = weight;
    }

    // normalize to prevent clamping
    float sumOfWeights = 2.0f * std::accumulate(weights.begin(), weights.end(), 0.0f);
    sumOfWeights -= weights[0];
    std::transform(weights.begin(), weights.end(), weights.begin(), [sumOfWeights](const float& val) { return val / sumOfWeights; });

    std::string offsetValuesString = toString(offsets[0]);
    for (size_t idx = 1; idx < offsets.size(); idx++) {
        offsetValuesString += ", " + toString(offsets[idx]);
    }

    std::string weightValuesString = toString(weights[0]);
    for (size_t idx = 1; idx < weights.size(); idx++) {
        weightValuesString += ", " + toString(weights[idx]);
    }

    auto format = gl::GlslProg::Format().vertex(sVertexShaderPassThrough).fragment(FragmentShaderGaussianBlur);
    format.define("DEFAULT_OVERRIDE");
    format.define("SAMPLE_COUNT", toString(weights.size()));
    format.define("OFFSET_VALUES", offsetValuesString);
    format.define("WEIGHT_VALUES", weightValuesString);
    try {
        mShader = gl::GlslProg::create(format);
    } catch (gl::GlslProgExc e) {
        throw e;
    }
}
<|endoftext|>


<commit_before>#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ptrace.h>
#include <unistd.h>
#include "ptbox.h"

pt_debugger::pt_debugger() : on_return_callback(NULL) {}

bool has_null(char *buf, unsigned long size) {
    for (unsigned long i = 0; i < size; ++i) {
        if (buf[i] == '\0')
            return true;
    }
    return false;
}

void pt_debugger::set_process(pt_process *proc) {
    process = proc;
}

void pt_debugger::new_process() {}

void pt_debugger::settid(pid_t tid) {
    this->tid = tid;
    if (!syscall_.count(tid)) syscall_[tid] = -1;
#if PTBOX_FREEBSD
    struct reg bsd_regs;
    ptrace(PT_GETREGS, tid, (caddr_t) &bsd_regs, 0);
    map_regs_to_linux(&bsd_regs, &bsd_converted_regs);
#endif
    if (syscall_[tid] == -1)
        syscall_[tid] = this->syscall();
    else {
#if PTBOX_FREEBSD
        bsd_converted_regs.orig_rax = syscall_[tid];
#endif
        syscall_[tid] = -1;
    }
}

long pt_debugger::peek_reg(int idx) {
#if PTBOX_FREEBSD
    return ((reg_type*)&bsd_converted_regs)[idx];
#else
    return ptrace(PTRACE_PEEKUSER, tid, sizeof(long) * idx, 0);
#endif
}

void pt_debugger::poke_reg(int idx, long data) {
#if PTBOX_FREEBSD
    ((reg_type*)&bsd_converted_regs)[idx] = data;

    struct reg bsd_regs;
    map_regs_from_linux(&bsd_regs, &bsd_converted_regs);
    ptrace(PT_SETREGS, tid, (caddr_t) &bsd_regs, 0);
#else
    ptrace(PTRACE_POKEUSER, tid, sizeof(long) * idx, data);
#endif
}

char *pt_debugger::readstr(unsigned long addr, size_t max_size) {
    size_t size = 4096, read = 0;
    char *buf = (char *) malloc(size);
    union {
        long val;
        char byte[sizeof(long)];
    } data;

    while (true) {
        if (read + sizeof(long) > size) {
            if (max_size && size >= max_size) {
                buf[max_size-1] = 0;
                break;
            }

            size += 4096;
            if (max_size && size > max_size)
                size = max_size;

            void *nbuf = realloc(buf, size);
            if (!nbuf) {
                buf[size-4097] = 0;
                break;
            }
            buf = (char *) nbuf;
        }
#if PTBOX_FREEBSD
        // TODO: we could use PT_IO to speed up this entire function by reading chunks rather than byte
        data.val = ptrace(PT_READ_D, tid, (caddr_t) (addr + read), 0);
#else
        data.val = ptrace(PTRACE_PEEKDATA, tid, addr + read, NULL);
#endif
        memcpy(buf + read, data.byte, sizeof(long));
        if (has_null(data.byte, sizeof(long)))
            break;
        read += sizeof(long);
    }
    return buf;
}

void pt_debugger::freestr(char *buf) {
    free(buf);
}

pt_debugger::~pt_debugger() {}
<commit_msg>FreeBSD PT_READ_D only reads an int; #192<commit_after>#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ptrace.h>
#include <unistd.h>
#include "ptbox.h"

pt_debugger::pt_debugger() : on_return_callback(NULL) {}

bool has_null(char *buf, unsigned long size) {
    for (unsigned long i = 0; i < size; ++i) {
        if (buf[i] == '\0')
            return true;
    }
    return false;
}

void pt_debugger::set_process(pt_process *proc) {
    process = proc;
}

void pt_debugger::new_process() {}

void pt_debugger::settid(pid_t tid) {
    this->tid = tid;
    if (!syscall_.count(tid)) syscall_[tid] = -1;
#if PTBOX_FREEBSD
    struct reg bsd_regs;
    ptrace(PT_GETREGS, tid, (caddr_t) &bsd_regs, 0);
    map_regs_to_linux(&bsd_regs, &bsd_converted_regs);
#endif
    if (syscall_[tid] == -1)
        syscall_[tid] = this->syscall();
    else {
#if PTBOX_FREEBSD
        bsd_converted_regs.orig_rax = syscall_[tid];
#endif
        syscall_[tid] = -1;
    }
}

long pt_debugger::peek_reg(int idx) {
#if PTBOX_FREEBSD
    return ((reg_type*)&bsd_converted_regs)[idx];
#else
    return ptrace(PTRACE_PEEKUSER, tid, sizeof(long) * idx, 0);
#endif
}

void pt_debugger::poke_reg(int idx, long data) {
#if PTBOX_FREEBSD
    ((reg_type*)&bsd_converted_regs)[idx] = data;

    struct reg bsd_regs;
    map_regs_from_linux(&bsd_regs, &bsd_converted_regs);
    ptrace(PT_SETREGS, tid, (caddr_t) &bsd_regs, 0);
#else
    ptrace(PTRACE_POKEUSER, tid, sizeof(long) * idx, data);
#endif
}

#if PTBOX_FREEBSD
typedef int ptrace_read_t;
#else
typedef long ptrace_read_t;
#endif

char *pt_debugger::readstr(unsigned long addr, size_t max_size) {
    size_t size = 4096, read = 0;
    char *buf = (char *) malloc(size);
    union {
        ptrace_read_t val;
        char byte[sizeof(ptrace_read_t)];
    } data;

    while (true) {
        if (read + sizeof(ptrace_read_t) > size) {
            if (max_size && size >= max_size) {
                buf[max_size-1] = 0;
                break;
            }

            size += 4096;
            if (max_size && size > max_size)
                size = max_size;

            void *nbuf = realloc(buf, size);
            if (!nbuf) {
                buf[size-4097] = 0;
                break;
            }
            buf = (char *) nbuf;
        }
#if PTBOX_FREEBSD
        // TODO: we could use PT_IO to speed up this entire function by reading chunks rather than byte
        data.val = ptrace(PT_READ_D, tid, (caddr_t) (addr + read), 0);
#else
        data.val = ptrace(PTRACE_PEEKDATA, tid, addr + read, NULL);
#endif
        memcpy(buf + read, data.byte, sizeof(ptrace_read_t));
        if (has_null(data.byte, sizeof(ptrace_read_t)))
            break;
        read += sizeof(ptrace_read_t);
    }
    return buf;
}

void pt_debugger::freestr(char *buf) {
    free(buf);
}

pt_debugger::~pt_debugger() {}
<|endoftext|>


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

    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    This program 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 2 of the License, or
    (at your option) any later version.

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/
#include <kaboutdata.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kcmdlineargs.h>

#include <calendar/plugin.h>

#include "kocore.h"

int main(int argc,char **argv)
{
  KAboutData aboutData("korgplugins",I18N_NOOP("KOrgPlugins"),"0.1");
  KCmdLineArgs::init(argc,argv,&aboutData);

  KApplication app;

  KTrader::OfferList plugins = KOCore::self()->availablePlugins("Calendar/Plugin");
  KTrader::OfferList::ConstIterator it;
  for(it = plugins.begin(); it != plugins.end(); ++it) {
    kdDebug(5850) << "Plugin: " << (*it)->desktopEntryName() << " ("
              << (*it)->name() << ")" << endl;
    KOrg::Plugin *p = KOCore::self()->loadPlugin(*it);
    if (!p) {
      kdDebug(5850) << "Plugin loading failed." << endl;
    } else {
      kdDebug(5850) << "PLUGIN INFO: " << p->info() << endl;
    }
  }

  plugins = KOCore::self()->availablePlugins("KOrganizer/Part");
  for(it = plugins.begin(); it != plugins.end(); ++it) {
    kdDebug(5850) << "Part: " << (*it)->desktopEntryName() << " ("
              << (*it)->name() << ")" << endl;
    KOrg::Part *p = KOCore::self()->loadPart(*it,0);
    if (!p) {
      kdDebug(5850) << "Plugin loading failed." << endl;
    } else {
      kdDebug(5850) << "PLUGIN INFO: " << p->info() << endl;
    }
  }

  plugins = KOCore::self()->availablePlugins("KOrganizer/View");
  for(it = plugins.begin(); it != plugins.end(); ++it) {
    kdDebug(5850) << "Part: " << (*it)->desktopEntryName() << " ("
              << (*it)->name() << ")" << endl;
#if 0
    KOrg::Part *p = KOCore::self()->loadPart(*it,0,0);
    if (!p) {
      kdDebug(5850) << "Plugin loading failed." << endl;
    } else {
      kdDebug(5850) << "PLUGIN INFO: " << p->info() << endl;
    }
#endif
  }

#if 0
  KOrg::TextDecoration::List tdl = KOCore::self()->textDecorations();
  KOrg::TextDecoration *td = tdl.first();
  while(td) {
    kdDebug(5850) << "TEXT DECORATION INFO: " << td->info() << endl;
    td = tdl.next();
  }

  KOrg::WidgetDecoration *moon = KOCore::self()->loadWidgetDecoration("moon");
  if (moon) {
    QWidget *wid = moon->daySmall(0,QDate::currentDate());
    app.setMainWidget(wid);
    wid->show();
    app.exec();
  }
#endif
}
<commit_msg>Update the make check to the new plugin structure of korganizer, or at least make it compile with it. There's still a problem with KOrganizer::KOrganizer being unresolved in libkorganizer, because the import dialog uses KOrganizer, but libkorganizer doesn't link korganizer.cpp in.<commit_after>/*
    This file is part of KOrganizer.

    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    This program 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 2 of the License, or
    (at your option) any later version.

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/
#include <kaboutdata.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kcmdlineargs.h>

#include <calendar/plugin.h>

#include "kocore.h"

int main(int argc,char **argv)
{
  KAboutData aboutData("korgplugins",I18N_NOOP("KOrgPlugins"),"0.1");
  KCmdLineArgs::init(argc,argv,&aboutData);

  KApplication app;

  KTrader::OfferList plugins = KOCore::self()->availablePlugins();
  KTrader::OfferList::ConstIterator it;
  for(it = plugins.begin(); it != plugins.end(); ++it) {
    kdDebug(5850) << "Plugin: " << (*it)->desktopEntryName() << " ("
              << (*it)->name() << ")" << endl;
    KOrg::Plugin *p = KOCore::self()->loadPlugin(*it);
    if (!p) {
      kdDebug(5850) << "Plugin loading failed." << endl;
    } else {
      kdDebug(5850) << "PLUGIN INFO: " << p->info() << endl;
    }
  }

  plugins = KOCore::self()->availableParts();
  for(it = plugins.begin(); it != plugins.end(); ++it) {
    kdDebug(5850) << "Part: " << (*it)->desktopEntryName() << " ("
              << (*it)->name() << ")" << endl;
    KOrg::Part *p = KOCore::self()->loadPart(*it,0);
    if (!p) {
      kdDebug(5850) << "Plugin loading failed." << endl;
    } else {
      kdDebug(5850) << "PLUGIN INFO: " << p->info() << endl;
    }
  }

  plugins = KOCore::self()->availableCalendarDecorations();
  for(it = plugins.begin(); it != plugins.end(); ++it) {
    kdDebug(5850) << "CalendarDecoration: " << (*it)->desktopEntryName() << " ("
              << (*it)->name() << ")" << endl;
#if 0
		// TODO: Update this to calendar decorations
    KOrg::Part *p = KOCore::self()->loadPart(*it,0,0);
    if (!p) {
      kdDebug(5850) << "Plugin loading failed." << endl;
    } else {
      kdDebug(5850) << "PLUGIN INFO: " << p->info() << endl;
    }
#endif
  }

#if 0
  KOrg::TextDecoration::List tdl = KOCore::self()->textDecorations();
  KOrg::TextDecoration *td = tdl.first();
  while(td) {
    kdDebug(5850) << "TEXT DECORATION INFO: " << td->info() << endl;
    td = tdl.next();
  }

  KOrg::WidgetDecoration *moon = KOCore::self()->loadWidgetDecoration("moon");
  if (moon) {
    QWidget *wid = moon->daySmall(0,QDate::currentDate());
    app.setMainWidget(wid);
    wid->show();
    app.exec();
  }
#endif
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "shortcutsettings.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/command_p.h>
#include <coreplugin/actionmanager/commandsfile.h>

#include <utils/fancylineedit.h>

#include <QKeyEvent>
#include <QFileDialog>
#include <QLineEdit>
#include <QTreeWidgetItem>
#include <QCoreApplication>
#include <QDebug>

Q_DECLARE_METATYPE(Core::Internal::ShortcutItem*)

using namespace Core;
using namespace Core::Internal;

ShortcutSettings::ShortcutSettings(QObject *parent)
    : CommandMappings(parent), m_initialized(false)
{
    connect(ActionManager::instance(), SIGNAL(commandListChanged()), this, SLOT(initialize()));

    setId(Core::Constants::SETTINGS_ID_SHORTCUTS);
    setDisplayName(tr("Keyboard"));
    setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
    setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::SETTINGS_TR_CATEGORY_CORE));
    setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
}

QWidget *ShortcutSettings::widget()
{
    m_initialized = true;
    m_keyNum = m_key[0] = m_key[1] = m_key[2] = m_key[3] = 0;

    QWidget *w = CommandMappings::widget();

    const QString pageTitle = tr("Keyboard Shortcuts");
    const QString targetLabelText = tr("Key sequence:");
    const QString editTitle = tr("Shortcut");

    setPageTitle(pageTitle);
    setTargetLabelText(targetLabelText);
    setTargetEditTitle(editTitle);
    setTargetHeader(editTitle);
    targetEdit()->setPlaceholderText(tr("Type to set shortcut"));

    return w;
}

void ShortcutSettings::apply()
{
    foreach (ShortcutItem *item, m_scitems)
        item->m_cmd->setKeySequence(item->m_key);
}

void ShortcutSettings::finish()
{
    qDeleteAll(m_scitems);
    m_scitems.clear();

    CommandMappings::finish();
    m_initialized = false;
}

bool ShortcutSettings::eventFilter(QObject *o, QEvent *e)
{
    Q_UNUSED(o)

    if ( e->type() == QEvent::KeyPress ) {
        QKeyEvent *k = static_cast<QKeyEvent*>(e);
        handleKeyEvent(k);
        return true;
    }

    if ( e->type() == QEvent::Shortcut ||
         e->type() == QEvent::KeyRelease ) {
        return true;
    }

    if (e->type() == QEvent::ShortcutOverride) {
        // for shortcut overrides, we need to accept as well
        e->accept();
        return true;
    }

    return false;
}

void ShortcutSettings::commandChanged(QTreeWidgetItem *current)
{
    CommandMappings::commandChanged(current);
    if (!current || !current->data(0, Qt::UserRole).isValid())
        return;
    ShortcutItem *scitem = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
    setKeySequence(scitem->m_key);
    markCollisions(scitem);
}

void ShortcutSettings::targetIdentifierChanged()
{
    QTreeWidgetItem *current = commandList()->currentItem();
    if (current && current->data(0, Qt::UserRole).isValid()) {
        ShortcutItem *scitem = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
        scitem->m_key = QKeySequence(m_key[0], m_key[1], m_key[2], m_key[3]);
        if (scitem->m_cmd->defaultKeySequence() != scitem->m_key)
            setModified(current, true);
        else
            setModified(current, false);
        current->setText(2, scitem->m_key.toString(QKeySequence::NativeText));
        markCollisions(scitem);
    }
}

bool ShortcutSettings::hasConflicts() const
{
    QTreeWidgetItem *current = commandList()->currentItem();
    if (!current || !current->data(0, Qt::UserRole).isValid())
        return false;

    ShortcutItem *item = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
    if (!item)
        return false;

    const QKeySequence currentKey = QKeySequence::fromString(targetEdit()->text(), QKeySequence::NativeText);
    if (currentKey.isEmpty())
        return false;

    const Id globalId(Constants::C_GLOBAL);
    const Context itemContext = item->m_cmd->context();

    foreach (ShortcutItem *listItem, m_scitems) {
        if (item == listItem)
            continue;
        if (listItem->m_key.isEmpty())
            continue;
        if (listItem->m_key.matches(currentKey) == QKeySequence::NoMatch)
            continue;

        const Context listContext = listItem->m_cmd->context();
        if (itemContext.contains(globalId) && !listContext.isEmpty())
            return true;
        if (listContext.contains(globalId) && !itemContext.isEmpty())
            return true;
        foreach (Id id, listContext)
            if (itemContext.contains(id))
                return true;
    }
    return false;
}

void ShortcutSettings::setKeySequence(const QKeySequence &key)
{
    m_key[0] = m_key[1] = m_key[2] = m_key[3] = 0;
    m_keyNum = key.count();
    for (int i = 0; i < m_keyNum; ++i) {
        m_key[i] = key[i];
    }
    targetEdit()->setText(key.toString(QKeySequence::NativeText));
}

void ShortcutSettings::resetTargetIdentifier()
{
    QTreeWidgetItem *current = commandList()->currentItem();
    if (current && current->data(0, Qt::UserRole).isValid()) {
        ShortcutItem *scitem = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
        setKeySequence(scitem->m_cmd->defaultKeySequence());
    }
}

void ShortcutSettings::removeTargetIdentifier()
{
    m_keyNum = m_key[0] = m_key[1] = m_key[2] = m_key[3] = 0;
    targetEdit()->clear();

    foreach (ShortcutItem *item, m_scitems)
        markCollisions(item);
}

void ShortcutSettings::importAction()
{
    QString fileName = QFileDialog::getOpenFileName(widget(), tr("Import Keyboard Mapping Scheme"),
        ICore::resourcePath() + QLatin1String("/schemes/"),
        tr("Keyboard Mapping Scheme (*.kms)"));
    if (!fileName.isEmpty()) {

        CommandsFile cf(fileName);
        QMap<QString, QKeySequence> mapping = cf.importCommands();

        foreach (ShortcutItem *item, m_scitems) {
            QString sid = item->m_cmd->id().toString();
            if (mapping.contains(sid)) {
                item->m_key = mapping.value(sid);
                item->m_item->setText(2, item->m_key.toString(QKeySequence::NativeText));
                if (item->m_item == commandList()->currentItem())
                    commandChanged(item->m_item);

                if (item->m_cmd->defaultKeySequence() != item->m_key)
                    setModified(item->m_item, true);
                else
                    setModified(item->m_item, false);
            }
        }

        foreach (ShortcutItem *item, m_scitems)
            markCollisions(item);
    }
}

void ShortcutSettings::defaultAction()
{
    foreach (ShortcutItem *item, m_scitems) {
        item->m_key = item->m_cmd->defaultKeySequence();
        item->m_item->setText(2, item->m_key.toString(QKeySequence::NativeText));
        setModified(item->m_item, false);
        if (item->m_item == commandList()->currentItem())
            commandChanged(item->m_item);
    }

    foreach (ShortcutItem *item, m_scitems)
        markCollisions(item);
}

void ShortcutSettings::exportAction()
{
    QString fileName = DocumentManager::getSaveFileNameWithExtension(
        tr("Export Keyboard Mapping Scheme"),
        ICore::resourcePath() + QLatin1String("/schemes/"),
        tr("Keyboard Mapping Scheme (*.kms)"));
    if (!fileName.isEmpty()) {
        CommandsFile cf(fileName);
        cf.exportCommands(m_scitems);
    }
}

void ShortcutSettings::clear()
{
    QTreeWidget *tree = commandList();
    for (int i = tree->topLevelItemCount()-1; i >= 0 ; --i) {
        delete tree->takeTopLevelItem(i);
    }
    qDeleteAll(m_scitems);
    m_scitems.clear();
}

void ShortcutSettings::initialize()
{
    if (!m_initialized)
        return;
    clear();
    QMap<QString, QTreeWidgetItem *> sections;

    foreach (Command *c, ActionManager::commands()) {
        if (c->hasAttribute(Command::CA_NonConfigurable))
            continue;
        if (c->action() && c->action()->isSeparator())
            continue;

        QTreeWidgetItem *item = 0;
        ShortcutItem *s = new ShortcutItem;
        m_scitems << s;
        item = new QTreeWidgetItem;
        s->m_cmd = c;
        s->m_item = item;

        const QString identifier = c->id().toString();
        int pos = identifier.indexOf(QLatin1Char('.'));
        const QString section = identifier.left(pos);
        const QString subId = identifier.mid(pos + 1);
        if (!sections.contains(section)) {
            QTreeWidgetItem *categoryItem = new QTreeWidgetItem(commandList(), QStringList() << section);
            QFont f = categoryItem->font(0);
            f.setBold(true);
            categoryItem->setFont(0, f);
            sections.insert(section, categoryItem);
            commandList()->expandItem(categoryItem);
        }
        sections[section]->addChild(item);

        s->m_key = c->keySequence();
        item->setText(0, subId);
        item->setText(1, c->description());
        item->setText(2, s->m_key.toString(QKeySequence::NativeText));
        if (s->m_cmd->defaultKeySequence() != s->m_key)
            setModified(item, true);

        item->setData(0, Qt::UserRole, qVariantFromValue(s));

        markCollisions(s);
    }
    filterChanged(filterText());
}

void ShortcutSettings::handleKeyEvent(QKeyEvent *e)
{
    int nextKey = e->key();
    if ( m_keyNum > 3 ||
         nextKey == Qt::Key_Control ||
         nextKey == Qt::Key_Shift ||
         nextKey == Qt::Key_Meta ||
         nextKey == Qt::Key_Alt )
         return;

    nextKey |= translateModifiers(e->modifiers(), e->text());
    switch (m_keyNum) {
        case 0:
            m_key[0] = nextKey;
            break;
        case 1:
            m_key[1] = nextKey;
            break;
        case 2:
            m_key[2] = nextKey;
            break;
        case 3:
            m_key[3] = nextKey;
            break;
        default:
            break;
    }
    m_keyNum++;
    QKeySequence ks(m_key[0], m_key[1], m_key[2], m_key[3]);
    targetEdit()->setText(ks.toString(QKeySequence::NativeText));
    e->accept();
}

int ShortcutSettings::translateModifiers(Qt::KeyboardModifiers state,
                                         const QString &text)
{
    int result = 0;
    // The shift modifier only counts when it is not used to type a symbol
    // that is only reachable using the shift key anyway
    if ((state & Qt::ShiftModifier) && (text.size() == 0
                                        || !text.at(0).isPrint()
                                        || text.at(0).isLetterOrNumber()
                                        || text.at(0).isSpace()))
        result |= Qt::SHIFT;
    if (state & Qt::ControlModifier)
        result |= Qt::CTRL;
    if (state & Qt::MetaModifier)
        result |= Qt::META;
    if (state & Qt::AltModifier)
        result |= Qt::ALT;
    return result;
}

void ShortcutSettings::markCollisions(ShortcutItem *item)
{
    bool hasCollision = false;
    if (!item->m_key.isEmpty()) {
        Id globalId = Context(Constants::C_GLOBAL).at(0);
        const Context itemContext = item->m_cmd->context();

        foreach (ShortcutItem *currentItem, m_scitems) {

            if (currentItem->m_key.isEmpty() || item == currentItem
                    || item->m_key != currentItem->m_key)
                continue;

            foreach (Id id, currentItem->m_cmd->context()) {
                // conflict if context is identical, OR if one
                // of the contexts is the global context
                const Context thisContext = currentItem->m_cmd->context();
                if (itemContext.contains(id)
                        || (itemContext.contains(globalId) && !thisContext.isEmpty())
                        || (thisContext.contains(globalId) && !itemContext.isEmpty())) {
                    currentItem->m_item->setForeground(2, Qt::red);
                    hasCollision = true;
                }
            }
        }
    }
    item->m_item->setForeground(2, hasCollision ? Qt::red : commandList()->palette().foreground());
}

<commit_msg>Shortcut settings: Update collision markers when resetting shortcut<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "shortcutsettings.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/command_p.h>
#include <coreplugin/actionmanager/commandsfile.h>

#include <utils/fancylineedit.h>

#include <QKeyEvent>
#include <QFileDialog>
#include <QLineEdit>
#include <QTreeWidgetItem>
#include <QCoreApplication>
#include <QDebug>

Q_DECLARE_METATYPE(Core::Internal::ShortcutItem*)

using namespace Core;
using namespace Core::Internal;

ShortcutSettings::ShortcutSettings(QObject *parent)
    : CommandMappings(parent), m_initialized(false)
{
    connect(ActionManager::instance(), SIGNAL(commandListChanged()), this, SLOT(initialize()));

    setId(Core::Constants::SETTINGS_ID_SHORTCUTS);
    setDisplayName(tr("Keyboard"));
    setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
    setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::SETTINGS_TR_CATEGORY_CORE));
    setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
}

QWidget *ShortcutSettings::widget()
{
    m_initialized = true;
    m_keyNum = m_key[0] = m_key[1] = m_key[2] = m_key[3] = 0;

    QWidget *w = CommandMappings::widget();

    const QString pageTitle = tr("Keyboard Shortcuts");
    const QString targetLabelText = tr("Key sequence:");
    const QString editTitle = tr("Shortcut");

    setPageTitle(pageTitle);
    setTargetLabelText(targetLabelText);
    setTargetEditTitle(editTitle);
    setTargetHeader(editTitle);
    targetEdit()->setPlaceholderText(tr("Type to set shortcut"));

    return w;
}

void ShortcutSettings::apply()
{
    foreach (ShortcutItem *item, m_scitems)
        item->m_cmd->setKeySequence(item->m_key);
}

void ShortcutSettings::finish()
{
    qDeleteAll(m_scitems);
    m_scitems.clear();

    CommandMappings::finish();
    m_initialized = false;
}

bool ShortcutSettings::eventFilter(QObject *o, QEvent *e)
{
    Q_UNUSED(o)

    if ( e->type() == QEvent::KeyPress ) {
        QKeyEvent *k = static_cast<QKeyEvent*>(e);
        handleKeyEvent(k);
        return true;
    }

    if ( e->type() == QEvent::Shortcut ||
         e->type() == QEvent::KeyRelease ) {
        return true;
    }

    if (e->type() == QEvent::ShortcutOverride) {
        // for shortcut overrides, we need to accept as well
        e->accept();
        return true;
    }

    return false;
}

void ShortcutSettings::commandChanged(QTreeWidgetItem *current)
{
    CommandMappings::commandChanged(current);
    if (!current || !current->data(0, Qt::UserRole).isValid())
        return;
    ShortcutItem *scitem = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
    setKeySequence(scitem->m_key);
    markCollisions(scitem);
}

void ShortcutSettings::targetIdentifierChanged()
{
    QTreeWidgetItem *current = commandList()->currentItem();
    if (current && current->data(0, Qt::UserRole).isValid()) {
        ShortcutItem *scitem = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
        scitem->m_key = QKeySequence(m_key[0], m_key[1], m_key[2], m_key[3]);
        if (scitem->m_cmd->defaultKeySequence() != scitem->m_key)
            setModified(current, true);
        else
            setModified(current, false);
        current->setText(2, scitem->m_key.toString(QKeySequence::NativeText));
        markCollisions(scitem);
    }
}

bool ShortcutSettings::hasConflicts() const
{
    QTreeWidgetItem *current = commandList()->currentItem();
    if (!current || !current->data(0, Qt::UserRole).isValid())
        return false;

    ShortcutItem *item = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
    if (!item)
        return false;

    const QKeySequence currentKey = QKeySequence::fromString(targetEdit()->text(), QKeySequence::NativeText);
    if (currentKey.isEmpty())
        return false;

    const Id globalId(Constants::C_GLOBAL);
    const Context itemContext = item->m_cmd->context();

    foreach (ShortcutItem *listItem, m_scitems) {
        if (item == listItem)
            continue;
        if (listItem->m_key.isEmpty())
            continue;
        if (listItem->m_key.matches(currentKey) == QKeySequence::NoMatch)
            continue;

        const Context listContext = listItem->m_cmd->context();
        if (itemContext.contains(globalId) && !listContext.isEmpty())
            return true;
        if (listContext.contains(globalId) && !itemContext.isEmpty())
            return true;
        foreach (Id id, listContext)
            if (itemContext.contains(id))
                return true;
    }
    return false;
}

void ShortcutSettings::setKeySequence(const QKeySequence &key)
{
    m_key[0] = m_key[1] = m_key[2] = m_key[3] = 0;
    m_keyNum = key.count();
    for (int i = 0; i < m_keyNum; ++i) {
        m_key[i] = key[i];
    }
    targetEdit()->setText(key.toString(QKeySequence::NativeText));
}

void ShortcutSettings::resetTargetIdentifier()
{
    QTreeWidgetItem *current = commandList()->currentItem();
    if (current && current->data(0, Qt::UserRole).isValid()) {
        ShortcutItem *scitem = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
        setKeySequence(scitem->m_cmd->defaultKeySequence());
        foreach (ShortcutItem *item, m_scitems)
            markCollisions(item);
    }
}

void ShortcutSettings::removeTargetIdentifier()
{
    m_keyNum = m_key[0] = m_key[1] = m_key[2] = m_key[3] = 0;
    targetEdit()->clear();

    foreach (ShortcutItem *item, m_scitems)
        markCollisions(item);
}

void ShortcutSettings::importAction()
{
    QString fileName = QFileDialog::getOpenFileName(widget(), tr("Import Keyboard Mapping Scheme"),
        ICore::resourcePath() + QLatin1String("/schemes/"),
        tr("Keyboard Mapping Scheme (*.kms)"));
    if (!fileName.isEmpty()) {

        CommandsFile cf(fileName);
        QMap<QString, QKeySequence> mapping = cf.importCommands();

        foreach (ShortcutItem *item, m_scitems) {
            QString sid = item->m_cmd->id().toString();
            if (mapping.contains(sid)) {
                item->m_key = mapping.value(sid);
                item->m_item->setText(2, item->m_key.toString(QKeySequence::NativeText));
                if (item->m_item == commandList()->currentItem())
                    commandChanged(item->m_item);

                if (item->m_cmd->defaultKeySequence() != item->m_key)
                    setModified(item->m_item, true);
                else
                    setModified(item->m_item, false);
            }
        }

        foreach (ShortcutItem *item, m_scitems)
            markCollisions(item);
    }
}

void ShortcutSettings::defaultAction()
{
    foreach (ShortcutItem *item, m_scitems) {
        item->m_key = item->m_cmd->defaultKeySequence();
        item->m_item->setText(2, item->m_key.toString(QKeySequence::NativeText));
        setModified(item->m_item, false);
        if (item->m_item == commandList()->currentItem())
            commandChanged(item->m_item);
    }

    foreach (ShortcutItem *item, m_scitems)
        markCollisions(item);
}

void ShortcutSettings::exportAction()
{
    QString fileName = DocumentManager::getSaveFileNameWithExtension(
        tr("Export Keyboard Mapping Scheme"),
        ICore::resourcePath() + QLatin1String("/schemes/"),
        tr("Keyboard Mapping Scheme (*.kms)"));
    if (!fileName.isEmpty()) {
        CommandsFile cf(fileName);
        cf.exportCommands(m_scitems);
    }
}

void ShortcutSettings::clear()
{
    QTreeWidget *tree = commandList();
    for (int i = tree->topLevelItemCount()-1; i >= 0 ; --i) {
        delete tree->takeTopLevelItem(i);
    }
    qDeleteAll(m_scitems);
    m_scitems.clear();
}

void ShortcutSettings::initialize()
{
    if (!m_initialized)
        return;
    clear();
    QMap<QString, QTreeWidgetItem *> sections;

    foreach (Command *c, ActionManager::commands()) {
        if (c->hasAttribute(Command::CA_NonConfigurable))
            continue;
        if (c->action() && c->action()->isSeparator())
            continue;

        QTreeWidgetItem *item = 0;
        ShortcutItem *s = new ShortcutItem;
        m_scitems << s;
        item = new QTreeWidgetItem;
        s->m_cmd = c;
        s->m_item = item;

        const QString identifier = c->id().toString();
        int pos = identifier.indexOf(QLatin1Char('.'));
        const QString section = identifier.left(pos);
        const QString subId = identifier.mid(pos + 1);
        if (!sections.contains(section)) {
            QTreeWidgetItem *categoryItem = new QTreeWidgetItem(commandList(), QStringList() << section);
            QFont f = categoryItem->font(0);
            f.setBold(true);
            categoryItem->setFont(0, f);
            sections.insert(section, categoryItem);
            commandList()->expandItem(categoryItem);
        }
        sections[section]->addChild(item);

        s->m_key = c->keySequence();
        item->setText(0, subId);
        item->setText(1, c->description());
        item->setText(2, s->m_key.toString(QKeySequence::NativeText));
        if (s->m_cmd->defaultKeySequence() != s->m_key)
            setModified(item, true);

        item->setData(0, Qt::UserRole, qVariantFromValue(s));

        markCollisions(s);
    }
    filterChanged(filterText());
}

void ShortcutSettings::handleKeyEvent(QKeyEvent *e)
{
    int nextKey = e->key();
    if ( m_keyNum > 3 ||
         nextKey == Qt::Key_Control ||
         nextKey == Qt::Key_Shift ||
         nextKey == Qt::Key_Meta ||
         nextKey == Qt::Key_Alt )
         return;

    nextKey |= translateModifiers(e->modifiers(), e->text());
    switch (m_keyNum) {
        case 0:
            m_key[0] = nextKey;
            break;
        case 1:
            m_key[1] = nextKey;
            break;
        case 2:
            m_key[2] = nextKey;
            break;
        case 3:
            m_key[3] = nextKey;
            break;
        default:
            break;
    }
    m_keyNum++;
    QKeySequence ks(m_key[0], m_key[1], m_key[2], m_key[3]);
    targetEdit()->setText(ks.toString(QKeySequence::NativeText));
    e->accept();
}

int ShortcutSettings::translateModifiers(Qt::KeyboardModifiers state,
                                         const QString &text)
{
    int result = 0;
    // The shift modifier only counts when it is not used to type a symbol
    // that is only reachable using the shift key anyway
    if ((state & Qt::ShiftModifier) && (text.size() == 0
                                        || !text.at(0).isPrint()
                                        || text.at(0).isLetterOrNumber()
                                        || text.at(0).isSpace()))
        result |= Qt::SHIFT;
    if (state & Qt::ControlModifier)
        result |= Qt::CTRL;
    if (state & Qt::MetaModifier)
        result |= Qt::META;
    if (state & Qt::AltModifier)
        result |= Qt::ALT;
    return result;
}

void ShortcutSettings::markCollisions(ShortcutItem *item)
{
    bool hasCollision = false;
    if (!item->m_key.isEmpty()) {
        Id globalId = Context(Constants::C_GLOBAL).at(0);
        const Context itemContext = item->m_cmd->context();

        foreach (ShortcutItem *currentItem, m_scitems) {

            if (currentItem->m_key.isEmpty() || item == currentItem
                    || item->m_key != currentItem->m_key)
                continue;

            foreach (Id id, currentItem->m_cmd->context()) {
                // conflict if context is identical, OR if one
                // of the contexts is the global context
                const Context thisContext = currentItem->m_cmd->context();
                if (itemContext.contains(id)
                        || (itemContext.contains(globalId) && !thisContext.isEmpty())
                        || (thisContext.contains(globalId) && !itemContext.isEmpty())) {
                    currentItem->m_item->setForeground(2, Qt::red);
                    hasCollision = true;
                }
            }
        }
    }
    item->m_item->setForeground(2, hasCollision ? Qt::red : commandList()->palette().foreground());
}

<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** 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.
**
**
**************************************************************************/

#include "remotegdbserveradapter.h"

#include "debuggeractions.h"
#include "debuggerstartparameters.h"
#include "debuggercore.h"
#include "debuggerstringutils.h"
#include "gdbengine.h"
#include "gdbmi.h"

#include <utils/qtcassert.h>
#include <utils/fancymainwindow.h>
#include <projectexplorer/abi.h>

#include <QFileInfo>
#include <QMessageBox>

namespace Debugger {
namespace Internal {

#define CB(callback) \
    static_cast<GdbEngine::GdbCommandCallback>(&GdbRemoteServerEngine::callback), \
    STRINGIFY(callback)

///////////////////////////////////////////////////////////////////////
//
// RemoteGdbAdapter
//
///////////////////////////////////////////////////////////////////////

GdbRemoteServerEngine::GdbRemoteServerEngine(const DebuggerStartParameters &startParameters)
    : GdbEngine(startParameters)
{
    connect(&m_uploadProc, SIGNAL(error(QProcess::ProcessError)),
        SLOT(uploadProcError(QProcess::ProcessError)));
    connect(&m_uploadProc, SIGNAL(readyReadStandardOutput()),
        SLOT(readUploadStandardOutput()));
    connect(&m_uploadProc, SIGNAL(readyReadStandardError()),
        SLOT(readUploadStandardError()));
    connect(&m_uploadProc, SIGNAL(finished(int)),
        SLOT(uploadProcFinished()));
}

GdbEngine::DumperHandling GdbRemoteServerEngine::dumperHandling() const
{
    using namespace ProjectExplorer;
    const Abi abi = startParameters().toolChainAbi;
    if (abi.os() == Abi::WindowsOS
            || abi.binaryFormat() == Abi::ElfFormat)
        return DumperLoadedByGdb;
    return DumperLoadedByGdbPreload;
}

void GdbRemoteServerEngine::setupEngine()
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
    showMessage(_("TRYING TO START ADAPTER"));
    if (!startParameters().serverStartScript.isEmpty()) {
        m_uploadProc.start(_("/bin/sh ") + startParameters().serverStartScript);
        m_uploadProc.waitForStarted();
    }
    if (startParameters().remoteSetupNeeded)
        notifyEngineRequestRemoteSetup();
    else
        startGdb();
}

void GdbRemoteServerEngine::uploadProcError(QProcess::ProcessError error)
{
    QString msg;
    switch (error) {
        case QProcess::FailedToStart:
            msg = tr("The upload process failed to start. Shell missing?");
            break;
        case QProcess::Crashed:
            msg = tr("The upload process crashed some time after starting "
                "successfully.");
            break;
        case QProcess::Timedout:
            msg = tr("The last waitFor...() function timed out. "
                "The state of QProcess is unchanged, and you can try calling "
                "waitFor...() again.");
            break;
        case QProcess::WriteError:
            msg = tr("An error occurred when attempting to write "
                "to the upload process. For example, the process may not be running, "
                "or it may have closed its input channel.");
            break;
        case QProcess::ReadError:
            msg = tr("An error occurred when attempting to read from "
                "the upload process. For example, the process may not be running.");
            break;
        default:
            msg = tr("An unknown error in the upload process occurred. "
                "This is the default return value of error().");
    }

    showMessage(msg, StatusBar);
    showMessageBox(QMessageBox::Critical, tr("Error"), msg);
}

void GdbRemoteServerEngine::readUploadStandardOutput()
{
    const QByteArray ba = m_uploadProc.readAllStandardOutput();
    const QString msg = QString::fromLocal8Bit(ba, ba.length());
    showMessage(msg, LogOutput);
    showMessage(msg, AppOutput);
}

void GdbRemoteServerEngine::readUploadStandardError()
{
    const QByteArray ba = m_uploadProc.readAllStandardError();
    const QString msg = QString::fromLocal8Bit(ba, ba.length());
    showMessage(msg, LogOutput);
    showMessage(msg, AppError);
}

void GdbRemoteServerEngine::uploadProcFinished()
{
    if (m_uploadProc.exitStatus() == QProcess::NormalExit
        && m_uploadProc.exitCode() == 0)
        startGdb();
    else
        notifyEngineRemoteSetupFailed(m_uploadProc.errorString());
}

void GdbRemoteServerEngine::setupInferior()
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    const DebuggerStartParameters &sp = startParameters();
#ifdef Q_OS_WIN
    #define PATHSEP ";"
#else
    #define PATHSEP ":"
#endif
    QString executableFileName;
    if (!sp.executable.isEmpty()) {
        QFileInfo fi(sp.executable);
        executableFileName = fi.absoluteFilePath();
    }
    QString symbolFileName;
    if (!sp.symbolFileName.isEmpty()) {
        QFileInfo fi(sp.symbolFileName);
        symbolFileName = fi.absoluteFilePath();
    }

    //const QByteArray sysroot = sp.sysroot.toLocal8Bit();
    //const QByteArray remoteArch = sp.remoteArchitecture.toLatin1();
    const QString args = sp.processArgs;

//    if (!remoteArch.isEmpty())
//        postCommand("set architecture " + remoteArch);
    const QString solibSearchPath = sp.solibSearchPath.join(QLatin1String(PATHSEP));
    if (!solibSearchPath.isEmpty())
        postCommand("set solib-search-path " + solibSearchPath.toLocal8Bit());

    if (!args.isEmpty())
        postCommand("-exec-arguments " + args.toLocal8Bit());

    // This has to be issued before 'target remote'. On pre-7.0 the
    // command is not present and will result in ' No symbol table is
    // loaded.  Use the "file" command.' as gdb tries to set the
    // value of a variable with name 'target-async'.
    //
    // Testing with -list-target-features which was introduced at
    // the same time would not work either, as this need an existing
    // target.
    //
    // Using it even without a target and having it fail might still
    // be better as:
    // Some external comment: '[but] "set target-async on" with a native
    // windows gdb will work, but then fail when you actually do
    // "run"/"attach", I think..

    // gdb/mi/mi-main.c:1958: internal-error:
    // mi_execute_async_cli_command: Assertion `is_running (inferior_ptid)'
    // failed.\nA problem internal to GDB has been detected,[...]
    if (debuggerCore()->boolSetting(TargetAsync))
        postCommand("set target-async on", CB(handleSetTargetAsync));

    if (executableFileName.isEmpty() && symbolFileName.isEmpty()) {
        showMessage(tr("No symbol file given."), StatusBar);
        callTargetRemote();
        return;
    }

    if (!symbolFileName.isEmpty()) {
        postCommand("-file-symbol-file \""
                    + symbolFileName.toLocal8Bit() + '"',
                    CB(handleFileExecAndSymbols));
    }
    if (!executableFileName.isEmpty()) {
        postCommand("-file-exec-and-symbols \"" + executableFileName.toLocal8Bit() + '"',
            CB(handleFileExecAndSymbols));
    }
}

void GdbRemoteServerEngine::handleSetTargetAsync(const GdbResponse &response)
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    if (response.resultClass == GdbResultError)
        qDebug() << "Adapter too old: does not support asynchronous mode.";
}

void GdbRemoteServerEngine::handleFileExecAndSymbols(const GdbResponse &response)
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    if (response.resultClass == GdbResultDone) {
        callTargetRemote();
    } else {
        QByteArray reason = response.data.findChild("msg").data();
        QString msg = tr("Reading debug information failed:\n");
        msg += QString::fromLocal8Bit(reason);
        if (reason.endsWith("No such file or directory.")) {
            showMessage(_("INFERIOR STARTUP: BINARY NOT FOUND"));
            showMessage(msg, StatusBar);
            callTargetRemote(); // Proceed nevertheless.
        } else {
            notifyInferiorSetupFailed(msg);
        }
    }
}

void GdbRemoteServerEngine::callTargetRemote()
{
    //m_breakHandler->clearBreakMarkers();

    // "target remote" does three things:
    //     (1) connects to the gdb server
    //     (2) starts the remote application
    //     (3) stops the remote application (early, e.g. in the dynamic linker)
    QByteArray channel = startParameters().remoteChannel.toLatin1();

    // Don't touch channels with explicitly set protocols.
    if (!channel.startsWith("tcp:") && !channel.startsWith("udp:")
            && !channel.startsWith("file:") && channel.contains(':'))
    {
        // "Fix" the IPv6 case with host names without '['...']'
        if (!channel.startsWith('[') && channel.count(':') >= 2) {
            channel.insert(0, '[');
            channel.insert(channel.lastIndexOf(':'), ']');
        }
        channel = "tcp:" + channel;
    }

    if (m_isQnxGdb)
        postCommand("target qnx " + channel, CB(handleTargetQnx));
    else
        postCommand("target remote " + channel, CB(handleTargetRemote));
}

void GdbRemoteServerEngine::handleTargetRemote(const GdbResponse &record)
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    if (record.resultClass == GdbResultDone) {
        // gdb server will stop the remote application itself.
        showMessage(_("INFERIOR STARTED"));
        showMessage(msgAttachedToStoppedInferior(), StatusBar);
        handleInferiorPrepared();
    } else {
        // 16^error,msg="hd:5555: Connection timed out."
        QString msg = msgConnectRemoteServerFailed(
            QString::fromLocal8Bit(record.data.findChild("msg").data()));
        notifyInferiorSetupFailed(msg);
    }
}

void GdbRemoteServerEngine::handleTargetQnx(const GdbResponse &response)
{
    QTC_ASSERT(m_isQnxGdb, qDebug() << m_isQnxGdb);
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    if (response.resultClass == GdbResultDone) {
        // gdb server will stop the remote application itself.
        showMessage(_("INFERIOR STARTED"));
        showMessage(msgAttachedToStoppedInferior(), StatusBar);

        const qint64 pid = isMasterEngine() ? startParameters().attachPID : masterEngine()->startParameters().attachPID;
        if (pid > -1) {
            postCommand("attach " + QByteArray::number(pid), CB(handleAttach));
        } else {
            handleInferiorPrepared();
        }
    } else {
        // 16^error,msg="hd:5555: Connection timed out."
        QString msg = msgConnectRemoteServerFailed(
            QString::fromLocal8Bit(response.data.findChild("msg").data()));
        notifyInferiorSetupFailed(msg);
    }
}

void GdbRemoteServerEngine::handleAttach(const GdbResponse &response)
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    switch (response.resultClass) {
    case GdbResultDone:
    case GdbResultRunning: {
        showMessage(_("INFERIOR ATTACHED"));
        showMessage(msgAttachedToStoppedInferior(), StatusBar);
        handleInferiorPrepared();
        break;
    }
    case GdbResultError:
        if (response.data.findChild("msg").data() == "ptrace: Operation not permitted.") {
            notifyInferiorSetupFailed(DumperHelper::msgPtraceError(startParameters().startMode));
            break;
        }
        // if msg != "ptrace: ..." fall through
    default:
        QString msg = QString::fromLocal8Bit(response.data.findChild("msg").data());
        notifyInferiorSetupFailed(msg);
    }
}

void GdbRemoteServerEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());

    const QString remoteExecutable = startParameters().remoteExecutable;
    if (!remoteExecutable.isEmpty()) {
        // Cannot use -exec-run for QNX gdb as it does not support path parameter for the MI call
        const QByteArray command = m_isQnxGdb ? "run" : "-exec-run";
        postCommand(command + " " + remoteExecutable.toLocal8Bit(), GdbEngine::RunRequest, CB(handleExecRun));
    } else {
        notifyEngineRunAndInferiorStopOk();
        continueInferiorInternal();
    }
}

void GdbRemoteServerEngine::handleExecRun(const GdbResponse &response)
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
    if (response.resultClass == GdbResultRunning) {
        notifyEngineRunAndInferiorRunOk();
        showMessage(_("INFERIOR STARTED"));
        showMessage(msgInferiorSetupOk(), StatusBar);
    } else {
        QString msg = QString::fromLocal8Bit(response.data.findChild("msg").data());
        showMessage(msg);
        notifyEngineRunFailed();
    }
}

void GdbRemoteServerEngine::interruptInferior2()
{
    QTC_ASSERT(state() == InferiorStopRequested, qDebug() << state());
    if (debuggerCore()->boolSetting(TargetAsync)) {
        postCommand("-exec-interrupt", GdbEngine::Immediate,
            CB(handleInterruptInferior));
    } else {
        bool ok = m_gdbProc.interrupt();
        if (!ok) {
            // FIXME: Extra state needed?
            showMessage(_("NOTE: INFERIOR STOP NOT POSSIBLE"));
            showStatusMessage(tr("Interrupting not possible"));
            notifyInferiorRunOk();
        }
    }
}

void GdbRemoteServerEngine::handleInterruptInferior(const GdbResponse &response)
{
    if (response.resultClass == GdbResultDone) {
        // The gdb server will trigger extra output that we will pick up
        // to do a proper state transition.
    } else {
        // FIXME: On some gdb versions like git 170ffa5d7dd this produces
        // >810^error,msg="mi_cmd_exec_interrupt: Inferior not executing."
        notifyInferiorStopOk();
    }
}

void GdbRemoteServerEngine::shutdownEngine()
{
    notifyAdapterShutdownOk();
}

void GdbRemoteServerEngine::notifyEngineRemoteSetupDone(int gdbServerPort, int qmlPort)
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
    DebuggerEngine::notifyEngineRemoteSetupDone(gdbServerPort, qmlPort);

    if (qmlPort != -1)
        startParameters().qmlServerPort = qmlPort;
    if (gdbServerPort != -1) {
        QString &rc = startParameters().remoteChannel;
        const int sepIndex = rc.lastIndexOf(QLatin1Char(':'));
        if (sepIndex != -1) {
            rc.replace(sepIndex + 1, rc.count() - sepIndex - 1,
                       QString::number(gdbServerPort));
        }
    }
    startGdb();
}

void GdbRemoteServerEngine::notifyEngineRemoteSetupFailed(const QString &reason)
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
    DebuggerEngine::notifyEngineRemoteSetupFailed(reason);
    handleAdapterStartFailed(reason);
}

} // namespace Internal
} // namespace Debugger
<commit_msg>QNX: Fixed launching application when debugging on Windows<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** 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.
**
**
**************************************************************************/

#include "remotegdbserveradapter.h"

#include "debuggeractions.h"
#include "debuggerstartparameters.h"
#include "debuggercore.h"
#include "debuggerstringutils.h"
#include "gdbengine.h"
#include "gdbmi.h"

#include <utils/qtcassert.h>
#include <utils/fancymainwindow.h>
#include <projectexplorer/abi.h>

#include <QFileInfo>
#include <QMessageBox>

namespace Debugger {
namespace Internal {

#define CB(callback) \
    static_cast<GdbEngine::GdbCommandCallback>(&GdbRemoteServerEngine::callback), \
    STRINGIFY(callback)

///////////////////////////////////////////////////////////////////////
//
// RemoteGdbAdapter
//
///////////////////////////////////////////////////////////////////////

GdbRemoteServerEngine::GdbRemoteServerEngine(const DebuggerStartParameters &startParameters)
    : GdbEngine(startParameters)
{
    connect(&m_uploadProc, SIGNAL(error(QProcess::ProcessError)),
        SLOT(uploadProcError(QProcess::ProcessError)));
    connect(&m_uploadProc, SIGNAL(readyReadStandardOutput()),
        SLOT(readUploadStandardOutput()));
    connect(&m_uploadProc, SIGNAL(readyReadStandardError()),
        SLOT(readUploadStandardError()));
    connect(&m_uploadProc, SIGNAL(finished(int)),
        SLOT(uploadProcFinished()));
}

GdbEngine::DumperHandling GdbRemoteServerEngine::dumperHandling() const
{
    using namespace ProjectExplorer;
    const Abi abi = startParameters().toolChainAbi;
    if (abi.os() == Abi::WindowsOS
            || abi.binaryFormat() == Abi::ElfFormat)
        return DumperLoadedByGdb;
    return DumperLoadedByGdbPreload;
}

void GdbRemoteServerEngine::setupEngine()
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
    showMessage(_("TRYING TO START ADAPTER"));
    if (!startParameters().serverStartScript.isEmpty()) {
        m_uploadProc.start(_("/bin/sh ") + startParameters().serverStartScript);
        m_uploadProc.waitForStarted();
    }
    if (startParameters().remoteSetupNeeded)
        notifyEngineRequestRemoteSetup();
    else
        startGdb();
}

void GdbRemoteServerEngine::uploadProcError(QProcess::ProcessError error)
{
    QString msg;
    switch (error) {
        case QProcess::FailedToStart:
            msg = tr("The upload process failed to start. Shell missing?");
            break;
        case QProcess::Crashed:
            msg = tr("The upload process crashed some time after starting "
                "successfully.");
            break;
        case QProcess::Timedout:
            msg = tr("The last waitFor...() function timed out. "
                "The state of QProcess is unchanged, and you can try calling "
                "waitFor...() again.");
            break;
        case QProcess::WriteError:
            msg = tr("An error occurred when attempting to write "
                "to the upload process. For example, the process may not be running, "
                "or it may have closed its input channel.");
            break;
        case QProcess::ReadError:
            msg = tr("An error occurred when attempting to read from "
                "the upload process. For example, the process may not be running.");
            break;
        default:
            msg = tr("An unknown error in the upload process occurred. "
                "This is the default return value of error().");
    }

    showMessage(msg, StatusBar);
    showMessageBox(QMessageBox::Critical, tr("Error"), msg);
}

void GdbRemoteServerEngine::readUploadStandardOutput()
{
    const QByteArray ba = m_uploadProc.readAllStandardOutput();
    const QString msg = QString::fromLocal8Bit(ba, ba.length());
    showMessage(msg, LogOutput);
    showMessage(msg, AppOutput);
}

void GdbRemoteServerEngine::readUploadStandardError()
{
    const QByteArray ba = m_uploadProc.readAllStandardError();
    const QString msg = QString::fromLocal8Bit(ba, ba.length());
    showMessage(msg, LogOutput);
    showMessage(msg, AppError);
}

void GdbRemoteServerEngine::uploadProcFinished()
{
    if (m_uploadProc.exitStatus() == QProcess::NormalExit
        && m_uploadProc.exitCode() == 0)
        startGdb();
    else
        notifyEngineRemoteSetupFailed(m_uploadProc.errorString());
}

void GdbRemoteServerEngine::setupInferior()
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    const DebuggerStartParameters &sp = startParameters();
#ifdef Q_OS_WIN
    #define PATHSEP ";"
#else
    #define PATHSEP ":"
#endif
    QString executableFileName;
    if (!sp.executable.isEmpty()) {
        QFileInfo fi(sp.executable);
        executableFileName = fi.absoluteFilePath();
    }
    QString symbolFileName;
    if (!sp.symbolFileName.isEmpty()) {
        QFileInfo fi(sp.symbolFileName);
        symbolFileName = fi.absoluteFilePath();
    }

    //const QByteArray sysroot = sp.sysroot.toLocal8Bit();
    //const QByteArray remoteArch = sp.remoteArchitecture.toLatin1();
    const QString args = sp.processArgs;

//    if (!remoteArch.isEmpty())
//        postCommand("set architecture " + remoteArch);
    const QString solibSearchPath = sp.solibSearchPath.join(QLatin1String(PATHSEP));
    if (!solibSearchPath.isEmpty())
        postCommand("set solib-search-path " + solibSearchPath.toLocal8Bit());

    if (!args.isEmpty())
        postCommand("-exec-arguments " + args.toLocal8Bit());

    // This has to be issued before 'target remote'. On pre-7.0 the
    // command is not present and will result in ' No symbol table is
    // loaded.  Use the "file" command.' as gdb tries to set the
    // value of a variable with name 'target-async'.
    //
    // Testing with -list-target-features which was introduced at
    // the same time would not work either, as this need an existing
    // target.
    //
    // Using it even without a target and having it fail might still
    // be better as:
    // Some external comment: '[but] "set target-async on" with a native
    // windows gdb will work, but then fail when you actually do
    // "run"/"attach", I think..

    // gdb/mi/mi-main.c:1958: internal-error:
    // mi_execute_async_cli_command: Assertion `is_running (inferior_ptid)'
    // failed.\nA problem internal to GDB has been detected,[...]
    if (debuggerCore()->boolSetting(TargetAsync))
        postCommand("set target-async on", CB(handleSetTargetAsync));

    if (executableFileName.isEmpty() && symbolFileName.isEmpty()) {
        showMessage(tr("No symbol file given."), StatusBar);
        callTargetRemote();
        return;
    }

    if (!symbolFileName.isEmpty()) {
        postCommand("-file-symbol-file \""
                    + symbolFileName.toLocal8Bit() + '"',
                    CB(handleFileExecAndSymbols));
    }
    if (!executableFileName.isEmpty()) {
        postCommand("-file-exec-and-symbols \"" + executableFileName.toLocal8Bit() + '"',
            CB(handleFileExecAndSymbols));
    }
}

void GdbRemoteServerEngine::handleSetTargetAsync(const GdbResponse &response)
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    if (response.resultClass == GdbResultError)
        qDebug() << "Adapter too old: does not support asynchronous mode.";
}

void GdbRemoteServerEngine::handleFileExecAndSymbols(const GdbResponse &response)
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    if (response.resultClass == GdbResultDone) {
        callTargetRemote();
    } else {
        QByteArray reason = response.data.findChild("msg").data();
        QString msg = tr("Reading debug information failed:\n");
        msg += QString::fromLocal8Bit(reason);
        if (reason.endsWith("No such file or directory.")) {
            showMessage(_("INFERIOR STARTUP: BINARY NOT FOUND"));
            showMessage(msg, StatusBar);
            callTargetRemote(); // Proceed nevertheless.
        } else {
            notifyInferiorSetupFailed(msg);
        }
    }
}

void GdbRemoteServerEngine::callTargetRemote()
{
    //m_breakHandler->clearBreakMarkers();

    // "target remote" does three things:
    //     (1) connects to the gdb server
    //     (2) starts the remote application
    //     (3) stops the remote application (early, e.g. in the dynamic linker)
    QByteArray channel = startParameters().remoteChannel.toLatin1();

    // Don't touch channels with explicitly set protocols.
    if (!channel.startsWith("tcp:") && !channel.startsWith("udp:")
            && !channel.startsWith("file:") && channel.contains(':'))
    {
        // "Fix" the IPv6 case with host names without '['...']'
        if (!channel.startsWith('[') && channel.count(':') >= 2) {
            channel.insert(0, '[');
            channel.insert(channel.lastIndexOf(':'), ']');
        }
        channel = "tcp:" + channel;
    }

    if (m_isQnxGdb)
        postCommand("target qnx " + channel, CB(handleTargetQnx));
    else
        postCommand("target remote " + channel, CB(handleTargetRemote));
}

void GdbRemoteServerEngine::handleTargetRemote(const GdbResponse &record)
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    if (record.resultClass == GdbResultDone) {
        // gdb server will stop the remote application itself.
        showMessage(_("INFERIOR STARTED"));
        showMessage(msgAttachedToStoppedInferior(), StatusBar);
        handleInferiorPrepared();
    } else {
        // 16^error,msg="hd:5555: Connection timed out."
        QString msg = msgConnectRemoteServerFailed(
            QString::fromLocal8Bit(record.data.findChild("msg").data()));
        notifyInferiorSetupFailed(msg);
    }
}

void GdbRemoteServerEngine::handleTargetQnx(const GdbResponse &response)
{
    QTC_ASSERT(m_isQnxGdb, qDebug() << m_isQnxGdb);
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    if (response.resultClass == GdbResultDone) {
        // gdb server will stop the remote application itself.
        showMessage(_("INFERIOR STARTED"));
        showMessage(msgAttachedToStoppedInferior(), StatusBar);

        const qint64 pid = isMasterEngine() ? startParameters().attachPID : masterEngine()->startParameters().attachPID;
        if (pid > -1) {
            postCommand("attach " + QByteArray::number(pid), CB(handleAttach));
        } else {
            handleInferiorPrepared();
        }
    } else {
        // 16^error,msg="hd:5555: Connection timed out."
        QString msg = msgConnectRemoteServerFailed(
            QString::fromLocal8Bit(response.data.findChild("msg").data()));
        notifyInferiorSetupFailed(msg);
    }
}

void GdbRemoteServerEngine::handleAttach(const GdbResponse &response)
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    switch (response.resultClass) {
    case GdbResultDone:
    case GdbResultRunning: {
        showMessage(_("INFERIOR ATTACHED"));
        showMessage(msgAttachedToStoppedInferior(), StatusBar);
        handleInferiorPrepared();
        break;
    }
    case GdbResultError:
        if (response.data.findChild("msg").data() == "ptrace: Operation not permitted.") {
            notifyInferiorSetupFailed(DumperHelper::msgPtraceError(startParameters().startMode));
            break;
        }
        // if msg != "ptrace: ..." fall through
    default:
        QString msg = QString::fromLocal8Bit(response.data.findChild("msg").data());
        notifyInferiorSetupFailed(msg);
    }
}

void GdbRemoteServerEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());

    const QString remoteExecutable = startParameters().remoteExecutable;
    if (!remoteExecutable.isEmpty()) {
        // Cannot use -exec-run for QNX gdb 7.4 as it does not support path parameter for the MI call
        const bool useRun = m_isQnxGdb && m_gdbVersion > 70300;
        const QByteArray command = useRun ? "run" : "-exec-run";
        postCommand(command + " " + remoteExecutable.toLocal8Bit(), GdbEngine::RunRequest, CB(handleExecRun));
    } else {
        notifyEngineRunAndInferiorStopOk();
        continueInferiorInternal();
    }
}

void GdbRemoteServerEngine::handleExecRun(const GdbResponse &response)
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
    if (response.resultClass == GdbResultRunning) {
        notifyEngineRunAndInferiorRunOk();
        showMessage(_("INFERIOR STARTED"));
        showMessage(msgInferiorSetupOk(), StatusBar);
    } else {
        QString msg = QString::fromLocal8Bit(response.data.findChild("msg").data());
        showMessage(msg);
        notifyEngineRunFailed();
    }
}

void GdbRemoteServerEngine::interruptInferior2()
{
    QTC_ASSERT(state() == InferiorStopRequested, qDebug() << state());
    if (debuggerCore()->boolSetting(TargetAsync)) {
        postCommand("-exec-interrupt", GdbEngine::Immediate,
            CB(handleInterruptInferior));
    } else {
        bool ok = m_gdbProc.interrupt();
        if (!ok) {
            // FIXME: Extra state needed?
            showMessage(_("NOTE: INFERIOR STOP NOT POSSIBLE"));
            showStatusMessage(tr("Interrupting not possible"));
            notifyInferiorRunOk();
        }
    }
}

void GdbRemoteServerEngine::handleInterruptInferior(const GdbResponse &response)
{
    if (response.resultClass == GdbResultDone) {
        // The gdb server will trigger extra output that we will pick up
        // to do a proper state transition.
    } else {
        // FIXME: On some gdb versions like git 170ffa5d7dd this produces
        // >810^error,msg="mi_cmd_exec_interrupt: Inferior not executing."
        notifyInferiorStopOk();
    }
}

void GdbRemoteServerEngine::shutdownEngine()
{
    notifyAdapterShutdownOk();
}

void GdbRemoteServerEngine::notifyEngineRemoteSetupDone(int gdbServerPort, int qmlPort)
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
    DebuggerEngine::notifyEngineRemoteSetupDone(gdbServerPort, qmlPort);

    if (qmlPort != -1)
        startParameters().qmlServerPort = qmlPort;
    if (gdbServerPort != -1) {
        QString &rc = startParameters().remoteChannel;
        const int sepIndex = rc.lastIndexOf(QLatin1Char(':'));
        if (sepIndex != -1) {
            rc.replace(sepIndex + 1, rc.count() - sepIndex - 1,
                       QString::number(gdbServerPort));
        }
    }
    startGdb();
}

void GdbRemoteServerEngine::notifyEngineRemoteSetupFailed(const QString &reason)
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
    DebuggerEngine::notifyEngineRemoteSetupFailed(reason);
    handleAdapterStartFailed(reason);
}

} // namespace Internal
} // namespace Debugger
<|endoftext|>