<commit_before>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: yuanyi03@baidu.com

#include "curl_downloader.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "common/logging.h"
#include "common/asm_atomic.h"
extern "C" {
#include "curl/curl.h"
}

extern int FLAGS_agent_curl_recv_buffer_size;

static pthread_once_t once_control = PTHREAD_ONCE_INIT;

// destroy func process level
static void GlobalDestroy() {
    curl_global_cleanup();
}

// init func process level
static void GlobalInit() {
    curl_global_init(CURL_GLOBAL_ALL);
    ::atexit(GlobalDestroy);
}

namespace galaxy {

static int OPEN_FLAGS = O_CREAT | O_WRONLY;
static int OPEN_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IRWXO;

CurlDownloader::CurlDownloader()
    : recv_buffer_size_(0),
      used_length_(0),
      recv_buffer_(NULL),
      output_fd_(-1),
      stoped_(0) {
    if (FLAGS_agent_curl_recv_buffer_size <= 16 * 1024) {
        recv_buffer_size_ = 16 * 1024;
    }
    else {
        recv_buffer_size_ = FLAGS_agent_curl_recv_buffer_size;
    }
    recv_buffer_ = new char[recv_buffer_size_];
    pthread_once(&once_control, GlobalInit);
}

CurlDownloader::~CurlDownloader() {
    if (recv_buffer_) {
        delete recv_buffer_;
        recv_buffer_ = NULL;
    }
}

void CurlDownloader::Stop() {
    common::atomic_swap(&stoped_, 1);
}

size_t CurlDownloader::RecvTrunkData(char* ptr,
                                     size_t size,
                                     size_t nmemb,
                                     void* user_data) {
    CurlDownloader* downloader =
        static_cast<CurlDownloader*>(user_data);
    assert(downloader);

    if (common::atomic_add_ret_old(&downloader->stoped_, 0) == 1) {
        return 0;
    }

    if (size * nmemb <= 0) {
        return size * nmemb;
    }

    if (downloader->used_length_ == downloader->recv_buffer_size_
            || size * nmemb > static_cast<size_t>(downloader->recv_buffer_size_ - downloader->used_length_)) {
        // flush to disk
        if (write(downloader->output_fd_,
                    downloader->recv_buffer_, downloader->used_length_) == -1) {
            LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno));
            return 0;
        }
        LOG(INFO, "write file %d", downloader->used_length_);
        downloader->used_length_ = 0;
    }

    memcpy(downloader->recv_buffer_ + downloader->used_length_, ptr, size * nmemb);
    downloader->used_length_ += size * nmemb;
    return size * nmemb;
}

int CurlDownloader::Fetch(const std::string& uri, const std::string& path) {
    output_fd_ = open(path.c_str(), OPEN_FLAGS, OPEN_MODE);
    if (output_fd_ == -1) {
        LOG(WARNING, "open file failed %s err[%d: %s]",
                path.c_str(), errno, strerror(errno));
        return -1;
    }

    LOG(INFO, "start to curl data %s", uri.c_str());
    CURL* curl = curl_easy_init();
    int ret;
    do {
        ret = curl_easy_setopt(curl, CURLOPT_URL, uri.c_str());
        if (ret != CURLE_OK) {
            LOG(WARNING, "libcurl setopt %s failed [%d: %s]",
                    "CURLOPT_URL", ret, curl_easy_strerror((CURLcode)ret));
            break;
        }

        ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
        if (ret != CURLE_OK) {
            LOG(WARNING, "libcurl setopt %s failed [%d: %s]",
                    "CURLOPT_WRITEDATA", ret, curl_easy_strerror((CURLcode)ret));
            break;
        }

        ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlDownloader::RecvTrunkData);
        if (ret != CURLE_OK) {
            LOG(WARNING, "libcurl setopt %s failed [%d: %s]",
                    "CURLOPT_WRITEFUNCTION", ret, curl_easy_strerror((CURLcode)ret));
            break;
        }

        ret = curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        if (ret != CURLE_OK) {
            LOG(WARNING, "libcurl setopt %s failed [%d: %s]",
                    "CURLOPT_VERBOSE", ret, curl_easy_strerror((CURLcode)ret));
            break;
        }

        ret = curl_easy_perform(curl);
        if (ret != CURLE_OK) {
            LOG(WARNING, "libcurl perform failed [%d: %s]",
                    ret, curl_easy_strerror((CURLcode)ret));
            break;
        }

        if (used_length_ != 0) {
            if (write(output_fd_, recv_buffer_, used_length_)
                    == -1) {
                LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno));
                ret = -1;
                break;
            }
            LOG(INFO, "write file %d", used_length_);
            used_length_ = 0;
        }
    } while(0);

    if (curl != NULL) {
        curl_easy_cleanup(curl);
    }

    if (ret != CURLE_OK) {
        return -1;
    }
    return 0;
}

}   // ending namespace galaxy

/* vim: set ts=4 sw=4 sts=4 tw=100 */
<commit_msg>remove atomic<commit_after>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: yuanyi03@baidu.com

#include "curl_downloader.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "common/logging.h"
extern "C" {
#include "curl/curl.h"
}

extern int FLAGS_agent_curl_recv_buffer_size;

static pthread_once_t once_control = PTHREAD_ONCE_INIT;

// destroy func process level
static void GlobalDestroy() {
    curl_global_cleanup();
}

// init func process level
static void GlobalInit() {
    curl_global_init(CURL_GLOBAL_ALL);
    ::atexit(GlobalDestroy);
}

namespace galaxy {

static int OPEN_FLAGS = O_CREAT | O_WRONLY;
static int OPEN_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IRWXO;

CurlDownloader::CurlDownloader()
    : recv_buffer_size_(0),
      used_length_(0),
      recv_buffer_(NULL),
      output_fd_(-1),
      stoped_(0) {
    if (FLAGS_agent_curl_recv_buffer_size <= 16 * 1024) {
        recv_buffer_size_ = 16 * 1024;
    }
    else {
        recv_buffer_size_ = FLAGS_agent_curl_recv_buffer_size;
    }
    recv_buffer_ = new char[recv_buffer_size_];
    pthread_once(&once_control, GlobalInit);
}

CurlDownloader::~CurlDownloader() {
    if (recv_buffer_) {
        delete recv_buffer_;
        recv_buffer_ = NULL;
    }
}

void CurlDownloader::Stop() {
    stoped_ = 1;
}

size_t CurlDownloader::RecvTrunkData(char* ptr,
                                     size_t size,
                                     size_t nmemb,
                                     void* user_data) {
    CurlDownloader* downloader =
        static_cast<CurlDownloader*>(user_data);
    assert(downloader);

    if (stoped_ == 1) {
        return 0;
    }

    if (size * nmemb <= 0) {
        return size * nmemb;
    }

    if (downloader->used_length_ == downloader->recv_buffer_size_
            || size * nmemb > static_cast<size_t>(downloader->recv_buffer_size_ - downloader->used_length_)) {
        // flush to disk
        if (write(downloader->output_fd_,
                    downloader->recv_buffer_, downloader->used_length_) == -1) {
            LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno));
            return 0;
        }
        LOG(INFO, "write file %d", downloader->used_length_);
        downloader->used_length_ = 0;
    }

    memcpy(downloader->recv_buffer_ + downloader->used_length_, ptr, size * nmemb);
    downloader->used_length_ += size * nmemb;
    return size * nmemb;
}

int CurlDownloader::Fetch(const std::string& uri, const std::string& path) {
    output_fd_ = open(path.c_str(), OPEN_FLAGS, OPEN_MODE);
    if (output_fd_ == -1) {
        LOG(WARNING, "open file failed %s err[%d: %s]",
                path.c_str(), errno, strerror(errno));
        return -1;
    }

    LOG(INFO, "start to curl data %s", uri.c_str());
    CURL* curl = curl_easy_init();
    int ret;
    do {
        ret = curl_easy_setopt(curl, CURLOPT_URL, uri.c_str());
        if (ret != CURLE_OK) {
            LOG(WARNING, "libcurl setopt %s failed [%d: %s]",
                    "CURLOPT_URL", ret, curl_easy_strerror((CURLcode)ret));
            break;
        }

        ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
        if (ret != CURLE_OK) {
            LOG(WARNING, "libcurl setopt %s failed [%d: %s]",
                    "CURLOPT_WRITEDATA", ret, curl_easy_strerror((CURLcode)ret));
            break;
        }

        ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlDownloader::RecvTrunkData);
        if (ret != CURLE_OK) {
            LOG(WARNING, "libcurl setopt %s failed [%d: %s]",
                    "CURLOPT_WRITEFUNCTION", ret, curl_easy_strerror((CURLcode)ret));
            break;
        }

        ret = curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        if (ret != CURLE_OK) {
            LOG(WARNING, "libcurl setopt %s failed [%d: %s]",
                    "CURLOPT_VERBOSE", ret, curl_easy_strerror((CURLcode)ret));
            break;
        }

        ret = curl_easy_perform(curl);
        if (ret != CURLE_OK) {
            LOG(WARNING, "libcurl perform failed [%d: %s]",
                    ret, curl_easy_strerror((CURLcode)ret));
            break;
        }

        if (used_length_ != 0) {
            if (write(output_fd_, recv_buffer_, used_length_)
                    == -1) {
                LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno));
                ret = -1;
                break;
            }
            LOG(INFO, "write file %d", used_length_);
            used_length_ = 0;
        }
    } while(0);

    if (curl != NULL) {
        curl_easy_cleanup(curl);
    }

    if (ret != CURLE_OK) {
        return -1;
    }
    return 0;
}

}   // ending namespace galaxy

