<commit_before>// OutputCanvas.cpp

#include "stdafx.h"
#include "OutputCanvas.h"
#include "Program.h"
#include "NCCode.h"
#include "PythonStuff.h"
#include <wx/file.h>

BEGIN_EVENT_TABLE(COutputTextCtrl, wxTextCtrl)
    EVT_MOUSE_EVENTS(COutputTextCtrl::OnMouse)
END_EVENT_TABLE()

void COutputTextCtrl::OnMouse( wxMouseEvent& event )
{
	if(event.LeftUp())
	{
		wxTextPos pos = GetInsertionPoint();
		if(theApp.m_program && theApp.m_program->m_nc_code)
		{
			theApp.m_program->m_nc_code->HighlightBlock(pos);
			heeksCAD->Repaint();
		}
	}

	event.Skip();
}

BEGIN_EVENT_TABLE(COutputCanvas, wxScrolledWindow)
    EVT_SIZE(COutputCanvas::OnSize)
END_EVENT_TABLE()

static void OnOpen(wxCommandEvent& event)
{
	wxString ext_str(_T("*.*")); // to do, use the machine's NC extension
	wxString wildcard_string = wxString(_("NC files")) + _T(" |") + ext_str;
    wxFileDialog dialog(theApp.m_output_canvas, _("Open NC file"), wxEmptyString, wxEmptyString, wildcard_string);
    dialog.CentreOnParent();

    if (dialog.ShowModal() == wxID_OK)
    {
		HeeksPyBackplot(dialog.GetPath().c_str());
	}
}

static void OnSave(wxCommandEvent& event)
{
	wxString ext_str(_T("*.tap")); // to do, use the machine's NC extension
	wxString wildcard_string = wxString(_("NC files")) + _T(" |") + ext_str;
	wxFileDialog fd(theApp.m_output_canvas, _("Save NC file"), wxEmptyString, wxEmptyString, wildcard_string, wxSAVE|wxOVERWRITE_PROMPT);
	fd.SetFilterIndex(1);
	if (fd.ShowModal() == wxID_OK)
	{
		wxString nc_file_str = fd.GetPath().c_str();
		wxFile ofs(nc_file_str.c_str(), wxFile::write);
		if(!ofs.IsOpened())
		{
			wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + nc_file_str);
			return;
		}

		ofs.Write(theApp.m_output_canvas->m_textCtrl->GetValue());
		HeeksPyBackplot(nc_file_str);
	}
}

COutputCanvas::COutputCanvas(wxWindow* parent)
        : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize,
                           wxHSCROLL | wxVSCROLL | wxNO_FULL_REPAINT_ON_RESIZE)
{
	m_textCtrl = new COutputTextCtrl( this, 100, _T(""),	wxPoint(180,170), wxSize(200,70), wxTE_MULTILINE | wxTE_DONTWRAP | wxTE_RICH);

	// make a tool bar
	m_toolBar = new wxToolBar(this, -1, wxDefaultPosition, wxDefaultSize, wxTB_NODIVIDER | wxTB_FLAT);
	m_toolBar->SetToolBitmapSize(wxSize(32, 32));

	// add toolbar buttons
	heeksCAD->AddToolBarButton(m_toolBar, _T("Open"), wxBitmap(theApp.GetDllFolder() + _T("/bitmaps/open.png"), wxBITMAP_TYPE_PNG), _T("Open an NC file"), OnOpen);
	heeksCAD->AddToolBarButton(m_toolBar, _T("Save"), wxBitmap(theApp.GetDllFolder() + _T("/bitmaps/save.png"), wxBITMAP_TYPE_PNG), _T("Save the NC file"), OnSave);

	m_toolBar->Realize();

	Resize();
}

void COutputCanvas::OnSize(wxSizeEvent& event)
{
    Resize();

    event.Skip();
}

void COutputCanvas::Resize()
{
	wxSize size = GetClientSize();
	wxSize toolbar_size = m_toolBar->GetClientSize();
	m_textCtrl->SetSize(0, 0, size.x, size.y - 39 );
	m_toolBar->SetSize(0, size.y - 39 , size.x, 39 );
}

void COutputCanvas::Clear()
{
	m_textCtrl->Clear();
}

<commit_msg>added wxTE_RICH2 style to the output window's text control, so that it doesn't show all the text being added, line by line, in Windows.<commit_after>// OutputCanvas.cpp

#include "stdafx.h"
#include "OutputCanvas.h"
#include "Program.h"
#include "NCCode.h"
#include "PythonStuff.h"
#include <wx/file.h>

BEGIN_EVENT_TABLE(COutputTextCtrl, wxTextCtrl)
    EVT_MOUSE_EVENTS(COutputTextCtrl::OnMouse)
END_EVENT_TABLE()

void COutputTextCtrl::OnMouse( wxMouseEvent& event )
{
	if(event.LeftUp())
	{
		wxTextPos pos = GetInsertionPoint();
		if(theApp.m_program && theApp.m_program->m_nc_code)
		{
			theApp.m_program->m_nc_code->HighlightBlock(pos);
			heeksCAD->Repaint();
		}
	}

	event.Skip();
}

BEGIN_EVENT_TABLE(COutputCanvas, wxScrolledWindow)
    EVT_SIZE(COutputCanvas::OnSize)
END_EVENT_TABLE()

static void OnOpen(wxCommandEvent& event)
{
	wxString ext_str(_T("*.*")); // to do, use the machine's NC extension
	wxString wildcard_string = wxString(_("NC files")) + _T(" |") + ext_str;
    wxFileDialog dialog(theApp.m_output_canvas, _("Open NC file"), wxEmptyString, wxEmptyString, wildcard_string);
    dialog.CentreOnParent();

    if (dialog.ShowModal() == wxID_OK)
    {
		HeeksPyBackplot(dialog.GetPath().c_str());
	}
}

static void OnSave(wxCommandEvent& event)
{
	wxString ext_str(_T("*.tap")); // to do, use the machine's NC extension
	wxString wildcard_string = wxString(_("NC files")) + _T(" |") + ext_str;
	wxFileDialog fd(theApp.m_output_canvas, _("Save NC file"), wxEmptyString, wxEmptyString, wildcard_string, wxSAVE|wxOVERWRITE_PROMPT);
	fd.SetFilterIndex(1);
	if (fd.ShowModal() == wxID_OK)
	{
		wxString nc_file_str = fd.GetPath().c_str();
		wxFile ofs(nc_file_str.c_str(), wxFile::write);
		if(!ofs.IsOpened())
		{
			wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + nc_file_str);
			return;
		}

		ofs.Write(theApp.m_output_canvas->m_textCtrl->GetValue());
		HeeksPyBackplot(nc_file_str);
	}
}

COutputCanvas::COutputCanvas(wxWindow* parent)
        : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize,
                           wxHSCROLL | wxVSCROLL | wxNO_FULL_REPAINT_ON_RESIZE)
{
	m_textCtrl = new COutputTextCtrl( this, 100, _T(""),	wxPoint(180,170), wxSize(200,70), wxTE_MULTILINE | wxTE_DONTWRAP | wxTE_RICH | wxTE_RICH2);

	// make a tool bar
	m_toolBar = new wxToolBar(this, -1, wxDefaultPosition, wxDefaultSize, wxTB_NODIVIDER | wxTB_FLAT);
	m_toolBar->SetToolBitmapSize(wxSize(32, 32));

	// add toolbar buttons
	heeksCAD->AddToolBarButton(m_toolBar, _T("Open"), wxBitmap(theApp.GetDllFolder() + _T("/bitmaps/open.png"), wxBITMAP_TYPE_PNG), _T("Open an NC file"), OnOpen);
	heeksCAD->AddToolBarButton(m_toolBar, _T("Save"), wxBitmap(theApp.GetDllFolder() + _T("/bitmaps/save.png"), wxBITMAP_TYPE_PNG), _T("Save the NC file"), OnSave);

	m_toolBar->Realize();

	Resize();
}

void COutputCanvas::OnSize(wxSizeEvent& event)
{
    Resize();

    event.Skip();
}

void COutputCanvas::Resize()
{
	wxSize size = GetClientSize();
	wxSize toolbar_size = m_toolBar->GetClientSize();
	m_textCtrl->SetSize(0, 0, size.x, size.y - 39 );
	m_toolBar->SetSize(0, size.y - 39 , size.x, 39 );
}

void COutputCanvas::Clear()
{
	m_textCtrl->Clear();
}

<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

#include "condor_common.h"
#include "dap_constants.h"
#include "dap_utility.h"
#include "dap_error.h"
#include "dap_logger.h"
#include <unistd.h>

/* ============================================================================
 * Transfer a file from local disk to local disk
 * ==========================================================================*/
