<commit_before>#include "project.h"
/**
 * @brief Project::Project
 * @param id
 * @param name
 */
Project::Project(FileHandler* file_handler, ID id, std::string name){
    this->file_handler = file_handler;
    this->name = name;
    this->save_name = name;
    this->id = id;
    this->dir = -1;
    this->dir_videos = -1;
    this->dir_bookmarks = -1;
    this->v_id = 0;
    this->videos.clear();
    this->changes_made = true;
}
/**
 * @brief Project::Project
 */
Project::Project(FileHandler* file_handler){
    this->file_handler = file_handler;
    this->name = "";
    this->save_name = "";
    this->id = -1;
    this->id = 0;
    this->dir = -1;
    this->dir_bookmarks = -1;
    this->dir_videos = -1;
    this->videos.clear();
}

/**
 * @brief Project::~Project
 * Clears contents of video map
 */
Project::~Project(){
    for (auto vid_it = this->videos.begin(); vid_it != this->videos.end(); ++vid_it) {
        delete vid_it->second;
    }
    for (auto rep_it = this->reports.begin(); rep_it != this->reports.end(); ++rep_it) {
        delete *rep_it;
    }
}

/**
 * @brief Project::remove_video
 * @param id
 * Remove video from videos and delete its contents.
 */
void Project::remove_video_project(ID id){
    VideoProject* temp = this->videos.at(id);
    delete temp;
    videos.erase(id);
    this->changes_made = true;
}

/**
 * @brief Project::add_video
 * @return Video ID to be used for identifying the video.
 */
ID Project::add_video(Video* vid){
    vid->id = this->v_id;
    this->videos.insert(std::make_pair(this->v_id, new VideoProject(vid)));
    this->changes_made = true;
    return this->v_id++;
}

/**
 * @brief Project::add_report
 * @param file_path
 */
void Project::add_report(std::string file_path){
    this->reports.push_back(new Report(file_path));
    this->saved = false;
}

/**
 * @brief Project::add_report
 * @param report
 * Required for load, object locally allocated
 */
void Project::add_report(Report* report){
    this->reports.push_back(report);
}

/**
 * @brief Project::add_video
 * @return Video ID to be used for identifying the video.
 */
ID Project::add_video_project(VideoProject* vid_proj){
    vid_proj->get_video()->id = this->v_id;
    this->videos.insert(std::make_pair(this->v_id, vid_proj));
    this->changes_made = true;
    return this->v_id++;
}
/**
 * @brief Project::delete_artifacts
 * Delete all projects files.
 */
void Project::delete_artifacts(){
    // Delete files in all videoprojects
    for(auto it = videos.begin(); it != videos.end(); it++){
        VideoProject* vp = it->second;
        vp->delete_artifacts();
    }
    // Delete all reports.
    for(auto it = reports.begin(); it != reports.end(); it++){
        Report* temp = *it;
        QFile file (QString::fromStdString(temp->get_file_path()));
        file.remove();
    }
}

/**
 * @brief Project::read
 * @param json
 * Read project parameters from json object.
 */
void Project::read(const QJsonObject& json){
    this->name = json["name"].toString().toStdString();
    this->dir = file_handler->create_directory(json["root_dir"].toString());
    this->dir_bookmarks = file_handler->create_directory(json["bookmark_dir"].toString());
    this->dir_videos = file_handler->create_directory(json["video_dir"].toString());
    this->save_name = this->name;
    // Read videos from json
    QJsonArray json_vid_projs = json["videos"].toArray();
    for (int i = 0; i < json_vid_projs.size(); ++i) {
        QJsonObject json_vid_proj = json_vid_projs[i].toObject();
        VideoProject* v = new VideoProject();
        v->read(json_vid_proj);
        this->add_video_project(v);
    }
    // Read reports from json
    QJsonArray json_reports = json["reports"].toArray();
    for (int i = 0; i < json_reports.size(); ++i) {
        QJsonObject json_report = json_reports[i].toObject();
        Report* report = new Report();
        report->read(json_report);
        this->add_report(report);
    }
}

/**
 * @brief Project::write
 * @param json
 * Write project parameters to json object.
 */
void Project::write(QJsonObject& json){
    json["name"] = QString::fromStdString(this->name);
    json["root_dir"] =  file_handler->get_dir(this->dir).absolutePath();
    json["bookmark_dir"] = file_handler->get_dir(this->dir_bookmarks).absolutePath();
    json["video_dir"] = file_handler->get_dir(this->dir_videos).absolutePath();
    QJsonArray json_proj;
    // Write Videos to json
    for(auto it = this->videos.begin(); it != this->videos.end(); it++){
        QJsonObject json_vid_proj;
        VideoProject* v = it->second;
        v->write(json_vid_proj);
        json_proj.append(json_vid_proj);
    }
    json["videos"] = json_proj;
    // Write reports to json
    QJsonArray json_reports;
    for(auto it = this->reports.begin(); it != this->reports.end(); it++){
        QJsonObject json_report;
        Report* report = *it;
        report->write(json_report);
        json_reports.append(json_report);
    }
    json["reports"] = json_reports;
}

/**
 * @brief Project::add_bookmark
 * @param v_id the id of the video
 * @param bookmark
 * Add new bookmark to Videoproj corresponding to id.
 */
ID Project::add_bookmark(ID v_id, Bookmark *bookmark){
    VideoProject* v = this->videos.at(v_id);
    this->changes_made = true;
    return v->add_bookmark(bookmark);
}

/**
 * @brief Project::is_saved
 * @return true if saved
 */
bool Project::is_saved(){
    return !this->changes_made;
}

/**
 * @brief Project::save_project
 * @return sets saved =true
 */
void Project::save_project(){
    this->changes_made = false;
}

/**
 * @brief Project::get_videos
 * @return videos&
 */
std::map<ID, VideoProject* > &Project::get_videos(){
    return this->videos;
}
<commit_msg>Fixed old variable name. (#149)<commit_after>#include "project.h"
/**
 * @brief Project::Project
 * @param id
 * @param name
 */
Project::Project(FileHandler* file_handler, ID id, std::string name){
    this->file_handler = file_handler;
    this->name = name;
    this->save_name = name;
    this->id = id;
    this->dir = -1;
    this->dir_videos = -1;
    this->dir_bookmarks = -1;
    this->v_id = 0;
    this->videos.clear();
    this->changes_made = true;
}
/**
 * @brief Project::Project
 */
Project::Project(FileHandler* file_handler){
    this->file_handler = file_handler;
    this->name = "";
    this->save_name = "";
    this->id = -1;
    this->id = 0;
    this->dir = -1;
    this->dir_bookmarks = -1;
    this->dir_videos = -1;
    this->videos.clear();
}

/**
 * @brief Project::~Project
 * Clears contents of video map
 */
Project::~Project(){
    for (auto vid_it = this->videos.begin(); vid_it != this->videos.end(); ++vid_it) {
        delete vid_it->second;
    }
    for (auto rep_it = this->reports.begin(); rep_it != this->reports.end(); ++rep_it) {
        delete *rep_it;
    }
}

/**
 * @brief Project::remove_video
 * @param id
 * Remove video from videos and delete its contents.
 */
void Project::remove_video_project(ID id){
    VideoProject* temp = this->videos.at(id);
    delete temp;
    videos.erase(id);
    this->changes_made = true;
}

/**
 * @brief Project::add_video
 * @return Video ID to be used for identifying the video.
 */
ID Project::add_video(Video* vid){
    vid->id = this->v_id;
    this->videos.insert(std::make_pair(this->v_id, new VideoProject(vid)));
    this->changes_made = true;
    return this->v_id++;
}

/**
 * @brief Project::add_report
 * @param file_path
 */
void Project::add_report(std::string file_path){
    this->reports.push_back(new Report(file_path));
    this->changes_made = true;
}

/**
 * @brief Project::add_report
 * @param report
 * Required for load, object locally allocated
 */
void Project::add_report(Report* report){
    this->reports.push_back(report);
}

/**
 * @brief Project::add_video
 * @return Video ID to be used for identifying the video.
 */
ID Project::add_video_project(VideoProject* vid_proj){
    vid_proj->get_video()->id = this->v_id;
    this->videos.insert(std::make_pair(this->v_id, vid_proj));
    this->changes_made = true;
    return this->v_id++;
}
/**
 * @brief Project::delete_artifacts
 * Delete all projects files.
 */
void Project::delete_artifacts(){
    // Delete files in all videoprojects
    for(auto it = videos.begin(); it != videos.end(); it++){
        VideoProject* vp = it->second;
        vp->delete_artifacts();
    }
    // Delete all reports.
    for(auto it = reports.begin(); it != reports.end(); it++){
        Report* temp = *it;
        QFile file (QString::fromStdString(temp->get_file_path()));
        file.remove();
    }
}

/**
 * @brief Project::read
 * @param json
 * Read project parameters from json object.
 */
void Project::read(const QJsonObject& json){
    this->name = json["name"].toString().toStdString();
    this->dir = file_handler->create_directory(json["root_dir"].toString());
    this->dir_bookmarks = file_handler->create_directory(json["bookmark_dir"].toString());
    this->dir_videos = file_handler->create_directory(json["video_dir"].toString());
    this->save_name = this->name;
    // Read videos from json
    QJsonArray json_vid_projs = json["videos"].toArray();
    for (int i = 0; i < json_vid_projs.size(); ++i) {
        QJsonObject json_vid_proj = json_vid_projs[i].toObject();
        VideoProject* v = new VideoProject();
        v->read(json_vid_proj);
        this->add_video_project(v);
    }
    // Read reports from json
    QJsonArray json_reports = json["reports"].toArray();
    for (int i = 0; i < json_reports.size(); ++i) {
        QJsonObject json_report = json_reports[i].toObject();
        Report* report = new Report();
        report->read(json_report);
        this->add_report(report);
    }
}

/**
 * @brief Project::write
 * @param json
 * Write project parameters to json object.
 */
void Project::write(QJsonObject& json){
    json["name"] = QString::fromStdString(this->name);
    json["root_dir"] =  file_handler->get_dir(this->dir).absolutePath();
    json["bookmark_dir"] = file_handler->get_dir(this->dir_bookmarks).absolutePath();
    json["video_dir"] = file_handler->get_dir(this->dir_videos).absolutePath();
    QJsonArray json_proj;
    // Write Videos to json
    for(auto it = this->videos.begin(); it != this->videos.end(); it++){
        QJsonObject json_vid_proj;
        VideoProject* v = it->second;
        v->write(json_vid_proj);
        json_proj.append(json_vid_proj);
    }
    json["videos"] = json_proj;
    // Write reports to json
    QJsonArray json_reports;
    for(auto it = this->reports.begin(); it != this->reports.end(); it++){
        QJsonObject json_report;
        Report* report = *it;
        report->write(json_report);
        json_reports.append(json_report);
    }
    json["reports"] = json_reports;
}

/**
 * @brief Project::add_bookmark
 * @param v_id the id of the video
 * @param bookmark
 * Add new bookmark to Videoproj corresponding to id.
 */
ID Project::add_bookmark(ID v_id, Bookmark *bookmark){
    VideoProject* v = this->videos.at(v_id);
    this->changes_made = true;
    return v->add_bookmark(bookmark);
}

/**
 * @brief Project::is_saved
 * @return true if saved
 */
bool Project::is_saved(){
    return !this->changes_made;
}

/**
 * @brief Project::save_project
 * @return sets saved =true
 */
void Project::save_project(){
    this->changes_made = false;
}

/**
 * @brief Project::get_videos
 * @return videos&
 */
std::map<ID, VideoProject* > &Project::get_videos(){
    return this->videos;
}
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2022 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/volume/algorithm/volumemap.h>

#include <algorithm>
#include <unordered_map>
#include <inviwo/core/util/exception.h>

namespace inviwo {

void remap(std::shared_ptr<Volume>& volume, std::vector<int> src, std::vector<int> dst,
           int missingValue, bool useMissingValue) {

    if (src.size() == 0 || src.size() != dst.size()) {
        throw Exception(IVW_CONTEXT_CUSTOM("Remap"), "Invalid dataframe size (src = {}, dst = {})",
                        src.size(), dst.size());
    }

    // Create sorted copy of src and check if it contains duplicates
    std::vector<int> sorted = src;
    std::sort(sorted.begin(), sorted.end());
    auto uniqueIterator = std::unique(sorted.begin(), sorted.end());
    if (uniqueIterator != sorted.end()) {
        throw Exception(IVW_CONTEXT_CUSTOM("Remap"),
                        "Duplicate elements in source row (numberOfDuplicates = {})",
                        sorted.size() - std::distance(sorted.begin(), uniqueIterator));
    }

    auto volRep = volume->getEditableRepresentation<VolumeRAM>();

    volRep->dispatch<void, dispatching::filter::Scalars>([&](auto volram) {
        using ValueType = util::PrecisionValueType<decltype(volram)>;
        ValueType* dataPtr = volram->getDataTyped();
        const auto& dim = volram->getDimensions();

        // Check state of dataframe
        bool sorted = std::is_sorted(src.begin(), src.end());

        if (sorted && (src.back() - src.front()) ==
                          static_cast<int>(src.size()) - 1) {  // Sorted + continuous
            std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) {
                // Voxel value is inside src range
                if (static_cast<int>(v) >= src.front() && static_cast<int>(v) <= src.back()) {
                    int index = static_cast<int>(v) - src.front();
                    return static_cast<ValueType>(dst[index]);
                } else if (useMissingValue) {
                    return static_cast<ValueType>(missingValue);
                } else {
                    return v;
                }
            });
        } else if (sorted) {  // Sorted + non continuous
            std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) {
                auto index = std::distance(
                    src.begin(), std::lower_bound(src.begin(), src.end(), static_cast<int>(v)));
                if (index < static_cast<int>(src.size())) {
                    return static_cast<ValueType>(dst[index]);
                } else if (useMissingValue) {
                    return static_cast<ValueType>(missingValue);
                } else {
                    return v;
                }
            });
        } else {
            std::unordered_map<int, int> unorderedIndexMap;
            for (size_t i = 0; i < src.size(); ++i) {
                unorderedIndexMap[src[i]] = dst[i];
            }
            std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) {
                if (unorderedIndexMap.count(static_cast<int>(v)) == 1) {
                    return static_cast<ValueType>(unorderedIndexMap[static_cast<int>(v)]);
                } else if (useMissingValue) {
                    return static_cast<ValueType>(missingValue);
                } else {
                    return v;
                }
            });
        }
    });
}
}  // namespace inviwo
<commit_msg>Volume: duplicate fix<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2022 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/volume/algorithm/volumemap.h>