/* vim: set ts=4 sw=4 sts=4 tw=100 */
<|endoftext|>


<commit_before>/* dstar_from_grid.cpp
 */

#ifdef MACOS
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#endif

#include <stdlib.h>
#include <unistd.h>
#include "dstar.h"

namespace dstar {
class DstarInterface () {
};
} // End dstar namespace.
int hh, ww;

int window;
Dstar *dstar;

int scale = 6;
int mbutton = 0;
int mstate = 0;

bool b_autoreplan = true;

void InitGL(int Width, int Height)
{
  hh = Height;
  ww = Width;

  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  glClearDepth(1.0);

  glViewport(0,0,Width,Height);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0,Width,0,Height,-100,100);
  glMatrixMode(GL_MODELVIEW);
}

void ReSizeGLScene(int Width, int Height)
{
  hh = Height;
  ww = Width;

  glViewport(0,0,Width,Height);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0,Width,0,Height,-100,100);
  glMatrixMode(GL_MODELVIEW);

}

void DrawGLScene()
{

  usleep(100);

  glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
  glLoadIdentity();
  glPushMatrix();

  glScaled(scale,scale,1);

  if (b_autoreplan) dstar->replan();

  dstar->draw();

  glPopMatrix();
  glutSwapBuffers();

}

void keyPressed(unsigned char key, int x, int y)
{
  usleep(100);

  switch(key) {
  case 'q':
  case 'Q':
    glutDestroyWindow(window);
    exit(0);
    break;
  case 'r':
  case 'R':
    dstar->replan();
    break;
  case 'a':
  case 'A':
    b_autoreplan = !b_autoreplan;
    break;
  case 'c':
  case 'C':
    dstar->init(40,50,140, 90);
    break;
  }

}

void mouseFunc(int button, int state, int x, int y) {

  y = hh -y+scale/2;
  x += scale/2;

  mbutton = button;

  if ((mstate = state) == GLUT_DOWN) {
    if (button == GLUT_LEFT_BUTTON) {
      dstar->updateCell(x/scale, y/scale, -1);
    } else if (button == GLUT_RIGHT_BUTTON) {
      dstar->updateStart(x/scale, y/scale);
    } else if (button == GLUT_MIDDLE_BUTTON) {
      dstar->updateGoal(x/scale, y/scale);
    }
  }
}

void mouseMotionFunc(int x, int y)  {

  y = hh -y+scale/2;
  x += scale/2;

  y /= scale;
  x /= scale;

  if (mstate == GLUT_DOWN) {
    if (mbutton == GLUT_LEFT_BUTTON) {
      dstar->updateCell(x, y, -1);
    } else if (mbutton == GLUT_RIGHT_BUTTON) {
      dstar->updateStart(x, y);
    } else if (mbutton == GLUT_MIDDLE_BUTTON) {
      dstar->updateGoal(x, y);
    }
  }

}

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

  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
  glutInitWindowSize(1000, 800);
  glutInitWindowPosition(50, 20);

  window = glutCreateWindow("Dstar Visualizer");

  glutDisplayFunc(&DrawGLScene);
  glutIdleFunc(&DrawGLScene);
  glutReshapeFunc(&ReSizeGLScene);
  glutKeyboardFunc(&keyPressed);
  glutMouseFunc(&mouseFunc);
  glutMotionFunc(&mouseMotionFunc);

  InitGL(800, 600);

  dstar = new Dstar();
  dstar->init(40,50,140, 90);

  printf("----------------------------------\n");
  printf("Dstar Visualizer\n");
  printf("Commands:\n");
  printf("[q/Q] - Quit\n");
  printf("[r/R] - Replan\n");
  printf("[a/A] - Toggle Auto Replan\n");
  printf("[c/C] - Clear (restart)\n");
  printf("left mouse click - make cell untraversable (cost -1)\n");
  printf("middle mouse click - move goal to cell\n");
  printf("right mouse click - move start to cell\n");
  printf("----------------------------------\n");

  glutMainLoop();

  return 1;
}
<commit_msg>First iteration of dstar_from_grid.cpp<commit_after>/* dstar_from_grid.cpp
 */

#ifdef MACOS
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#endif

#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <unistd.h>

#include "dstar_lite/dstar.h"

int hh, ww;

int window;
Dstar *dstar;

int scale = 50;
int mbutton = 0;
int mstate = 0;

bool b_autoreplan = false;

void InitGL(int Width, int Height) {
  hh = Height;
  ww = Width;

  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  glClearDepth(1.0);

  glViewport(0,0,Width,Height);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0,Width,0,Height,-100,100);
  glMatrixMode(GL_MODELVIEW);
}

void ReSizeGLScene(int Width, int Height) {
  hh = Height;
  ww = Width;

  glViewport(0,0,Width,Height);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0,Width,0,Height,-100,100);
  glMatrixMode(GL_MODELVIEW);
}

void DrawGLScene() {
  usleep(100);

  glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
  glLoadIdentity();
  glPushMatrix();

  glScaled(scale,scale,1);

  if (b_autoreplan) dstar->replan();

  dstar->draw();

  glPopMatrix();
  glutSwapBuffers();
}

void keyPressed(unsigned char key, int x, int y) {
  usleep(100);

  switch(key) {
  case 'q':
  case 'Q':
    glutDestroyWindow(window);
    exit(0);
    break;
  case 'r':
  case 'R':
    dstar->replan();
    break;
  case 'a':
  case 'A':
    b_autoreplan = !b_autoreplan;
    break;
  case 'c':
  case 'C':
    dstar->init(1, 1, 3, 3);
    break;
  }
}

void mouseFunc(int button, int state, int x, int y) {
  y = hh -y+scale/2;
  x += scale/2;

  mbutton = button;

  if ((mstate = state) == GLUT_DOWN) {
    if (button == GLUT_LEFT_BUTTON) {
      dstar->updateCell(x/scale, y/scale, -1);
    } else if (button == GLUT_RIGHT_BUTTON) {
      dstar->updateStart(x/scale, y/scale);
    } else if (button == GLUT_MIDDLE_BUTTON) {
      dstar->updateGoal(x/scale, y/scale);
    }
  }
}

void mouseMotionFunc(int x, int y) {
  y = hh -y+scale/2;
  x += scale/2;

  y /= scale;
  x /= scale;

  if (mstate == GLUT_DOWN) {
    if (mbutton == GLUT_LEFT_BUTTON) {
      dstar->updateCell(x, y, -1);
    } else if (mbutton == GLUT_RIGHT_BUTTON) {
      dstar->updateStart(x, y);
    } else if (mbutton == GLUT_MIDDLE_BUTTON) {
      dstar->updateGoal(x, y);
    }
  }
}

int main(int argc, char **argv) {
  // Init GLUT
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);

  // Parse csv file with world grids.
  // Currently only loads the first grid in the csv file...
  ifstream file("../resources/gridworld_8.csv");
  std::vector<string> value;
  string tmp;
  if (file.is_open()) {
    while (getline(file, tmp)) {
      value.push_back(tmp);
    }
    file.close();
  } else {
    cout << "Could not open the csv file." << endl;
  }

  // Construct a grid.
  const uint grid_size = (uint)std::sqrt(value.size());
  std::vector<std::vector<int>> occupancy_grid (grid_size, vector<int>(grid_size));

  uint i = 0;
  uint j = 0;
  bool first = true;

  // Reshape input to a grid with x, y coordinates
  for (uint k = 0; k < value.size(); k++) {
    j = k % ((uint)std::sqrt(value.size()));

    // Check that we are not out of bounds.
    if ( i < grid_size && j < grid_size) {
      occupancy_grid[i][j] = std::atoi(&value.at(k).at(0));
    } else {
      cerr << "Index out of bounds, check that input grid is squared." << endl;
    }

    if (j == 0) {
      if (first) {
        first = false;
      } else {
        i++;
      }
    }
  }

  // Initialize window for visualization.
  glutInitWindowSize(500, 500);
  glutInitWindowPosition(20, 20);

  window = glutCreateWindow("Dstar Visualizer");

  glutDisplayFunc(&DrawGLScene);
  glutIdleFunc(&DrawGLScene);
  glutReshapeFunc(&ReSizeGLScene);
  glutKeyboardFunc(&keyPressed);
  glutMouseFunc(&mouseFunc);
  glutMotionFunc(&mouseMotionFunc);

  InitGL(30, 20);

  dstar = new Dstar();
  dstar->init(3, 2, 6, 6);
  for (uint i = 0; i < occupancy_grid.size(); i++) {
    for (uint j = 0; j < occupancy_grid.at(i).size(); j++) {
      std::cout << "Occ grid vals: " << occupancy_grid[i][j] << '\n';
      if (occupancy_grid.at(i).at(j) == 1) {
        dstar->updateCell(i+1, j+1, -1);
      }
    }
  }
  dstar->draw();

  printf("----------------------------------\n");
  printf("Dstar Visualizer\n");
  printf("Commands:\n");
  printf("[q/Q] - Quit\n");
  printf("[r/R] - Replan\n");
  printf("[a/A] - Toggle Auto Replan\n");
  printf("[c/C] - Clear (restart)\n");
  printf("left mouse click - make cell untraversable (cost -1)\n");
  printf("middle mouse click - move goal to cell\n");
  printf("right mouse click - move start to cell\n");
  printf("----------------------------------\n");

  glutMainLoop();

  return 1;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: mcnttype.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: tra $ $Date: 2001-02-26 06:59:47 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _MCNTTYPE_HXX_