int transfer_from_file_to_file(char *src_file, char *dest_file)
{
    int in_fd, out_fd;
    char *buf;
    long src_filesize, dest_filesize;
    int bytes_read, bytes_written;
    struct stat src_filestat, dest_filestat;

    //start transfer
    buf = (char*)malloc(sizeof(char) * BUF_SIZE);

    //get the src filesize info
    if (!lstat(src_file, &src_filestat))  //if file exists
      src_filesize = src_filestat.st_size;

    //open the input file for reading
    in_fd = safe_open_wrapper(src_file, O_RDONLY);
    if (in_fd < 0){
      fprintf(stdout,"Error in opening file : %s\n",src_file);
      free(buf);
      return DAP_ERROR;
    }

    //get dest directory name
    char tmpstr[MAXSTR], dir[MAXSTR], dest_fname[MAXSTR];
    char *t = NULL, *p = NULL;

    strcpy(tmpstr, dest_file);
    strcpy(dir, "");

    t = strtok(tmpstr,"/");
    while(1){
      if (t == NULL) break;
      if (p!= NULL) strcat(strcat(dir, "/"), p);
      if ((p = strtok(NULL,"/")) != NULL){
	strcat(strcat(dir, "/"), t);   //get file name
      }
      else {
	strcpy(dest_fname, t);
	break;
      }
      t = strtok(NULL,"/");
    }

    if (t == NULL){
      if (p != NULL)
	strcpy(dest_fname, p);
      else
	strcpy(dest_fname, "");
    }

    if (!strcmp(dir, ""))
      strcpy (dir,"/");

    //check if dest directory exists, if not create
    struct stat dest_dirstat;
    if (lstat(dir, &dest_dirstat)){ //if dest dir does not exist
      char command[MAXSTR];

      snprintf(command, MAXSTR, "mkdir -p %s", dir);
      if (system(command) == -1){
	fprintf(stdout,"Error in creating directory : %s\n",dir);
	return DAP_ERROR;
      }
    }

    //open the output file for writing
    out_fd = safe_open_wrapper(dest_file, O_CREAT | O_RDWR, 00777);
    if (out_fd < 0){
      fprintf(stdout,"Error in opening file : %s\n",dest_file);
      free(buf);
      close(in_fd);
      return DAP_ERROR;
    }

    //transfer file
    while ( (bytes_read = read(in_fd, buf, BUF_SIZE)) > 0){
      bytes_written = write(out_fd, buf, bytes_read);

      if (bytes_written != bytes_read){
	fprintf(stdout,"Error! read = %d, written = %d\n",bytes_read, bytes_written);
	free(buf);
	close(in_fd);
	close(out_fd);
	return DAP_ERROR;
      }
    }

    //get the dest filesize info
    if (!lstat(dest_file, &dest_filestat))  //if file exists
      dest_filesize = dest_filestat.st_size;

    if (src_filesize != dest_filesize){
      printf("src and dest file sizes do not match!!\n");
      free(buf);
      close(in_fd);
      close(out_fd);
      return DAP_ERROR;
    }

    //otherwise file is transfered succesfully..
    printf("SUCCESS!\n");
    free(buf);
    close(in_fd);
    close(out_fd);
    return DAP_SUCCESS;

}

int main(int argc, char *argv[])
{

  char src_protocol[MAXSTR], src_host[MAXSTR], src_file[MAXSTR];
  char dest_protocol[MAXSTR], dest_host[MAXSTR], dest_file[MAXSTR];
  char src_url[MAXSTR], dest_url[MAXSTR];
  int status = 0;

  if (argc < 3){
    fprintf(stderr, "==============================================================\n");
    fprintf(stderr, "USAGE: %s <src_url> <dest_url>\n", argv[0]);
    fprintf(stderr, "==============================================================\n");
    exit(-1);
  }

  strncpy(src_url, argv[1], MAXSTR);
  strncpy(dest_url, argv[2], MAXSTR);

  parse_url(src_url, src_protocol, src_host, src_file);
  parse_url(dest_url, dest_protocol, dest_host, dest_file);

  fprintf(stdout, "Transfering file:%s from host %s to file:%s on host %s..\n",
	  src_file, src_host, dest_file, dest_host);

  if ( !strcmp(src_protocol, "file") && !strcmp(dest_protocol, "file")){
    status = transfer_from_file_to_file(src_file, dest_file);
  }

  return status;

}

<commit_msg>Coverity CID 1722<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

#include "condor_common.h"
#include "dap_constants.h"
#include "dap_utility.h"
#include "dap_error.h"
#include "dap_logger.h"
#include <unistd.h>

/* ============================================================================
 * Transfer a file from local disk to local disk
 * ==========================================================================*/
int transfer_from_file_to_file(char *src_file, char *dest_file)
{
    int in_fd, out_fd;
    char *buf;
    long src_filesize, dest_filesize;
    int bytes_read, bytes_written;
    struct stat src_filestat, dest_filestat;

    //start transfer
    buf = (char*)malloc(sizeof(char) * BUF_SIZE);

    //get the src filesize info
    if (!lstat(src_file, &src_filestat))  //if file exists
      src_filesize = src_filestat.st_size;

    //open the input file for reading
    in_fd = safe_open_wrapper(src_file, O_RDONLY);
    if (in_fd < 0){
      fprintf(stdout,"Error in opening file : %s\n",src_file);
      free(buf);
      return DAP_ERROR;
    }

    //get dest directory name
    char tmpstr[MAXSTR], dir[MAXSTR], dest_fname[MAXSTR];
    char *t = NULL, *p = NULL;

    strcpy(tmpstr, dest_file);
    strcpy(dir, "");

    t = strtok(tmpstr,"/");
    while(1){
      if (t == NULL) break;
      if (p!= NULL) strcat(strcat(dir, "/"), p);
      if ((p = strtok(NULL,"/")) != NULL){
	strcat(strcat(dir, "/"), t);   //get file name
      }
      else {
	strcpy(dest_fname, t);
	break;
      }
      t = strtok(NULL,"/");
    }

    if (t == NULL){
      if (p != NULL)
	strcpy(dest_fname, p);
      else
	strcpy(dest_fname, "");
    }

    if (!strcmp(dir, ""))
      strcpy (dir,"/");

    //check if dest directory exists, if not create
    struct stat dest_dirstat;
    if (lstat(dir, &dest_dirstat)){ //if dest dir does not exist
      char command[MAXSTR];

      snprintf(command, MAXSTR, "mkdir -p %s", dir);
      if (system(command) == -1){
	fprintf(stdout,"Error in creating directory : %s\n",dir);
	return DAP_ERROR;
      }
    }

    //open the output file for writing
    out_fd = safe_open_wrapper(dest_file, O_CREAT | O_RDWR, 00777);
    if (out_fd < 0){
      fprintf(stdout,"Error in opening file : %s\n",dest_file);
      free(buf);
      close(in_fd);
      return DAP_ERROR;
    }

    //transfer file
    while ( (bytes_read = read(in_fd, buf, BUF_SIZE)) > 0){
      bytes_written = write(out_fd, buf, bytes_read);

      if (bytes_written != bytes_read){
	fprintf(stdout,"Error! read = %d, written = %d\n",bytes_read, bytes_written);
	free(buf);
	close(in_fd);
	close(out_fd);
	return DAP_ERROR;
      }
    }

    //get the dest filesize info
    if (!lstat(dest_file, &dest_filestat))  //if file exists
      dest_filesize = dest_filestat.st_size;

    if (src_filesize != dest_filesize){
      printf("src and dest file sizes do not match!!\n");
      free(buf);
      close(in_fd);
      close(out_fd);
      return DAP_ERROR;
    }

    //otherwise file is transfered succesfully..
    printf("SUCCESS!\n");
    free(buf);
    close(in_fd);
    close(out_fd);
    return DAP_SUCCESS;

}

int main(int argc, char *argv[])
{

  char src_protocol[MAXSTR], src_host[MAXSTR], src_file[MAXSTR];
  char dest_protocol[MAXSTR], dest_host[MAXSTR], dest_file[MAXSTR];
  char src_url[MAXSTR], dest_url[MAXSTR];
  int status = 0;

  if (argc < 3){
    fprintf(stderr, "==============================================================\n");
    fprintf(stderr, "USAGE: %s <src_url> <dest_url>\n", argv[0]);
    fprintf(stderr, "==============================================================\n");
    exit(-1);
  }

  strncpy(src_url, argv[1], MAXSTR-1);
  strncpy(dest_url, argv[2], MAXSTR-1);

  parse_url(src_url, src_protocol, src_host, src_file);
  parse_url(dest_url, dest_protocol, dest_host, dest_file);

  fprintf(stdout, "Transfering file:%s from host %s to file:%s on host %s..\n",
	  src_file, src_host, dest_file, dest_host);

  if ( !strcmp(src_protocol, "file") && !strcmp(dest_protocol, "file")){
    status = transfer_from_file_to_file(src_file, dest_file);
  }

  return status;

}

<|endoftext|>


<commit_before>#include "saxendanalyzer.h"
#include "streamindexer.h"
#include "inputstreamreader.h"
#include "indexwriter.h"
#include <libxml/parser.h>
using namespace jstreams;
using namespace std;

class SaxEndAnalyzer::Private {
public:
    xmlParserCtxtPtr ctxt;
    xmlSAXHandler handler;
    Indexable* idx;
    bool error;
    bool stop;
    int32_t chars;

    static void charactersSAXFunc(void* ctx, const xmlChar * ch, int len);
    static void errorSAXFunc(void* ctx, const char * msg, ...);

    Private() {
        ctxt = 0;
        memset(&handler, 0, sizeof(xmlSAXHandler));
        handler.characters = charactersSAXFunc;
        handler.error = errorSAXFunc;
    }
    ~Private() {
        reset();
    }
    void reset() {
        if (ctxt) {
            xmlFreeParserCtxt(ctxt);
            ctxt = 0;
        }
        error = false;
        stop = false;
        chars = 0;
    }
    void init(Indexable*i, const char* data, int32_t len) {
        reset();
        int initlen = (1024 > len) ?len :1024;
        idx = i;
        const char* name = 0;
        if (i) name = i->getName().c_str();
        xmlKeepBlanksDefault(0);
        ctxt = xmlCreatePushParserCtxt(&handler, this, data, initlen, name);
        if (ctxt == 0) {
            error = true;
            stop = true;
        } else {
            ctxt->validate = 1;
            // we need to call push once to do validation
            push(data+initlen, len-initlen);
        }
    }
    void push(const char* data, int32_t len) {
        xmlParseChunk(ctxt, data, len, 0);
    }
    void finish() {
        xmlParseChunk(ctxt, 0, 0, 1);
    }
};
void
SaxEndAnalyzer::Private::charactersSAXFunc(void* ctx, const xmlChar * ch,
        int len) {
    Private* p = (Private*)ctx;

    // skip whitespace
    const char* end = (const char*)ch+len;
    const char* c = (const char*)ch;
    while (c < end && isspace(*c)) c++;
    if (c == end) return;

    if (p->idx) {
        p->idx->addText((const char*)c, end-c);
    }
    p->chars += end-c;
    if (p->chars > 1000000) {
        p->stop = true;
    }
}
void
SaxEndAnalyzer::Private::errorSAXFunc(void* ctx, const char* msg, ...) {
    Private* p = (Private*)ctx;
    p->stop = p->error = true;
}
SaxEndAnalyzer::SaxEndAnalyzer() {
    p = new Private();
}
SaxEndAnalyzer::~SaxEndAnalyzer() {
    delete p;
}