#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <inviwo/core/util/exception.h>

namespace inviwo {

void remap(std::shared_ptr<Volume>& volume, std::vector<int> src, std::vector<int> dst,
           int missingValue, bool useMissingValue) {

    if (src.size() == 0 || src.size() != dst.size()) {
        throw Exception(IVW_CONTEXT_CUSTOM("Remap"), "Invalid dataframe size (src = {}, dst = {})",
                        src.size(), dst.size());
    }

    // Create sorted copy of src and check if it contains duplicates
    std::unordered_set<int> set(src.begin(), src.end());
    if (src.size() != set.size()) {
        throw Exception(IVW_CONTEXT_CUSTOM("Remap"),
                        "Duplicate elements in source row (numberOfDuplicates = {})",
                        src.size() - set.size());
    }

    auto volRep = volume->getEditableRepresentation<VolumeRAM>();

    volRep->dispatch<void, dispatching::filter::Scalars>([&](auto volram) {
        using ValueType = util::PrecisionValueType<decltype(volram)>;
        ValueType* dataPtr = volram->getDataTyped();
        const auto& dim = volram->getDimensions();

        // Check state of dataframe
        bool sorted = std::is_sorted(src.begin(), src.end());

        if (sorted && (src.back() - src.front()) ==
                          static_cast<int>(src.size()) - 1) {  // Sorted + continuous
            std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) {
                // Voxel value is inside src range
                if (static_cast<int>(v) >= src.front() && static_cast<int>(v) <= src.back()) {
                    int index = static_cast<int>(v) - src.front();
                    return static_cast<ValueType>(dst[index]);
                } else if (useMissingValue) {
                    return static_cast<ValueType>(missingValue);
                } else {
                    return v;
                }
            });
        } else if (sorted) {  // Sorted + non continuous
            std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) {
                auto index = std::distance(
                    src.begin(), std::lower_bound(src.begin(), src.end(), static_cast<int>(v)));
                if (index < static_cast<int>(src.size())) {
                    return static_cast<ValueType>(dst[index]);
                } else if (useMissingValue) {
                    return static_cast<ValueType>(missingValue);
                } else {
                    return v;
                }
            });
        } else {
            std::unordered_map<int, int> unorderedIndexMap;
            for (size_t i = 0; i < src.size(); ++i) {
                unorderedIndexMap[src[i]] = dst[i];
            }
            std::transform(dataPtr, dataPtr + glm::compMul(dim), dataPtr, [&](const ValueType& v) {
                if (unorderedIndexMap.count(static_cast<int>(v)) == 1) {
                    return static_cast<ValueType>(unorderedIndexMap[static_cast<int>(v)]);
                } else if (useMissingValue) {
                    return static_cast<ValueType>(missingValue);
                } else {
                    return v;
                }
            });
        }
    });
}
}  // namespace inviwo
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include <mitkToFDistanceImageToSurfaceFilter.h>
#include <mitkInstantiateAccessFunctions.h>
#include <mitkSurface.h>

#include <itkImage.h>

#include <vtkCellArray.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkFloatArray.h>
#include <vtkPolyDataNormals.h>
#include <vtkCleanPolyData.h>
#include <vtkSmartPointer.h>

#include <math.h>

mitk::ToFDistanceImageToSurfaceFilter::ToFDistanceImageToSurfaceFilter() :
    m_IplScalarImage(NULL), m_CameraIntrinsics(), m_TextureImageWidth(0), m_TextureImageHeight(0), m_InterPixelDistance(), m_TextureIndex(0)
{
    m_InterPixelDistance.Fill(0.045);
    m_CameraIntrinsics = mitk::CameraIntrinsics::New();
    m_CameraIntrinsics->SetFocalLength(295.78960196187319,296.1255427948447);
    m_CameraIntrinsics->SetFocalLength(5.9421434211923247e+02,5.9104053696870778e+02);
    m_CameraIntrinsics->SetPrincipalPoint(3.3930780975300314e+02,2.4273913761751615e+02);
    m_CameraIntrinsics->SetDistorsionCoeffs(-0.36874385358645773f,-0.14339503290129013,0.0033210108720361795,-0.004277703352074105);
    m_ReconstructionMode = WithInterPixelDistance;
}

mitk::ToFDistanceImageToSurfaceFilter::~ToFDistanceImageToSurfaceFilter()
{
}

void mitk::ToFDistanceImageToSurfaceFilter::SetInput( Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics )
{
  this->SetCameraIntrinsics(cameraIntrinsics);
  this->SetInput(0,distanceImage);
}

void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx,  Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics )
{
  this->SetCameraIntrinsics(cameraIntrinsics);
  this->SetInput(idx,distanceImage);
}

void mitk::ToFDistanceImageToSurfaceFilter::SetInput(  mitk::Image* distanceImage )
{
  this->SetInput(0,distanceImage);
}

//TODO: braucht man diese Methode?
void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx,  mitk::Image* distanceImage )
{
  if ((distanceImage == NULL) && (idx == this->GetNumberOfInputs() - 1)) // if the last input is set to NULL, reduce the number of inputs by one
    this->SetNumberOfInputs(this->GetNumberOfInputs() - 1);
  else
    this->ProcessObject::SetNthInput(idx, distanceImage);   // Process object is not const-correct so the const_cast is required here

  this->CreateOutputsForAllInputs();
}

mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput()
{
  return this->GetInput(0);
}

mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput( unsigned int idx )
{
  if (this->GetNumberOfInputs() < 1)
    return NULL; //TODO: geeignete exception werfen
  return static_cast< mitk::Image*>(this->ProcessObject::GetInput(idx));
}