#include "mcnttype.hxx"
#endif

//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace rtl;
using namespace std;
using namespace osl;

//------------------------------------------------------------------------
// constants
//------------------------------------------------------------------------

const OUString TSPECIALS = OUString::createFromAscii( "()<>@,;:\\\"/[]?=" );
const OUString TOKEN     = OUString::createFromAscii( "!#$%&'*+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~." );
const OUString SPACE     = OUString::createFromAscii( " " );
const OUString SEMICOLON = OUString::createFromAscii( ";" );

//------------------------------------------------------------------------
// ctor
//------------------------------------------------------------------------

CMimeContentType::CMimeContentType( const OUString& aCntType )
{
    init( aCntType );
}

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

OUString SAL_CALL CMimeContentType::getMediaType( ) throw(RuntimeException)
{
    return m_MediaType;
}

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

OUString SAL_CALL CMimeContentType::getMediaSubtype( ) throw(RuntimeException)
{
    return m_MediaSubtype;
}

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

OUString SAL_CALL CMimeContentType::getFullMediaType( ) throw(RuntimeException)
{
    return m_MediaType + OUString::createFromAscii( "/" ) + m_MediaSubtype;
}

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

Sequence< OUString > SAL_CALL CMimeContentType::getParameters( ) throw(RuntimeException)
{
    MutexGuard aGuard( m_aMutex );

    Sequence< OUString > seqParams;

    map< OUString, OUString >::iterator iter;
    map< OUString, OUString >::iterator iter_end = m_ParameterMap.end( );

    for ( iter = m_ParameterMap.begin( ); iter != iter_end; ++iter )
    {
        seqParams.realloc( seqParams.getLength( ) + 1 );
        seqParams[seqParams.getLength( ) - 1] = iter->first;
    }

    return seqParams;
}

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

sal_Bool SAL_CALL CMimeContentType::hasParameter( const OUString& aName ) throw(RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return ( m_ParameterMap.end( ) != m_ParameterMap.find( aName ) );
}

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

OUString SAL_CALL CMimeContentType::getParameterValue( const OUString& aName ) throw(NoSuchElementException, RuntimeException)
{
    MutexGuard aGuard( m_aMutex );

    if ( !hasParameter( aName ) )
        throw NoSuchElementException( );

    return m_ParameterMap.find( aName )->second;
}

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

void SAL_CALL CMimeContentType::init( const OUString& aCntType ) throw( IllegalArgumentException )
{
    if ( !aCntType.getLength( ) )
        throw IllegalArgumentException( );

    m_nPos = 0;
    m_ContentType = aCntType;
    getSym( );
    type();
}

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

void SAL_CALL CMimeContentType::getSym( void )
{
    if ( m_nPos < m_ContentType.getLength( ) )
    {
        m_nxtSym = OUString( &m_ContentType[m_nPos], 1 );
        ++m_nPos;
        return;
    }

    m_nxtSym = OUString( );
}

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

void SAL_CALL CMimeContentType::acceptSym( const OUString& pSymTlb )
{
    if ( pSymTlb.indexOf( m_nxtSym ) < 0 )
        throw IllegalArgumentException( );

    getSym();
}

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

void SAL_CALL CMimeContentType::skipSpaces( void )
{
    while ( SPACE == m_nxtSym )
        getSym( );
}

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

void SAL_CALL CMimeContentType::type( void )
{
    skipSpaces( );

    // check FIRST( type )
    if ( !isInRange( m_nxtSym, TOKEN ) )
        throw IllegalArgumentException( );

    // parse
    while(  m_nxtSym.getLength( ) )
    {
        if ( isInRange( m_nxtSym, TOKEN ) )
            m_MediaType += m_nxtSym;
        else if ( isInRange( m_nxtSym, OUString::createFromAscii( "/ " ) ) )
            break;
        else
            throw IllegalArgumentException( );
        getSym( );
    }

    // check FOLLOW( type )
    skipSpaces( );
    acceptSym( OUString::createFromAscii( "/" ) );

    subtype( );
}

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

void SAL_CALL CMimeContentType::subtype( void )
{
    skipSpaces( );

    // check FIRST( subtype )
    if ( !isInRange( m_nxtSym, TOKEN ) )
        throw IllegalArgumentException( );

    while( m_nxtSym.getLength( ) )
    {
        if ( isInRange( m_nxtSym, TOKEN ) )
            m_MediaSubtype += m_nxtSym;
        else if ( isInRange( m_nxtSym, OUString::createFromAscii( "; " ) ) )
            break;
        else
            throw IllegalArgumentException( );
        getSym( );
    }

    // parse the rest
    skipSpaces( );
    trailer();
}

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

void SAL_CALL CMimeContentType::trailer( void )
{
    while( m_nxtSym.getLength( ) )
    {
        if ( m_nxtSym == OUString::createFromAscii( "(" ) )
        {
            getSym( );
            comment( );
            acceptSym( OUString::createFromAscii( ")" ) );
        }
        else if ( m_nxtSym == OUString::createFromAscii( ";" ) )
        {
            // get the parameter name
            getSym( );
            skipSpaces( );

            if ( !isInRange( m_nxtSym, TOKEN ) )
                throw IllegalArgumentException( );

            OUString pname = pName( );

            skipSpaces();
            acceptSym( OUString::createFromAscii( "=" ) );

            // get the parameter value
            skipSpaces( );

            OUString pvalue = pValue( );

            // insert into map
            if ( !m_ParameterMap.insert( pair < const OUString, OUString > ( pname, pvalue ) ).second )
                throw IllegalArgumentException( );
        }
        else
            throw IllegalArgumentException( );

        skipSpaces( );
    }
}

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

OUString SAL_CALL CMimeContentType::pName( )
{
    OUString pname;

    while( m_nxtSym.getLength( ) )
    {
        if ( isInRange( m_nxtSym, TOKEN ) )
            pname += m_nxtSym;
        else if ( isInRange( m_nxtSym, OUString::createFromAscii( "= " ) ) )
            break;
        else
            throw IllegalArgumentException( );
        getSym( );
    }

    return pname;
}

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

OUString SAL_CALL CMimeContentType::pValue( )
{
    OUString pvalue;

    // quoted pvalue
    if ( m_nxtSym == OUString::createFromAscii( "\"" ) )
    {
        getSym( );
        pvalue = quotedPValue( );

        if (  OUString( &pvalue[pvalue.getLength() - 1], 1 ) != OUString::createFromAscii( "\"" ) )
            throw IllegalArgumentException( );

        // remove the last quote-sign
        OUString qpvalue( pvalue, pvalue.getLength( ) - 1 );
        pvalue = qpvalue;

        if ( !pvalue.getLength( ) )
            throw IllegalArgumentException( );
    }
    else if ( isInRange( m_nxtSym, TOKEN ) ) // unquoted pvalue
    {
        pvalue = nonquotedPValue( );
    }
    else
        throw IllegalArgumentException( );

    return pvalue;
}

//------------------------------------------------------------------------
// the following combinations within a quoted value are not allowed:
// '";' (quote sign followed by semicolon) and '" ' (quote sign followed
// by space)
//------------------------------------------------------------------------

OUString SAL_CALL CMimeContentType::quotedPValue( )
{
    OUString pvalue;
    sal_Bool bAfterQuoteSign = sal_False;

    while ( m_nxtSym.getLength( ) )
    {
        if ( bAfterQuoteSign && ((m_nxtSym == SPACE)||(m_nxtSym == SEMICOLON) ) )
            break;
        else if ( isInRange( m_nxtSym, TOKEN + TSPECIALS + SPACE ) )
        {
            pvalue += m_nxtSym;
            if ( m_nxtSym == OUString::createFromAscii( "\"" ) )
                bAfterQuoteSign = sal_True;
            else
                bAfterQuoteSign = sal_False;
        }
        else
            throw IllegalArgumentException( );
        getSym( );
    }

    return pvalue;
}

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

OUString SAL_CALL CMimeContentType::nonquotedPValue( )
{
    OUString pvalue;

    while ( m_nxtSym.getLength( ) )
    {
        if ( isInRange( m_nxtSym, TOKEN ) )
            pvalue += m_nxtSym;
        else if ( isInRange( m_nxtSym, OUString::createFromAscii( "; " ) ) )
            break;
        else
            throw IllegalArgumentException( );
        getSym( );
    }

    return pvalue;
}

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

void SAL_CALL CMimeContentType::comment( void )
{
    while ( m_nxtSym.getLength( ) )
    {
        if ( isInRange( m_nxtSym, TOKEN + SPACE ) )
            getSym( );
        else if ( m_nxtSym == OUString::createFromAscii( ")" ) )
            break;
        else
            throw IllegalArgumentException( );
    }
}

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

sal_Bool SAL_CALL CMimeContentType::isInRange( const rtl::OUString& aChr, const rtl::OUString& aRange )
{
    return ( aRange.indexOf( aChr ) > -1 );
}<commit_msg>INTEGRATION: CWS rt02 (1.4.102); FILE MERGED 2003/10/01 12:05:56 rt 1.4.102.1: #i19697# No newline at end of file<commit_after>/*************************************************************************
 *
 *  $RCSfile: mcnttype.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2003-10-06 14:36:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _MCNTTYPE_HXX_