bool
SaxEndAnalyzer::checkHeader(const char* header, int32_t headersize) const {
    p->init(0, header, headersize);
    return !p->error;
}

char
SaxEndAnalyzer::analyze(std::string filename, jstreams::InputStream *in,
        int depth, StreamIndexer *indexer, Indexable* i) {

    const char* b;
    int32_t nread = in->read(b, 4, 0);
    if (nread >= 4) {
        p->init(i, b, nread);
        nread = in->read(b, 1, 0);
    }
    while (nread > 0 && !p->stop) {
        p->push(b, nread);
        nread = in->read(b, 1, 0);
    }
    p->finish();
    if (p->ctxt->encoding) {
        i->setField("encoding", (const char*)p->ctxt->encoding);
    }
    i->setMimeType("text/xml");
    if (nread != Eof) {
        error = in->getError();
        return -1;
    }
    return 0;
}
<commit_msg>debug output on closing clucene index<commit_after>#include "saxendanalyzer.h"
#include "streamindexer.h"
#include "inputstreamreader.h"
#include "indexwriter.h"
#include <libxml/parser.h>
using namespace jstreams;
using namespace std;

class SaxEndAnalyzer::Private {
public:
    xmlParserCtxtPtr ctxt;
    xmlSAXHandler handler;
    Indexable* idx;
    bool error;
    bool stop;
    string rootelement;
    int32_t chars;

    static void charactersSAXFunc(void* ctx, const xmlChar * ch, int len);
    static void errorSAXFunc(void* ctx, const char * msg, ...);
    static void startElementSAXFunc(void * ctx, const xmlChar * name,
        const xmlChar ** atts);
    static void startElementNsSAX2Func(void * ctx,
        const xmlChar* localname, const xmlChar* prefix, const xmlChar* URI,
        int nb_namespaces, const xmlChar ** namespaces, int nb_attributes,
        int nb_defaulted, const xmlChar ** attributes);

    Private() {
        ctxt = 0;
        memset(&handler, 0, sizeof(xmlSAXHandler));
        handler.characters = charactersSAXFunc;
        handler.error = errorSAXFunc;
        handler.startElement = startElementSAXFunc;
        handler.startElementNs = startElementNsSAX2Func;
    }
    ~Private() {
        reset();
    }
    void reset() {
        if (ctxt) {
            xmlFreeParserCtxt(ctxt);
            ctxt = 0;
        }
        error = false;
        stop = false;
        chars = 0;
        rootelement = "";
    }
    void init(Indexable*i, const char* data, int32_t len) {
        reset();
        int initlen = (1024 > len) ?len :1024;
        idx = i;
        const char* name = 0;
        if (i) name = i->getName().c_str();
        xmlKeepBlanksDefault(0);
        ctxt = xmlCreatePushParserCtxt(&handler, this, data, initlen, name);
        if (ctxt == 0) {
            error = true;
            stop = true;
        } else {
//            ctxt->sax2 = 1;
            // we need to call push once to do validation
            push(data+initlen, len-initlen);
        }
    }
    void push(const char* data, int32_t len) {
        xmlParseChunk(ctxt, data, len, 0);
    }
    void finish() {
        xmlParseChunk(ctxt, 0, 0, 1);
    }
};
void
SaxEndAnalyzer::Private::charactersSAXFunc(void* ctx, const xmlChar * ch,
        int len) {
    Private* p = (Private*)ctx;

    // skip whitespace
    const char* end = (const char*)ch+len;
    const char* c = (const char*)ch;
    while (c < end && isspace(*c)) c++;
    if (c == end) return;

    if (p->idx) {
        p->idx->addText((const char*)c, end-c);
    }
    p->chars += end-c;
    if (p->chars > 1000000) {
        p->stop = true;
    }
}
void
SaxEndAnalyzer::Private::errorSAXFunc(void* ctx, const char* msg, ...) {
    Private* p = (Private*)ctx;
    p->stop = p->error = true;
}
void
SaxEndAnalyzer::Private::startElementNsSAX2Func(void * ctx,
        const xmlChar* localname, const xmlChar* prefix, const xmlChar* URI,
        int nb_namespaces, const xmlChar ** namespaces, int nb_attributes,
        int nb_defaulted, const xmlChar ** attributes) {
    Private* p = (Private*)ctx;
    if(URI && p->rootelement.size() == 0) {
        p->rootelement = (const char*)URI;
    }
}
void
SaxEndAnalyzer::Private::startElementSAXFunc(void* ctx, const xmlChar* name,
        const xmlChar** atts) {
    Private* p = (Private*)ctx;
    if(name && p->rootelement.size() == 0) {
        p->rootelement = (const char*)name;
    }
}
SaxEndAnalyzer::SaxEndAnalyzer() {
    p = new Private();
}
SaxEndAnalyzer::~SaxEndAnalyzer() {
    delete p;
}

bool
SaxEndAnalyzer::checkHeader(const char* header, int32_t headersize) const {
    p->init(0, header, headersize);
    return !p->error;
}

char
SaxEndAnalyzer::analyze(std::string filename, jstreams::InputStream *in,
        int depth, StreamIndexer *indexer, Indexable* i) {

    const char* b;
    int32_t nread = in->read(b, 4, 0);
    if (nread >= 4) {
        p->init(i, b, nread);
        nread = in->read(b, 1, 0);
    }
    while (nread > 0 && !p->stop) {
        p->push(b, nread);
        nread = in->read(b, 1, 0);
    }
    p->finish();
    if (p->ctxt->encoding) {
        i->setField("encoding", (const char*)p->ctxt->encoding);
    }
    i->setMimeType("text/xml");
    i->setField("root", p->rootelement);
    if (nread != Eof) {
        error = in->getError();
        return -1;
    }
    return 0;
}
<|endoftext|>


<commit_before>/*
	news.cpp
*/

#include "../IRCBot/include/command-interface.hpp"
#include "../IRCBot/include/bot.hpp"
#include "../IRCBot/include/packet.hpp"

#include <chrono>
#include <stdexcept>
#include <random>
#include <unordered_map>

#include "./include/json.hpp"
#include "./include/http.hpp"
#include "./include/url-shortener.hpp"

#include "./include/environment.hpp"

class NewsCommand : protected IRC::CommandInterface {

	/* to keep track of articles and cache link shortening... */
	struct Article {
		std::string title, desc, link, string_form;

		Article(const std::string& t, const std::string& d, const std::string& l)
			: title(t), desc(d), link(l) {}

		std::string to_string(void) {
			if (string_form.empty()) {
				std::string url = ShortenURL::get_shortened_url(link);
				string_form = title + " -> " + (url.empty() ? link : url);
			}
			return string_form;
		}
	};

	std::string api_key, category, newsapi_url;

	std::vector<std::string> sources; /* tracks name of sources. API will handle the URLs. */

	/* tracks if user has already been sent some article. */
	std::unordered_map<std::string, std::vector<bool>> news_track;

	const size_t MAX_NEWS;
	std::vector<Article> articles;

	const std::chrono::hours MAX_NO_UPDATE_TIME;
	std::chrono::system_clock::time_point last_time; /* last time news was updated... */

	void get_sources(void);
	void update_nicks(const std::string&, const std::string&);
	void get_news(void);
	void get_news_from_src(const std::string& source);

  public:

	NewsCommand() : IRC::CommandInterface("@news", "feeds you a news article. Powered by NewsApi.org"), MAX_NEWS(20), MAX_NO_UPDATE_TIME(std::chrono::hours(24)) {
		try {
			newsapi_url	= ENVIRONMENT["newsapi"]["newsapi_url"];
			category    = ENVIRONMENT["newsapi"]["category"];
			api_key	    = ENVIRONMENT["newsapi"]["api_key"];
			get_sources();
			last_time = std::chrono::system_clock::now();
		} catch (std::exception& e) {
			std::cerr << "Something wrong in NewsCommand::NewsCommand(): " << e.what() << '\n';
			newsapi_url = category = api_key = "";
		}
	}

	bool triggered(const IRC::Packet& p) {

		/* update nicks */
		if (p.type == IRC::Packet::PacketType::NICK)
			update_nicks(p.sender, p.content);

		/* update news sources */
		auto elapsed = std::chrono::system_clock::now() - last_time;
		if (articles.empty() || elapsed >= MAX_NO_UPDATE_TIME)
			get_news();
		last_time = std::chrono::system_clock::now();

		return IRC::CommandInterface::triggered(p);
	}

	void run(const IRC::Packet& p) {

		/*
			find news article that caller hasn't seen yet
			and return that
		*/
		if (news_track.find(p.sender) == news_track.end())
			news_track[p.sender] = std::vector<bool>(articles.size(), false);

		if (articles.empty() && news_track[p.sender].back()) {
			p.owner->privmsg(p.sender,"No new news at the moment.");
			return;
		}

		p.owner->privmsg(p.sender,"One sec...");

		size_t i = 0;
		while(i < articles.size() && news_track[p.sender][i])
			++i;

		news_track[p.sender][i] = true;
		p.owner->privmsg(p.sender, articles.at(i).to_string());
	}
};