void mitk::ToFDistanceImageToSurfaceFilter::GenerateData()
{
  mitk::Surface::Pointer output = this->GetOutput();
  assert(output);
  mitk::Image::Pointer input = this->GetInput();
  assert(input);
  // mesh points
  int xDimension = input->GetDimension(0);
  int yDimension = input->GetDimension(1);
  unsigned int size = xDimension*yDimension; //size of the image-array
  std::vector<bool> isPointValid;
  isPointValid.resize(size);
  int pointCount = 0;
  vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
  points->SetDataTypeToDouble();
  vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkFloatArray> scalarArray = vtkSmartPointer<vtkFloatArray>::New();
  vtkSmartPointer<vtkFloatArray> textureCoords = vtkSmartPointer<vtkFloatArray>::New();
  textureCoords->SetNumberOfComponents(2);

//  float textureScaleCorrection1 = 0.0;
//  float textureScaleCorrection2 = 0.0;
//  if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0)
//  {
//    textureScaleCorrection1 = float(this->m_TextureImageHeight) / float(this->m_TextureImageWidth);
//    textureScaleCorrection2 = ((float(this->m_TextureImageWidth) - float(this->m_TextureImageHeight))/2) / float(this->m_TextureImageWidth);
//  }

  float* scalarFloatData = NULL;

  if (this->m_IplScalarImage) // if scalar image is defined use it for texturing
  {
    scalarFloatData = (float*)this->m_IplScalarImage->imageData;
  }
  else if (this->GetInput(m_TextureIndex)) // otherwise use intensity image (input(2))
  {
    scalarFloatData = (float*)this->GetInput(m_TextureIndex)->GetData();
  }

    float* inputFloatData = (float*)(input->GetSliceData(0, 0, 0)->GetData());
    //calculate world coordinates
    mitk::ToFProcessingCommon::ToFPoint2D focalLengthInPixelUnits;
    mitk::ToFProcessingCommon::ToFScalarType focalLengthInMm;
    if((m_ReconstructionMode == WithOutInterPixelDistance) || (m_ReconstructionMode == Kinect))
    {
        focalLengthInPixelUnits[0] = m_CameraIntrinsics->GetFocalLengthX();
        focalLengthInPixelUnits[1] = m_CameraIntrinsics->GetFocalLengthY();
    }
    else if( m_ReconstructionMode == WithInterPixelDistance)
    {
        //convert focallength from pixel to mm
        focalLengthInMm = (m_CameraIntrinsics->GetFocalLengthX()*m_InterPixelDistance[0]+m_CameraIntrinsics->GetFocalLengthY()*m_InterPixelDistance[1])/2.0;
    }

    mitk::ToFProcessingCommon::ToFPoint2D principalPoint;
    principalPoint[0] = m_CameraIntrinsics->GetPrincipalPointX();
    principalPoint[1] = m_CameraIntrinsics->GetPrincipalPointY();

    mitk::Point3D origin = input->GetGeometry()->GetOrigin();

    for (int j=0; j<yDimension; j++)
    {
        for (int i=0; i<xDimension; i++)
        {
            // distance value
            mitk::Index3D pixel;
            pixel[0] = i;
            pixel[1] = j;
            pixel[2] = 0;

      unsigned int pixelID = pixel[0]+pixel[1]*xDimension;

      mitk::ToFProcessingCommon::ToFScalarType distance = (double)inputFloatData[pixelID];

            mitk::ToFProcessingCommon::ToFPoint3D cartesianCoordinates;
            switch (m_ReconstructionMode)
            {
            case WithOutInterPixelDistance:
            {
                cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint);
                break;
            }
            case WithInterPixelDistance:
            {
                cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(i+origin[0],j+origin[1],distance,focalLengthInMm,m_InterPixelDistance,principalPoint);
                break;
            }
            case Kinect:
            {
                cartesianCoordinates = mitk::ToFProcessingCommon::KinectIndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint);
                break;
            }
            default:
            {
                MITK_ERROR << "Incorrect reconstruction mode!";
            }
            }

                //Epsilon here, because we may have small float values like 0.00000001 which in fact represents 0.
                if (distance<=mitk::eps)
                {
                    isPointValid[pointCount] = false;
                }
                else
                {
                    isPointValid[pointCount] = true;
                    points->InsertPoint(pixelID, cartesianCoordinates.GetDataPointer());

        if((i >= 1) && (j >= 1))
        {
          vtkIdType xy = i+j*xDimension;
          vtkIdType x_1y = i-1+j*xDimension;
          vtkIdType xy_1 = i+(j-1)*xDimension;
          vtkIdType x_1y_1 = (i-1)+(j-1)*xDimension;

          if (isPointValid[xy]&&isPointValid[x_1y]&&isPointValid[x_1y_1]&&isPointValid[xy_1]) // check if points of cell are valid
          {
            polys->InsertNextCell(3);
            polys->InsertCellPoint(x_1y);
            polys->InsertCellPoint(xy);
            polys->InsertCellPoint(x_1y_1);

            polys->InsertNextCell(3);
            polys->InsertCellPoint(x_1y_1);
            polys->InsertCellPoint(xy);
            polys->InsertCellPoint(xy_1);
          }
        }

        if (scalarFloatData)
        {
          scalarArray->InsertTuple1(pixelID, scalarFloatData[pixel[0]+pixel[1]*xDimension]);
          //scalarArray->InsertTuple1(pixelID, scalarFloatData[pixelID]);
        }
        if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0)
        {

          float xNorm = (((float)pixel[0])/xDimension)/**textureScaleCorrection1 + textureScaleCorrection2 */; // correct video texture scale 640 * 480!!
          float yNorm = ((float)pixel[1])/yDimension; //don't flip. we don't need to flip.
          textureCoords->InsertTuple2(pixelID, xNorm, yNorm);
        }
      }
      pointCount++;
    }
  }

  vtkSmartPointer<vtkPolyData> mesh = vtkSmartPointer<vtkPolyData>::New();
  mesh->SetPoints(points);
  mesh->SetPolys(polys);
  if (scalarArray->GetNumberOfTuples()>0)
  {
    mesh->GetPointData()->SetScalars(scalarArray);
    if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0)
    {
      mesh->GetPointData()->SetTCoords(textureCoords);
    }
  }
  output->SetVtkPolyData(mesh);
}

void mitk::ToFDistanceImageToSurfaceFilter::CreateOutputsForAllInputs()
{
  this->SetNumberOfOutputs(this->GetNumberOfInputs());  // create outputs for all inputs
  for (unsigned int idx = 0; idx < this->GetNumberOfOutputs(); ++idx)
    if (this->GetOutput(idx) == NULL)
    {
    DataObjectPointer newOutput = this->MakeOutput(idx);
    this->SetNthOutput(idx, newOutput);
  }
  this->Modified();
}

void mitk::ToFDistanceImageToSurfaceFilter::GenerateOutputInformation()
{
  this->GetOutput();
  itkDebugMacro(<<"GenerateOutputInformation()");
}

void mitk::ToFDistanceImageToSurfaceFilter::SetScalarImage(IplImage* iplScalarImage)
{
  this->m_IplScalarImage = iplScalarImage;
  this->Modified();
}

IplImage* mitk::ToFDistanceImageToSurfaceFilter::GetScalarImage()
{
  return this->m_IplScalarImage;
}

void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageWidth(int width)
{
  this->m_TextureImageWidth = width;
}

void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageHeight(int height)
{
  this->m_TextureImageHeight = height;
}
<commit_msg>COMP: Format commit.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include <mitkToFDistanceImageToSurfaceFilter.h>
#include <mitkInstantiateAccessFunctions.h>
#include <mitkSurface.h>

#include <itkImage.h>

#include <vtkCellArray.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkFloatArray.h>
#include <vtkPolyDataNormals.h>
#include <vtkCleanPolyData.h>
#include <vtkSmartPointer.h>

#include <math.h>

mitk::ToFDistanceImageToSurfaceFilter::ToFDistanceImageToSurfaceFilter() :
  m_IplScalarImage(NULL), m_CameraIntrinsics(), m_TextureImageWidth(0), m_TextureImageHeight(0), m_InterPixelDistance(), m_TextureIndex(0)
{
  m_InterPixelDistance.Fill(0.045);
  m_CameraIntrinsics = mitk::CameraIntrinsics::New();
  m_CameraIntrinsics->SetFocalLength(295.78960196187319,296.1255427948447);
  m_CameraIntrinsics->SetFocalLength(5.9421434211923247e+02,5.9104053696870778e+02);
  m_CameraIntrinsics->SetPrincipalPoint(3.3930780975300314e+02,2.4273913761751615e+02);
  m_CameraIntrinsics->SetDistorsionCoeffs(-0.36874385358645773f,-0.14339503290129013,0.0033210108720361795,-0.004277703352074105);
  m_ReconstructionMode = WithInterPixelDistance;
}

mitk::ToFDistanceImageToSurfaceFilter::~ToFDistanceImageToSurfaceFilter()
{
}

void mitk::ToFDistanceImageToSurfaceFilter::SetInput( Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics )
{
  this->SetCameraIntrinsics(cameraIntrinsics);
  this->SetInput(0,distanceImage);
}

void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx,  Image* distanceImage, mitk::CameraIntrinsics::Pointer cameraIntrinsics )
{
  this->SetCameraIntrinsics(cameraIntrinsics);
  this->SetInput(idx,distanceImage);
}

void mitk::ToFDistanceImageToSurfaceFilter::SetInput(  mitk::Image* distanceImage )
{
  this->SetInput(0,distanceImage);
}

//TODO: braucht man diese Methode?
void mitk::ToFDistanceImageToSurfaceFilter::SetInput( unsigned int idx,  mitk::Image* distanceImage )
{
  if ((distanceImage == NULL) && (idx == this->GetNumberOfInputs() - 1)) // if the last input is set to NULL, reduce the number of inputs by one
    this->SetNumberOfInputs(this->GetNumberOfInputs() - 1);
  else
    this->ProcessObject::SetNthInput(idx, distanceImage);   // Process object is not const-correct so the const_cast is required here

  this->CreateOutputsForAllInputs();
}

mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput()
{
  return this->GetInput(0);
}

mitk::Image* mitk::ToFDistanceImageToSurfaceFilter::GetInput( unsigned int idx )
{
  if (this->GetNumberOfInputs() < 1)
    return NULL; //TODO: geeignete exception werfen
  return static_cast< mitk::Image*>(this->ProcessObject::GetInput(idx));
}

void mitk::ToFDistanceImageToSurfaceFilter::GenerateData()
{
  mitk::Surface::Pointer output = this->GetOutput();
  assert(output);
  mitk::Image::Pointer input = this->GetInput();
  assert(input);
  // mesh points
  int xDimension = input->GetDimension(0);
  int yDimension = input->GetDimension(1);
  unsigned int size = xDimension*yDimension; //size of the image-array
  std::vector<bool> isPointValid;
  isPointValid.resize(size);
  int pointCount = 0;
  vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
  points->SetDataTypeToDouble();
  vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkFloatArray> scalarArray = vtkSmartPointer<vtkFloatArray>::New();
  vtkSmartPointer<vtkFloatArray> textureCoords = vtkSmartPointer<vtkFloatArray>::New();
  textureCoords->SetNumberOfComponents(2);

  //  float textureScaleCorrection1 = 0.0;
  //  float textureScaleCorrection2 = 0.0;
  //  if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0)
  //  {
  //    textureScaleCorrection1 = float(this->m_TextureImageHeight) / float(this->m_TextureImageWidth);
  //    textureScaleCorrection2 = ((float(this->m_TextureImageWidth) - float(this->m_TextureImageHeight))/2) / float(this->m_TextureImageWidth);
  //  }

  float* scalarFloatData = NULL;

  if (this->m_IplScalarImage) // if scalar image is defined use it for texturing
  {
    scalarFloatData = (float*)this->m_IplScalarImage->imageData;
  }
  else if (this->GetInput(m_TextureIndex)) // otherwise use intensity image (input(2))
  {
    scalarFloatData = (float*)this->GetInput(m_TextureIndex)->GetData();
  }

  float* inputFloatData = (float*)(input->GetSliceData(0, 0, 0)->GetData());
  //calculate world coordinates
  mitk::ToFProcessingCommon::ToFPoint2D focalLengthInPixelUnits;
  mitk::ToFProcessingCommon::ToFScalarType focalLengthInMm;
  if((m_ReconstructionMode == WithOutInterPixelDistance) || (m_ReconstructionMode == Kinect))
  {
    focalLengthInPixelUnits[0] = m_CameraIntrinsics->GetFocalLengthX();
    focalLengthInPixelUnits[1] = m_CameraIntrinsics->GetFocalLengthY();
  }
  else if( m_ReconstructionMode == WithInterPixelDistance)
  {
    //convert focallength from pixel to mm
    focalLengthInMm = (m_CameraIntrinsics->GetFocalLengthX()*m_InterPixelDistance[0]+m_CameraIntrinsics->GetFocalLengthY()*m_InterPixelDistance[1])/2.0;
  }

  mitk::ToFProcessingCommon::ToFPoint2D principalPoint;
  principalPoint[0] = m_CameraIntrinsics->GetPrincipalPointX();
  principalPoint[1] = m_CameraIntrinsics->GetPrincipalPointY();

  mitk::Point3D origin = input->GetGeometry()->GetOrigin();

  for (int j=0; j<yDimension; j++)
  {
    for (int i=0; i<xDimension; i++)
    {
      // distance value
      mitk::Index3D pixel;
      pixel[0] = i;
      pixel[1] = j;
      pixel[2] = 0;

      unsigned int pixelID = pixel[0]+pixel[1]*xDimension;

      mitk::ToFProcessingCommon::ToFScalarType distance = (double)inputFloatData[pixelID];

      mitk::ToFProcessingCommon::ToFPoint3D cartesianCoordinates;
      switch (m_ReconstructionMode)
      {
      case WithOutInterPixelDistance:
      {
        cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint);
        break;
      }
      case WithInterPixelDistance:
      {
        cartesianCoordinates = mitk::ToFProcessingCommon::IndexToCartesianCoordinatesWithInterpixdist(i+origin[0],j+origin[1],distance,focalLengthInMm,m_InterPixelDistance,principalPoint);
        break;
      }
      case Kinect:
      {
        cartesianCoordinates = mitk::ToFProcessingCommon::KinectIndexToCartesianCoordinates(i+origin[0],j+origin[1],distance,focalLengthInPixelUnits,principalPoint);
        break;
      }
      default:
      {
        MITK_ERROR << "Incorrect reconstruction mode!";
      }
      }

      //Epsilon here, because we may have small float values like 0.00000001 which in fact represents 0.
      if (distance<=mitk::eps)
      {
        isPointValid[pointCount] = false;
      }
      else
      {
        isPointValid[pointCount] = true;
        points->InsertPoint(pixelID, cartesianCoordinates.GetDataPointer());

        if((i >= 1) && (j >= 1))
        {
          vtkIdType xy = i+j*xDimension;
          vtkIdType x_1y = i-1+j*xDimension;
          vtkIdType xy_1 = i+(j-1)*xDimension;
          vtkIdType x_1y_1 = (i-1)+(j-1)*xDimension;

          if (isPointValid[xy]&&isPointValid[x_1y]&&isPointValid[x_1y_1]&&isPointValid[xy_1]) // check if points of cell are valid
          {
            polys->InsertNextCell(3);
            polys->InsertCellPoint(x_1y);
            polys->InsertCellPoint(xy);
            polys->InsertCellPoint(x_1y_1);

            polys->InsertNextCell(3);
            polys->InsertCellPoint(x_1y_1);
            polys->InsertCellPoint(xy);
            polys->InsertCellPoint(xy_1);
          }
        }

        if (scalarFloatData)
        {
          scalarArray->InsertTuple1(pixelID, scalarFloatData[pixel[0]+pixel[1]*xDimension]);
          //scalarArray->InsertTuple1(pixelID, scalarFloatData[pixelID]);
        }
        if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0)
        {

          float xNorm = (((float)pixel[0])/xDimension)/**textureScaleCorrection1 + textureScaleCorrection2 */; // correct video texture scale 640 * 480!!
          float yNorm = ((float)pixel[1])/yDimension; //don't flip. we don't need to flip.
          textureCoords->InsertTuple2(pixelID, xNorm, yNorm);
        }
      }
      pointCount++;
    }
  }

  vtkSmartPointer<vtkPolyData> mesh = vtkSmartPointer<vtkPolyData>::New();
  mesh->SetPoints(points);
  mesh->SetPolys(polys);
  if (scalarArray->GetNumberOfTuples()>0)
  {
    mesh->GetPointData()->SetScalars(scalarArray);
    if (this->m_TextureImageHeight > 0.0 && this->m_TextureImageWidth > 0.0)
    {
      mesh->GetPointData()->SetTCoords(textureCoords);
    }
  }
  output->SetVtkPolyData(mesh);
}