#include "mcnttype.hxx"
#endif

//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace rtl;
using namespace std;
using namespace osl;

//------------------------------------------------------------------------
// constants
//------------------------------------------------------------------------

const OUString TSPECIALS = OUString::createFromAscii( "()<>@,;:\\\"/[]?=" );
const OUString TOKEN     = OUString::createFromAscii( "!#$%&'*+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~." );
const OUString SPACE     = OUString::createFromAscii( " " );
const OUString SEMICOLON = OUString::createFromAscii( ";" );

//------------------------------------------------------------------------
// ctor
//------------------------------------------------------------------------

CMimeContentType::CMimeContentType( const OUString& aCntType )
{
    init( aCntType );
}

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

OUString SAL_CALL CMimeContentType::getMediaType( ) throw(RuntimeException)
{
    return m_MediaType;
}

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

OUString SAL_CALL CMimeContentType::getMediaSubtype( ) throw(RuntimeException)
{
    return m_MediaSubtype;
}

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

OUString SAL_CALL CMimeContentType::getFullMediaType( ) throw(RuntimeException)
{
    return m_MediaType + OUString::createFromAscii( "/" ) + m_MediaSubtype;
}

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

Sequence< OUString > SAL_CALL CMimeContentType::getParameters( ) throw(RuntimeException)
{
    MutexGuard aGuard( m_aMutex );

    Sequence< OUString > seqParams;

    map< OUString, OUString >::iterator iter;
    map< OUString, OUString >::iterator iter_end = m_ParameterMap.end( );

    for ( iter = m_ParameterMap.begin( ); iter != iter_end; ++iter )
    {
        seqParams.realloc( seqParams.getLength( ) + 1 );
        seqParams[seqParams.getLength( ) - 1] = iter->first;
    }

    return seqParams;
}

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

sal_Bool SAL_CALL CMimeContentType::hasParameter( const OUString& aName ) throw(RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return ( m_ParameterMap.end( ) != m_ParameterMap.find( aName ) );
}

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

OUString SAL_CALL CMimeContentType::getParameterValue( const OUString& aName ) throw(NoSuchElementException, RuntimeException)
{
    MutexGuard aGuard( m_aMutex );

    if ( !hasParameter( aName ) )
        throw NoSuchElementException( );

    return m_ParameterMap.find( aName )->second;
}

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

void SAL_CALL CMimeContentType::init( const OUString& aCntType ) throw( IllegalArgumentException )
{
    if ( !aCntType.getLength( ) )
        throw IllegalArgumentException( );

    m_nPos = 0;
    m_ContentType = aCntType;
    getSym( );
    type();
}

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

void SAL_CALL CMimeContentType::getSym( void )
{
    if ( m_nPos < m_ContentType.getLength( ) )
    {
        m_nxtSym = OUString( &m_ContentType[m_nPos], 1 );
        ++m_nPos;
        return;
    }

    m_nxtSym = OUString( );
}

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

void SAL_CALL CMimeContentType::acceptSym( const OUString& pSymTlb )
{
    if ( pSymTlb.indexOf( m_nxtSym ) < 0 )
        throw IllegalArgumentException( );

    getSym();
}

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

void SAL_CALL CMimeContentType::skipSpaces( void )
{
    while ( SPACE == m_nxtSym )
        getSym( );
}

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

void SAL_CALL CMimeContentType::type( void )
{
    skipSpaces( );

    // check FIRST( type )
    if ( !isInRange( m_nxtSym, TOKEN ) )
        throw IllegalArgumentException( );

    // parse
    while(  m_nxtSym.getLength( ) )
    {
        if ( isInRange( m_nxtSym, TOKEN ) )
            m_MediaType += m_nxtSym;
        else if ( isInRange( m_nxtSym, OUString::createFromAscii( "/ " ) ) )
            break;
        else
            throw IllegalArgumentException( );
        getSym( );
    }

    // check FOLLOW( type )
    skipSpaces( );
    acceptSym( OUString::createFromAscii( "/" ) );

    subtype( );
}

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

void SAL_CALL CMimeContentType::subtype( void )
{
    skipSpaces( );

    // check FIRST( subtype )
    if ( !isInRange( m_nxtSym, TOKEN ) )
        throw IllegalArgumentException( );

    while( m_nxtSym.getLength( ) )
    {
        if ( isInRange( m_nxtSym, TOKEN ) )
            m_MediaSubtype += m_nxtSym;
        else if ( isInRange( m_nxtSym, OUString::createFromAscii( "; " ) ) )
            break;
        else
            throw IllegalArgumentException( );
        getSym( );
    }

    // parse the rest
    skipSpaces( );
    trailer();
}

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

void SAL_CALL CMimeContentType::trailer( void )
{
    while( m_nxtSym.getLength( ) )
    {
        if ( m_nxtSym == OUString::createFromAscii( "(" ) )
        {
            getSym( );
            comment( );
            acceptSym( OUString::createFromAscii( ")" ) );
        }
        else if ( m_nxtSym == OUString::createFromAscii( ";" ) )
        {
            // get the parameter name
            getSym( );
            skipSpaces( );

            if ( !isInRange( m_nxtSym, TOKEN ) )
                throw IllegalArgumentException( );

            OUString pname = pName( );

            skipSpaces();
            acceptSym( OUString::createFromAscii( "=" ) );

            // get the parameter value
            skipSpaces( );

            OUString pvalue = pValue( );

            // insert into map
            if ( !m_ParameterMap.insert( pair < const OUString, OUString > ( pname, pvalue ) ).second )
                throw IllegalArgumentException( );
        }
        else
            throw IllegalArgumentException( );

        skipSpaces( );
    }
}

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

OUString SAL_CALL CMimeContentType::pName( )
{
    OUString pname;

    while( m_nxtSym.getLength( ) )
    {
        if ( isInRange( m_nxtSym, TOKEN ) )
            pname += m_nxtSym;
        else if ( isInRange( m_nxtSym, OUString::createFromAscii( "= " ) ) )
            break;
        else
            throw IllegalArgumentException( );
        getSym( );
    }

    return pname;
}

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

OUString SAL_CALL CMimeContentType::pValue( )
{
    OUString pvalue;

    // quoted pvalue
    if ( m_nxtSym == OUString::createFromAscii( "\"" ) )
    {
        getSym( );
        pvalue = quotedPValue( );

        if (  OUString( &pvalue[pvalue.getLength() - 1], 1 ) != OUString::createFromAscii( "\"" ) )
            throw IllegalArgumentException( );

        // remove the last quote-sign
        OUString qpvalue( pvalue, pvalue.getLength( ) - 1 );
        pvalue = qpvalue;

        if ( !pvalue.getLength( ) )
            throw IllegalArgumentException( );
    }
    else if ( isInRange( m_nxtSym, TOKEN ) ) // unquoted pvalue
    {
        pvalue = nonquotedPValue( );
    }
    else
        throw IllegalArgumentException( );

    return pvalue;
}

//------------------------------------------------------------------------
// the following combinations within a quoted value are not allowed:
// '";' (quote sign followed by semicolon) and '" ' (quote sign followed
// by space)
//------------------------------------------------------------------------

OUString SAL_CALL CMimeContentType::quotedPValue( )
{
    OUString pvalue;
    sal_Bool bAfterQuoteSign = sal_False;

    while ( m_nxtSym.getLength( ) )
    {
        if ( bAfterQuoteSign && ((m_nxtSym == SPACE)||(m_nxtSym == SEMICOLON) ) )
            break;
        else if ( isInRange( m_nxtSym, TOKEN + TSPECIALS + SPACE ) )
        {
            pvalue += m_nxtSym;
            if ( m_nxtSym == OUString::createFromAscii( "\"" ) )
                bAfterQuoteSign = sal_True;
            else
                bAfterQuoteSign = sal_False;
        }
        else
            throw IllegalArgumentException( );
        getSym( );
    }

    return pvalue;
}

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

OUString SAL_CALL CMimeContentType::nonquotedPValue( )
{
    OUString pvalue;

    while ( m_nxtSym.getLength( ) )
    {
        if ( isInRange( m_nxtSym, TOKEN ) )
            pvalue += m_nxtSym;
        else if ( isInRange( m_nxtSym, OUString::createFromAscii( "; " ) ) )
            break;
        else
            throw IllegalArgumentException( );
        getSym( );
    }

    return pvalue;
}

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

void SAL_CALL CMimeContentType::comment( void )
{
    while ( m_nxtSym.getLength( ) )
    {
        if ( isInRange( m_nxtSym, TOKEN + SPACE ) )
            getSym( );
        else if ( m_nxtSym == OUString::createFromAscii( ")" ) )
            break;
        else
            throw IllegalArgumentException( );
    }
}

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