void NewsCommand::get_sources(void) {

	try {
		std::string call = MyHTTP::get(newsapi_url + "/sources?language=en&category=" + category);
		auto json_obj = nlohmann::json::parse(call);

		/* check if API fail. */
		if (json_obj["status"] != "ok") {
		 	sources.clear();
			return;
		}

		for (auto& s : json_obj["sources"])
			sources.push_back(s["id"].get<std::string>());
	} catch (std::exception& e) {
		std::cerr << "Error in NewsCommand::get_sources(): " << e.what() << '\n';
		return;
	}
}

void NewsCommand::update_nicks(const std::string& old, const std::string& _new) {
	auto it = news_track.find(old);
	if (it != news_track.end()) {
		news_track[_new] = news_track[old];
		news_track.erase(it);
	}
}

template<typename T>
static void stuffle(std::vector<T>& arr);

void NewsCommand::get_news(void) {
	if (api_key.empty()) return; /* no way to access news */

	articles.clear(); /* flush any old articles out... */
	news_track.clear(); /* all new news so refresh news_track (all articles marked unread) */

	for(auto& source : sources) {
		get_news_from_src(source);
		if (articles.size() >= MAX_NEWS)
			break;
	}

	stuffle(articles);
}

template<typename T>
static void stuffle(std::vector<T>& arr) {
	static std::minstd_rand gen(std::chrono::system_clock::now().time_since_epoch().count());
	for (size_t i = 0; i < arr.size(); ++i)
		std::swap(arr[i], arr[gen() % arr.size()]);
}

void NewsCommand::get_news_from_src(const std::string& source) {
	try {
		std::string call = MyHTTP::get(newsapi_url + "/articles?sortBy=latest&source=" + source + "&apiKey=" + api_key);
		auto json_obj = nlohmann::json::parse(call);

		if (json_obj["status"] != "ok")
			return;

		for (auto& article : json_obj["articles"])
			articles.push_back(Article(article["title"].get<std::string>(),
			                           article["description"].get<std::string>(),
									   article["url"].get<std::string>()));

	} catch (std::exception& e) {
		std::cerr << "Error in NewsCommand::get_news_from_src(...): " << e.what() << '\n';
	}
}

extern "C" IRC::CommandInterface* maker(IRC::Bot* b = nullptr) {
	return (IRC::CommandInterface*)(new NewsCommand);
}
<commit_msg>shuffle up sources<commit_after>/*
	news.cpp
*/

#include "../IRCBot/include/command-interface.hpp"
#include "../IRCBot/include/bot.hpp"
#include "../IRCBot/include/packet.hpp"

#include <chrono>
#include <stdexcept>
#include <random>
#include <unordered_map>

#include "./include/json.hpp"
#include "./include/http.hpp"
#include "./include/url-shortener.hpp"

#include "./include/environment.hpp"

class NewsCommand : protected IRC::CommandInterface {

	/* to keep track of articles and cache link shortening... */
	struct Article {
		std::string title, desc, link, string_form;

		Article(const std::string& t, const std::string& d, const std::string& l)
			: title(t), desc(d), link(l) {}

		std::string to_string(void) {
			if (string_form.empty()) {
				std::string url = ShortenURL::get_shortened_url(link);
				string_form = title + " -> " + (url.empty() ? link : url);
			}
			return string_form;
		}
	};

	std::string api_key, category, newsapi_url;

	std::vector<std::string> sources; /* tracks name of sources. API will handle the URLs. */

	/* tracks if user has already been sent some article. */
	std::unordered_map<std::string, std::vector<bool>> news_track;

	const size_t MAX_NEWS;
	std::vector<Article> articles;

	const std::chrono::hours MAX_NO_UPDATE_TIME;
	std::chrono::system_clock::time_point last_time; /* last time news was updated... */

	void get_sources(void);
	void update_nicks(const std::string&, const std::string&);
	void get_news(void);
	void get_news_from_src(const std::string& source);

  public:

	NewsCommand() : IRC::CommandInterface("@news", "feeds you a news article. Powered by NewsApi.org"), MAX_NEWS(20), MAX_NO_UPDATE_TIME(std::chrono::hours(24)) {
		try {
			newsapi_url	= ENVIRONMENT["newsapi"]["newsapi_url"];
			category    = ENVIRONMENT["newsapi"]["category"];
			api_key	    = ENVIRONMENT["newsapi"]["api_key"];
			get_sources();
			last_time = std::chrono::system_clock::now();
		} catch (std::exception& e) {
			std::cerr << "Something wrong in NewsCommand::NewsCommand(): " << e.what() << '\n';
			newsapi_url = category = api_key = "";
		}
	}

	bool triggered(const IRC::Packet& p) {

		/* update nicks */
		if (p.type == IRC::Packet::PacketType::NICK)
			update_nicks(p.sender, p.content);

		/* update news sources */
		auto elapsed = std::chrono::system_clock::now() - last_time;
		if (articles.empty() || elapsed >= MAX_NO_UPDATE_TIME)
			get_news();
		last_time = std::chrono::system_clock::now();

		return IRC::CommandInterface::triggered(p);
	}

	void run(const IRC::Packet& p) {

		/*
			find news article that caller hasn't seen yet
			and return that
		*/
		if (news_track.find(p.sender) == news_track.end())
			news_track[p.sender] = std::vector<bool>(articles.size(), false);

		if (articles.empty() && news_track[p.sender].back()) {
			p.owner->privmsg(p.sender,"No new news at the moment.");
			return;
		}

		p.owner->privmsg(p.sender,"One sec...");

		size_t i = 0;
		while(i < articles.size() && news_track[p.sender][i])
			++i;

		news_track[p.sender][i] = true;
		p.owner->privmsg(p.sender, articles.at(i).to_string());
	}
};

void NewsCommand::get_sources(void) {

	try {
		std::string call = MyHTTP::get(newsapi_url + "/sources?language=en&category=" + category);
		auto json_obj = nlohmann::json::parse(call);

		/* check if API fail. */
		if (json_obj["status"] != "ok") {
		 	sources.clear();
			return;
		}

		for (auto& s : json_obj["sources"])
			sources.push_back(s["id"].get<std::string>());
	} catch (std::exception& e) {
		std::cerr << "Error in NewsCommand::get_sources(): " << e.what() << '\n';
		return;
	}
}

void NewsCommand::update_nicks(const std::string& old, const std::string& _new) {
	auto it = news_track.find(old);
	if (it != news_track.end()) {
		news_track[_new] = news_track[old];
		news_track.erase(it);
	}
}

template<typename T>
static void stuffle(std::vector<T>& arr);

void NewsCommand::get_news(void) {
	if (api_key.empty()) return; /* no way to access news */

	articles.clear(); /* flush any old articles out... */
	news_track.clear(); /* all new news so refresh news_track (all articles marked unread) */

	stuffle(sources); /* switch up the source order each period... */
	for(auto& source : sources) {
		get_news_from_src(source);
		if (articles.size() >= MAX_NEWS)
			break;
	}

	stuffle(articles);
}

template<typename T>
static void stuffle(std::vector<T>& arr) {
	static std::minstd_rand gen(std::chrono::system_clock::now().time_since_epoch().count());
	for (size_t i = 0; i < arr.size(); ++i)
		std::swap(arr[i], arr[gen() % arr.size()]);
}

void NewsCommand::get_news_from_src(const std::string& source) {
	try {
		std::string call = MyHTTP::get(newsapi_url + "/articles?sortBy=latest&source=" + source + "&apiKey=" + api_key);
		auto json_obj = nlohmann::json::parse(call);

		if (json_obj["status"] != "ok")
			return;

		for (auto& article : json_obj["articles"])
			articles.push_back(Article(article["title"].get<std::string>(),
			                           article["description"].get<std::string>(),
									   article["url"].get<std::string>()));

	} catch (std::exception& e) {
		std::cerr << "Error in NewsCommand::get_news_from_src(...): " << e.what() << '\n';
	}
}