void mitk::ToFDistanceImageToSurfaceFilter::CreateOutputsForAllInputs()
{
  this->SetNumberOfOutputs(this->GetNumberOfInputs());  // create outputs for all inputs
  for (unsigned int idx = 0; idx < this->GetNumberOfOutputs(); ++idx)
    if (this->GetOutput(idx) == NULL)
    {
      DataObjectPointer newOutput = this->MakeOutput(idx);
      this->SetNthOutput(idx, newOutput);
    }
  this->Modified();
}

void mitk::ToFDistanceImageToSurfaceFilter::GenerateOutputInformation()
{
  this->GetOutput();
  itkDebugMacro(<<"GenerateOutputInformation()");
}

void mitk::ToFDistanceImageToSurfaceFilter::SetScalarImage(IplImage* iplScalarImage)
{
  this->m_IplScalarImage = iplScalarImage;
  this->Modified();
}

IplImage* mitk::ToFDistanceImageToSurfaceFilter::GetScalarImage()
{
  return this->m_IplScalarImage;
}

void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageWidth(int width)
{
  this->m_TextureImageWidth = width;
}

void mitk::ToFDistanceImageToSurfaceFilter::SetTextureImageHeight(int height)
{
  this->m_TextureImageHeight = height;
}
<|endoftext|>


<commit_before>/*  -*- c++ -*-
    filehtmlwriter.cpp

    This file is part of KMail, the KDE mail client.
    Copyright (c) 2003 Marc Mutz <mutz@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail 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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "filehtmlwriter.h"

#include <kdebug.h>

#include <qstring.h>

namespace KMail {

  FileHtmlWriter::FileHtmlWriter( const QString & filename )
    : HtmlWriter(),
      mFile( filename.isEmpty() ? QString( "filehtmlwriter.out" ) : filename )
  {
    mStream.setEncoding( QTextStream::UnicodeUTF8 );
  }

  FileHtmlWriter::~FileHtmlWriter() {
    if ( mFile.isOpen() ) {
      kdWarning( 5006 ) << "FileHtmlWriter: file still open!" << endl;
      mStream.unsetDevice();
      mFile.close();
    }
  }

  void FileHtmlWriter::begin() {
    openOrWarn();
  }

  void FileHtmlWriter::end() {
    flush();
    mStream.unsetDevice();
    mFile.close();
  }

  void FileHtmlWriter::reset() {
    if ( mFile.isOpen() ) {
      mStream.unsetDevice();
      mFile.close();
    }
  }

  void FileHtmlWriter::write( const QString & str ) {
    mStream << str;
  }

  void FileHtmlWriter::queue( const QString & str ) {
    write( str );
  }

  void FileHtmlWriter::flush() {
    mFile.flush();
  }

  void FileHtmlWriter::openOrWarn() {
    if ( mFile.isOpen() ) {
      kdWarning( 5006 ) << "FileHtmlWriter: file still open!" << endl;
      mStream.unsetDevice();
      mFile.close();
    }
    if ( !mFile.open( IO_WriteOnly ) )
      kdWarning( 5006 ) << "FileHtmlWriter: Cannot open file " << mFile.name() << endl;
    else
      mStream.setDevice( &mFile );
  }

}; // namespace KMail
<commit_msg>flush on write (helps with debugging)<commit_after>/*  -*- c++ -*-
    filehtmlwriter.cpp

    This file is part of KMail, the KDE mail client.
    Copyright (c) 2003 Marc Mutz <mutz@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail 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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "filehtmlwriter.h"

#include <kdebug.h>

#include <qstring.h>

namespace KMail {

  FileHtmlWriter::FileHtmlWriter( const QString & filename )
    : HtmlWriter(),
      mFile( filename.isEmpty() ? QString( "filehtmlwriter.out" ) : filename )
  {
    mStream.setEncoding( QTextStream::UnicodeUTF8 );
  }

  FileHtmlWriter::~FileHtmlWriter() {
    if ( mFile.isOpen() ) {
      kdWarning( 5006 ) << "FileHtmlWriter: file still open!" << endl;
      mStream.unsetDevice();
      mFile.close();
    }
  }

  void FileHtmlWriter::begin() {
    openOrWarn();
  }

  void FileHtmlWriter::end() {
    flush();
    mStream.unsetDevice();
    mFile.close();
  }

  void FileHtmlWriter::reset() {
    if ( mFile.isOpen() ) {
      mStream.unsetDevice();
      mFile.close();
    }
  }

  void FileHtmlWriter::write( const QString & str ) {
    mStream << str;
    flush();
  }

  void FileHtmlWriter::queue( const QString & str ) {
    write( str );
  }

  void FileHtmlWriter::flush() {
    mFile.flush();
  }

  void FileHtmlWriter::openOrWarn() {
    if ( mFile.isOpen() ) {
      kdWarning( 5006 ) << "FileHtmlWriter: file still open!" << endl;
      mStream.unsetDevice();
      mFile.close();
    }
    if ( !mFile.open( IO_WriteOnly ) )
      kdWarning( 5006 ) << "FileHtmlWriter: Cannot open file " << mFile.name() << endl;
    else
      mStream.setDevice( &mFile );
  }

}; // namespace KMail
<|endoftext|>


<commit_before>/* -*- c++ -*-
    kmmimeparttree.h A MIME part tree viwer.

    This file is part of KMail, the KDE mail client.
    Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "kmmimeparttree.h"

#include "kmreaderwin.h"
#include "partNode.h"
#include "kmmsgpart.h"
#include "kmkernel.h"
#include "kmcommands.h"

#include <kdebug.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <kiconloader.h>

#include <QClipboard>
#include <QStyle>
//Added by qt3to4:
#include <q3header.h>
#include <kurl.h>

KMMimePartTree::KMMimePartTree( KMReaderWin* readerWin,
                                QWidget* parent )
    : K3ListView( parent ),
      mReaderWin( readerWin ), mSizeColumn(0)
{
    setStyleDependantFrameWidth();
    addColumn( i18n("Description") );
    addColumn( i18n("Type") );
    addColumn( i18n("Encoding") );
    mSizeColumn = addColumn( i18n("Size") );
    setColumnAlignment( 3, Qt::AlignRight );

    restoreLayoutIfPresent();
    connect( this, SIGNAL( clicked( Q3ListViewItem* ) ),
             this, SLOT( itemClicked( Q3ListViewItem* ) ) );
    connect( this, SIGNAL( contextMenuRequested( Q3ListViewItem*,
                                                 const QPoint&, int ) ),
             this, SLOT( itemRightClicked( Q3ListViewItem*, const QPoint& ) ) );
    setSelectionMode( Q3ListView::Extended );
    setRootIsDecorated( false );
    setAllColumnsShowFocus( true );
    setShowToolTips( true );
    setSorting(-1);
    setDragEnabled( true );
}

static const char configGroup[] = "MimePartTree";

KMMimePartTree::~KMMimePartTree() {
  saveLayout( KMKernel::config(), configGroup );
}

void KMMimePartTree::restoreLayoutIfPresent() {
  // first column: soaks up the rest of the space:
  setColumnWidthMode( 0, Manual );
  header()->setStretchEnabled( true, 0 );
  // rest of the columns:
  if ( KMKernel::config()->hasGroup( configGroup ) ) {
    // there is a saved layout. use it...
    restoreLayout( KMKernel::config(), configGroup );
    // and disable Maximum mode:
    for ( int i = 1 ; i < 4 ; ++i )
      setColumnWidthMode( i, Manual );
  } else {
    // columns grow with their contents:
    for ( int i = 1 ; i < 4 ; ++i )
      setColumnWidthMode( i, Maximum );
  }
}

void KMMimePartTree::itemClicked( Q3ListViewItem* item )
{
  if ( const KMMimePartTreeItem * i = dynamic_cast<KMMimePartTreeItem*>( item ) ) {
    if( mReaderWin->mRootNode == i->node() )
      mReaderWin->update( true ); // Force update
    else
      mReaderWin->setMsgPart( i->node() );
  } else
    kWarning(5006) <<"Item was not a KMMimePartTreeItem!";
}

void KMMimePartTree::itemRightClicked( Q3ListViewItem *item,
                                       const QPoint &point )
{
   // TODO: remove this member var?
   mCurrentContextMenuItem = dynamic_cast<KMMimePartTreeItem *>( item );
   if ( 0 == mCurrentContextMenuItem ) {
     kDebug(5006) <<"Item was not a KMMimePartTreeItem!";
     return;
   }

   kDebug(5006) <<"\n**\n** KMMimePartTree::itemRightClicked() **\n**";

   QMenu popup;
   popup.addAction( SmallIcon( "document-save-as" ),i18n( "Save &As..." ),
                    this, SLOT( slotSaveAs() ) );
   if ( mCurrentContextMenuItem->node()->nodeId() > 2 &&
        mCurrentContextMenuItem->node()->typeString() != "Multipart" ) {
     popup.addAction( SmallIcon( "file-open" ), i18nc( "to open", "Open" ),
                      this, SLOT( slotOpen() ) );
     popup.addAction( i18n( "Open With..." ), this, SLOT( slotOpenWith() ) );
     popup.addAction( i18nc( "to view something", "View" ), this, SLOT( slotView() ) );
   }
   /*
    * FIXME make optional?
   popup.addAction( i18n( "Save as &Encoded..." ), this,
                    SLOT( slotSaveAsEncoded() ) );
   */
   popup.addAction( i18n( "Save All Attachments..." ), this,
                    SLOT( slotSaveAll() ) );
   // edit + delete only for attachments
   if ( mCurrentContextMenuItem->node()->nodeId() > 2 &&
        mCurrentContextMenuItem->node()->typeString() != "Multipart" ) {
     popup.addAction( SmallIcon( "edit-copy" ), i18n( "Copy" ),
                      this, SLOT( slotCopy() ) );
     if ( GlobalSettings::self()->allowAttachmentDeletion() )
       popup.addAction( SmallIcon( "edit-delete" ), i18n( "Delete Attachment" ),
                        this, SLOT( slotDelete() ) );
     if ( GlobalSettings::self()->allowAttachmentEditing() )
       popup.addAction( SmallIcon( "document-properties" ), i18n( "Edit Attachment" ),
                        this, SLOT( slotEdit() ) );
   }
   if ( mCurrentContextMenuItem->node()->nodeId() > 0 )
     popup.addAction( i18n( "Properties" ), this, SLOT( slotProperties() ) );
   popup.exec( point );
   mCurrentContextMenuItem = 0;
}