sal_Bool SAL_CALL CMimeContentType::isInRange( const rtl::OUString& aChr, const rtl::OUString& aRange )
{
    return ( aRange.indexOf( aChr ) > -1 );
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <stdexcept>

#include <dlfcn.h>

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include <QApplication>
#include <QMainWindow>
#include <QMenu>
#include <QAction>
#include <QKeyEvent>
#include <QHBoxLayout>

#include <dependency_graph/graph.h>
#include <dependency_graph/node_base.inl>
#include <dependency_graph/datablock.inl>
#include <dependency_graph/metadata.inl>
#include <dependency_graph/attr.inl>

#include <qt_node_editor/node.h>
#include <qt_node_editor/connected_edge.h>
#include <qt_node_editor/graph_widget.h>

#include <possumwood_sdk/app.h>
#include <possumwood_sdk/gl.h>

#include "adaptor.h"
#include "main_window.h"
#include "gl_init.h"

namespace po = boost::program_options;
namespace fs = boost::filesystem;

using std::cout;
using std::endl;
using std::flush;

#ifndef PLUGIN_DIR
#define PLUGIN_DIR "./plugins"
#endif

int main(int argc, char* argv[]) {
	// // Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "produce help message")
		("plugin_directory", po::value<std::string>()->default_value(PLUGIN_DIR),
			"directory to search for plugins")
		("scene", po::value<std::string>(), "open a scene file")
	;

	// process the options
	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if(vm.count("help")) {
		cout << desc << "\n";
		return 1;
	}

	///////////////////////////////

	std::vector<void*> pluginHandles;

	// scan for plugins
	for(fs::directory_iterator itr(vm["plugin_directory"].as<std::string>());
	    itr != fs::directory_iterator(); ++itr) {
		if(fs::is_regular_file(itr->status()) && itr->path().extension() == ".so") {
			void* ptr = dlopen(itr->path().string().c_str(), RTLD_NOW);
			if(ptr)
				pluginHandles.push_back(ptr);
			else
				std::cout << dlerror() << std::endl;
		}
	}

	///////////////////////////////

	{
		GL_CHECK_ERR;

		{
			QSurfaceFormat format = QSurfaceFormat::defaultFormat();
			// way higher than currently supported - will fall back to highest
			format.setVersion(6, 0);
			format.setProfile(QSurfaceFormat::CoreProfile);

			format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);

			QSurfaceFormat::setDefaultFormat(format);
		}

		// create the application object
		QApplication app(argc, argv);

		GL_CHECK_ERR;

		// create the possumwood application
		possumwood::App papp;

		GL_CHECK_ERR;

		// make a main window
		MainWindow win;
		win.setWindowIcon(QIcon(":icons/app.png"));
		win.showMaximized();

		GL_CHECK_ERR;

		std::cout << "OpenGL version supported by this platform is "
		          << glGetString(GL_VERSION) << std::endl;

		GL_CHECK_ERR;

		// open the scene file, if specified on the command line
		if(vm.count("scene"))
			possumwood::App::instance().loadFile(boost::filesystem::path(vm["scene"].as<std::string>()));

		GL_CHECK_ERR;

		// and start the main application loop
		app.exec();

		GL_CHECK_ERR;
	}

	////////////////////////////////

	// unload all plugins
	while(!pluginHandles.empty()) {
		dlclose(pluginHandles.back());
		pluginHandles.pop_back();
	}

	return 0;
}
<commit_msg>Fixed HighDPI icons throughout the application (yay!)<commit_after>#include <iostream>
#include <string>
#include <stdexcept>

#include <dlfcn.h>

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include <QApplication>
#include <QMainWindow>
#include <QMenu>
#include <QAction>
#include <QKeyEvent>
#include <QHBoxLayout>

#include <dependency_graph/graph.h>
#include <dependency_graph/node_base.inl>
#include <dependency_graph/datablock.inl>
#include <dependency_graph/metadata.inl>
#include <dependency_graph/attr.inl>

#include <qt_node_editor/node.h>
#include <qt_node_editor/connected_edge.h>
#include <qt_node_editor/graph_widget.h>

#include <possumwood_sdk/app.h>
#include <possumwood_sdk/gl.h>

#include "adaptor.h"
#include "main_window.h"
#include "gl_init.h"

namespace po = boost::program_options;
namespace fs = boost::filesystem;

using std::cout;
using std::endl;
using std::flush;

#ifndef PLUGIN_DIR
#define PLUGIN_DIR "./plugins"
#endif