extern "C" IRC::CommandInterface* maker(IRC::Bot* b = nullptr) {
	return (IRC::CommandInterface*)(new NewsCommand);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ChartController_TextEdit.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 00:32:57 $
 *
 *  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
 *
 ************************************************************************/
#include "ChartController.hxx"

#include "DrawViewWrapper.hxx"
#include "ChartWindow.hxx"
#include "TitleHelper.hxx"
#include "chartview/ObjectIdentifier.hxx"
#include "macros.hxx"

#include <svx/svdotext.hxx>

// header for class SvxCharacterMap
#ifndef _SVX_CHARMAP_HXX
#include <svx/charmap.hxx>
#endif
// header for define RET_OK
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
// header for class SdrOutliner
#ifndef _SVDOUTL_HXX
#include <svx/svdoutl.hxx>
#endif

#ifndef _SVX_DIALOG_HXX
#include <svx/svxdlg.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
//using namespace ::com::sun::star::chart2;

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

void SAL_CALL ChartController::executeDispatch_EditText()
{
    this->StartTextEdit();
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

void ChartController::StartTextEdit()
{
    //the first marked object will be edited

    SdrObject* pTextObj = m_pDrawViewWrapper->getTextEditObject();
    if(!pTextObj)
        return;

    SdrOutliner* pOutliner = m_pDrawViewWrapper->getOutliner();
    //pOutliner->SetRefDevice(m_pChartWindow);
    //pOutliner->SetStyleSheetPool((SfxStyleSheetPool*)pStyleSheetPool);
    //pOutliner->SetDefaultLanguage( eLang );
    //pOutliner->SetHyphenator( xHyphenator );
    BOOL bEdit = m_pDrawViewWrapper->BegTextEdit( pTextObj
                    , m_pDrawViewWrapper->GetPageView()
                    , m_pChartWindow
                    , FALSE //bIsNewObj
                    , pOutliner
                    , NULL //pOutlinerView
                    , TRUE //bDontDeleteOutliner
                    , TRUE //bOnlyOneView
                    );
    if(bEdit)
    {
        // set undo manager at topmost shell ( SdDrawTextObjectBar )
        /*
        if( pViewSh )
            pViewSh->GetViewFrame()->GetDispatcher()->GetShell( 0 )->
                SetUndoManager(&pOutliner->GetUndoManager());
        */
        m_pDrawViewWrapper->SetEditMode();

        //we invalidate the outliner region because the outliner has some
        //paint problems (some characters are painted twice a little bit shifted)
        m_pChartWindow->Invalidate( m_pDrawViewWrapper->GetMarkedObjBoundRect() );
    }
}

bool ChartController::EndTextEdit()
{
    m_pDrawViewWrapper->EndTextEdit();
    SdrObject* pTextObject = m_pDrawViewWrapper->getTextEditObject();
    if(!pTextObject)
        return false;

    SdrOutliner* pOutliner = m_pDrawViewWrapper->getOutliner();
    OutlinerParaObject* pParaObj = pTextObject->GetOutlinerParaObject();
    if( pParaObj && pOutliner )
    {
        pOutliner->SetText( *pParaObj );

        String aString = pOutliner->GetText(
                            pOutliner->GetParagraph( 0 ),
                            pOutliner->GetParagraphCount() );
        uno::Reference< beans::XPropertySet > xPropSet =
            ObjectIdentifier::getObjectPropertySet( m_aSelectedObjectCID, getModel() );

        //Paragraph* pPara =
        TitleHelper::setCompleteString( aString, uno::Reference<
            ::com::sun::star::chart2::XTitle >::query( xPropSet ), m_xCC );
        try
        {
            //need to rebuild to react on changed size of title
            impl_rebuildView();
        }
        catch( uno::RuntimeException& e)
        {
            ASSERT_EXCEPTION( e );
        }
    }
    return true;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

void SAL_CALL ChartController::executeDispatch_InsertSpecialCharacter()
{
    SvxAbstractDialogFactory * pFact = SvxAbstractDialogFactory::Create();
    DBG_ASSERT( pFact, "No dialog factory" );
    AbstractSvxCharacterMap * pDlg = pFact->CreateSvxCharacterMap( NULL,  ResId( RID_SVXDLG_CHARMAP ), FALSE );
    DBG_ASSERT( pDlg, "Couldn't create SvxCharacterMap dialog" );

    //set fixed current font
    pDlg->SetFont( m_pDrawViewWrapper->getOutliner()->GetRefDevice()->GetFont() );
    pDlg->DisableFontSelection(); //maybe not necessary in future

    if( pDlg->Execute() == RET_OK )
    {
        String aString( pDlg->GetCharacters() );

        OutlinerView* pOutlinerView = m_pDrawViewWrapper->GetTextEditOutlinerView();
        SdrOutliner*  pOutliner = m_pDrawViewWrapper->getOutliner();

        if(!pOutliner || !pOutlinerView)
            return;

        // insert string to outliner

        // prevent flicker
        pOutlinerView->HideCursor();
        pOutliner->SetUpdateMode(FALSE);

        // delete current selection by inserting empty String, so current
        // attributes become unique (sel. has to be erased anyway)
        pOutlinerView->InsertText(String());

        //SfxUndoManager& rUndoMgr =  pOutliner->GetUndoManager();
        //rUndoMgr.EnterListAction( String( SchResId( STR_UNDO_INSERT_SPECCHAR )), String( SchResId( STR_UNDO_INSERT_SPECCHAR )));
        pOutlinerView->InsertText(aString, TRUE);

        ESelection aSel = pOutlinerView->GetSelection();
        aSel.nStartPara = aSel.nEndPara;
        aSel.nStartPos = aSel.nEndPos;
        pOutlinerView->SetSelection(aSel);

        //rUndoMgr.LeaveListAction();

        // show changes
        pOutliner->SetUpdateMode(TRUE);
        pOutlinerView->ShowCursor();
    }

    delete pDlg;
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.80); FILE MERGED 2006/09/01 17:18:39 kaib 1.7.80.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ChartController_TextEdit.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:05:32 $
 *
 *  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_chart2.hxx"
#include "ChartController.hxx"

#include "DrawViewWrapper.hxx"
#include "ChartWindow.hxx"
#include "TitleHelper.hxx"
#include "chartview/ObjectIdentifier.hxx"
#include "macros.hxx"

#include <svx/svdotext.hxx>

// header for class SvxCharacterMap
#ifndef _SVX_CHARMAP_HXX
#include <svx/charmap.hxx>
#endif
// header for define RET_OK
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
// header for class SdrOutliner
#ifndef _SVDOUTL_HXX
#include <svx/svdoutl.hxx>
#endif

#ifndef _SVX_DIALOG_HXX
#include <svx/svxdlg.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
//using namespace ::com::sun::star::chart2;

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

void SAL_CALL ChartController::executeDispatch_EditText()
{
    this->StartTextEdit();
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

void ChartController::StartTextEdit()
{
    //the first marked object will be edited

    SdrObject* pTextObj = m_pDrawViewWrapper->getTextEditObject();
    if(!pTextObj)
        return;

    SdrOutliner* pOutliner = m_pDrawViewWrapper->getOutliner();
    //pOutliner->SetRefDevice(m_pChartWindow);
    //pOutliner->SetStyleSheetPool((SfxStyleSheetPool*)pStyleSheetPool);
    //pOutliner->SetDefaultLanguage( eLang );
    //pOutliner->SetHyphenator( xHyphenator );
    BOOL bEdit = m_pDrawViewWrapper->BegTextEdit( pTextObj
                    , m_pDrawViewWrapper->GetPageView()
                    , m_pChartWindow
                    , FALSE //bIsNewObj
                    , pOutliner
                    , NULL //pOutlinerView
                    , TRUE //bDontDeleteOutliner
                    , TRUE //bOnlyOneView
                    );
    if(bEdit)
    {
        // set undo manager at topmost shell ( SdDrawTextObjectBar )
        /*
        if( pViewSh )
            pViewSh->GetViewFrame()->GetDispatcher()->GetShell( 0 )->
                SetUndoManager(&pOutliner->GetUndoManager());
        */
        m_pDrawViewWrapper->SetEditMode();

        //we invalidate the outliner region because the outliner has some
        //paint problems (some characters are painted twice a little bit shifted)
        m_pChartWindow->Invalidate( m_pDrawViewWrapper->GetMarkedObjBoundRect() );
    }
}

bool ChartController::EndTextEdit()
{
    m_pDrawViewWrapper->EndTextEdit();
    SdrObject* pTextObject = m_pDrawViewWrapper->getTextEditObject();
    if(!pTextObject)
        return false;

    SdrOutliner* pOutliner = m_pDrawViewWrapper->getOutliner();
    OutlinerParaObject* pParaObj = pTextObject->GetOutlinerParaObject();
    if( pParaObj && pOutliner )
    {
        pOutliner->SetText( *pParaObj );

        String aString = pOutliner->GetText(
                            pOutliner->GetParagraph( 0 ),
                            pOutliner->GetParagraphCount() );
        uno::Reference< beans::XPropertySet > xPropSet =
            ObjectIdentifier::getObjectPropertySet( m_aSelectedObjectCID, getModel() );

        //Paragraph* pPara =
        TitleHelper::setCompleteString( aString, uno::Reference<
            ::com::sun::star::chart2::XTitle >::query( xPropSet ), m_xCC );
        try
        {
            //need to rebuild to react on changed size of title
            impl_rebuildView();
        }
        catch( uno::RuntimeException& e)
        {
            ASSERT_EXCEPTION( e );
        }
    }
    return true;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

void SAL_CALL ChartController::executeDispatch_InsertSpecialCharacter()
{
    SvxAbstractDialogFactory * pFact = SvxAbstractDialogFactory::Create();
    DBG_ASSERT( pFact, "No dialog factory" );
    AbstractSvxCharacterMap * pDlg = pFact->CreateSvxCharacterMap( NULL,  ResId( RID_SVXDLG_CHARMAP ), FALSE );
    DBG_ASSERT( pDlg, "Couldn't create SvxCharacterMap dialog" );

    //set fixed current font
    pDlg->SetFont( m_pDrawViewWrapper->getOutliner()->GetRefDevice()->GetFont() );
    pDlg->DisableFontSelection(); //maybe not necessary in future

    if( pDlg->Execute() == RET_OK )
    {
        String aString( pDlg->GetCharacters() );

        OutlinerView* pOutlinerView = m_pDrawViewWrapper->GetTextEditOutlinerView();
        SdrOutliner*  pOutliner = m_pDrawViewWrapper->getOutliner();

        if(!pOutliner || !pOutlinerView)
            return;

        // insert string to outliner

        // prevent flicker
        pOutlinerView->HideCursor();
        pOutliner->SetUpdateMode(FALSE);

        // delete current selection by inserting empty String, so current
        // attributes become unique (sel. has to be erased anyway)
        pOutlinerView->InsertText(String());

        //SfxUndoManager& rUndoMgr =  pOutliner->GetUndoManager();
        //rUndoMgr.EnterListAction( String( SchResId( STR_UNDO_INSERT_SPECCHAR )), String( SchResId( STR_UNDO_INSERT_SPECCHAR )));
        pOutlinerView->InsertText(aString, TRUE);

        ESelection aSel = pOutlinerView->GetSelection();
        aSel.nStartPara = aSel.nEndPara;
        aSel.nStartPos = aSel.nEndPos;
        pOutlinerView->SetSelection(aSel);

        //rUndoMgr.LeaveListAction();

        // show changes
        pOutliner->SetUpdateMode(TRUE);
        pOutlinerView->ShowCursor();
    }

    delete pDlg;
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>#pragma once
#include "util.cpp"
#include "photo_fits_schedule.cpp"
#include "possible_intervals.cpp"

bool try_photo(Input& input, Object& object, Collection& collection) {
	//is already done? You could have figured that out yourself, don't you?!
	if(input.objects[make_pair(object.lat, object.lon)].done) {
		return true;
	}
	//loop over satellites
	for(Satellite& satellite: input.satellites) {
		vector<pair<ll, ll>> intervals = possible_intervals(input, satellite, object);
		for(pair<ll, ll>& time_range: collection.time_ranges) {
			for(pair<ll, ll> interval: intervals) {
				for(ll time = max(interval.first, time_range.first); time < min(interval.second, time_range.second); time++) {
					if(photo_fits_schedule(input, satellite, object, time)) {
						input.objects[make_pair(object.lat, object.lon)].done = true;
						satellite.photos[time] = object;
						return true;
					}
				}
			}
		}
	}
	return false;
}

//start of the algorithm, call all subroutines
void schedule_photos(Input& input) {
    cerr << "Starting scheduling"
	vector<Collection> sorted_collections(input.c);
	for(int i = 0; i < input.c; i++) {
		sorted_collections[i] = input.collections[i];
	}
	sort(sorted_collections.begin(), sorted_collections.end(), [](const Collection& lhs, const Collection& rhs) {
   		return lhs.v/lhs.l > rhs.v/rhs.l;
	});

	//try them all
	for(Collection& collection: sorted_collections) {
        cerr << "Considering collection " << collection.id << "/" << input.c;
		bool ok = true;
		for(Object& object: collection.objects) {
			ok &= try_photo(input, object, collection);
		}
		input.collections[collection.id].done = ok;
		//todo remove photos if collection not finished
	}
}
<commit_msg>skip some time steps to make it faster<commit_after>#pragma once
#include "util.cpp"
#include "photo_fits_schedule.cpp"
#include "possible_intervals.cpp"

bool try_photo(Input& input, Object& object, Collection& collection) {
	//is already done? You could have figured that out yourself, don't you?!
	if(input.objects[make_pair(object.lat, object.lon)].done) {
		return true;
	}
	//loop over satellites
	for(Satellite& satellite: input.satellites) {
		vector<pair<ll, ll>> intervals = possible_intervals(input, satellite, object);
		for(pair<ll, ll>& time_range: collection.time_ranges) {
			for(pair<ll, ll> interval: intervals) {
				for(ll time = max(interval.first, time_range.first); time < min(interval.second, time_range.second); time+=1000) {
					if(photo_fits_schedule(input, satellite, object, time)) {
						input.objects[make_pair(object.lat, object.lon)].done = true;
						satellite.photos[time] = object;
						return true;
					}
				}
			}
		}
	}
	return false;
}

//start of the algorithm, call all subroutines
void schedule_photos(Input& input) {
    cerr << "Starting scheduling"
	vector<Collection> sorted_collections(input.c);
	for(int i = 0; i < input.c; i++) {
		sorted_collections[i] = input.collections[i];
	}
	sort(sorted_collections.begin(), sorted_collections.end(), [](const Collection& lhs, const Collection& rhs) {
   		return lhs.v/lhs.l > rhs.v/rhs.l;
	});

	//try them all
	for(Collection& collection: sorted_collections) {
        cerr << "Considering collection " << collection.id << "/" << input.c;
		bool ok = true;
		for(Object& object: collection.objects) {
			ok &= try_photo(input, object, collection);
		}
		input.collections[collection.id].done = ok;
		//todo remove photos if collection not finished
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: filecopy.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 00:53:16 $
 *
 *  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_tools.hxx"

#if defined WNT
#ifndef _SVWIN_H
#include <io.h>
#include <svwin.h>
#endif

#elif defined UNX
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>

#endif

#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include <stdio.h>

#ifndef _COMDEP_HXX
#include "comdep.hxx"
#endif

#ifndef _FSYS_HXX
#include "fsys.hxx"
#endif

#ifndef _STREAM_HXX
#include "stream.hxx"
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

using namespace ::osl;

/*************************************************************************
|*
|*    FileCopier::FileCopier()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 13.04.94
|*    Letzte Aenderung  MI 13.04.94
|*
*************************************************************************/

FileCopier::FileCopier() :

    nBytesTotal ( 0 ),
    nBytesCopied( 0 ),
    nBlockSize  ( 4096 ),
    pImp        ( new FileCopier_Impl )

{
}

// -----------------------------------------------------------------------

FileCopier::FileCopier( const DirEntry& rSource, const DirEntry& rTarget ) :

    aSource     ( rSource ),
    aTarget     ( rTarget ),
    nBytesTotal ( 0 ),
    nBytesCopied( 0 ),
    nBlockSize  ( 4096 ),
    pImp        ( new FileCopier_Impl )

{
}

// -----------------------------------------------------------------------

FileCopier::FileCopier( const FileCopier& rCopier ) :

    aSource         ( rCopier.aSource ),
    aTarget         ( rCopier.aTarget ),
    nBytesTotal     ( 0 ),
    nBytesCopied    ( 0 ),
    aProgressLink   ( rCopier.aProgressLink ),
    nBlockSize      ( 4096 ),
    pImp            ( new FileCopier_Impl )

{
}

/*************************************************************************
|*
|*    FileCopier::~FileCopier()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 13.04.94
|*    Letzte Aenderung  MI 13.04.94
|*
*************************************************************************/

FileCopier::~FileCopier()
{
    delete pImp;
}

/*************************************************************************
|*
|*    FileCopier::operator =()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 13.04.94
|*    Letzte Aenderung  MI 13.04.94
|*
*************************************************************************/

FileCopier& FileCopier::operator = ( const FileCopier &rCopier )
{
    aSource = rCopier.aSource;
    aTarget = rCopier.aTarget;
    nBytesTotal = rCopier.nBytesTotal;
    nBytesCopied = rCopier.nBytesCopied;
    nBytesCopied = rCopier.nBytesCopied;
    nBlockSize = rCopier.nBlockSize;
    aProgressLink = rCopier.aProgressLink;
    *pImp = *(rCopier.pImp);
    return *this;
}

/*************************************************************************
|*
|*    FileCopier::Progress()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 13.04.94
|*    Letzte Aenderung  MI 13.04.94
|*
*************************************************************************/

BOOL FileCopier::Progress()
{
    if ( !aProgressLink )
        return TRUE;
    else
    {
        if ( aProgressLink.Call( this ) )
            return TRUE;
        return ( 0 == Error( ERRCODE_ABORT, 0, 0 ) );
    }
}

//---------------------------------------------------------------------------

ErrCode FileCopier::Error( ErrCode eErr, const DirEntry* pSource, const DirEntry* pTarget )
{
    // kein Fehler oder kein ErrorHandler?
    if ( !eErr || !pImp->aErrorLink )
        // => Error beibehalten
        return eErr;

    // sonst gesetzten ErrorHandler fragen
    pImp->pErrSource = pSource;
    pImp->pErrTarget = pTarget;
    pImp->eErr = eErr;
    ErrCode eRet = (ErrCode) pImp->aErrorLink.Call( this );
    pImp->pErrSource = 0;
    pImp->pErrTarget = 0;
    return eRet;
}

//---------------------------------------------------------------------------

const DirEntry* FileCopier::GetErrorSource() const
{
    return pImp->pErrSource;
}

//---------------------------------------------------------------------------

const DirEntry* FileCopier::GetErrorTarget() const
{
    return pImp->pErrTarget;
}

//---------------------------------------------------------------------------

ErrCode FileCopier::GetError() const
{
    return pImp->eErr;
}

//---------------------------------------------------------------------------

void FileCopier::SetErrorHdl( const Link &rLink )
{
    pImp->aErrorLink = rLink;
}

//---------------------------------------------------------------------------

const Link& FileCopier::GetErrorHdl() const
{
    return pImp->aErrorLink ;
}

/*************************************************************************
|*
|*    FileCopier::Execute()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 13.04.94
|*    Letzte Aenderung  PB 16.06.00
|*
*************************************************************************/

FSysError FileCopier::DoCopy_Impl(
    const DirEntry &rSource, const DirEntry &rTarget )
{
    FSysError eRet = FSYS_ERR_OK;
    ErrCode eWarn = FSYS_ERR_OK;

    // HPFS->FAT?
    FSysPathStyle eSourceStyle = DirEntry::GetPathStyle( rSource.ImpGetTopPtr()->GetName() );
    FSysPathStyle eTargetStyle = DirEntry::GetPathStyle( rTarget.ImpGetTopPtr()->GetName() );
    BOOL bMakeShortNames = ( eSourceStyle == FSYS_STYLE_HPFS && eTargetStyle == FSYS_STYLE_FAT );

    // Zieldateiname ggf. kuerzen
    DirEntry aTgt;
    if ( bMakeShortNames )
    {
        aTgt = rTarget.GetPath();
        aTgt.MakeShortName( rTarget.GetName() );
    }
    else
        aTgt = rTarget;

    // kein Move wenn Namen gekuerzt werden muessten
    if ( bMakeShortNames && FSYS_ACTION_MOVE == ( pImp->nActions & FSYS_ACTION_MOVE ) && aTgt != rTarget )
        return ERRCODE_IO_NAMETOOLONG;

    // source is directory?
    FileStat aSourceFileStat( rSource );
    if ( aSourceFileStat.IsKind( FSYS_KIND_DIR ) )
    {
        // recursive copy
        eRet = Error( aTgt.MakeDir() ? FSYS_ERR_OK : FSYS_ERR_UNKNOWN, 0, &aTgt );
        Dir aSourceDir( rSource, FSYS_KIND_DIR|FSYS_KIND_FILE );
        for ( USHORT n = 0; ERRCODE_TOERROR(eRet) == FSYS_ERR_OK && n < aSourceDir.Count(); ++n )
        {
            const DirEntry &rSubSource = aSourceDir[n];
            DirEntryFlag eFlag = rSubSource.GetFlag();
            if ( eFlag != FSYS_FLAG_CURRENT && eFlag != FSYS_FLAG_PARENT )
            {
                DirEntry aSubTarget( aTgt );
                aSubTarget += rSubSource.GetName();
                eRet = DoCopy_Impl( rSubSource, aSubTarget );
                if ( eRet && !eWarn )
                eWarn = eRet;
            }
        }
    }
    else if ( aSourceFileStat.IsKind(FSYS_KIND_FILE) )
    {
        if ( ( FSYS_ACTION_KEEP_EXISTING == ( pImp->nActions & FSYS_ACTION_KEEP_EXISTING ) ) &&
             aTgt.Exists() )
        {
            // Do not overwrite existing file in target folder.
            return ERRCODE_NONE;
        }

        // copy file
        nBytesCopied = 0;
        nBytesTotal = FileStat( rSource ).GetSize();

        ::rtl::OUString aFileName;
        FileBase::getFileURLFromSystemPath( ::rtl::OUString(rSource.GetFull()), aFileName );
        SvFileStream aSrc( aFileName, STREAM_READ|STREAM_NOCREATE|STREAM_SHARE_DENYNONE );

        if ( !aSrc.GetError() )
        {
#ifdef UNX
            struct stat buf;
            if ( fstat( aSrc.GetFileHandle(), &buf ) == -1 )
                eRet = Error( FSYS_ERR_ACCESSDENIED, 0, &aTgt );
#endif
            ::rtl::OUString aTargetFileName;
            FileBase::getFileURLFromSystemPath( ::rtl::OUString(aTgt.GetFull()), aTargetFileName );

            SvFileStream aTargetStream( aTargetFileName, STREAM_WRITE | STREAM_TRUNC | STREAM_SHARE_DENYWRITE );
            if ( !aTargetStream.GetError() )
            {
#ifdef UNX
                if ( fchmod( aTargetStream.GetFileHandle(), buf.st_mode ) == -1 )
                    eRet = Error( FSYS_ERR_ACCESSDENIED, 0, &aTgt );
#endif
                size_t nAllocSize = 0, nSize = 0;
                char *pBuf = 0;
                while ( Progress() && nSize == nAllocSize && eRet == FSYS_ERR_OK )
                {
                    // adjust the block-size
                    if ( nBlockSize > nAllocSize )
                    {
                        delete[] pBuf;
                        nAllocSize = nBlockSize;
                        pBuf = new char[nAllocSize];
                    }

                    // copy one block
                    nSize = aSrc.Read( pBuf, nBlockSize );
                    aTargetStream.Write( pBuf, nSize );
                    if ( aTargetStream.GetError() )
                        eRet = Error( aTargetStream.GetError(), 0, &aTgt );

                    // adjust counters
                    nBytesCopied += nSize;
                    if ( nBytesCopied > nBytesTotal )
                        nBytesTotal = nBytesCopied;
                }
                delete[] pBuf;
            }
            else
                eRet = Error( aTargetStream.GetError(), 0, &aTgt );

            // unvollstaendiges File wieder loeschen
            aTargetStream.Close();

            if ( nBytesCopied != nBytesTotal )
            {
                aTgt.Kill();
            }
        }
        else
            eRet = Error( aSrc.GetError(), &rSource, 0 );
    }
    else if ( aSourceFileStat.IsKind(FSYS_KIND_NONE) )
        eRet = Error( ERRCODE_IO_NOTEXISTS, &rSource, 0 );
    else
        eRet = Error( ERRCODE_IO_NOTSUPPORTED, &rSource, 0 );

#ifdef WNT
    // Set LastWriteTime and Attributes of the target identical with the source

    if ( FSYS_ERR_OK == ERRCODE_TOERROR(eRet) )
    {
        WIN32_FIND_DATA fdSource;
        ByteString aFullSource(aSource.GetFull(), osl_getThreadTextEncoding());
        ByteString aFullTarget(aTgt.GetFull(), osl_getThreadTextEncoding());
        HANDLE  hFind = FindFirstFile( aFullSource.GetBuffer() , &fdSource );
        if ( hFind != INVALID_HANDLE_VALUE )
        {
            FindClose( hFind );

            HANDLE hFile = CreateFile( aFullTarget.GetBuffer(), GENERIC_WRITE,
                                       FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                                       OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );

            if ( hFile != INVALID_HANDLE_VALUE )
            {
                SetFileTime( hFile, NULL, NULL, &fdSource.ftLastWriteTime );
                CloseHandle( hFile );
            }

            SetFileAttributes( aFullTarget.GetBuffer(), fdSource.dwFileAttributes );
        }
    }
#endif
    // bei Move ggf. das File/Dir loeschen
    if ( FSYS_ERR_OK == ERRCODE_TOERROR(eRet) && ( pImp->nActions  & FSYS_ACTION_MOVE ) )
    {
        ErrCode eKillErr = Error( rSource.Kill() | ERRCODE_WARNING_MASK, &rSource, 0 );
        if ( eKillErr != ERRCODE_WARNING_MASK )
        {
            if ( rSource.Exists() )
                // loeschen ging nicht => dann die Kopie wieder loeschen
                aTgt.Kill( pImp->nActions );
            if ( !eWarn )
                eWarn = eKillErr;
        }
    }

    return !eRet ? eWarn : eRet;
}

// -----------------------------------------------------------------------

FSysError FileCopier::Execute( FSysAction nActions )
{
    return ExecuteExact( nActions );
}

// -----------------------------------------------------------------------

FSysError FileCopier::ExecuteExact( FSysAction nActions, FSysExact eExact )
{
    DirEntry aAbsSource = DirEntry( aSource);
    DirEntry aAbsTarget = DirEntry( aTarget );
    pImp->nActions = nActions;

    // check if both pathes are accessible and source and target are different
    if ( !aAbsTarget.ToAbs() || !aAbsSource.ToAbs() || aAbsTarget == aAbsSource )
        return FSYS_ERR_ACCESSDENIED;

    // check if copy would be endless recursive into itself
    if ( FSYS_ACTION_RECURSIVE == ( nActions & FSYS_ACTION_RECURSIVE ) &&
         aAbsSource.Contains( aAbsTarget ) )
        return ERRCODE_IO_RECURSIVE;

    // target is directory?
    if ( eExact == FSYS_NOTEXACT &&
         FileStat( aAbsTarget ).IsKind(FSYS_KIND_DIR) && FileStat( aAbsSource ).IsKind(FSYS_KIND_FILE) )
        // append name of source
        aAbsTarget += aSource.GetName();

    // recursive copy
    return DoCopy_Impl( aAbsSource, aAbsTarget );
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.7.90); FILE MERGED 2007/06/06 10:20:32 vg 1.7.90.2: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01 2007/06/04 13:32:24 vg 1.7.90.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: filecopy.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 22:10:48 $
 *
 *  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_tools.hxx"

#if defined WNT
#ifndef _SVWIN_H
#include <io.h>
#include <tools/svwin.h>
#endif

#elif defined UNX
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>

#endif

#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include <stdio.h>

#ifndef _COMDEP_HXX
#include "comdep.hxx"
#endif

#ifndef _FSYS_HXX
#include <tools/fsys.hxx>
#endif

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

using namespace ::osl;

/*************************************************************************
|*
|*    FileCopier::FileCopier()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 13.04.94
|*    Letzte Aenderung  MI 13.04.94
|*
*************************************************************************/

FileCopier::FileCopier() :

    nBytesTotal ( 0 ),
    nBytesCopied( 0 ),
    nBlockSize  ( 4096 ),
    pImp        ( new FileCopier_Impl )

{
}

// -----------------------------------------------------------------------

FileCopier::FileCopier( const DirEntry& rSource, const DirEntry& rTarget ) :

    aSource     ( rSource ),
    aTarget     ( rTarget ),
    nBytesTotal ( 0 ),
    nBytesCopied( 0 ),
    nBlockSize  ( 4096 ),
    pImp        ( new FileCopier_Impl )

{
}

// -----------------------------------------------------------------------

FileCopier::FileCopier( const FileCopier& rCopier ) :

    aSource         ( rCopier.aSource ),
    aTarget         ( rCopier.aTarget ),
    nBytesTotal     ( 0 ),
    nBytesCopied    ( 0 ),
    aProgressLink   ( rCopier.aProgressLink ),
    nBlockSize      ( 4096 ),
    pImp            ( new FileCopier_Impl )

{
}

/*************************************************************************
|*
|*    FileCopier::~FileCopier()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 13.04.94
|*    Letzte Aenderung  MI 13.04.94
|*
*************************************************************************/

FileCopier::~FileCopier()
{
    delete pImp;
}

/*************************************************************************
|*
|*    FileCopier::operator =()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 13.04.94
|*    Letzte Aenderung  MI 13.04.94
|*
*************************************************************************/

FileCopier& FileCopier::operator = ( const FileCopier &rCopier )
{
    aSource = rCopier.aSource;
    aTarget = rCopier.aTarget;
    nBytesTotal = rCopier.nBytesTotal;
    nBytesCopied = rCopier.nBytesCopied;
    nBytesCopied = rCopier.nBytesCopied;
    nBlockSize = rCopier.nBlockSize;
    aProgressLink = rCopier.aProgressLink;
    *pImp = *(rCopier.pImp);
    return *this;
}

/*************************************************************************
|*
|*    FileCopier::Progress()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 13.04.94
|*    Letzte Aenderung  MI 13.04.94
|*
*************************************************************************/

BOOL FileCopier::Progress()
{
    if ( !aProgressLink )
        return TRUE;
    else
    {
        if ( aProgressLink.Call( this ) )
            return TRUE;
        return ( 0 == Error( ERRCODE_ABORT, 0, 0 ) );
    }
}

//---------------------------------------------------------------------------

ErrCode FileCopier::Error( ErrCode eErr, const DirEntry* pSource, const DirEntry* pTarget )
{
    // kein Fehler oder kein ErrorHandler?
    if ( !eErr || !pImp->aErrorLink )
        // => Error beibehalten
        return eErr;

    // sonst gesetzten ErrorHandler fragen
    pImp->pErrSource = pSource;
    pImp->pErrTarget = pTarget;
    pImp->eErr = eErr;
    ErrCode eRet = (ErrCode) pImp->aErrorLink.Call( this );
    pImp->pErrSource = 0;
    pImp->pErrTarget = 0;
    return eRet;
}

//---------------------------------------------------------------------------

const DirEntry* FileCopier::GetErrorSource() const
{
    return pImp->pErrSource;
}

//---------------------------------------------------------------------------

const DirEntry* FileCopier::GetErrorTarget() const
{
    return pImp->pErrTarget;
}

//---------------------------------------------------------------------------

ErrCode FileCopier::GetError() const
{
    return pImp->eErr;
}

//---------------------------------------------------------------------------

void FileCopier::SetErrorHdl( const Link &rLink )
{
    pImp->aErrorLink = rLink;
}

//---------------------------------------------------------------------------

const Link& FileCopier::GetErrorHdl() const
{
    return pImp->aErrorLink ;
}

/*************************************************************************
|*
|*    FileCopier::Execute()
|*
|*    Beschreibung      FSYS.SDW
|*    Ersterstellung    MI 13.04.94
|*    Letzte Aenderung  PB 16.06.00
|*
*************************************************************************/

FSysError FileCopier::DoCopy_Impl(
    const DirEntry &rSource, const DirEntry &rTarget )
{
    FSysError eRet = FSYS_ERR_OK;
    ErrCode eWarn = FSYS_ERR_OK;

    // HPFS->FAT?
    FSysPathStyle eSourceStyle = DirEntry::GetPathStyle( rSource.ImpGetTopPtr()->GetName() );
    FSysPathStyle eTargetStyle = DirEntry::GetPathStyle( rTarget.ImpGetTopPtr()->GetName() );
    BOOL bMakeShortNames = ( eSourceStyle == FSYS_STYLE_HPFS && eTargetStyle == FSYS_STYLE_FAT );

    // Zieldateiname ggf. kuerzen
    DirEntry aTgt;
    if ( bMakeShortNames )
    {
        aTgt = rTarget.GetPath();
        aTgt.MakeShortName( rTarget.GetName() );
    }
    else
        aTgt = rTarget;

    // kein Move wenn Namen gekuerzt werden muessten
    if ( bMakeShortNames && FSYS_ACTION_MOVE == ( pImp->nActions & FSYS_ACTION_MOVE ) && aTgt != rTarget )
        return ERRCODE_IO_NAMETOOLONG;

    // source is directory?
    FileStat aSourceFileStat( rSource );
    if ( aSourceFileStat.IsKind( FSYS_KIND_DIR ) )
    {
        // recursive copy
        eRet = Error( aTgt.MakeDir() ? FSYS_ERR_OK : FSYS_ERR_UNKNOWN, 0, &aTgt );
        Dir aSourceDir( rSource, FSYS_KIND_DIR|FSYS_KIND_FILE );
        for ( USHORT n = 0; ERRCODE_TOERROR(eRet) == FSYS_ERR_OK && n < aSourceDir.Count(); ++n )
        {
            const DirEntry &rSubSource = aSourceDir[n];
            DirEntryFlag eFlag = rSubSource.GetFlag();
            if ( eFlag != FSYS_FLAG_CURRENT && eFlag != FSYS_FLAG_PARENT )
            {
                DirEntry aSubTarget( aTgt );
                aSubTarget += rSubSource.GetName();
                eRet = DoCopy_Impl( rSubSource, aSubTarget );
                if ( eRet && !eWarn )
                eWarn = eRet;
            }
        }
    }
    else if ( aSourceFileStat.IsKind(FSYS_KIND_FILE) )
    {
        if ( ( FSYS_ACTION_KEEP_EXISTING == ( pImp->nActions & FSYS_ACTION_KEEP_EXISTING ) ) &&
             aTgt.Exists() )
        {
            // Do not overwrite existing file in target folder.
            return ERRCODE_NONE;
        }

        // copy file
        nBytesCopied = 0;
        nBytesTotal = FileStat( rSource ).GetSize();

        ::rtl::OUString aFileName;
        FileBase::getFileURLFromSystemPath( ::rtl::OUString(rSource.GetFull()), aFileName );
        SvFileStream aSrc( aFileName, STREAM_READ|STREAM_NOCREATE|STREAM_SHARE_DENYNONE );

        if ( !aSrc.GetError() )
        {
#ifdef UNX
            struct stat buf;
            if ( fstat( aSrc.GetFileHandle(), &buf ) == -1 )
                eRet = Error( FSYS_ERR_ACCESSDENIED, 0, &aTgt );
#endif
            ::rtl::OUString aTargetFileName;
            FileBase::getFileURLFromSystemPath( ::rtl::OUString(aTgt.GetFull()), aTargetFileName );

            SvFileStream aTargetStream( aTargetFileName, STREAM_WRITE | STREAM_TRUNC | STREAM_SHARE_DENYWRITE );
            if ( !aTargetStream.GetError() )
            {
#ifdef UNX
                if ( fchmod( aTargetStream.GetFileHandle(), buf.st_mode ) == -1 )
                    eRet = Error( FSYS_ERR_ACCESSDENIED, 0, &aTgt );
#endif
                size_t nAllocSize = 0, nSize = 0;
                char *pBuf = 0;
                while ( Progress() && nSize == nAllocSize && eRet == FSYS_ERR_OK )
                {
                    // adjust the block-size
                    if ( nBlockSize > nAllocSize )
                    {
                        delete[] pBuf;
                        nAllocSize = nBlockSize;
                        pBuf = new char[nAllocSize];
                    }

                    // copy one block
                    nSize = aSrc.Read( pBuf, nBlockSize );
                    aTargetStream.Write( pBuf, nSize );
                    if ( aTargetStream.GetError() )
                        eRet = Error( aTargetStream.GetError(), 0, &aTgt );

                    // adjust counters
                    nBytesCopied += nSize;
                    if ( nBytesCopied > nBytesTotal )
                        nBytesTotal = nBytesCopied;
                }
                delete[] pBuf;
            }
            else
                eRet = Error( aTargetStream.GetError(), 0, &aTgt );

            // unvollstaendiges File wieder loeschen
            aTargetStream.Close();

            if ( nBytesCopied != nBytesTotal )
            {
                aTgt.Kill();
            }
        }
        else
            eRet = Error( aSrc.GetError(), &rSource, 0 );
    }
    else if ( aSourceFileStat.IsKind(FSYS_KIND_NONE) )
        eRet = Error( ERRCODE_IO_NOTEXISTS, &rSource, 0 );
    else
        eRet = Error( ERRCODE_IO_NOTSUPPORTED, &rSource, 0 );

#ifdef WNT
    // Set LastWriteTime and Attributes of the target identical with the source

    if ( FSYS_ERR_OK == ERRCODE_TOERROR(eRet) )
    {
        WIN32_FIND_DATA fdSource;
        ByteString aFullSource(aSource.GetFull(), osl_getThreadTextEncoding());
        ByteString aFullTarget(aTgt.GetFull(), osl_getThreadTextEncoding());
        HANDLE  hFind = FindFirstFile( aFullSource.GetBuffer() , &fdSource );
        if ( hFind != INVALID_HANDLE_VALUE )
        {
            FindClose( hFind );

            HANDLE hFile = CreateFile( aFullTarget.GetBuffer(), GENERIC_WRITE,
                                       FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                                       OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );

            if ( hFile != INVALID_HANDLE_VALUE )
            {
                SetFileTime( hFile, NULL, NULL, &fdSource.ftLastWriteTime );
                CloseHandle( hFile );
            }

            SetFileAttributes( aFullTarget.GetBuffer(), fdSource.dwFileAttributes );
        }
    }
#endif
    // bei Move ggf. das File/Dir loeschen
    if ( FSYS_ERR_OK == ERRCODE_TOERROR(eRet) && ( pImp->nActions  & FSYS_ACTION_MOVE ) )
    {
        ErrCode eKillErr = Error( rSource.Kill() | ERRCODE_WARNING_MASK, &rSource, 0 );
        if ( eKillErr != ERRCODE_WARNING_MASK )
        {
            if ( rSource.Exists() )
                // loeschen ging nicht => dann die Kopie wieder loeschen
                aTgt.Kill( pImp->nActions );
            if ( !eWarn )
                eWarn = eKillErr;
        }
    }

    return !eRet ? eWarn : eRet;
}

// -----------------------------------------------------------------------

FSysError FileCopier::Execute( FSysAction nActions )
{
    return ExecuteExact( nActions );
}

// -----------------------------------------------------------------------

FSysError FileCopier::ExecuteExact( FSysAction nActions, FSysExact eExact )
{
    DirEntry aAbsSource = DirEntry( aSource);
    DirEntry aAbsTarget = DirEntry( aTarget );
    pImp->nActions = nActions;

    // check if both pathes are accessible and source and target are different
    if ( !aAbsTarget.ToAbs() || !aAbsSource.ToAbs() || aAbsTarget == aAbsSource )
        return FSYS_ERR_ACCESSDENIED;

    // check if copy would be endless recursive into itself
    if ( FSYS_ACTION_RECURSIVE == ( nActions & FSYS_ACTION_RECURSIVE ) &&
         aAbsSource.Contains( aAbsTarget ) )
        return ERRCODE_IO_RECURSIVE;

    // target is directory?
    if ( eExact == FSYS_NOTEXACT &&
         FileStat( aAbsTarget ).IsKind(FSYS_KIND_DIR) && FileStat( aAbsSource ).IsKind(FSYS_KIND_FILE) )
        // append name of source
        aAbsTarget += aSource.GetName();

    // recursive copy
    return DoCopy_Impl( aAbsSource, aAbsTarget );
}
<|endoftext|>