//-----------------------------------------------------------------------------
void KMMimePartTree::slotSaveAs()
{
  saveSelectedBodyParts( false );
}

//-----------------------------------------------------------------------------
void KMMimePartTree::slotSaveAsEncoded()
{
  saveSelectedBodyParts( true );
}

//-----------------------------------------------------------------------------
void KMMimePartTree::saveSelectedBodyParts( bool encoded )
{
  QList<Q3ListViewItem*> selected = selectedItems();

  Q_ASSERT( !selected.isEmpty() );
  if ( selected.isEmpty() )
    return;

  QList<partNode*> parts;
  for ( QList<Q3ListViewItem*>::Iterator it = selected.begin(); it != selected.end(); ++it ) {
    parts.append( static_cast<KMMimePartTreeItem *>( *it )->node() );
  }
  mReaderWin->setUpdateAttachment();
  KMSaveAttachmentsCommand *command =
    new KMSaveAttachmentsCommand( this, parts, mReaderWin->message(), encoded );
  command->start();
}

//-----------------------------------------------------------------------------
void KMMimePartTree::slotSaveAll()
{
    if( childCount() == 0)
        return;

    mReaderWin->setUpdateAttachment();
    KMCommand *command =
      new KMSaveAttachmentsCommand( this, mReaderWin->message() );
    command->start();
}

//-----------------------------------------------------------------------------
void KMMimePartTree::setStyleDependantFrameWidth()
{
  // set the width of the frame to a reasonable value for the current GUI style
  int frameWidth;
#if 0 // is this hack still needed with kde4?
  if( !qstrcmp( style()->metaObject()->className(), "KeramikStyle" ) )
    frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth ) - 1;
  else
#endif
    frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth );
  if ( frameWidth < 0 )
    frameWidth = 0;
  if ( frameWidth != lineWidth() )
    setLineWidth( frameWidth );
}

//-----------------------------------------------------------------------------
void KMMimePartTree::styleChange( QStyle& oldStyle )
{
  setStyleDependantFrameWidth();
  K3ListView::styleChange( oldStyle );
}

//-----------------------------------------------------------------------------
void KMMimePartTree::correctSize( Q3ListViewItem * item )
{
  if (!item) return;

  KIO::filesize_t totalSize = 0;
  Q3ListViewItem * myChild = item->firstChild();
  while ( myChild )
  {
    totalSize += static_cast<KMMimePartTreeItem*>(myChild)->origSize();
    myChild = myChild->nextSibling();
  }
  if ( totalSize > static_cast<KMMimePartTreeItem*>(item)->origSize() )
    item->setText( mSizeColumn, KIO::convertSize(totalSize) );
  if ( item->parent() )
    correctSize( item->parent() );
}

void KMMimePartTree::slotDelete()
{
  QList<Q3ListViewItem*> selected = selectedItems();
  if ( selected.count() != 1 )
    return;
  mReaderWin->slotDeleteAttachment( static_cast<KMMimePartTreeItem*>( selected.first() )->node() );
}

void KMMimePartTree::slotEdit()
{
  QList<Q3ListViewItem*> selected = selectedItems();
  if ( selected.count() != 1 )
    return;
  mReaderWin->slotEditAttachment( static_cast<KMMimePartTreeItem*>( selected.first() )->node() );
}

void KMMimePartTree::slotOpen()
{
  startHandleAttachmentCommand( KMHandleAttachmentCommand::Open );
}

void KMMimePartTree::slotOpenWith()
{
  startHandleAttachmentCommand( KMHandleAttachmentCommand::OpenWith );
}

void KMMimePartTree::slotView()
{
  startHandleAttachmentCommand( KMHandleAttachmentCommand::View );
}

void KMMimePartTree::slotProperties()
{
  startHandleAttachmentCommand( KMHandleAttachmentCommand::Properties );
}

void KMMimePartTree::startHandleAttachmentCommand( int action )
{
  QList<Q3ListViewItem *> selected = selectedItems();
  if ( selected.count() != 1 )
    return;
  partNode *node = static_cast<KMMimePartTreeItem *>( selected.first() )->node();
  QString name = mReaderWin->tempFileUrlFromPartNode( node ).path();
  KMHandleAttachmentCommand *command = new KMHandleAttachmentCommand(
      node, mReaderWin->message(), node->nodeId(), name,
      KMHandleAttachmentCommand::AttachmentAction( action ),
      KService::Ptr(), this );
  connect( command, SIGNAL( showAttachment( int, const QString& ) ),
           mReaderWin, SLOT( slotAtmView( int, const QString& ) ) );
  command->start();
}

void KMMimePartTree::slotCopy()
{
  QList<Q3ListViewItem *> selected = selectedItems();
  if ( selected.count() != 1 )
    return;
  partNode *node = static_cast<KMMimePartTreeItem *>( selected.first() )->node();
  QList<QUrl> urls;
  KUrl kUrl = mReaderWin->tempFileUrlFromPartNode( node );
  QUrl url = QUrl::fromPercentEncoding( kUrl.toEncoded() );
  if ( !url.isValid() )
    return;
  urls.append( url );

  QMimeData *mimeData = new QMimeData;
  mimeData->setUrls( urls );
  QApplication::clipboard()->setMimeData( mimeData, QClipboard::Clipboard );
}

//=============================================================================
KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTree * parent,
                                        partNode* node,
                                        const QString & description,
                                        const QString & mimetype,
                                        const QString & encoding,
                                        KIO::filesize_t size )
  : Q3ListViewItem( parent, description,
		   QString(), // set by setIconAndTextForType()
		   encoding,
		   KIO::convertSize( size ) ),
    mPartNode( node ), mOrigSize(size)
{
  Q_ASSERT(parent);
  if( node )
    node->setMimePartTreeItem( this );
  setIconAndTextForType( mimetype );
  parent->correctSize(this);
}

KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTreeItem * parent,
                                        partNode* node,
                                        const QString & description,
                                        const QString & mimetype,
                                        const QString & encoding,
                                        KIO::filesize_t size,
                                        bool revertOrder )
  : Q3ListViewItem( parent, description,
		   QString(), // set by setIconAndTextForType()
		   encoding,
		   KIO::convertSize( size ) ),
    mPartNode( node ), mOrigSize(size)
{
  if( revertOrder && nextSibling() ){
    Q3ListViewItem* sib = nextSibling();
    while( sib->nextSibling() )
      sib = sib->nextSibling();
    moveItem( sib );
  }
  if( node )
    node->setMimePartTreeItem( this );
  setIconAndTextForType( mimetype );
  if ( listView() )
    static_cast<KMMimePartTree*>(listView())->correctSize(this);
}

void KMMimePartTreeItem::setIconAndTextForType( const QString & mime )
{
  QString mimetype = mime.toLower();
  if ( mimetype.startsWith( "multipart/" ) ) {
    setText( 1, mimetype );
    setPixmap( 0, SmallIcon("folder") );
  } else if ( mimetype == "application/octet-stream" ) {
    setText( 1, i18n("Unspecified Binary Data") ); // do not show "Unknown"...
    setPixmap( 0, SmallIcon("application-octet-stream") );
  } else {
    KMimeType::Ptr mtp = KMimeType::mimeType( mimetype );
    setText( 1, (mtp && !mtp->comment().isEmpty()) ? mtp->comment() : mimetype );
    setPixmap( 0, mtp ? KIconLoader::global()->loadMimeTypeIcon(mtp->iconName(), KIconLoader::Small) : SmallIcon("unknown") );
  }
}

void KMMimePartTree::startDrag()
{
  KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( currentItem() );
  if ( !item )
    return;
  partNode *node = item->node();
  if ( !node )
    return;

  QList<QUrl> urls;
  KUrl kUrl = mReaderWin->tempFileUrlFromPartNode( node );
  QUrl url = QUrl::fromPercentEncoding( kUrl.toEncoded() );
  if ( !url.isValid() )
    return;
  urls.append( url );

  QDrag *drag = new QDrag( this );
  QMimeData *mimeData = new QMimeData;
  mimeData->setUrls( urls );
  drag->setMimeData( mimeData );
  QApplication::clipboard()->setMimeData( mimeData, QClipboard::Clipboard );
  drag->exec( Qt::CopyAction );
}

#include "kmmimeparttree.moc"