int main(int argc, char* argv[]) {
	// // Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "produce help message")
		("plugin_directory", po::value<std::string>()->default_value(PLUGIN_DIR),
			"directory to search for plugins")
		("scene", po::value<std::string>(), "open a scene file")
	;

	// process the options
	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if(vm.count("help")) {
		cout << desc << "\n";
		return 1;
	}

	///////////////////////////////

	std::vector<void*> pluginHandles;

	// scan for plugins
	for(fs::directory_iterator itr(vm["plugin_directory"].as<std::string>());
	    itr != fs::directory_iterator(); ++itr) {
		if(fs::is_regular_file(itr->status()) && itr->path().extension() == ".so") {
			void* ptr = dlopen(itr->path().string().c_str(), RTLD_NOW);
			if(ptr)
				pluginHandles.push_back(ptr);
			else
				std::cout << dlerror() << std::endl;
		}
	}

	///////////////////////////////

	{
		GL_CHECK_ERR;

		{
			QSurfaceFormat format = QSurfaceFormat::defaultFormat();
			// way higher than currently supported - will fall back to highest
			format.setVersion(6, 0);
			format.setProfile(QSurfaceFormat::CoreProfile);

			format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);

			QSurfaceFormat::setDefaultFormat(format);
		}

		// create the application object
		QApplication app(argc, argv);
		QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
		QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);

		GL_CHECK_ERR;

		// create the possumwood application
		possumwood::App papp;

		GL_CHECK_ERR;

		// make a main window
		MainWindow win;
		win.setWindowIcon(QIcon(":icons/app.png"));
		win.showMaximized();

		GL_CHECK_ERR;

		std::cout << "OpenGL version supported by this platform is "
		          << glGetString(GL_VERSION) << std::endl;

		GL_CHECK_ERR;

		// open the scene file, if specified on the command line
		if(vm.count("scene"))
			possumwood::App::instance().loadFile(boost::filesystem::path(vm["scene"].as<std::string>()));

		GL_CHECK_ERR;

		// and start the main application loop
		app.exec();

		GL_CHECK_ERR;
	}

	////////////////////////////////

	// unload all plugins
	while(!pluginHandles.empty()) {
		dlclose(pluginHandles.back());
		pluginHandles.pop_back();
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library 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.
 *
 * Olad.cpp
 * Main file for olad, parses the options, forks if required and runs the
 * daemon.
 * Copyright (C) 2005-2007 Simon Newton
 *
 */

#if HAVE_CONFIG_H
#  include <config.h>
#endif

#include <getopt.h>
#include <iostream>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sysexits.h>
#include <unistd.h>

#include <memory>

#include "ola/Logging.h"
#include "ola/base/Init.h"
#include "ola/base/Credentials.h"
#include "olad/OlaDaemon.h"

using ola::OlaDaemon;
using std::string;
using std::cout;
using std::cerr;
using std::endl;

// the daemon
OlaDaemon *global_olad = NULL;

// options struct
typedef struct {
  ola::log_level level;
  ola::log_output output;
  bool daemon;
  bool help;
  bool version;
  int httpd;
  int http_quit;
  int http_port;
  int rpc_port;
  string http_data_dir;
  string config_dir;
  string interface;
} ola_options;

/*
 * Terminate cleanly on interrupt
 */
static void sig_interupt(int signo) {
  if (global_olad)
    global_olad->Terminate();
  (void) signo;
}

/*
 * Reload plugins
 */
static void sig_hup(int signo) {
  if (global_olad)
    global_olad->ReloadPlugins();
  (void) signo;
}

/*
 * Change logging level
 *
 * need to fix race conditions here
 */
static void sig_user1(int signo) {
  ola::IncrementLogLevel();
  (void) signo;
}

/*
 * Set up the signal handlers.
 * @return true on success, false on failure
 */
static bool InstallSignals() {
  if (!ola::InstallSignal(SIGINT, sig_interupt))
    return false;

  if (!ola::InstallSignal(SIGTERM, sig_interupt))
    return false;

  if (!ola::InstallSignal(SIGHUP, sig_hup))
    return false;

  if (!ola::InstallSignal(SIGUSR1, sig_user1))
    return false;
  return true;
}

/*
 * Display the help message
 */
static void DisplayHelp() {
  cout <<
  "Usage: olad [options]\n"
  "\n"
  "Start the OLA Daemon.\n"
  "\n"
  "  -c, --config-dir         Path to the config directory\n"
  "  -d, --http-data-dir      Path to the static content.\n"
  "  -f, --daemon             Fork into background.\n"
  "  -h, --help               Display this help message and exit.\n"
  "  -i, --interface <interface name|ip> Network interface to use.\n"
  "  -l, --log-level <level>  Set the logging level 0 .. 4 .\n"
  "  -p, --http-port          Port to run the http server on (default " <<
    ola::OlaServer::DEFAULT_HTTP_PORT << ")\n" <<
  "  -r, --rpc-port           Port to listen for RPCs on (default " <<
    ola::OlaDaemon::DEFAULT_RPC_PORT << ")\n" <<
  "  -s, --syslog             Log to syslog rather than stderr.\n"
  "  -v, --version            Print the version number\n"
  "  --no-http                Don't run the http server\n"
  "  --no-http-quit           Disable the /quit handler\n"
  << endl;
}

/*
 * Parse the command line options
 *
 * @param argc
 * @param argv
 * @param opts  pointer to the options struct
 */
static bool ParseOptions(int argc, char *argv[], ola_options *opts) {
  static struct option long_options[] = {
      {"config-dir", required_argument, 0, 'c'},
      {"help", no_argument, 0, 'h'},
      {"http-data-dir", required_argument, 0, 'd'},
      {"http-port", required_argument, 0, 'p'},
      {"interface", required_argument, 0, 'i'},
      {"log-level", required_argument, 0, 'l'},
      {"no-daemon", no_argument, 0, 'f'},
      {"no-http", no_argument, &opts->httpd, 0},
      {"no-http-quit", no_argument, &opts->http_quit, 0},
      {"rpc-port", required_argument, 0, 'r'},
      {"syslog", no_argument, 0, 's'},
      {"version", no_argument, 0, 'v'},
      {0, 0, 0, 0}
    };

  bool options_valid = true;
  int c, ll;
  int option_index = 0;

  while (1) {
    c = getopt_long(argc,
                    argv,
                    "c:d:fhi:l:p:r:sv",
                    long_options,
                    &option_index);
    if (c == -1)
      break;

    switch (c) {
      case 0:
        break;
      case 'c':
        opts->config_dir = optarg;
        break;
      case 'd':
        opts->http_data_dir = optarg;
        break;
      case 'f':
        opts->daemon = true;
        break;
      case 'h':
        opts->help = true;
        break;
      case 'i':
        opts->interface = optarg;
        break;
      case 's':
        opts->output = ola::OLA_LOG_SYSLOG;
        break;
      case 'l':
        ll = atoi(optarg);
        switch (ll) {
          case 0:
            // nothing is written at this level
            // so this turns logging off
            opts->level = ola::OLA_LOG_NONE;
            break;
          case 1:
            opts->level = ola::OLA_LOG_FATAL;
            break;
          case 2:
            opts->level = ola::OLA_LOG_WARN;
            break;
          case 3:
            opts->level = ola::OLA_LOG_INFO;
            break;
          case 4:
            opts->level = ola::OLA_LOG_DEBUG;
            break;
          default :
            cerr << "Invalid log level " << optarg << endl;
            options_valid = false;
            break;
        }
        break;
      case 'p':
        opts->http_port = atoi(optarg);
        break;
      case 'r':
        opts->rpc_port = atoi(optarg);
        break;
      case 'v':
        opts->version = true;
        break;
      case '?':
        break;
      default:
       break;
    }
  }
  return options_valid;
}

/*
 * Parse the options, and take action
 *
 * @param argc
 * @param argv
 * @param opts a pointer to the ola_options struct
 */
static void Setup(int argc, char*argv[], ola_options *opts) {
  opts->level = ola::OLA_LOG_WARN;
  opts->output = ola::OLA_LOG_STDERR;
  opts->daemon = false;
  opts->help = false;
  opts->version = false;
  opts->httpd = 1;
  opts->http_quit = 1;
  opts->http_port = ola::OlaServer::DEFAULT_HTTP_PORT;
  opts->rpc_port = ola::OlaDaemon::DEFAULT_RPC_PORT;
  opts->http_data_dir = "";
  opts->config_dir = "";
  opts->interface = "";

  if (!ParseOptions(argc, argv, opts)) {
    DisplayHelp();
    exit(EX_USAGE);
  }

  if (opts->help) {
    DisplayHelp();
    exit(EX_OK);
  }

  if (opts->version) {
    cout << "OLA Daemon version " << VERSION << endl;
    exit(EX_OK);
  }

  // setup the logging
  ola::InitLogging(opts->level, opts->output);
  OLA_INFO << "OLA Daemon version " << VERSION;

  if (opts->daemon)
    ola::Daemonise();
}

/*
 * Main
 */
int main(int argc, char *argv[]) {
  ola_options opts;
  ola::ExportMap export_map;
  Setup(argc, argv, &opts);

  #ifndef OLAD_SKIP_ROOT_CHECK
  if (!ola::GetEUID()) {
    OLA_FATAL << "Attempting to run as root, aborting.";
    return EX_UNAVAILABLE;
  }
  #endif

  ola::ServerInit(argc, argv, &export_map);

  if (!InstallSignals())
    OLA_WARN << "Failed to install signal handlers";

  ola::ola_server_options ola_options;
  ola_options.http_enable = opts.httpd;
  ola_options.http_enable_quit = opts.http_quit;
  ola_options.http_port = opts.http_port;
  ola_options.http_data_dir = opts.http_data_dir;
  ola_options.interface = opts.interface;

  std::auto_ptr<OlaDaemon> olad(
      new OlaDaemon(ola_options, &export_map, opts.rpc_port, opts.config_dir));
  if (olad.get() && olad->Init()) {
    global_olad = olad.get();
    olad->Run();
    return EX_OK;
  }
  global_olad = NULL;
  return EX_UNAVAILABLE;
}
<commit_msg> * fix the daemon command line option<commit_after>/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library 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.
 *
 * Olad.cpp
 * Main file for olad, parses the options, forks if required and runs the
 * daemon.
 * Copyright (C) 2005-2007 Simon Newton
 *
 */

#if HAVE_CONFIG_H
#  include <config.h>
#endif

#include <getopt.h>
#include <iostream>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sysexits.h>
#include <unistd.h>

#include <memory>

#include "ola/Logging.h"
#include "ola/base/Init.h"
#include "ola/base/Credentials.h"
#include "olad/OlaDaemon.h"

using ola::OlaDaemon;
using std::string;
using std::cout;
using std::cerr;
using std::endl;

// the daemon
OlaDaemon *global_olad = NULL;

// options struct
typedef struct {
  ola::log_level level;
  ola::log_output output;
  bool daemon;
  bool help;
  bool version;
  int httpd;
  int http_quit;
  int http_port;
  int rpc_port;
  string http_data_dir;
  string config_dir;
  string interface;
} ola_options;

/*
 * Terminate cleanly on interrupt
 */
static void sig_interupt(int signo) {
  if (global_olad)
    global_olad->Terminate();
  (void) signo;
}

/*
 * Reload plugins
 */
static void sig_hup(int signo) {
  if (global_olad)
    global_olad->ReloadPlugins();
  (void) signo;
}

/*
 * Change logging level
 *
 * need to fix race conditions here
 */
static void sig_user1(int signo) {
  ola::IncrementLogLevel();
  (void) signo;
}

/*
 * Set up the signal handlers.
 * @return true on success, false on failure
 */
static bool InstallSignals() {
  if (!ola::InstallSignal(SIGINT, sig_interupt))
    return false;

  if (!ola::InstallSignal(SIGTERM, sig_interupt))
    return false;

  if (!ola::InstallSignal(SIGHUP, sig_hup))
    return false;

  if (!ola::InstallSignal(SIGUSR1, sig_user1))
    return false;
  return true;
}

/*
 * Display the help message
 */
static void DisplayHelp() {
  cout <<
  "Usage: olad [options]\n"
  "\n"
  "Start the OLA Daemon.\n"
  "\n"
  "  -c, --config-dir         Path to the config directory\n"
  "  -d, --http-data-dir      Path to the static content.\n"
  "  -f, --daemon             Fork into background.\n"
  "  -h, --help               Display this help message and exit.\n"
  "  -i, --interface <interface name|ip> Network interface to use.\n"
  "  -l, --log-level <level>  Set the logging level 0 .. 4 .\n"
  "  -p, --http-port          Port to run the http server on (default " <<
    ola::OlaServer::DEFAULT_HTTP_PORT << ")\n" <<
  "  -r, --rpc-port           Port to listen for RPCs on (default " <<
    ola::OlaDaemon::DEFAULT_RPC_PORT << ")\n" <<
  "  -s, --syslog             Log to syslog rather than stderr.\n"
  "  -v, --version            Print the version number\n"
  "  --no-http                Don't run the http server\n"
  "  --no-http-quit           Disable the /quit handler\n"
  << endl;
}

/*
 * Parse the command line options
 *
 * @param argc
 * @param argv
 * @param opts  pointer to the options struct
 */
static bool ParseOptions(int argc, char *argv[], ola_options *opts) {
  static struct option long_options[] = {
      {"config-dir", required_argument, 0, 'c'},
      {"help", no_argument, 0, 'h'},
      {"http-data-dir", required_argument, 0, 'd'},
      {"http-port", required_argument, 0, 'p'},
      {"interface", required_argument, 0, 'i'},
      {"log-level", required_argument, 0, 'l'},
      {"daemon", no_argument, 0, 'f'},
      {"no-http", no_argument, &opts->httpd, 0},
      {"no-http-quit", no_argument, &opts->http_quit, 0},
      {"rpc-port", required_argument, 0, 'r'},
      {"syslog", no_argument, 0, 's'},
      {"version", no_argument, 0, 'v'},
      {0, 0, 0, 0}
    };

  bool options_valid = true;
  int c, ll;
  int option_index = 0;

  while (1) {
    c = getopt_long(argc,
                    argv,
                    "c:d:fhi:l:p:r:sv",
                    long_options,
                    &option_index);
    if (c == -1)
      break;

    switch (c) {
      case 0:
        break;
      case 'c':
        opts->config_dir = optarg;
        break;
      case 'd':
        opts->http_data_dir = optarg;
        break;
      case 'f':
        opts->daemon = true;
        break;
      case 'h':
        opts->help = true;
        break;
      case 'i':
        opts->interface = optarg;
        break;
      case 's':
        opts->output = ola::OLA_LOG_SYSLOG;
        break;
      case 'l':
        ll = atoi(optarg);
        switch (ll) {
          case 0:
            // nothing is written at this level
            // so this turns logging off
            opts->level = ola::OLA_LOG_NONE;
            break;
          case 1:
            opts->level = ola::OLA_LOG_FATAL;
            break;
          case 2:
            opts->level = ola::OLA_LOG_WARN;
            break;
          case 3:
            opts->level = ola::OLA_LOG_INFO;
            break;
          case 4:
            opts->level = ola::OLA_LOG_DEBUG;
            break;
          default :
            cerr << "Invalid log level " << optarg << endl;
            options_valid = false;
            break;
        }
        break;
      case 'p':
        opts->http_port = atoi(optarg);
        break;
      case 'r':
        opts->rpc_port = atoi(optarg);
        break;
      case 'v':
        opts->version = true;
        break;
      case '?':
        break;
      default:
       break;
    }
  }
  return options_valid;
}

/*
 * Parse the options, and take action
 *
 * @param argc
 * @param argv
 * @param opts a pointer to the ola_options struct
 */
static void Setup(int argc, char*argv[], ola_options *opts) {
  opts->level = ola::OLA_LOG_WARN;
  opts->output = ola::OLA_LOG_STDERR;
  opts->daemon = false;
  opts->help = false;
  opts->version = false;
  opts->httpd = 1;
  opts->http_quit = 1;
  opts->http_port = ola::OlaServer::DEFAULT_HTTP_PORT;
  opts->rpc_port = ola::OlaDaemon::DEFAULT_RPC_PORT;
  opts->http_data_dir = "";
  opts->config_dir = "";
  opts->interface = "";

  if (!ParseOptions(argc, argv, opts)) {
    DisplayHelp();
    exit(EX_USAGE);
  }

  if (opts->help) {
    DisplayHelp();
    exit(EX_OK);
  }

  if (opts->version) {
    cout << "OLA Daemon version " << VERSION << endl;
    exit(EX_OK);
  }

  // setup the logging
  ola::InitLogging(opts->level, opts->output);
  OLA_INFO << "OLA Daemon version " << VERSION;

  if (opts->daemon)
    ola::Daemonise();
}

/*
 * Main
 */
int main(int argc, char *argv[]) {
  ola_options opts;
  ola::ExportMap export_map;
  Setup(argc, argv, &opts);

  #ifndef OLAD_SKIP_ROOT_CHECK
  if (!ola::GetEUID()) {
    OLA_FATAL << "Attempting to run as root, aborting.";
    return EX_UNAVAILABLE;
  }
  #endif

  ola::ServerInit(argc, argv, &export_map);

  if (!InstallSignals())
    OLA_WARN << "Failed to install signal handlers";

  ola::ola_server_options ola_options;
  ola_options.http_enable = opts.httpd;
  ola_options.http_enable_quit = opts.http_quit;
  ola_options.http_port = opts.http_port;
  ola_options.http_data_dir = opts.http_data_dir;
  ola_options.interface = opts.interface;

  std::auto_ptr<OlaDaemon> olad(
      new OlaDaemon(ola_options, &export_map, opts.rpc_port, opts.config_dir));
  if (olad.get() && olad->Init()) {
    global_olad = olad.get();
    olad->Run();
    return EX_OK;
  }
  global_olad = NULL;
  return EX_UNAVAILABLE;
}
<|endoftext|>


<commit_before>// [AsmJit]
// Complete x86/x64 JIT and Remote Assembler for C++.
//
// [License]
// Zlib - See LICENSE.md file in the package.

// [Export]
#define ASMJIT_EXPORTS

// [Dependencies - AsmJit]
#include "../base/cputicks.h"

// [Dependencies - Posix]
#if defined(ASMJIT_OS_POSIX)
# include <time.h>
# include <unistd.h>
#endif // ASMJIT_OS_POSIX

// [Dependencies - Mac]
#if defined(ASMJIT_OS_MAC)
# include <mach/mach_time.h>
#endif // ASMJIT_OS_MAC

// [Api-Begin]
#include "../apibegin.h"

namespace asmjit {

// ============================================================================
// [asmjit::CpuTicks - Windows]
// ============================================================================

#if defined(ASMJIT_OS_WINDOWS)
static volatile uint32_t CpuTicks_hiResOk;
static volatile double CpuTicks_hiResFreq;

uint32_t CpuTicks::now() {
  do {
    uint32_t hiResOk = CpuTicks_hiResOk;

    if (hiResOk == 1) {
      LARGE_INTEGER now;
      if (!::QueryPerformanceCounter(&now))
        break;
      return (int64_t)(double(now.QuadPart) / CpuTicks_hiResFreq);
    }

    if (hiResOk == 0) {
      LARGE_INTEGER qpf;
      if (!::QueryPerformanceFrequency(&qpf)) {
        _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0);
        break;
      }

      LARGE_INTEGER now;
      if (!::QueryPerformanceCounter(&now)) {
        _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0);
        break;
      }

      double freqDouble = double(qpf.QuadPart) / 1000.0;

      CpuTicks_hiResFreq = freqDouble;
      _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 1, 0);

      return static_cast<uint32_t>(
        static_cast<int64_t>(double(now.QuadPart) / freqDouble) & 0xFFFFFFFF);
    }
  } while (0);

  // Bail to mmsystem.
  return ::GetTickCount();
}

// ============================================================================
// [asmjit::CpuTicks - Mac]
// ============================================================================

#elif defined(ASMJIT_OS_MAC)
static mach_timebase_info_data_t CpuTicks_machTime;

uint32_t CpuTicks::now() {
  // Initialize the first time CpuTicks::now() is called (See Apple's QA1398).
  if (CpuTicks_machTime.denom == 0) {
    if (mach_timebase_info(&CpuTicks_machTime) != KERN_SUCCESS);
      return 0;
  }

  // mach_absolute_time() returns nanoseconds, we need just milliseconds.
  uint64_t t = mach_absolute_time() / 1000000;

  t = t * CpuTicks_machTime.numer / CpuTicks_machTime.denom;
  return static_cast<uint32_t>(t & 0xFFFFFFFFU)
}

// ============================================================================
// [asmjit::CpuTicks - Posix]
// ============================================================================

#else
uint32_t CpuTicks::now() {
#if defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
  struct timespec ts;

  if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
    return 0;

  uint64_t t = (uint64_t(ts.tv_sec ) * 1000) + (uint64_t(ts.tv_nsec) / 1000000);
  return static_cast<uint32_t>(t & 0xFFFFFFFFU);
#else  // _POSIX_MONOTONIC_CLOCK
#error "AsmJit - Unsupported OS."
  return 0;
#endif  // _POSIX_MONOTONIC_CLOCK
}
#endif // ASMJIT_OS

} // asmjit namespace

// [Api-End]
#include "../apiend.h"
<commit_msg>Fix typo<commit_after>// [AsmJit]
// Complete x86/x64 JIT and Remote Assembler for C++.
//
// [License]
// Zlib - See LICENSE.md file in the package.

// [Export]
#define ASMJIT_EXPORTS

// [Dependencies - AsmJit]
#include "../base/cputicks.h"

// [Dependencies - Posix]
#if defined(ASMJIT_OS_POSIX)
# include <time.h>
# include <unistd.h>
#endif // ASMJIT_OS_POSIX

// [Dependencies - Mac]
#if defined(ASMJIT_OS_MAC)
# include <mach/mach_time.h>
#endif // ASMJIT_OS_MAC

// [Api-Begin]
#include "../apibegin.h"

namespace asmjit {

// ============================================================================
// [asmjit::CpuTicks - Windows]
// ============================================================================

#if defined(ASMJIT_OS_WINDOWS)
static volatile uint32_t CpuTicks_hiResOk;
static volatile double CpuTicks_hiResFreq;

uint32_t CpuTicks::now() {
  do {
    uint32_t hiResOk = CpuTicks_hiResOk;

    if (hiResOk == 1) {
      LARGE_INTEGER now;
      if (!::QueryPerformanceCounter(&now))
        break;
      return (int64_t)(double(now.QuadPart) / CpuTicks_hiResFreq);
    }

    if (hiResOk == 0) {
      LARGE_INTEGER qpf;
      if (!::QueryPerformanceFrequency(&qpf)) {
        _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0);
        break;
      }

      LARGE_INTEGER now;
      if (!::QueryPerformanceCounter(&now)) {
        _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0);
        break;
      }

      double freqDouble = double(qpf.QuadPart) / 1000.0;

      CpuTicks_hiResFreq = freqDouble;
      _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 1, 0);

      return static_cast<uint32_t>(
        static_cast<int64_t>(double(now.QuadPart) / freqDouble) & 0xFFFFFFFF);
    }
  } while (0);

  // Bail to mmsystem.
  return ::GetTickCount();
}

// ============================================================================
// [asmjit::CpuTicks - Mac]
// ============================================================================

#elif defined(ASMJIT_OS_MAC)
static mach_timebase_info_data_t CpuTicks_machTime;

uint32_t CpuTicks::now() {
  // Initialize the first time CpuTicks::now() is called (See Apple's QA1398).
  if (CpuTicks_machTime.denom == 0) {
    if (mach_timebase_info(&CpuTicks_machTime) != KERN_SUCCESS);
      return 0;
  }

  // mach_absolute_time() returns nanoseconds, we need just milliseconds.
  uint64_t t = mach_absolute_time() / 1000000;

  t = t * CpuTicks_machTime.numer / CpuTicks_machTime.denom;
  return static_cast<uint32_t>(t & 0xFFFFFFFFU);
}