<commit_msg>Don't put the URLs of the mime part in the clipboard. The QDrag already has ownership, so the clipboard can't have ownership too.<commit_after>/* -*- c++ -*-
    kmmimeparttree.h A MIME part tree viwer.

    This file is part of KMail, the KDE mail client.
    Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "kmmimeparttree.h"

#include "kmreaderwin.h"
#include "partNode.h"
#include "kmmsgpart.h"
#include "kmkernel.h"
#include "kmcommands.h"

#include <kdebug.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <kiconloader.h>

#include <QClipboard>
#include <QStyle>
//Added by qt3to4:
#include <q3header.h>
#include <kurl.h>

KMMimePartTree::KMMimePartTree( KMReaderWin* readerWin,
                                QWidget* parent )
    : K3ListView( parent ),
      mReaderWin( readerWin ), mSizeColumn(0)
{
    setStyleDependantFrameWidth();
    addColumn( i18n("Description") );
    addColumn( i18n("Type") );
    addColumn( i18n("Encoding") );
    mSizeColumn = addColumn( i18n("Size") );
    setColumnAlignment( 3, Qt::AlignRight );

    restoreLayoutIfPresent();
    connect( this, SIGNAL( clicked( Q3ListViewItem* ) ),
             this, SLOT( itemClicked( Q3ListViewItem* ) ) );
    connect( this, SIGNAL( contextMenuRequested( Q3ListViewItem*,
                                                 const QPoint&, int ) ),
             this, SLOT( itemRightClicked( Q3ListViewItem*, const QPoint& ) ) );
    setSelectionMode( Q3ListView::Extended );
    setRootIsDecorated( false );
    setAllColumnsShowFocus( true );
    setShowToolTips( true );
    setSorting(-1);
    setDragEnabled( true );
}

static const char configGroup[] = "MimePartTree";

KMMimePartTree::~KMMimePartTree() {
  saveLayout( KMKernel::config(), configGroup );
}

void KMMimePartTree::restoreLayoutIfPresent() {
  // first column: soaks up the rest of the space:
  setColumnWidthMode( 0, Manual );
  header()->setStretchEnabled( true, 0 );
  // rest of the columns:
  if ( KMKernel::config()->hasGroup( configGroup ) ) {
    // there is a saved layout. use it...
    restoreLayout( KMKernel::config(), configGroup );
    // and disable Maximum mode:
    for ( int i = 1 ; i < 4 ; ++i )
      setColumnWidthMode( i, Manual );
  } else {
    // columns grow with their contents:
    for ( int i = 1 ; i < 4 ; ++i )
      setColumnWidthMode( i, Maximum );
  }
}

void KMMimePartTree::itemClicked( Q3ListViewItem* item )
{
  if ( const KMMimePartTreeItem * i = dynamic_cast<KMMimePartTreeItem*>( item ) ) {
    if( mReaderWin->mRootNode == i->node() )
      mReaderWin->update( true ); // Force update
    else
      mReaderWin->setMsgPart( i->node() );
  } else
    kWarning(5006) <<"Item was not a KMMimePartTreeItem!";
}

void KMMimePartTree::itemRightClicked( Q3ListViewItem *item,
                                       const QPoint &point )
{
   // TODO: remove this member var?
   mCurrentContextMenuItem = dynamic_cast<KMMimePartTreeItem *>( item );
   if ( 0 == mCurrentContextMenuItem ) {
     kDebug(5006) <<"Item was not a KMMimePartTreeItem!";
     return;
   }

   kDebug(5006) <<"\n**\n** KMMimePartTree::itemRightClicked() **\n**";

   QMenu popup;
   popup.addAction( SmallIcon( "document-save-as" ),i18n( "Save &As..." ),
                    this, SLOT( slotSaveAs() ) );
   if ( mCurrentContextMenuItem->node()->nodeId() > 2 &&
        mCurrentContextMenuItem->node()->typeString() != "Multipart" ) {
     popup.addAction( SmallIcon( "file-open" ), i18nc( "to open", "Open" ),
                      this, SLOT( slotOpen() ) );
     popup.addAction( i18n( "Open With..." ), this, SLOT( slotOpenWith() ) );
     popup.addAction( i18nc( "to view something", "View" ), this, SLOT( slotView() ) );
   }
   /*
    * FIXME make optional?
   popup.addAction( i18n( "Save as &Encoded..." ), this,
                    SLOT( slotSaveAsEncoded() ) );
   */
   popup.addAction( i18n( "Save All Attachments..." ), this,
                    SLOT( slotSaveAll() ) );
   // edit + delete only for attachments
   if ( mCurrentContextMenuItem->node()->nodeId() > 2 &&
        mCurrentContextMenuItem->node()->typeString() != "Multipart" ) {
     popup.addAction( SmallIcon( "edit-copy" ), i18n( "Copy" ),
                      this, SLOT( slotCopy() ) );
     if ( GlobalSettings::self()->allowAttachmentDeletion() )
       popup.addAction( SmallIcon( "edit-delete" ), i18n( "Delete Attachment" ),
                        this, SLOT( slotDelete() ) );
     if ( GlobalSettings::self()->allowAttachmentEditing() )
       popup.addAction( SmallIcon( "document-properties" ), i18n( "Edit Attachment" ),
                        this, SLOT( slotEdit() ) );
   }
   if ( mCurrentContextMenuItem->node()->nodeId() > 0 )
     popup.addAction( i18n( "Properties" ), this, SLOT( slotProperties() ) );
   popup.exec( point );
   mCurrentContextMenuItem = 0;
}

//-----------------------------------------------------------------------------
void KMMimePartTree::slotSaveAs()
{
  saveSelectedBodyParts( false );
}

//-----------------------------------------------------------------------------
void KMMimePartTree::slotSaveAsEncoded()
{
  saveSelectedBodyParts( true );
}

//-----------------------------------------------------------------------------
void KMMimePartTree::saveSelectedBodyParts( bool encoded )
{
  QList<Q3ListViewItem*> selected = selectedItems();

  Q_ASSERT( !selected.isEmpty() );
  if ( selected.isEmpty() )
    return;

  QList<partNode*> parts;
  for ( QList<Q3ListViewItem*>::Iterator it = selected.begin(); it != selected.end(); ++it ) {
    parts.append( static_cast<KMMimePartTreeItem *>( *it )->node() );
  }
  mReaderWin->setUpdateAttachment();
  KMSaveAttachmentsCommand *command =
    new KMSaveAttachmentsCommand( this, parts, mReaderWin->message(), encoded );
  command->start();
}

//-----------------------------------------------------------------------------
void KMMimePartTree::slotSaveAll()
{
    if( childCount() == 0)
        return;

    mReaderWin->setUpdateAttachment();
    KMCommand *command =
      new KMSaveAttachmentsCommand( this, mReaderWin->message() );
    command->start();
}

//-----------------------------------------------------------------------------
void KMMimePartTree::setStyleDependantFrameWidth()
{
  // set the width of the frame to a reasonable value for the current GUI style
  int frameWidth;
#if 0 // is this hack still needed with kde4?
  if( !qstrcmp( style()->metaObject()->className(), "KeramikStyle" ) )
    frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth ) - 1;
  else
#endif
    frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth );
  if ( frameWidth < 0 )
    frameWidth = 0;
  if ( frameWidth != lineWidth() )
    setLineWidth( frameWidth );
}

//-----------------------------------------------------------------------------
void KMMimePartTree::styleChange( QStyle& oldStyle )
{
  setStyleDependantFrameWidth();
  K3ListView::styleChange( oldStyle );
}

//-----------------------------------------------------------------------------
void KMMimePartTree::correctSize( Q3ListViewItem * item )
{
  if (!item) return;

  KIO::filesize_t totalSize = 0;
  Q3ListViewItem * myChild = item->firstChild();
  while ( myChild )
  {
    totalSize += static_cast<KMMimePartTreeItem*>(myChild)->origSize();
    myChild = myChild->nextSibling();
  }
  if ( totalSize > static_cast<KMMimePartTreeItem*>(item)->origSize() )
    item->setText( mSizeColumn, KIO::convertSize(totalSize) );
  if ( item->parent() )
    correctSize( item->parent() );
}

void KMMimePartTree::slotDelete()
{
  QList<Q3ListViewItem*> selected = selectedItems();
  if ( selected.count() != 1 )
    return;
  mReaderWin->slotDeleteAttachment( static_cast<KMMimePartTreeItem*>( selected.first() )->node() );
}

void KMMimePartTree::slotEdit()
{
  QList<Q3ListViewItem*> selected = selectedItems();
  if ( selected.count() != 1 )
    return;
  mReaderWin->slotEditAttachment( static_cast<KMMimePartTreeItem*>( selected.first() )->node() );
}

void KMMimePartTree::slotOpen()
{
  startHandleAttachmentCommand( KMHandleAttachmentCommand::Open );
}

void KMMimePartTree::slotOpenWith()
{
  startHandleAttachmentCommand( KMHandleAttachmentCommand::OpenWith );
}

void KMMimePartTree::slotView()
{
  startHandleAttachmentCommand( KMHandleAttachmentCommand::View );
}

void KMMimePartTree::slotProperties()
{
  startHandleAttachmentCommand( KMHandleAttachmentCommand::Properties );
}

void KMMimePartTree::startHandleAttachmentCommand( int action )
{
  QList<Q3ListViewItem *> selected = selectedItems();
  if ( selected.count() != 1 )
    return;
  partNode *node = static_cast<KMMimePartTreeItem *>( selected.first() )->node();
  QString name = mReaderWin->tempFileUrlFromPartNode( node ).path();
  KMHandleAttachmentCommand *command = new KMHandleAttachmentCommand(
      node, mReaderWin->message(), node->nodeId(), name,
      KMHandleAttachmentCommand::AttachmentAction( action ),
      KService::Ptr(), this );
  connect( command, SIGNAL( showAttachment( int, const QString& ) ),
           mReaderWin, SLOT( slotAtmView( int, const QString& ) ) );
  command->start();
}

void KMMimePartTree::slotCopy()
{
  QList<Q3ListViewItem *> selected = selectedItems();
  if ( selected.count() != 1 )
    return;
  partNode *node = static_cast<KMMimePartTreeItem *>( selected.first() )->node();
  QList<QUrl> urls;
  KUrl kUrl = mReaderWin->tempFileUrlFromPartNode( node );
  QUrl url = QUrl::fromPercentEncoding( kUrl.toEncoded() );
  if ( !url.isValid() )
    return;
  urls.append( url );

  QMimeData *mimeData = new QMimeData;
  mimeData->setUrls( urls );
  QApplication::clipboard()->setMimeData( mimeData, QClipboard::Clipboard );
}

//=============================================================================
KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTree * parent,
                                        partNode* node,
                                        const QString & description,
                                        const QString & mimetype,
                                        const QString & encoding,
                                        KIO::filesize_t size )
  : Q3ListViewItem( parent, description,
		   QString(), // set by setIconAndTextForType()
		   encoding,
		   KIO::convertSize( size ) ),
    mPartNode( node ), mOrigSize(size)
{
  Q_ASSERT(parent);
  if( node )
    node->setMimePartTreeItem( this );
  setIconAndTextForType( mimetype );
  parent->correctSize(this);
}

KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTreeItem * parent,
                                        partNode* node,
                                        const QString & description,
                                        const QString & mimetype,
                                        const QString & encoding,
                                        KIO::filesize_t size,
                                        bool revertOrder )
  : Q3ListViewItem( parent, description,
		   QString(), // set by setIconAndTextForType()
		   encoding,
		   KIO::convertSize( size ) ),
    mPartNode( node ), mOrigSize(size)
{
  if( revertOrder && nextSibling() ){
    Q3ListViewItem* sib = nextSibling();
    while( sib->nextSibling() )
      sib = sib->nextSibling();
    moveItem( sib );
  }
  if( node )
    node->setMimePartTreeItem( this );
  setIconAndTextForType( mimetype );
  if ( listView() )
    static_cast<KMMimePartTree*>(listView())->correctSize(this);
}

void KMMimePartTreeItem::setIconAndTextForType( const QString & mime )
{
  QString mimetype = mime.toLower();
  if ( mimetype.startsWith( "multipart/" ) ) {
    setText( 1, mimetype );
    setPixmap( 0, SmallIcon("folder") );
  } else if ( mimetype == "application/octet-stream" ) {
    setText( 1, i18n("Unspecified Binary Data") ); // do not show "Unknown"...
    setPixmap( 0, SmallIcon("application-octet-stream") );
  } else {
    KMimeType::Ptr mtp = KMimeType::mimeType( mimetype );
    setText( 1, (mtp && !mtp->comment().isEmpty()) ? mtp->comment() : mimetype );
    setPixmap( 0, mtp ? KIconLoader::global()->loadMimeTypeIcon(mtp->iconName(), KIconLoader::Small) : SmallIcon("unknown") );
  }
}