// ============================================================================
// [asmjit::CpuTicks - Posix]
// ============================================================================

#else
uint32_t CpuTicks::now() {
#if defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
  struct timespec ts;

  if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
    return 0;

  uint64_t t = (uint64_t(ts.tv_sec ) * 1000) + (uint64_t(ts.tv_nsec) / 1000000);
  return static_cast<uint32_t>(t & 0xFFFFFFFFU);
#else  // _POSIX_MONOTONIC_CLOCK
#error "AsmJit - Unsupported OS."
  return 0;
#endif  // _POSIX_MONOTONIC_CLOCK
}
#endif // ASMJIT_OS

} // asmjit namespace

// [Api-End]
#include "../apiend.h"
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "srciter.hxx"
#include <stdio.h>
#include <tools/fsys.hxx>

//
// class SourceTreeIterator
//

/*****************************************************************************/
SourceTreeIterator::SourceTreeIterator(
    const ByteString &rRootDirectory, const ByteString &rVersion , bool bLocal_in )
/*****************************************************************************/
                : bInExecute( sal_False ) , bLocal( bLocal_in )
{
    (void) rVersion ;

    if(!bLocal){
        rtl::OUString sRootDirectory( rRootDirectory.GetBuffer() , rRootDirectory.Len() , RTL_TEXTENCODING_UTF8 );
        aRootDirectory = transex::Directory( sRootDirectory );
    }
}

/*****************************************************************************/
SourceTreeIterator::~SourceTreeIterator()
/*****************************************************************************/
{
}

/*****************************************************************************/
void SourceTreeIterator::ExecuteDirectory( transex::Directory& aDirectory )
/*****************************************************************************/
{
    if ( bInExecute ) {
        rtl::OUString sDirName = aDirectory.getDirectoryName();

        static rtl::OUString WCARD1 ( rtl::OUString::createFromAscii( "unxlng" ) );
        static rtl::OUString WCARD2 ( rtl::OUString::createFromAscii( "unxsol" ) );
        static rtl::OUString WCARD3 ( rtl::OUString::createFromAscii( "wntmsc" ) );
        static rtl::OUString WCARD4 ( rtl::OUString::createFromAscii( "common" ) );
        static rtl::OUString WCARD5 ( rtl::OUString::createFromAscii( "unxmac" ) );
        static rtl::OUString WCARD6 ( rtl::OUString::createFromAscii( "unxubt" ) );
        static rtl::OUString WCARD7 ( rtl::OUString::createFromAscii( ".svn" ) );

        if( sDirName.indexOf( WCARD1 , 0 ) > -1 ||
            sDirName.indexOf( WCARD2 , 0 ) > -1 ||
            sDirName.indexOf( WCARD3 , 0 ) > -1 ||
            sDirName.indexOf( WCARD4 , 0 ) > -1 ||
            sDirName.indexOf( WCARD5 , 0 ) > -1 ||
            sDirName.indexOf( WCARD6 , 0 ) > -1 ||
            sDirName.indexOf( WCARD7 , 0 ) > -1
           )    return;
        //printf("**** %s \n", OUStringToOString( sDirName , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() );

        rtl::OUString sDirNameTmp = aDirectory.getFullName();
        ByteString sDirNameTmpB( rtl::OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() );

#ifdef WNT
        sDirNameTmpB.Append( ByteString("\\no_localization") );
#else
        sDirNameTmpB.Append( ByteString("/no_localization") );
#endif
        //printf("**** %s \n", OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() );

        DirEntry aDE( sDirNameTmpB.GetBuffer() );
        if( aDE.Exists() )
        {
            //printf("#### no_localization file found ... skipping");
            return;
        }

        aDirectory.setSkipLinks( bSkipLinks );
        aDirectory.readDirectory();
        OnExecuteDirectory( aDirectory.getFullName() );
        if ( aDirectory.getSubDirectories().size() )
            for ( sal_uLong i=0;i < aDirectory.getSubDirectories().size();i++ )
                ExecuteDirectory( aDirectory.getSubDirectories()[ i ] );
    }
}

/*****************************************************************************/
sal_Bool SourceTreeIterator::StartExecute()
/*****************************************************************************/
{

    bInExecute = sal_True;                  // FIXME
    ExecuteDirectory( aRootDirectory );

    if ( bInExecute ) {                 // FIXME
        bInExecute = sal_False;
        return sal_True;
    }
    return sal_False;
}

/*****************************************************************************/
void SourceTreeIterator::EndExecute()
/*****************************************************************************/
{
    bInExecute = sal_False;
}

/*****************************************************************************/
void SourceTreeIterator::OnExecuteDirectory( const rtl::OUString &rDirectory )
/*****************************************************************************/
{
    fprintf( stdout, "%s\n", rtl::OUStringToOString( rDirectory, RTL_TEXTENCODING_UTF8, rDirectory.getLength() ).getStr() );
}
<commit_msg>masterfix DEV300: skip .hg subdirs<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "srciter.hxx"
#include <stdio.h>
#include <tools/fsys.hxx>

//
// class SourceTreeIterator
//

/*****************************************************************************/
SourceTreeIterator::SourceTreeIterator(
    const ByteString &rRootDirectory, const ByteString &rVersion , bool bLocal_in )
/*****************************************************************************/
                : bInExecute( sal_False ) , bLocal( bLocal_in )
{
    (void) rVersion ;

    if(!bLocal){
        rtl::OUString sRootDirectory( rRootDirectory.GetBuffer() , rRootDirectory.Len() , RTL_TEXTENCODING_UTF8 );
        aRootDirectory = transex::Directory( sRootDirectory );
    }
}

/*****************************************************************************/
SourceTreeIterator::~SourceTreeIterator()
/*****************************************************************************/
{
}

/*****************************************************************************/
void SourceTreeIterator::ExecuteDirectory( transex::Directory& aDirectory )
/*****************************************************************************/
{
    if ( bInExecute ) {
        rtl::OUString sDirName = aDirectory.getDirectoryName();

        static rtl::OUString WCARD1 ( rtl::OUString::createFromAscii( "unxlng" ) );
        static rtl::OUString WCARD2 ( rtl::OUString::createFromAscii( "unxsol" ) );
        static rtl::OUString WCARD3 ( rtl::OUString::createFromAscii( "wntmsc" ) );
        static rtl::OUString WCARD4 ( rtl::OUString::createFromAscii( "common" ) );
        static rtl::OUString WCARD5 ( rtl::OUString::createFromAscii( "unxmac" ) );
        static rtl::OUString WCARD6 ( rtl::OUString::createFromAscii( "unxubt" ) );
        static rtl::OUString WCARD7 ( rtl::OUString::createFromAscii( ".svn" ) );
        static rtl::OUString WCARD8 ( rtl::OUString::createFromAscii( ".hg" ) );

        if( sDirName.indexOf( WCARD1 , 0 ) > -1 ||
            sDirName.indexOf( WCARD2 , 0 ) > -1 ||
            sDirName.indexOf( WCARD3 , 0 ) > -1 ||
            sDirName.indexOf( WCARD4 , 0 ) > -1 ||
            sDirName.indexOf( WCARD5 , 0 ) > -1 ||
            sDirName.indexOf( WCARD6 , 0 ) > -1 ||
            sDirName.indexOf( WCARD7 , 0 ) > -1 ||
            sDirName.indexOf( WCARD8 , 0 ) > -1
           )    return;
        //printf("**** %s \n", OUStringToOString( sDirName , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() );

        rtl::OUString sDirNameTmp = aDirectory.getFullName();
        ByteString sDirNameTmpB( rtl::OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() );

#ifdef WNT
        sDirNameTmpB.Append( ByteString("\\no_localization") );
#else
        sDirNameTmpB.Append( ByteString("/no_localization") );
#endif
        //printf("**** %s \n", OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() );

        DirEntry aDE( sDirNameTmpB.GetBuffer() );
        if( aDE.Exists() )
        {
            //printf("#### no_localization file found ... skipping");
            return;
        }

        aDirectory.setSkipLinks( bSkipLinks );
        aDirectory.readDirectory();
        OnExecuteDirectory( aDirectory.getFullName() );
        if ( aDirectory.getSubDirectories().size() )
            for ( sal_uLong i=0;i < aDirectory.getSubDirectories().size();i++ )
                ExecuteDirectory( aDirectory.getSubDirectories()[ i ] );
    }
}

/*****************************************************************************/
sal_Bool SourceTreeIterator::StartExecute()
/*****************************************************************************/
{

    bInExecute = sal_True;                  // FIXME
    ExecuteDirectory( aRootDirectory );

    if ( bInExecute ) {                 // FIXME
        bInExecute = sal_False;
        return sal_True;
    }
    return sal_False;
}

/*****************************************************************************/
void SourceTreeIterator::EndExecute()
/*****************************************************************************/
{
    bInExecute = sal_False;
}

/*****************************************************************************/
void SourceTreeIterator::OnExecuteDirectory( const rtl::OUString &rDirectory )
/*****************************************************************************/
{
    fprintf( stdout, "%s\n", rtl::OUStringToOString( rDirectory, RTL_TEXTENCODING_UTF8, rDirectory.getLength() ).getStr() );
}
<|endoftext|>