void KMMimePartTree::startDrag()
{
  KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( currentItem() );
  if ( !item )
    return;
  partNode *node = item->node();
  if ( !node )
    return;

  QList<QUrl> urls;
  KUrl kUrl = mReaderWin->tempFileUrlFromPartNode( node );
  QUrl url = QUrl::fromPercentEncoding( kUrl.toEncoded() );
  if ( !url.isValid() )
    return;
  urls.append( url );

  QDrag *drag = new QDrag( this );
  QMimeData *mimeData = new QMimeData;
  mimeData->setUrls( urls );
  drag->setMimeData( mimeData );
  drag->exec( Qt::CopyAction );
}

#include "kmmimeparttree.moc"

<|endoftext|>


<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_TEMPLATE_CONFIG
#define MFEM_TEMPLATE_CONFIG

// the main MFEM config header
#include "config.hpp"

// --- MFEM_STATIC_ASSERT
#if (__cplusplus >= 201103L)
#define MFEM_STATIC_ASSERT(cond, msg) static_assert((cond), msg)
#else
#define MFEM_STATIC_ASSERT(cond, msg) if (cond) { }
#endif

// --- MFEM_ALWAYS_INLINE
#if !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__))
#define MFEM_ALWAYS_INLINE __attribute__((always_inline))
#else
#define MFEM_ALWAYS_INLINE
#endif

// --- MFEM_VECTORIZE_LOOP (disabled)
#if (__cplusplus >= 201103L) && !defined(MFEM_DEBUG) && defined(__GNUC__)
//#define MFEM_VECTORIZE_LOOP _Pragma("GCC ivdep")
#define MFEM_VECTORIZE_LOOP
#else
#define MFEM_VECTORIZE_LOOP
#endif

// --- MFEM_ALIGN_AS
#if (__cplusplus >= 201103L)
#define MFEM_ALIGN_AS(bytes) alignas(bytes)
#elif !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__))
#define MFEM_ALIGN_AS(bytes) __attribute__ ((aligned (bytes)))
#else
#define MFEM_ALIGN_AS(bytes)
#endif

// --- POSIX MEMALIGN
#ifdef _WIN32
#define MFEM_POSIX_MEMALIGN(p,a,s) (((*(p))=_aligned_malloc((s),(a))),*(p)?0:errno)
#define MFEM_POSIX_MEMALIGN_FREE _aligned_free
#else
#define MFEM_POSIX_MEMALIGN posix_memalign
#define MFEM_POSIX_MEMALIGN_FREE free
#endif

// --- AutoSIMD or intrinsics
#ifndef MFEM_USE_SIMD
#include "simd/auto.hpp"
#else
#if defined(__VSX__)
#include "simd/vsx.hpp"
#elif defined (__bgq__)
#include "simd/qpx.hpp"
#elif defined(__x86_64__)
#include "simd/x86.hpp"
#else
#error Unknown SIMD architecture
#endif
#endif

// --- SIMD and BLOCK sizes
#if defined(_WIN32)
#define MFEM_SIMD_SIZE 8
#define MFEM_TEMPLATE_BLOCK_SIZE 1
#elif defined(__VSX__)
#define MFEM_SIMD_SIZE 16
#define MFEM_TEMPLATE_BLOCK_SIZE 2
#elif defined(__x86_64__)
#define MFEM_SIMD_SIZE 32
#define MFEM_TEMPLATE_BLOCK_SIZE 4
#else
#error Unknown SIMD architecture
#endif

template<typename complex_t, typename real_t, bool simd>
struct AutoImplTraits
{
   static const int block_size = MFEM_TEMPLATE_BLOCK_SIZE;

   static const int align_size = MFEM_SIMD_SIZE; // in bytes

   static const int batch_size = 1;

   static const int simd_size = simd?(MFEM_SIMD_SIZE/sizeof(complex_t)):1;

   static const int valign_size = simd?simd_size:1;

   typedef AutoSIMD<complex_t,simd_size,valign_size> vcomplex_t;
   typedef AutoSIMD<   real_t,simd_size,valign_size> vreal_t;
#ifndef MFEM_USE_SIMD
   typedef AutoSIMD<      int,simd_size,valign_size> vint_t;
#endif // MFEM_USE_SIMD
};

#define MFEM_TEMPLATE_ENABLE_SERIALIZE

// #define MFEM_TEMPLATE_ELTRANS_HAS_NODE_DOFS
// #define MFEM_TEMPLATE_ELTRANS_RESULT_HAS_NODES
// #define MFEM_TEMPLATE_FIELD_EVAL_DATA_HAS_DOFS
#define MFEM_TEMPLATE_INTRULE_COEFF_PRECOMP

// derived macros
#define MFEM_ROUNDUP(val,base) ((((val)+(base)-1)/(base))*(base))
#define MFEM_ALIGN_SIZE(size,type) \
   MFEM_ROUNDUP(size,(MFEM_SIMD_SIZE)/sizeof(type))

#ifdef MFEM_COUNT_FLOPS
namespace mfem
{
namespace internal
{
extern long long flop_count;
}
}
#define MFEM_FLOPS_RESET() (mfem::internal::flop_count = 0)
#define MFEM_FLOPS_ADD(cnt) (mfem::internal::flop_count += (cnt))
#define MFEM_FLOPS_GET() (mfem::internal::flop_count)
#else
#define MFEM_FLOPS_RESET()
#define MFEM_FLOPS_ADD(cnt)
#define MFEM_FLOPS_GET() (0)
#endif

#endif // MFEM_TEMPLATE_CONFIG
<commit_msg>Cleanup config/tconfig<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_TEMPLATE_CONFIG
#define MFEM_TEMPLATE_CONFIG

// the main MFEM config header
#include "config.hpp"

// --- MFEM_STATIC_ASSERT
#if (__cplusplus >= 201103L)
#define MFEM_STATIC_ASSERT(cond, msg) static_assert((cond), msg)
#else
#define MFEM_STATIC_ASSERT(cond, msg) if (cond) { }
#endif

// --- MFEM_ALWAYS_INLINE
#if !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__))
#define MFEM_ALWAYS_INLINE __attribute__((always_inline))
#else
#define MFEM_ALWAYS_INLINE
#endif

// --- MFEM_VECTORIZE_LOOP (disabled)
#if (__cplusplus >= 201103L) && !defined(MFEM_DEBUG) && defined(__GNUC__)
//#define MFEM_VECTORIZE_LOOP _Pragma("GCC ivdep")
#define MFEM_VECTORIZE_LOOP
#else
#define MFEM_VECTORIZE_LOOP
#endif

// --- MFEM_ALIGN_AS
#if (__cplusplus >= 201103L)
#define MFEM_ALIGN_AS(bytes) alignas(bytes)
#elif !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__))
#define MFEM_ALIGN_AS(bytes) __attribute__ ((aligned (bytes)))
#else
#define MFEM_ALIGN_AS(bytes)
#endif

// --- POSIX MEMALIGN
#ifdef _WIN32
#define MFEM_POSIX_MEMALIGN(p,a,s) (((*(p))=_aligned_malloc((s),(a))),*(p)?0:errno)
#define MFEM_POSIX_MEMALIGN_FREE _aligned_free
#else
#define MFEM_POSIX_MEMALIGN posix_memalign
#define MFEM_POSIX_MEMALIGN_FREE free
#endif

// --- AutoSIMD or intrinsics
#ifndef MFEM_USE_SIMD
#include "simd/auto.hpp"
#else
#if defined(__VSX__)
#include "simd/vsx.hpp"
#elif defined (__bgq__)
#include "simd/qpx.hpp"
#elif defined(__x86_64__)
#include "simd/x86.hpp"
#else
#error Unknown SIMD architecture
#endif
#endif

// --- SIMD and BLOCK sizes
#if defined(_WIN32)
#define MFEM_SIMD_SIZE 8
#define MFEM_TEMPLATE_BLOCK_SIZE 1
#elif defined(__VSX__)
#define MFEM_SIMD_SIZE 16
#define MFEM_TEMPLATE_BLOCK_SIZE 2
#elif defined(__x86_64__)
#define MFEM_SIMD_SIZE 32
#define MFEM_TEMPLATE_BLOCK_SIZE 4
#else
#error Unknown SIMD architecture
#endif

template<typename complex_t, typename real_t, bool simd>
struct AutoImplTraits
{
   static const int block_size = MFEM_TEMPLATE_BLOCK_SIZE;

   static const int align_size = MFEM_SIMD_SIZE; // in bytes

   static const int batch_size = 1;

   static const int simd_size = simd ? (MFEM_SIMD_SIZE/sizeof(complex_t)) : 1;

   static const int valign_size = simd ? simd_size : 1;

   typedef AutoSIMD<complex_t, simd_size, valign_size> vcomplex_t;
   typedef AutoSIMD<real_t, simd_size, valign_size> vreal_t;
#ifndef MFEM_USE_SIMD
   typedef AutoSIMD<int, simd_size, valign_size> vint_t;
#endif // MFEM_USE_SIMD
};

#define MFEM_TEMPLATE_ENABLE_SERIALIZE

// #define MFEM_TEMPLATE_ELTRANS_HAS_NODE_DOFS
// #define MFEM_TEMPLATE_ELTRANS_RESULT_HAS_NODES
// #define MFEM_TEMPLATE_FIELD_EVAL_DATA_HAS_DOFS
#define MFEM_TEMPLATE_INTRULE_COEFF_PRECOMP

// derived macros
#define MFEM_ROUNDUP(val,base) ((((val)+(base)-1)/(base))*(base))
#define MFEM_ALIGN_SIZE(size,type) \
   MFEM_ROUNDUP(size,(MFEM_SIMD_SIZE)/sizeof(type))

#ifdef MFEM_COUNT_FLOPS
namespace mfem
{
namespace internal
{
extern long long flop_count;
}
}
#define MFEM_FLOPS_RESET() (mfem::internal::flop_count = 0)
#define MFEM_FLOPS_ADD(cnt) (mfem::internal::flop_count += (cnt))
#define MFEM_FLOPS_GET() (mfem::internal::flop_count)
#else
#define MFEM_FLOPS_RESET()
#define MFEM_FLOPS_ADD(cnt)
#define MFEM_FLOPS_GET() (0)
#endif

#endif // MFEM_TEMPLATE_CONFIG
<|endoftext|>


<commit_before>/*
    kopeteballoon.cpp  -  Nice Balloon

    Copyright (c) 2002      by Duncan Mac-Vicar Prett <duncan@kde.org>

    Kopete    (c) 2002-2003      by the Kopete developers  <kopete-devel@kde.org>

    Portions of this code based on Kim Applet code
    Copyright (c) 2000-2002 by Malte Starostik        <malte@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.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qpointarray.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <qlayout.h>

#include <kdeversion.h>
#if KDE_IS_VERSION( 3, 1, 90 )
#include <kglobalsettings.h>
#endif

#include <kapplication.h>
#include <kdialog.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kactivelabel.h>

#include "kopeteballoon.h"
#include "systemtray.h"

KopeteBalloon::KopeteBalloon(const QString &text, const QString &pix)
: QWidget(0L, "KopeteBalloon", WStyle_StaysOnTop | WStyle_Customize |
	WStyle_NoBorder | WStyle_Tool | WX11BypassWM)
{
	setCaption("");

	QVBoxLayout *BalloonLayout = new QVBoxLayout(this, 22,
		KDialog::spacingHint(), "BalloonLayout");

	// BEGIN Layout1
	QHBoxLayout *Layout1 = new QHBoxLayout(BalloonLayout,
		KDialog::spacingHint(), "Layout1");
	//QLabel *mCaption = new QLabel(text, this, "mCaption");
	KActiveLabel *mCaption = new KActiveLabel(text, this, "mCaption");
	mCaption->setPalette(QToolTip::palette());
	mCaption->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );

	if (!pix.isEmpty())
	{
		QLabel *mImage = new QLabel(this, "mImage");
		mImage->setScaledContents(FALSE);
		mImage->setPixmap(locate("data", pix));

		Layout1->addWidget(mImage);
	}
	Layout1->addWidget(mCaption);
	// END Layout1

	// BEGIN Layout2
	QHBoxLayout *Layout2 = new QHBoxLayout(BalloonLayout,
		KDialog::spacingHint(), "Layout2");
	QPushButton *mViewButton = new QPushButton(i18n("to view", "View"), this,
		"mViewButton");
	QPushButton *mIgnoreButton = new QPushButton(i18n("Ignore"), this,
		"mIgnoreButton");

	Layout2->addStretch();
	Layout2->addWidget(mViewButton);
	Layout2->addWidget(mIgnoreButton);
	Layout2->addStretch();
	// END Layout2

	setPalette(QToolTip::palette());
	setAutoMask(TRUE);

	connect(mViewButton, SIGNAL(clicked()),
		this, SIGNAL(signalButtonClicked()));
	connect(mViewButton, SIGNAL(clicked()),
		this, SLOT(deleteLater()));
	connect(mIgnoreButton, SIGNAL(clicked()),
		this, SIGNAL(signalIgnoreButtonClicked()));
	connect(mIgnoreButton, SIGNAL(clicked()),
		this, SLOT(deleteLater()));
	connect(mCaption, SIGNAL(linkClicked(const QString &)),
		this, SIGNAL(signalIgnoreButtonClicked()));
	connect(mCaption, SIGNAL(linkClicked(const QString &)),
		this, SLOT(deleteLater()));
}

void KopeteBalloon::setAnchor(const QPoint &anchor)
{
	mAnchor = anchor;
	updateMask();
}

void KopeteBalloon::updateMask()
{
	QRegion mask(10, 10, width() - 20, height() - 20);

	QPoint corners[8] = {
		QPoint(width() - 50, 10),
		QPoint(10, 10),
		QPoint(10, height() - 50),
		QPoint(width() - 50, height() - 50),
		QPoint(width() - 10, 10),
		QPoint(10, 10),
		QPoint(10, height() - 10),
		QPoint(width() - 10, height() - 10)
	};

	for (int i = 0; i < 4; ++i)
	{
		QPointArray corner;
		corner.makeArc(corners[i].x(), corners[i].y(), 40, 40,
			i * 16 * 90, 16 * 90);
		corner.resize(corner.size() + 1);
		corner.setPoint(corner.size() - 1, corners[i + 4]);
		mask -= corner;
	}

	// get screen-geometry for screen our anchor is on
	// (geometry can differ from screen to screen!
	#if KDE_IS_VERSION( 3, 1, 90 )
		QRect deskRect = KGlobalSettings::desktopGeometry(mAnchor);
	#else
		QDesktopWidget* tmp = QApplication::desktop();
		QRect deskRect = tmp->screenGeometry(tmp->screenNumber(mAnchor));
	#endif

	bool bottom = (mAnchor.y() + height()) > (deskRect.height() - 48);
	bool right = (mAnchor.x() + width()) > (deskRect.width() - 48);

	QPointArray arrow(4);
	arrow.setPoint(0, QPoint(right ? width() : 0, bottom ? height() : 0));
	arrow.setPoint(1, QPoint(right ? width() - 10 : 10,
		bottom ? height() - 30 : 30));
	arrow.setPoint(2, QPoint(right ? width() - 30 : 30,
		bottom ? height() - 10 : 10));
	arrow.setPoint(3, arrow[0]);
	mask += arrow;
	setMask(mask);

	move(right ? mAnchor.x() - width() : ( mAnchor.x() < 0 ? 0 : mAnchor.x() ),
	     bottom ? mAnchor.y() - height() : ( mAnchor.y() < 0 ? 0 : mAnchor.y() ) );
}

#include "kopeteballoon.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>damn you balloon, show on my second display as well ;)<commit_after>/*
    kopeteballoon.cpp  -  Nice Balloon

    Copyright (c) 2002      by Duncan Mac-Vicar Prett <duncan@kde.org>

    Kopete    (c) 2002-2003      by the Kopete developers  <kopete-devel@kde.org>

    Portions of this code based on Kim Applet code
    Copyright (c) 2000-2002 by Malte Starostik        <malte@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.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qpointarray.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <qlayout.h>

#include <kdeversion.h>
#if KDE_IS_VERSION( 3, 1, 90 )
#include <kglobalsettings.h>
#endif

#include <kapplication.h>
#include <kdialog.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kactivelabel.h>

#include "kopeteballoon.h"
#include "systemtray.h"

KopeteBalloon::KopeteBalloon(const QString &text, const QString &pix)
: QWidget(0L, "KopeteBalloon", WStyle_StaysOnTop | WStyle_Customize |
	WStyle_NoBorder | WStyle_Tool | WX11BypassWM)
{
	setCaption("");

	QVBoxLayout *BalloonLayout = new QVBoxLayout(this, 22,
		KDialog::spacingHint(), "BalloonLayout");

	// BEGIN Layout1
	QHBoxLayout *Layout1 = new QHBoxLayout(BalloonLayout,
		KDialog::spacingHint(), "Layout1");
	//QLabel *mCaption = new QLabel(text, this, "mCaption");
	KActiveLabel *mCaption = new KActiveLabel(text, this, "mCaption");
	mCaption->setPalette(QToolTip::palette());
	mCaption->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );

	if (!pix.isEmpty())
	{
		QLabel *mImage = new QLabel(this, "mImage");
		mImage->setScaledContents(FALSE);
		mImage->setPixmap(locate("data", pix));

		Layout1->addWidget(mImage);
	}
	Layout1->addWidget(mCaption);
	// END Layout1

	// BEGIN Layout2
	QHBoxLayout *Layout2 = new QHBoxLayout(BalloonLayout,
		KDialog::spacingHint(), "Layout2");
	QPushButton *mViewButton = new QPushButton(i18n("to view", "View"), this,
		"mViewButton");
	QPushButton *mIgnoreButton = new QPushButton(i18n("Ignore"), this,
		"mIgnoreButton");

	Layout2->addStretch();
	Layout2->addWidget(mViewButton);
	Layout2->addWidget(mIgnoreButton);
	Layout2->addStretch();
	// END Layout2

	setPalette(QToolTip::palette());
	setAutoMask(TRUE);

	connect(mViewButton, SIGNAL(clicked()),
		this, SIGNAL(signalButtonClicked()));
	connect(mViewButton, SIGNAL(clicked()),
		this, SLOT(deleteLater()));
	connect(mIgnoreButton, SIGNAL(clicked()),
		this, SIGNAL(signalIgnoreButtonClicked()));
	connect(mIgnoreButton, SIGNAL(clicked()),
		this, SLOT(deleteLater()));
	connect(mCaption, SIGNAL(linkClicked(const QString &)),
		this, SIGNAL(signalIgnoreButtonClicked()));
	connect(mCaption, SIGNAL(linkClicked(const QString &)),
		this, SLOT(deleteLater()));
}

void KopeteBalloon::setAnchor(const QPoint &anchor)
{
	mAnchor = anchor;
	updateMask();
}

void KopeteBalloon::updateMask()
{
	QRegion mask(10, 10, width() - 20, height() - 20);

	QPoint corners[8] = {
		QPoint(width() - 50, 10),
		QPoint(10, 10),
		QPoint(10, height() - 50),
		QPoint(width() - 50, height() - 50),
		QPoint(width() - 10, 10),
		QPoint(10, 10),
		QPoint(10, height() - 10),
		QPoint(width() - 10, height() - 10)
	};

	for (int i = 0; i < 4; ++i)
	{
		QPointArray corner;
		corner.makeArc(corners[i].x(), corners[i].y(), 40, 40,
			i * 16 * 90, 16 * 90);
		corner.resize(corner.size() + 1);
		corner.setPoint(corner.size() - 1, corners[i + 4]);
		mask -= corner;
	}

	// get screen-geometry for screen our anchor is on
	// (geometry can differ from screen to screen!
	#if KDE_IS_VERSION( 3, 1, 90 )
		QRect deskRect = KGlobalSettings::desktopGeometry(mAnchor);
	#else
		QDesktopWidget* tmp = QApplication::desktop();
		QRect deskRect = tmp->screenGeometry(tmp->screenNumber(mAnchor));
	#endif

	bool bottom = (mAnchor.y() + height()) > ((deskRect.y() + deskRect.height()) - 48);
	bool right = (mAnchor.x() + width()) > ((deskRect.x() + deskRect.width()) - 48);

	QPointArray arrow(4);
	arrow.setPoint(0, QPoint(right ? width() : 0, bottom ? height() : 0));
	arrow.setPoint(1, QPoint(right ? width() - 10 : 10,
		bottom ? height() - 30 : 30));
	arrow.setPoint(2, QPoint(right ? width() - 30 : 30,
		bottom ? height() - 10 : 10));
	arrow.setPoint(3, arrow[0]);
	mask += arrow;
	setMask(mask);

	move(right ? mAnchor.x() - width() : ( mAnchor.x() < 0 ? 0 : mAnchor.x() ),
	     bottom ? mAnchor.y() - height() : ( mAnchor.y() < 0 ? 0 : mAnchor.y() ) );
}

#include "kopeteballoon.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: animationtransitionfilternode.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 08:35:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"

// must be first
#include "canvas/debug.hxx"
#include "canvas/verbosetrace.hxx"
#include "animationtransitionfilternode.hxx"
#include "transitionfactory.hxx"

namespace presentation {
namespace internal {

void AnimationTransitionFilterNode::dispose()
{
    mxTransitionFilterNode.clear();
    AnimationBaseNode::dispose();
}

AnimationActivitySharedPtr
AnimationTransitionFilterNode::createActivity() const
{
    return TransitionFactory::createShapeTransition(
        fillCommonParameters(),
        getShape(),
        getContext().mpLayerManager,
        mxTransitionFilterNode );
}

} // namespace internal
} // namespace presentation
<commit_msg>INTEGRATION: CWS presfixes09 (1.3.18); FILE MERGED 2006/10/18 19:55:09 thb 1.3.18.3: RESYNC: (1.4-1.5); FILE MERGED 2006/09/15 22:15:14 thb 1.3.18.2: RESYNC: (1.3-1.4); FILE MERGED 2006/03/24 18:23:17 thb 1.3.18.1: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: animationtransitionfilternode.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 15:31:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"

// must be first
#include "canvas/debug.hxx"
#include "canvas/verbosetrace.hxx"
#include "animationtransitionfilternode.hxx"
#include "transitionfactory.hxx"

namespace slideshow {
namespace internal {

void AnimationTransitionFilterNode::dispose()
{
    mxTransitionFilterNode.clear();
    AnimationBaseNode::dispose();
}

AnimationActivitySharedPtr
AnimationTransitionFilterNode::createActivity() const
{
    return TransitionFactory::createShapeTransition(
        fillCommonParameters(),
        getShape(),
        getContext().mpLayerManager,
        mxTransitionFilterNode );
}

} // namespace internal
} // namespace slideshow
<|endoftext|>