<commit_before>#include "LiquidCrystal.h"

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "WProgram.h"

// When the display powers up, it is configured as follows:
//
// 1. Display clear
// 2. Function set:
//    DL = 1; 8-bit interface data
//    N = 0; 1-line display
//    F = 0; 5x8 dot character font
// 3. Display on/off control:
//    D = 0; Display off
//    C = 0; Cursor off
//    B = 0; Blinking off
// 4. Entry mode set:
//    I/D = 1; Increment by 1
//    S = 0; No shift
//
// Note, however, that resetting the Arduino doesn't reset the LCD, so we
// can't assume that its in that state when a sketch starts (and the
// LiquidCrystal constructor is called).

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
			     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
  init(0, rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7);
}

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
			     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
  init(0, rs, 255, enable, d0, d1, d2, d3, d4, d5, d6, d7);
}

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)
{
  init(1, rs, rw, enable, d0, d1, d2, d3, 0, 0, 0, 0);
}

LiquidCrystal::LiquidCrystal(uint8_t rs,  uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)
{
  init(1, rs, 255, enable, d0, d1, d2, d3, 0, 0, 0, 0);
}

void LiquidCrystal::init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable,
			 uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
			 uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
  _rs_pin = rs;
  _rw_pin = rw;
  _enable_pin = enable;

  _data_pins[0] = d0;
  _data_pins[1] = d1;
  _data_pins[2] = d2;
  _data_pins[3] = d3;
  _data_pins[4] = d4;
  _data_pins[5] = d5;
  _data_pins[6] = d6;
  _data_pins[7] = d7;

  pinMode(_rs_pin, OUTPUT);
  // we can save 1 pin by not using RW. Indicate by passing 255 instead of pin#
  if (_rw_pin != 255) {
    pinMode(_rw_pin, OUTPUT);
  }
  pinMode(_enable_pin, OUTPUT);

  if (fourbitmode)
    _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS;
  else
    _displayfunction = LCD_8BITMODE | LCD_1LINE | LCD_5x8DOTS;

  begin(16, 1);
}

void LiquidCrystal::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) {
  if (lines > 1) {
    _displayfunction |= LCD_2LINE;
  }
  _numlines = lines;
  _currline = 0;

  // for some 1 line displays you can select a 10 pixel high font
  if ((dotsize != 0) && (lines == 1)) {
    _displayfunction |= LCD_5x10DOTS;
  }

  // SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION!
  // according to datasheet, we need at least 40ms after power rises above 2.7V
  // before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50
  delayMicroseconds(50000);
  // Now we pull both RS and R/W low to begin commands
  digitalWrite(_rs_pin, LOW);
  digitalWrite(_enable_pin, LOW);
  if (_rw_pin != 255) {
    digitalWrite(_rw_pin, LOW);
  }

  //put the LCD into 4 bit or 8 bit mode
  if (! (_displayfunction & LCD_8BITMODE)) {
    // this is according to the hitachi HD44780 datasheet
    // figure 24, pg 46

    // we start in 8bit mode, try to set 4 bit mode
    write4bits(0x03);
    delayMicroseconds(4500); // wait min 4.1ms

    // second try
    write4bits(0x03);
    delayMicroseconds(4500); // wait min 4.1ms

    // third go!
    write4bits(0x03);
    delayMicroseconds(150);

    // finally, set to 8-bit interface
    write4bits(0x02);
  } else {
    // this is according to the hitachi HD44780 datasheet
    // page 45 figure 23

    // Send function set command sequence
    command(LCD_FUNCTIONSET | _displayfunction);
    delayMicroseconds(4500);  // wait more than 4.1ms

    // second try
    command(LCD_FUNCTIONSET | _displayfunction);
    delayMicroseconds(150);

    // third go
    command(LCD_FUNCTIONSET | _displayfunction);
  }

  // finally, set # lines, font size, etc.
  command(LCD_FUNCTIONSET | _displayfunction);

  // turn the display on with no cursor or blinking default
  _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF;
  display();

  // clear it off
  clear();

  // Initialize to default text direction (for romance languages)
  _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT;
  // set the entry mode
  command(LCD_ENTRYMODESET | _displaymode);

}

/********** high level commands, for the user! */
void LiquidCrystal::clear()
{
  command(LCD_CLEARDISPLAY);  // clear display, set cursor position to zero
  delayMicroseconds(2000);  // this command takes a long time!
}

void LiquidCrystal::home()
{
  command(LCD_RETURNHOME);  // set cursor position to zero
  delayMicroseconds(2000);  // this command takes a long time!
}

void LiquidCrystal::setCursor(uint8_t col, uint8_t row)
{
  int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 };
  if ( row > _numlines ) {
    row = _numlines-1;    // we count rows starting w/0
  }

  command(LCD_SETDDRAMADDR | (col + row_offsets[row]));
}

// Turn the display on/off (quickly)
void LiquidCrystal::noDisplay() {
  _displaycontrol &= ~LCD_DISPLAYON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LiquidCrystal::display() {
  _displaycontrol |= LCD_DISPLAYON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// Turns the underline cursor on/off
void LiquidCrystal::noCursor() {
  _displaycontrol &= ~LCD_CURSORON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LiquidCrystal::cursor() {
  _displaycontrol |= LCD_CURSORON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// Turn on and off the blinking cursor
void LiquidCrystal::noBlink() {
  _displaycontrol &= ~LCD_BLINKON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LiquidCrystal::blink() {
  _displaycontrol |= LCD_BLINKON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// These commands scroll the display without changing the RAM
void LiquidCrystal::scrollDisplayLeft(void) {
  command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT);
}
void LiquidCrystal::scrollDisplayRight(void) {
  command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT);
}

// This is for text that flows Left to Right
void LiquidCrystal::leftToRight(void) {
  _displaymode |= LCD_ENTRYLEFT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// This is for text that flows Right to Left
void LiquidCrystal::rightToLeft(void) {
  _displaymode &= ~LCD_ENTRYLEFT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// This will 'right justify' text from the cursor
void LiquidCrystal::autoscroll(void) {
  _displaymode |= LCD_ENTRYSHIFTINCREMENT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// This will 'left justify' text from the cursor
void LiquidCrystal::noAutoscroll(void) {
  _displaymode &= ~LCD_ENTRYSHIFTINCREMENT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// Allows us to fill the first 8 CGRAM locations
// with custom characters
void LiquidCrystal::createChar(uint8_t location, uint8_t charmap[]) {
  location &= 0x7; // we only have 8 locations 0-7
  command(LCD_SETCGRAMADDR | (location << 3));
  for (int i=0; i<8; i++) {
    write(charmap[i]);
  }
}

/*********** mid level commands, for sending data/cmds */

inline void LiquidCrystal::command(uint8_t value) {
  send(value, LOW);
}

inline void LiquidCrystal::write(uint8_t value) {
  send(value, HIGH);
}

/************ low level data pushing commands **********/

// write either command or data, with automatic 4/8-bit selection
void LiquidCrystal::send(uint8_t value, uint8_t mode) {
  digitalWrite(_rs_pin, mode);

  // if there is a RW pin indicated, set it low to Write
  if (_rw_pin != 255) {
    digitalWrite(_rw_pin, LOW);
  }

  if (_displayfunction & LCD_8BITMODE) {
    write8bits(value);
  } else {
    write4bits(value>>4);
    write4bits(value);
  }
}

void LiquidCrystal::pulseEnable(void) {
  digitalWrite(_enable_pin, LOW);
  delayMicroseconds(1);
  digitalWrite(_enable_pin, HIGH);
  delayMicroseconds(1);    // enable pulse must be >450ns
  digitalWrite(_enable_pin, LOW);
  delayMicroseconds(100);   // commands need > 37us to settle
}

void LiquidCrystal::write4bits(uint8_t value) {
  for (int i = 0; i < 4; i++) {
    pinMode(_data_pins[i], OUTPUT);
    digitalWrite(_data_pins[i], (value >> i) & 0x01);
  }

  pulseEnable();
}

void LiquidCrystal::write8bits(uint8_t value) {
  for (int i = 0; i < 8; i++) {
    pinMode(_data_pins[i], OUTPUT);
    digitalWrite(_data_pins[i], (value >> i) & 0x01);
  }

  pulseEnable();
}
<commit_msg>When initializing LCD, comment specified "8-bit" mode when it should day "4 bit mode"<commit_after>#include "LiquidCrystal.h"

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "WProgram.h"

// When the display powers up, it is configured as follows:
//
// 1. Display clear
// 2. Function set:
//    DL = 1; 8-bit interface data
//    N = 0; 1-line display
//    F = 0; 5x8 dot character font
// 3. Display on/off control:
//    D = 0; Display off
//    C = 0; Cursor off
//    B = 0; Blinking off
// 4. Entry mode set:
//    I/D = 1; Increment by 1
//    S = 0; No shift
//
// Note, however, that resetting the Arduino doesn't reset the LCD, so we
// can't assume that its in that state when a sketch starts (and the
// LiquidCrystal constructor is called).

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
			     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
  init(0, rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7);
}

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
			     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
  init(0, rs, 255, enable, d0, d1, d2, d3, d4, d5, d6, d7);
}

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)
{
  init(1, rs, rw, enable, d0, d1, d2, d3, 0, 0, 0, 0);
}

LiquidCrystal::LiquidCrystal(uint8_t rs,  uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)
{
  init(1, rs, 255, enable, d0, d1, d2, d3, 0, 0, 0, 0);
}

void LiquidCrystal::init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable,
			 uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
			 uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
  _rs_pin = rs;
  _rw_pin = rw;
  _enable_pin = enable;

  _data_pins[0] = d0;
  _data_pins[1] = d1;
  _data_pins[2] = d2;
  _data_pins[3] = d3;
  _data_pins[4] = d4;
  _data_pins[5] = d5;
  _data_pins[6] = d6;
  _data_pins[7] = d7;

  pinMode(_rs_pin, OUTPUT);
  // we can save 1 pin by not using RW. Indicate by passing 255 instead of pin#
  if (_rw_pin != 255) {
    pinMode(_rw_pin, OUTPUT);
  }
  pinMode(_enable_pin, OUTPUT);

  if (fourbitmode)
    _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS;
  else
    _displayfunction = LCD_8BITMODE | LCD_1LINE | LCD_5x8DOTS;

  begin(16, 1);
}

void LiquidCrystal::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) {
  if (lines > 1) {
    _displayfunction |= LCD_2LINE;
  }
  _numlines = lines;
  _currline = 0;

  // for some 1 line displays you can select a 10 pixel high font
  if ((dotsize != 0) && (lines == 1)) {
    _displayfunction |= LCD_5x10DOTS;
  }

  // SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION!
  // according to datasheet, we need at least 40ms after power rises above 2.7V
  // before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50
  delayMicroseconds(50000);
  // Now we pull both RS and R/W low to begin commands
  digitalWrite(_rs_pin, LOW);
  digitalWrite(_enable_pin, LOW);
  if (_rw_pin != 255) {
    digitalWrite(_rw_pin, LOW);
  }

  //put the LCD into 4 bit or 8 bit mode
  if (! (_displayfunction & LCD_8BITMODE)) {
    // this is according to the hitachi HD44780 datasheet
    // figure 24, pg 46

    // we start in 8bit mode, try to set 4 bit mode
    write4bits(0x03);
    delayMicroseconds(4500); // wait min 4.1ms

    // second try
    write4bits(0x03);
    delayMicroseconds(4500); // wait min 4.1ms

    // third go!
    write4bits(0x03);
    delayMicroseconds(150);

    // finally, set to 4-bit interface
    write4bits(0x02);
  } else {
    // this is according to the hitachi HD44780 datasheet
    // page 45 figure 23

    // Send function set command sequence
    command(LCD_FUNCTIONSET | _displayfunction);
    delayMicroseconds(4500);  // wait more than 4.1ms

    // second try
    command(LCD_FUNCTIONSET | _displayfunction);
    delayMicroseconds(150);

    // third go
    command(LCD_FUNCTIONSET | _displayfunction);
  }

  // finally, set # lines, font size, etc.
  command(LCD_FUNCTIONSET | _displayfunction);

  // turn the display on with no cursor or blinking default
  _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF;
  display();

  // clear it off
  clear();

  // Initialize to default text direction (for romance languages)
  _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT;
  // set the entry mode
  command(LCD_ENTRYMODESET | _displaymode);

}

/********** high level commands, for the user! */
void LiquidCrystal::clear()
{
  command(LCD_CLEARDISPLAY);  // clear display, set cursor position to zero
  delayMicroseconds(2000);  // this command takes a long time!
}

void LiquidCrystal::home()
{
  command(LCD_RETURNHOME);  // set cursor position to zero
  delayMicroseconds(2000);  // this command takes a long time!
}

void LiquidCrystal::setCursor(uint8_t col, uint8_t row)
{
  int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 };
  if ( row > _numlines ) {
    row = _numlines-1;    // we count rows starting w/0
  }

  command(LCD_SETDDRAMADDR | (col + row_offsets[row]));
}

// Turn the display on/off (quickly)
void LiquidCrystal::noDisplay() {
  _displaycontrol &= ~LCD_DISPLAYON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LiquidCrystal::display() {
  _displaycontrol |= LCD_DISPLAYON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// Turns the underline cursor on/off
void LiquidCrystal::noCursor() {
  _displaycontrol &= ~LCD_CURSORON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LiquidCrystal::cursor() {
  _displaycontrol |= LCD_CURSORON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// Turn on and off the blinking cursor
void LiquidCrystal::noBlink() {
  _displaycontrol &= ~LCD_BLINKON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LiquidCrystal::blink() {
  _displaycontrol |= LCD_BLINKON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// These commands scroll the display without changing the RAM
void LiquidCrystal::scrollDisplayLeft(void) {
  command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT);
}
void LiquidCrystal::scrollDisplayRight(void) {
  command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT);
}

// This is for text that flows Left to Right
void LiquidCrystal::leftToRight(void) {
  _displaymode |= LCD_ENTRYLEFT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// This is for text that flows Right to Left
void LiquidCrystal::rightToLeft(void) {
  _displaymode &= ~LCD_ENTRYLEFT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// This will 'right justify' text from the cursor
void LiquidCrystal::autoscroll(void) {
  _displaymode |= LCD_ENTRYSHIFTINCREMENT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// This will 'left justify' text from the cursor
void LiquidCrystal::noAutoscroll(void) {
  _displaymode &= ~LCD_ENTRYSHIFTINCREMENT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// Allows us to fill the first 8 CGRAM locations
// with custom characters
void LiquidCrystal::createChar(uint8_t location, uint8_t charmap[]) {
  location &= 0x7; // we only have 8 locations 0-7
  command(LCD_SETCGRAMADDR | (location << 3));
  for (int i=0; i<8; i++) {
    write(charmap[i]);
  }
}

/*********** mid level commands, for sending data/cmds */

inline void LiquidCrystal::command(uint8_t value) {
  send(value, LOW);
}

inline void LiquidCrystal::write(uint8_t value) {
  send(value, HIGH);
}

/************ low level data pushing commands **********/

// write either command or data, with automatic 4/8-bit selection
void LiquidCrystal::send(uint8_t value, uint8_t mode) {
  digitalWrite(_rs_pin, mode);

  // if there is a RW pin indicated, set it low to Write
  if (_rw_pin != 255) {
    digitalWrite(_rw_pin, LOW);
  }

  if (_displayfunction & LCD_8BITMODE) {
    write8bits(value);
  } else {
    write4bits(value>>4);
    write4bits(value);
  }
}

void LiquidCrystal::pulseEnable(void) {
  digitalWrite(_enable_pin, LOW);
  delayMicroseconds(1);
  digitalWrite(_enable_pin, HIGH);
  delayMicroseconds(1);    // enable pulse must be >450ns
  digitalWrite(_enable_pin, LOW);
  delayMicroseconds(100);   // commands need > 37us to settle
}

void LiquidCrystal::write4bits(uint8_t value) {
  for (int i = 0; i < 4; i++) {
    pinMode(_data_pins[i], OUTPUT);
    digitalWrite(_data_pins[i], (value >> i) & 0x01);
  }

  pulseEnable();
}

void LiquidCrystal::write8bits(uint8_t value) {
  for (int i = 0; i < 8; i++) {
    pinMode(_data_pins[i], OUTPUT);
    digitalWrite(_data_pins[i], (value >> i) & 0x01);
  }

  pulseEnable();
}
<|endoftext|>


<commit_before>// $Id: fe_hermite_shape_3D.C,v 1.3 2005-09-02 18:48:55 roystgnr Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2005  Benjamin S. Kirk, John W. Peterson

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

// 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

// C++ inlcludes

// Local includes
#include "fe.h"
#include "elem.h"

// Anonymous namespace for persistant variables.
// This allows us to cache the global-to-local mapping transformation
// FIXME: This should also screw up multithreading royally
namespace
{
  static unsigned int old_elem_id = libMesh::invalid_uint;
  static std::vector<std::vector<Real> > dxdxi(3, std::vector<Real>(2, 0));
#ifdef DEBUG
  static std::vector<Real> dydxi(2), dzdeta(2), dxdzeta(2);
  static std::vector<Real> dzdxi(2), dxdeta(2), dydzeta(2);
#endif

// Compute the static coefficients for an element
void hermite_compute_coefs(const Elem* elem)
{
  // Coefficients are cached from old elements
  if (elem->id() == old_elem_id)
    return;

  old_elem_id = elem->id();

  const Order mapping_order        (elem->default_order());
  const ElemType mapping_elem_type (elem->type());
  const int n_mapping_shape_functions =
    FE<3,LAGRANGE>::n_shape_functions(mapping_elem_type,
				      mapping_order);

  std::vector<Point> dofpt;
  dofpt.push_back(Point(-1,-1,-1));
  dofpt.push_back(Point(1,1,1));

  for (int p = 0; p != 2; ++p)
    {
      dxdxi[0][p] = 0;
      dxdxi[1][p] = 0;
      dxdxi[2][p] = 0;
#ifdef DEBUG
      dydxi[p] = 0;
      dzdeta[p] = 0;
      dxdzeta[p] = 0;
      dzdxi[p] = 0;
      dxdeta[p] = 0;
      dydzeta[p] = 0;
#endif
      for (int i = 0; i != n_mapping_shape_functions; ++i)
        {
          const Real ddxi = FE<3,LAGRANGE>::shape_deriv
            (mapping_elem_type, mapping_order, i, 0, dofpt[p]);
          const Real ddeta = FE<3,LAGRANGE>::shape_deriv
            (mapping_elem_type, mapping_order, i, 1, dofpt[p]);
          const Real ddzeta = FE<3,LAGRANGE>::shape_deriv
            (mapping_elem_type, mapping_order, i, 2, dofpt[p]);

	  // dxdeta, dxdzeta, dydxi, dydzeta, dzdxi, dzdeta should all
          // be 0!
          dxdxi[0][p] += elem->point(i)(0) * ddxi;
          dxdxi[1][p] += elem->point(i)(1) * ddeta;
          dxdxi[2][p] += elem->point(i)(2) * ddzeta;
#ifdef DEBUG
          dydxi[p] += elem->point(i)(1) * ddxi;
          dzdeta[p] += elem->point(i)(2) * ddeta;
          dxdzeta[p] += elem->point(i)(0) * ddzeta;
          dzdxi[p] += elem->point(i)(2) * ddxi;
          dxdeta[p] += elem->point(i)(0) * ddeta;
          dydzeta[p] += elem->point(i)(1) * ddzeta;
#endif
        }
      // No singular elements!
      assert(dxdxi[0][p]);
      assert(dxdxi[1][p]);
      assert(dxdxi[2][p]);
      // No non-rectilinear or non-axis-aligned elements!
#ifdef DEBUG
      assert(std::abs(dydxi[p]) < 1e-9);
      assert(std::abs(dzdeta[p]) < 1e-9);
      assert(std::abs(dxdzeta[p]) < 1e-9);
      assert(std::abs(dzdxi[p]) < 1e-9);
      assert(std::abs(dxdeta[p]) < 1e-9);
      assert(std::abs(dydzeta[p]) < 1e-9);
#endif
    }
}

} // end anonymous namespace

template <>
Real FE<3,HERMITE>::shape(const ElemType,
			  const Order,
			  const unsigned int,
			  const Point&)
{
  std::cerr << "Hermite elements require the real element\n"
	    << "to construct gradient-based degrees of freedom."
	    << std::endl;

  error();
  return 0.;
}

template <>
Real FE<3,HERMITE>::shape(const Elem* elem,
			  const Order order,
			  const unsigned int i,
			  const Point& p)
{
  assert (elem != NULL);

  hermite_compute_coefs(elem);

  const ElemType type = elem->type();

  switch (order)
    {
      // 3rd-order tricubic Hermite functions
    case THIRD:
      {
	switch (type)
	  {
	  case HEX8:
	  case HEX20:
	  case HEX27:
	    {
	      assert (i<64);

              std::vector<unsigned int> bases1D;

              Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);

	      return coef *
                     FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                     FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                     FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
	    }
	  default:
            std::cerr << "ERROR: Unsupported element type!" << std::endl;
	    error();
	  }
      }
      // by default throw an error
    default:
      std::cerr << "ERROR: Unsupported polynomial order!" << std::endl;
      error();
    }

  error();
  return 0.;
}

template <>
Real FE<3,HERMITE>::shape_deriv(const ElemType,
				const Order,
				const unsigned int,
				const unsigned int,
				const Point&)
{
  std::cerr << "Hermite elements require the real element\n"
	    << "to construct gradient-based degrees of freedom."
	    << std::endl;

  error();
  return 0.;
}

template <>
Real FE<3,HERMITE>::shape_deriv(const Elem* elem,
				const Order order,
				const unsigned int i,
				const unsigned int j,
				const Point& p)
{
  assert (elem != NULL);
  assert (j == 0 || j == 1 || j == 2);

  hermite_compute_coefs(elem);

  const ElemType type = elem->type();

  switch (order)
    {
      // 3rd-order tricubic Hermite functions
    case THIRD:
      {
	switch (type)
	  {
	  case HEX8:
	  case HEX20:
	  case HEX27:
	    {
	      assert (i<64);

              std::vector<unsigned int> bases1D;

              Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);

              switch (j) // Derivative type
		{
		case 0:
                  return coef *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
                  break;
		case 1:
                  return coef *
                    FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
                  break;
		case 2:
                  return coef *
                    FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));
                  break;
                }

	    }
	  default:
            std::cerr << "ERROR: Unsupported element type!" << std::endl;
	    error();
	  }
      }
      // by default throw an error
    default:
      std::cerr << "ERROR: Unsupported polynomial order!" << std::endl;
      error();
    }

  error();
  return 0.;
}

template <>
Real FE<3,HERMITE>::shape_second_deriv(const Elem* elem,
                                      const Order order,
                                      const unsigned int i,
                                      const unsigned int j,
                                      const Point& p)
{
  assert (elem != NULL);

  hermite_compute_coefs(elem);

  const ElemType type = elem->type();

  switch (order)
    {
      // 3rd-order tricubic Hermite functions
    case THIRD:
      {
	switch (type)
	  {
	  case HEX8:
	  case HEX20:
	  case HEX27:
	    {
	      assert (i<64);

              std::vector<unsigned int> bases1D;

              Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);

              switch (j) // Derivative type
		{
		case 0:
                  return coef *
                    FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
                  break;
		case 1:
                  return coef *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
                  break;
		case 2:
                  return coef *
                    FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
                  break;
		case 3:
                  return coef *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));
                  break;
		case 4:
                  return coef *
                    FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));
                  break;
		case 5:
                  return coef *
                    FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[2],p(2));
                  break;
                }

	    }
	  default:
            std::cerr << "ERROR: Unsupported element type!" << std::endl;
	    error();
	  }
      }
      // by default throw an error
    default:
      std::cerr << "ERROR: Unsupported polynomial order!" << std::endl;
      error();
    }

  error();
  return 0.;
}
<commit_msg>Fixed broken yy derivative calculation<commit_after>// $Id: fe_hermite_shape_3D.C,v 1.4 2006-02-22 22:30:53 roystgnr Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2005  Benjamin S. Kirk, John W. Peterson

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

// 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

// C++ inlcludes

// Local includes
#include "fe.h"
#include "elem.h"

// Anonymous namespace for persistant variables.
// This allows us to cache the global-to-local mapping transformation
// FIXME: This should also screw up multithreading royally
namespace
{
  static unsigned int old_elem_id = libMesh::invalid_uint;
  static std::vector<std::vector<Real> > dxdxi(3, std::vector<Real>(2, 0));
#ifdef DEBUG
  static std::vector<Real> dydxi(2), dzdeta(2), dxdzeta(2);
  static std::vector<Real> dzdxi(2), dxdeta(2), dydzeta(2);
#endif

// Compute the static coefficients for an element
void hermite_compute_coefs(const Elem* elem)
{
  // Coefficients are cached from old elements
  if (elem->id() == old_elem_id)
    return;

  old_elem_id = elem->id();

  const Order mapping_order        (elem->default_order());
  const ElemType mapping_elem_type (elem->type());
  const int n_mapping_shape_functions =
    FE<3,LAGRANGE>::n_shape_functions(mapping_elem_type,
				      mapping_order);

  std::vector<Point> dofpt;
  dofpt.push_back(Point(-1,-1,-1));
  dofpt.push_back(Point(1,1,1));

  for (int p = 0; p != 2; ++p)
    {
      dxdxi[0][p] = 0;
      dxdxi[1][p] = 0;
      dxdxi[2][p] = 0;
#ifdef DEBUG
      dydxi[p] = 0;
      dzdeta[p] = 0;
      dxdzeta[p] = 0;
      dzdxi[p] = 0;
      dxdeta[p] = 0;
      dydzeta[p] = 0;
#endif
      for (int i = 0; i != n_mapping_shape_functions; ++i)
        {
          const Real ddxi = FE<3,LAGRANGE>::shape_deriv
            (mapping_elem_type, mapping_order, i, 0, dofpt[p]);
          const Real ddeta = FE<3,LAGRANGE>::shape_deriv
            (mapping_elem_type, mapping_order, i, 1, dofpt[p]);
          const Real ddzeta = FE<3,LAGRANGE>::shape_deriv
            (mapping_elem_type, mapping_order, i, 2, dofpt[p]);

	  // dxdeta, dxdzeta, dydxi, dydzeta, dzdxi, dzdeta should all
          // be 0!
          dxdxi[0][p] += elem->point(i)(0) * ddxi;
          dxdxi[1][p] += elem->point(i)(1) * ddeta;
          dxdxi[2][p] += elem->point(i)(2) * ddzeta;
#ifdef DEBUG
          dydxi[p] += elem->point(i)(1) * ddxi;
          dzdeta[p] += elem->point(i)(2) * ddeta;
          dxdzeta[p] += elem->point(i)(0) * ddzeta;
          dzdxi[p] += elem->point(i)(2) * ddxi;
          dxdeta[p] += elem->point(i)(0) * ddeta;
          dydzeta[p] += elem->point(i)(1) * ddzeta;
#endif
        }
      // No singular elements!
      assert(dxdxi[0][p]);
      assert(dxdxi[1][p]);
      assert(dxdxi[2][p]);
      // No non-rectilinear or non-axis-aligned elements!
#ifdef DEBUG
      assert(std::abs(dydxi[p]) < 1e-9);
      assert(std::abs(dzdeta[p]) < 1e-9);
      assert(std::abs(dxdzeta[p]) < 1e-9);
      assert(std::abs(dzdxi[p]) < 1e-9);
      assert(std::abs(dxdeta[p]) < 1e-9);
      assert(std::abs(dydzeta[p]) < 1e-9);
#endif
    }
}

} // end anonymous namespace

template <>
Real FE<3,HERMITE>::shape(const ElemType,
			  const Order,
			  const unsigned int,
			  const Point&)
{
  std::cerr << "Hermite elements require the real element\n"
	    << "to construct gradient-based degrees of freedom."
	    << std::endl;

  error();
  return 0.;
}

template <>
Real FE<3,HERMITE>::shape(const Elem* elem,
			  const Order order,
			  const unsigned int i,
			  const Point& p)
{
  assert (elem != NULL);

  hermite_compute_coefs(elem);

  const ElemType type = elem->type();

  switch (order)
    {
      // 3rd-order tricubic Hermite functions
    case THIRD:
      {
	switch (type)
	  {
	  case HEX8:
	  case HEX20:
	  case HEX27:
	    {
	      assert (i<64);

              std::vector<unsigned int> bases1D;

              Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);

	      return coef *
                     FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                     FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                     FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
	    }
	  default:
            std::cerr << "ERROR: Unsupported element type!" << std::endl;
	    error();
	  }
      }
      // by default throw an error
    default:
      std::cerr << "ERROR: Unsupported polynomial order!" << std::endl;
      error();
    }

  error();
  return 0.;
}

template <>
Real FE<3,HERMITE>::shape_deriv(const ElemType,
				const Order,
				const unsigned int,
				const unsigned int,
				const Point&)
{
  std::cerr << "Hermite elements require the real element\n"
	    << "to construct gradient-based degrees of freedom."
	    << std::endl;

  error();
  return 0.;
}

template <>
Real FE<3,HERMITE>::shape_deriv(const Elem* elem,
				const Order order,
				const unsigned int i,
				const unsigned int j,
				const Point& p)
{
  assert (elem != NULL);
  assert (j == 0 || j == 1 || j == 2);

  hermite_compute_coefs(elem);

  const ElemType type = elem->type();

  switch (order)
    {
      // 3rd-order tricubic Hermite functions
    case THIRD:
      {
	switch (type)
	  {
	  case HEX8:
	  case HEX20:
	  case HEX27:
	    {
	      assert (i<64);

              std::vector<unsigned int> bases1D;

              Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);

              switch (j) // Derivative type
		{
		case 0:
                  return coef *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
                  break;
		case 1:
                  return coef *
                    FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
                  break;
		case 2:
                  return coef *
                    FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));
                  break;
                }

	    }
	  default:
            std::cerr << "ERROR: Unsupported element type!" << std::endl;
	    error();
	  }
      }
      // by default throw an error
    default:
      std::cerr << "ERROR: Unsupported polynomial order!" << std::endl;
      error();
    }

  error();
  return 0.;
}

template <>
Real FE<3,HERMITE>::shape_second_deriv(const Elem* elem,
                                      const Order order,
                                      const unsigned int i,
                                      const unsigned int j,
                                      const Point& p)
{
  assert (elem != NULL);

  hermite_compute_coefs(elem);

  const ElemType type = elem->type();

  switch (order)
    {
      // 3rd-order tricubic Hermite functions
    case THIRD:
      {
	switch (type)
	  {
	  case HEX8:
	  case HEX20:
	  case HEX27:
	    {
	      assert (i<64);

              std::vector<unsigned int> bases1D;

              Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);

              switch (j) // Derivative type
		{
		case 0:
                  return coef *
                    FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
                  break;
		case 1:
                  return coef *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
                  break;
		case 2:
                  return coef *
                    FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));
                  break;
		case 3:
                  return coef *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));
                  break;
		case 4:
                  return coef *
                    FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));
                  break;
		case 5:
                  return coef *
                    FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *
                    FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *
                    FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[2],p(2));
                  break;
                }

	    }
	  default:
            std::cerr << "ERROR: Unsupported element type!" << std::endl;
	    error();
	  }
      }
      // by default throw an error
    default:
      std::cerr << "ERROR: Unsupported polynomial order!" << std::endl;
      error();
    }

  error();
  return 0.;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>
#include <boost/scoped_array.hpp>
#include <boost/scoped_ptr.hpp>

#include "database.h"
#include "db/driver.h"
#include "phml/combine.h"
#include "phml/import.h"
#include "sbml/parser.h"
#include "utf8path.h"

#include "system.h"

using std::cerr;
using std::endl;
using std::printf;
using std::sprintf;
using std::strcmp;

namespace {

bool SaveFile(const char *uuid, const char *xml_file)
{
	boost::scoped_array<char> db_file(new char[64]);
	sprintf(db_file.get(), "%s.db", uuid);
	return SaveGivenFile(db_file.get(), xml_file);
}

int ParseFile(void *data, int argc, char **argv, char **names)
{
	(void)data;
	(void)names;
	assert(argc == 1);
	boost::scoped_array<char> db_file(new char[64]); // large enough
	sprintf(db_file.get(), "%s.db", argv[0]);
	if (!ParseSbml(db_file.get())) return 1;
	return 0;
}

int CombineFile(void *data, int argc, char **argv, char **names)
{
	(void)names;
	assert(argc == 1);
	if (!Combine(argv[0],
				 ((char **)data)[1],
				 ((char **)data)[2],
				 ((char **)data)[3],
				 ((char **)data)[4],
				 ((char **)data)[5]))
		return 1;
	return 0;
}

bool TouchFile(const char *file)
{
	FILE *fp = std::fopen(file, "w");
	if (!fp) {
		cerr << "failed to touch " << file << endl;
		return false;
	}
	std::fclose(fp);
	return true;
}

void Usage()
{
	cerr << "usage: flint-combineall DB NAME VALUE FUNCTION ODE" << endl;
}

} // namespace

int main(int argc, char *argv[])
{
	if (argc == 2) {
		Usage();
		if (strcmp("-h", argv[1]) == 0 || strcmp("--help", argv[1]) == 0) {
			Usage();
			return EXIT_SUCCESS;
		}
		return EXIT_FAILURE;
	}
	if (argc != 6) {
		Usage();
		return EXIT_FAILURE;
	}

	boost::scoped_ptr<db::Driver> driver(new db::Driver(argv[1]));

	sqlite3_stmt *stmt;
	int e = sqlite3_prepare_v2(driver->db(),
							   "SELECT m.module_id, i.type, i.ref FROM imports AS i LEFT JOIN modules AS m ON i.module_rowid = m.rowid",
							   -1, &stmt, NULL);
	if (e != SQLITE_OK) {
		cerr << "failed to prepare statement: " << e << endl;
		return EXIT_FAILURE;
	}

	for (e = sqlite3_step(stmt); e == SQLITE_ROW; e = sqlite3_step(stmt)) {
		const unsigned char *uuid = sqlite3_column_text(stmt, 0);
		const unsigned char *type = sqlite3_column_text(stmt, 1);
		const unsigned char *ref = sqlite3_column_text(stmt, 2);

		if (strcmp((const char *)type, "external") == 0) {
			if (!SaveFile((const char *)uuid, (const char *)ref)) return EXIT_FAILURE;
		} else {
			if (!DumpImport(argv[1], (const char *)uuid)) return EXIT_FAILURE;
			boost::scoped_array<char> xml_file(new char[64]);
			sprintf(xml_file.get(), "%s.xml", uuid);
			boost::filesystem::path xml_path = boost::filesystem::absolute(xml_file.get());
			boost::scoped_array<char> xml_utf8(GetUtf8FromPath(xml_path));
			if (!SaveFile((const char *)uuid, xml_utf8.get())) return EXIT_FAILURE;
		}
	}
	if (e != SQLITE_DONE) {
		cerr << "failed to step statement: " << e << endl;
		return EXIT_FAILURE;
	}
	sqlite3_finalize(stmt);

	char *em;
	e = sqlite3_exec(driver->db(), "SELECT m.module_id FROM imports AS i LEFT JOIN modules AS m ON i.module_rowid = m.rowid",
					 ParseFile, NULL, &em);
	if (e != SQLITE_OK) {
		cerr << e << ": " << em << endl;
		sqlite3_free(em);
		return EXIT_FAILURE;
	}

	const char *name_file = argv[2];
	const char *value_file = argv[3];
	const char *function_file = argv[4];
	const char *ode_file = argv[5];
	if (!TouchFile(name_file)) return EXIT_FAILURE;
	if (!TouchFile(value_file)) return EXIT_FAILURE;
	if (!TouchFile(function_file)) return EXIT_FAILURE;
	if (!TouchFile(ode_file)) return EXIT_FAILURE;

	e = sqlite3_exec(driver->db(), "SELECT m.module_id FROM imports AS i LEFT JOIN modules AS m ON i.module_rowid = m.rowid",
					 CombineFile, argv, &em);
	if (e != SQLITE_OK) {
		cerr << e << ": " << em << endl;
		sqlite3_free(em);
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
<commit_msg>do the same thing in a simpler and faster way<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>

#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>
#include <boost/scoped_array.hpp>
#include <boost/scoped_ptr.hpp>

#include "database.h"
#include "db/driver.h"
#include "phml/combine.h"
#include "phml/import.h"
#include "sbml/parser.h"
#include "utf8path.h"

#include "system.h"

using std::cerr;
using std::endl;
using std::printf;
using std::sprintf;
using std::strcmp;

namespace {

bool SaveFile(const char *uuid, const char *xml_file)
{
	boost::scoped_array<char> db_file(new char[64]);
	sprintf(db_file.get(), "%s.db", uuid);
	return SaveGivenFile(db_file.get(), xml_file);
}

bool ParseFile(const char *uuid)
{
	boost::scoped_array<char> db_file(new char[64]); // large enough
	sprintf(db_file.get(), "%s.db", uuid);
	return ParseSbml(db_file.get());
}

bool TouchFile(const char *file)
{
	FILE *fp = std::fopen(file, "w");
	if (!fp) {
		cerr << "failed to touch " << file << endl;
		return false;
	}
	std::fclose(fp);
	return true;
}

typedef std::vector<std::string> UuidVector;

void Usage()
{
	cerr << "usage: flint-combineall DB NAME VALUE FUNCTION ODE" << endl;
}

} // namespace

int main(int argc, char *argv[])
{
	if (argc == 2) {
		Usage();
		if (strcmp("-h", argv[1]) == 0 || strcmp("--help", argv[1]) == 0) {
			Usage();
			return EXIT_SUCCESS;
		}
		return EXIT_FAILURE;
	}
	if (argc != 6) {
		Usage();
		return EXIT_FAILURE;
	}

	boost::scoped_ptr<db::Driver> driver(new db::Driver(argv[1]));

	UuidVector uv;
	sqlite3_stmt *stmt;
	int e = sqlite3_prepare_v2(driver->db(),
							   "SELECT m.module_id, i.type, i.ref FROM imports AS i LEFT JOIN modules AS m ON i.module_rowid = m.rowid",
							   -1, &stmt, NULL);
	if (e != SQLITE_OK) {
		cerr << "failed to prepare statement: " << e << endl;
		return EXIT_FAILURE;
	}

	for (e = sqlite3_step(stmt); e == SQLITE_ROW; e = sqlite3_step(stmt)) {
		const unsigned char *uuid = sqlite3_column_text(stmt, 0);
		const unsigned char *type = sqlite3_column_text(stmt, 1);
		const unsigned char *ref = sqlite3_column_text(stmt, 2);

		if (strcmp((const char *)type, "external") == 0) {
			if (!SaveFile((const char *)uuid, (const char *)ref)) return EXIT_FAILURE;
		} else {
			if (!DumpImport(argv[1], (const char *)uuid)) return EXIT_FAILURE;
			boost::scoped_array<char> xml_file(new char[64]);
			sprintf(xml_file.get(), "%s.xml", uuid);
			boost::filesystem::path xml_path = boost::filesystem::absolute(xml_file.get());
			boost::scoped_array<char> xml_utf8(GetUtf8FromPath(xml_path));
			if (!SaveFile((const char *)uuid, xml_utf8.get())) return EXIT_FAILURE;
		}
		uv.push_back((const char *)uuid);
	}
	if (e != SQLITE_DONE) {
		cerr << "failed to step statement: " << e << endl;
		return EXIT_FAILURE;
	}
	sqlite3_finalize(stmt);

	for (UuidVector::const_iterator it=uv.begin();it!=uv.end();++it) {
		if (!ParseFile(it->c_str())) return EXIT_FAILURE;
	}

	for (int i=2;i<6;i++) {
		if (!TouchFile(argv[i])) return EXIT_FAILURE;
	}

	for (UuidVector::const_iterator it=uv.begin();it!=uv.end();++it) {
		if (!Combine(it->c_str(),
					 argv[1],
					 argv[2],
					 argv[3],
					 argv[4],
					 argv[5]))
			return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The Syscoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <governancevalidators.h>

#include <base58.h>
#include <timedata.h>
#include <tinyformat.h>
#include <util/strencodings.h>
#include <validation.h>
#include <key_io.h>
#include <algorithm>

const size_t MAX_DATA_SIZE  = 512;
const size_t MAX_NAME_SIZE  = 40;

CProposalValidator::CProposalValidator(const std::string& strHexData) :
    objJSON(UniValue::VOBJ),
    fJSONValid(false),
    strErrorMessages()
{
    if(!strHexData.empty()) {
        ParseStrHexData(strHexData);
    }
}

void CProposalValidator::ParseStrHexData(const std::string& strHexData)
{
    std::vector<unsigned char> v = ParseHex(strHexData);
    if (v.size() > MAX_DATA_SIZE) {
        strErrorMessages = strprintf("data exceeds %lu characters;", MAX_DATA_SIZE);
        return;
    }
    ParseJSONData(std::string(v.begin(), v.end()));
}

bool CProposalValidator::Validate(bool fCheckExpiration)
{
    if(!fJSONValid) {
        strErrorMessages += "JSON parsing error;";
        return false;
    }
    if(!ValidateName()) {
        strErrorMessages += "Invalid name;";
        return false;
    }
    if(!ValidateStartEndEpoch(fCheckExpiration)) {
        strErrorMessages += "Invalid start:end range;";
        return false;
    }
    if(!ValidatePaymentAmount()) {
        strErrorMessages += "Invalid payment amount;";
        return false;
    }
    if(!ValidatePaymentAddress()) {
        strErrorMessages += "Invalid payment address;";
        return false;
    }
    if(!ValidateURL()) {
        strErrorMessages += "Invalid URL;";
        return false;
    }
    return true;
}

bool CProposalValidator::ValidateName()
{
    std::string strName;
    if(!GetDataValue("name", strName)) {
        strErrorMessages += "name field not found;";
        return false;
    }

    if(strName.size() > MAX_NAME_SIZE) {
        strErrorMessages += strprintf("name exceeds %lu characters;", MAX_NAME_SIZE);
        return false;
    }

    static const std::string strAllowedChars = "-_abcdefghijklmnopqrstuvwxyz0123456789";

    std::transform(strName.begin(), strName.end(), strName.begin(), ToLower);

    if(strName.find_first_not_of(strAllowedChars) != std::string::npos) {
        strErrorMessages += "name contains invalid characters;";
        return false;
    }

    return true;
}

bool CProposalValidator::ValidateStartEndEpoch(bool fCheckExpiration)
{
    int64_t nStartEpoch = 0;
    int64_t nEndEpoch = 0;

    if(!GetDataValue("start_epoch", nStartEpoch)) {
        strErrorMessages += "start_epoch field not found;";
        return false;
    }

    if(!GetDataValue("end_epoch", nEndEpoch)) {
        strErrorMessages += "end_epoch field not found;";
        return false;
    }

    if(nEndEpoch <= nStartEpoch) {
        strErrorMessages += "end_epoch <= start_epoch;";
        return false;
    }

    if(fCheckExpiration && nEndEpoch <= GetAdjustedTime()) {
        strErrorMessages += "expired;";
        return false;
    }

    return true;
}

bool CProposalValidator::ValidatePaymentAmount()
{
    double dValue = 0.0;

    if(!GetDataValue("payment_amount", dValue)) {
        strErrorMessages += "payment_amount field not found;";
        return false;
    }

    if(dValue <= 0.0) {
        strErrorMessages += "payment_amount is negative;";
        return false;
    }

    // TODO: Should check for an amount which exceeds the budget but this is
    // currently difficult because start and end epochs are defined in terms of
    // clock time instead of block height.

    return true;
}

bool CProposalValidator::ValidatePaymentAddress()
{
    std::string strPaymentAddress;

    if(!GetDataValue("payment_address", strPaymentAddress)) {
        strErrorMessages += "payment_address field not found;";
        return false;
    }

    if(std::find_if(strPaymentAddress.begin(), strPaymentAddress.end(), IsSpace) != strPaymentAddress.end()) {
        strErrorMessages += "payment_address can't have whitespaces;";
        return false;
    }

    const CTxDestination &address = DecodeDestination(strPaymentAddress);
    if(!IsValidDestination(address)) {
        strErrorMessages += "payment_address is invalid;";
        return false;
    }

    if(boost::get<ScriptHash>(&address) || boost::get<WitnessV0ScriptHash>(&address)) {
        strErrorMessages += "script addresses are not supported;";
        return false;
    }

    return true;
}

bool CProposalValidator::ValidateURL()
{
    std::string strURL;
    if(!GetDataValue("url", strURL)) {
        strErrorMessages += "url field not found;";
        return false;
    }

    if(std::find_if(strURL.begin(), strURL.end(), IsSpace) != strURL.end()) {
        strErrorMessages += "url can't have whitespaces;";
        return false;
    }

    if(strURL.size() < 4U) {
        strErrorMessages += "url too short;";
        return false;
    }

    if(!CheckURL(strURL)) {
        strErrorMessages += "url invalid;";
        return false;
    }

    return true;
}

void CProposalValidator::ParseJSONData(const std::string& strJSONData)
{
    fJSONValid = false;

    if(strJSONData.empty()) {
        return;
    }

    try {
        UniValue obj(UniValue::VOBJ);

        obj.read(strJSONData);

        if (obj.isObject()) {
            objJSON = obj;
        } else {
            std::vector<UniValue> arr1 = obj.getValues();
            std::vector<UniValue> arr2 = arr1.at(0).getValues();
            objJSON = arr2.at(1);
        }

        fJSONValid = true;
    }
    catch(std::exception& e) {
        strErrorMessages += std::string(e.what()) + std::string(";");
    }
    catch(...) {
        strErrorMessages += "Unknown exception;";
    }
}

bool CProposalValidator::GetDataValue(const std::string& strKey, std::string& strValueRet)
{
    bool fOK = false;
    try  {
        strValueRet = objJSON[strKey].get_str();
        fOK = true;
    }
    catch(std::exception& e) {
        strErrorMessages += std::string(e.what()) + std::string(";");
    }
    catch(...) {
        strErrorMessages += "Unknown exception;";
    }
    return fOK;
}

bool CProposalValidator::GetDataValue(const std::string& strKey, int64_t& nValueRet)
{
    bool fOK = false;
    try  {
        const UniValue uValue = objJSON[strKey];
        switch(uValue.getType()) {
        case UniValue::VNUM:
            nValueRet = uValue.get_int64();
            fOK = true;
            break;
        default:
            break;
        }
    }
    catch(std::exception& e) {
        strErrorMessages += std::string(e.what()) + std::string(";");
    }
    catch(...) {
        strErrorMessages += "Unknown exception;";
    }
    return fOK;
}

bool CProposalValidator::GetDataValue(const std::string& strKey, double& dValueRet)
{
    bool fOK = false;
    try  {
        const UniValue uValue = objJSON[strKey];
        switch(uValue.getType()) {
        case UniValue::VNUM:
            dValueRet = uValue.get_real();
            fOK = true;
            break;
        default:
            break;
        }
    }
    catch(std::exception& e) {
        strErrorMessages += std::string(e.what()) + std::string(";");
    }
    catch(...) {
        strErrorMessages += "Unknown exception;";
    }
    return fOK;
}

/*
  The purpose of this function is to replicate the behavior of the
  Python urlparse function used by sentinel (urlparse.py).  This function
  should return false whenever urlparse raises an exception and true
  otherwise.
 */
bool CProposalValidator::CheckURL(const std::string& strURLIn)
{
    std::string strRest(strURLIn);
    std::string::size_type nPos = strRest.find(':');

    if(nPos != std::string::npos) {
        //std::string strSchema = strRest.substr(0,nPos);

        if(nPos < strRest.size()) {
            strRest = strRest.substr(nPos + 1);
        }
        else {
            strRest = "";
        }
    }

    // Process netloc
    if((strRest.size() > 2) && (strRest.substr(0,2) == "//")) {
        static const std::string strNetlocDelimiters = "/?#";

        strRest = strRest.substr(2);

        std::string::size_type nPos2 = strRest.find_first_of(strNetlocDelimiters);

        std::string strNetloc = strRest.substr(0,nPos2);

        if((strNetloc.find('[') != std::string::npos) && (strNetloc.find(']') == std::string::npos)) {
            return false;
        }

        if((strNetloc.find(']') != std::string::npos) && (strNetloc.find('[') == std::string::npos)) {
            return false;
        }
    }

    return true;
}
<commit_msg>fix tolower<commit_after>// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The Syscoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <governancevalidators.h>

#include <base58.h>
#include <timedata.h>
#include <tinyformat.h>
#include <util/strencodings.h>
#include <validation.h>
#include <key_io.h>
#include <algorithm>

const size_t MAX_DATA_SIZE  = 512;
const size_t MAX_NAME_SIZE  = 40;

CProposalValidator::CProposalValidator(const std::string& strHexData) :
    objJSON(UniValue::VOBJ),
    fJSONValid(false),
    strErrorMessages()
{
    if(!strHexData.empty()) {
        ParseStrHexData(strHexData);
    }
}

void CProposalValidator::ParseStrHexData(const std::string& strHexData)
{
    std::vector<unsigned char> v = ParseHex(strHexData);
    if (v.size() > MAX_DATA_SIZE) {
        strErrorMessages = strprintf("data exceeds %lu characters;", MAX_DATA_SIZE);
        return;
    }
    ParseJSONData(std::string(v.begin(), v.end()));
}

bool CProposalValidator::Validate(bool fCheckExpiration)
{
    if(!fJSONValid) {
        strErrorMessages += "JSON parsing error;";
        return false;
    }
    if(!ValidateName()) {
        strErrorMessages += "Invalid name;";
        return false;
    }
    if(!ValidateStartEndEpoch(fCheckExpiration)) {
        strErrorMessages += "Invalid start:end range;";
        return false;
    }
    if(!ValidatePaymentAmount()) {
        strErrorMessages += "Invalid payment amount;";
        return false;
    }
    if(!ValidatePaymentAddress()) {
        strErrorMessages += "Invalid payment address;";
        return false;
    }
    if(!ValidateURL()) {
        strErrorMessages += "Invalid URL;";
        return false;
    }
    return true;
}

bool CProposalValidator::ValidateName()
{
    std::string strName;
    if(!GetDataValue("name", strName)) {
        strErrorMessages += "name field not found;";
        return false;
    }

    if(strName.size() > MAX_NAME_SIZE) {
        strErrorMessages += strprintf("name exceeds %lu characters;", MAX_NAME_SIZE);
        return false;
    }

    static const std::string strAllowedChars = "-_abcdefghijklmnopqrstuvwxyz0123456789";
    std::string strNameIn = ToLower(strName);

    if(strNameIn.find_first_not_of(strAllowedChars) != std::string::npos) {
        strErrorMessages += "name contains invalid characters;";
        return false;
    }

    return true;
}

bool CProposalValidator::ValidateStartEndEpoch(bool fCheckExpiration)
{
    int64_t nStartEpoch = 0;
    int64_t nEndEpoch = 0;

    if(!GetDataValue("start_epoch", nStartEpoch)) {
        strErrorMessages += "start_epoch field not found;";
        return false;
    }

    if(!GetDataValue("end_epoch", nEndEpoch)) {
        strErrorMessages += "end_epoch field not found;";
        return false;
    }

    if(nEndEpoch <= nStartEpoch) {
        strErrorMessages += "end_epoch <= start_epoch;";
        return false;
    }

    if(fCheckExpiration && nEndEpoch <= GetAdjustedTime()) {
        strErrorMessages += "expired;";
        return false;
    }

    return true;
}

bool CProposalValidator::ValidatePaymentAmount()
{
    double dValue = 0.0;

    if(!GetDataValue("payment_amount", dValue)) {
        strErrorMessages += "payment_amount field not found;";
        return false;
    }

    if(dValue <= 0.0) {
        strErrorMessages += "payment_amount is negative;";
        return false;
    }

    // TODO: Should check for an amount which exceeds the budget but this is
    // currently difficult because start and end epochs are defined in terms of
    // clock time instead of block height.

    return true;
}

bool CProposalValidator::ValidatePaymentAddress()
{
    std::string strPaymentAddress;

    if(!GetDataValue("payment_address", strPaymentAddress)) {
        strErrorMessages += "payment_address field not found;";
        return false;
    }

    if(std::find_if(strPaymentAddress.begin(), strPaymentAddress.end(), IsSpace) != strPaymentAddress.end()) {
        strErrorMessages += "payment_address can't have whitespaces;";
        return false;
    }

    const CTxDestination &address = DecodeDestination(strPaymentAddress);
    if(!IsValidDestination(address)) {
        strErrorMessages += "payment_address is invalid;";
        return false;
    }

    if(boost::get<ScriptHash>(&address) || boost::get<WitnessV0ScriptHash>(&address)) {
        strErrorMessages += "script addresses are not supported;";
        return false;
    }

    return true;
}

bool CProposalValidator::ValidateURL()
{
    std::string strURL;
    if(!GetDataValue("url", strURL)) {
        strErrorMessages += "url field not found;";
        return false;
    }

    if(std::find_if(strURL.begin(), strURL.end(), IsSpace) != strURL.end()) {
        strErrorMessages += "url can't have whitespaces;";
        return false;
    }

    if(strURL.size() < 4U) {
        strErrorMessages += "url too short;";
        return false;
    }

    if(!CheckURL(strURL)) {
        strErrorMessages += "url invalid;";
        return false;
    }

    return true;
}

void CProposalValidator::ParseJSONData(const std::string& strJSONData)
{
    fJSONValid = false;

    if(strJSONData.empty()) {
        return;
    }

    try {
        UniValue obj(UniValue::VOBJ);

        obj.read(strJSONData);

        if (obj.isObject()) {
            objJSON = obj;
        } else {
            std::vector<UniValue> arr1 = obj.getValues();
            std::vector<UniValue> arr2 = arr1.at(0).getValues();
            objJSON = arr2.at(1);
        }

        fJSONValid = true;
    }
    catch(std::exception& e) {
        strErrorMessages += std::string(e.what()) + std::string(";");
    }
    catch(...) {
        strErrorMessages += "Unknown exception;";
    }
}

bool CProposalValidator::GetDataValue(const std::string& strKey, std::string& strValueRet)
{
    bool fOK = false;
    try  {
        strValueRet = objJSON[strKey].get_str();
        fOK = true;
    }
    catch(std::exception& e) {
        strErrorMessages += std::string(e.what()) + std::string(";");
    }
    catch(...) {
        strErrorMessages += "Unknown exception;";
    }
    return fOK;
}

bool CProposalValidator::GetDataValue(const std::string& strKey, int64_t& nValueRet)
{
    bool fOK = false;
    try  {
        const UniValue uValue = objJSON[strKey];
        switch(uValue.getType()) {
        case UniValue::VNUM:
            nValueRet = uValue.get_int64();
            fOK = true;
            break;
        default:
            break;
        }
    }
    catch(std::exception& e) {
        strErrorMessages += std::string(e.what()) + std::string(";");
    }
    catch(...) {
        strErrorMessages += "Unknown exception;";
    }
    return fOK;
}

bool CProposalValidator::GetDataValue(const std::string& strKey, double& dValueRet)
{
    bool fOK = false;
    try  {
        const UniValue uValue = objJSON[strKey];
        switch(uValue.getType()) {
        case UniValue::VNUM:
            dValueRet = uValue.get_real();
            fOK = true;
            break;
        default:
            break;
        }
    }
    catch(std::exception& e) {
        strErrorMessages += std::string(e.what()) + std::string(";");
    }
    catch(...) {
        strErrorMessages += "Unknown exception;";
    }
    return fOK;
}

/*
  The purpose of this function is to replicate the behavior of the
  Python urlparse function used by sentinel (urlparse.py).  This function
  should return false whenever urlparse raises an exception and true
  otherwise.
 */
bool CProposalValidator::CheckURL(const std::string& strURLIn)
{
    std::string strRest(strURLIn);
    std::string::size_type nPos = strRest.find(':');

    if(nPos != std::string::npos) {
        //std::string strSchema = strRest.substr(0,nPos);

        if(nPos < strRest.size()) {
            strRest = strRest.substr(nPos + 1);
        }
        else {
            strRest = "";
        }
    }

    // Process netloc
    if((strRest.size() > 2) && (strRest.substr(0,2) == "//")) {
        static const std::string strNetlocDelimiters = "/?#";

        strRest = strRest.substr(2);

        std::string::size_type nPos2 = strRest.find_first_of(strNetlocDelimiters);

        std::string strNetloc = strRest.substr(0,nPos2);

        if((strNetloc.find('[') != std::string::npos) && (strNetloc.find(']') == std::string::npos)) {
            return false;
        }

        if((strNetloc.find(']') != std::string::npos) && (strNetloc.find('[') == std::string::npos)) {
            return false;
        }
    }

    return true;
}
<|endoftext|>


<commit_before>/*
 * fiberrenderer.cpp
 *
 *  Created on: 28.12.2012
 *      Author: Ralph
 */
#include "fiberrenderer.h"
#include "fiberrendererthread.h"

#include "glfunctions.h"

#include "../../data/enums.h"

#include <QtOpenGL/QGLShaderProgram>
#include <QtCore/QDebug>

FiberRenderer::FiberRenderer( QAbstractItemModel* roiModel, QVector< QVector< float > >& data )  :
    ObjectRenderer(),
    m_roiModel( roiModel ),
    vboIds( new GLuint[ 2 ] ),
    m_data( data ),
    m_numLines( data.size() ),
    m_numPoints( 0 ),
    m_isInitialized( false ),
    m_colorMode( 0 )
{
    m_boxMin.resize( 3 );
    m_boxMax.resize( 3 );

    connect( m_roiModel, SIGNAL( dataChanged( QModelIndex, QModelIndex ) ), this, SLOT( roiChanged( QModelIndex, QModelIndex ) ) );
    connect( m_roiModel, SIGNAL( rowsInserted( QModelIndex, int, int ) ), this, SLOT( roiInserted( QModelIndex, int, int ) ) );
    connect( m_roiModel, SIGNAL( rowsRemoved( QModelIndex, int, int ) ), this, SLOT( roiDeleted( QModelIndex, int, int ) ) );

    m_rootfield.resize( m_numLines );
    for ( int i = 0; i < m_numLines; ++i )
    {
        m_rootfield[i] = true;
    }
}

FiberRenderer::~FiberRenderer()
{
    glDeleteBuffers(1, &( vboIds[ 0 ] ) );
    glDeleteBuffers(1, &( vboIds[ 1 ] ) );
}

void FiberRenderer::init()
{
    glGenBuffers( 2, vboIds );
}

void FiberRenderer::draw( QMatrix4x4 mvp_matrix, QMatrix4x4 mv_matrixInvert )
{
    GLFunctions::getShader( "fiber" )->bind();
    // Set modelview-projection matrix
    GLFunctions::getShader( "fiber" )->setUniformValue( "mvp_matrix", mvp_matrix );
    GLFunctions::getShader( "fiber" )->setUniformValue( "mv_matrixInvert", mv_matrixInvert );
    GLFunctions::getShader( "fiber" )->setUniformValue( "u_colorMode", m_colorMode );

    initGeometry();

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    setShaderVars();

    for ( int i = 0; i < m_data.size(); ++i )
    {
        if ( m_rootfield[i] )
        {
            glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] );
        }
    }

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}

void FiberRenderer::setupTextures()
{
}

void FiberRenderer::setShaderVars()
{
    GLFunctions::setShaderVars( "fiber", model() );
}

void FiberRenderer::initGeometry()
{
    if ( m_isInitialized )
    {
        return;
    }
    qDebug() << "create fiber vbo's...";
    int numThreads = QThread::idealThreadCount();

    QVector<FiberRendererThread*> threads;
    // create threads
    for ( int i = 0; i < numThreads; ++i )
    {
        threads.push_back( new FiberRendererThread( m_data, i ) );
    }

    // run threads
    for ( int i = 0; i < numThreads; ++i )
    {
        threads[i]->start();
    }

    // wait for all threads to finish
    for ( int i = 0; i < numThreads; ++i )
    {
        threads[i]->wait();
    }

    QVector<float> verts;
    // combine verts from all threads
    for ( int i = 0; i < numThreads; ++i )
    {
        verts += *( threads[i]->getVerts() );
    }

    for ( int i = 0; i < numThreads; ++i )
    {
        delete threads[i];
    }

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 1 ] );
    glBufferData( GL_ELEMENT_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW );

    m_pointsPerLine.resize( m_data.size() );
    m_startIndexes.resize( m_data.size() );

    int currentStart = 0;
    for ( int i = 0; i < m_data.size(); ++i )
    {
        m_pointsPerLine[i] = m_data[i].size() / 3;
        m_startIndexes[i] = currentStart;
        currentStart += m_pointsPerLine[i];
    }
    qDebug() << "create fiber vbo's done";

    qDebug() << "start creating kdtree";
    m_numPoints = verts.size() / 9;
    m_kdVerts.reserve( m_numPoints * 3 );
    m_reverseIndexes.reserve( m_numPoints );
    for ( int i = 0; i < m_numLines; ++i )
    {
        for( int k = 0; k < m_data[i].size() / 3; ++k )
        {
            m_kdVerts.push_back( m_data[i][k * 3    ] );
            m_kdVerts.push_back( m_data[i][k * 3 + 1] );
            m_kdVerts.push_back( m_data[i][k * 3 + 2] );
            m_reverseIndexes.push_back( i );
        }
    }
    m_kdTree = new KdTree( m_numPoints, m_kdVerts.data() );
    qDebug() << "end creating kdtree";

    updatePresentRois();

    m_isInitialized = true;
}

void FiberRenderer::setRenderParams( int colorMode )
{
    m_colorMode = colorMode;
}

void FiberRenderer::updatePresentRois()
{
    int numBranches = m_roiModel->rowCount( QModelIndex() );

    for ( int i = 0; i < numBranches; ++i )
    {
        QList<QVector<bool> >newBranch;
        QVector<bool>newLeaf( m_numLines );
        newBranch.push_back( newLeaf );
        m_branchfields.push_back( newLeaf );
        m_bitfields.push_back( newBranch );
        updateBox( m_bitfields.size() - 1, 0 );

        int leafCount = m_roiModel->rowCount( createIndex( i, 0, 0 ) );

        for ( int k = 0; k < leafCount; ++k )
        {
            // inserted child roi
            QVector<bool>newLeaf( m_numLines );
            m_bitfields[i].push_back( newLeaf );
            updateBox( i, k + 1 );
        }
    }
}

void FiberRenderer::roiChanged( const QModelIndex &topLeft, const QModelIndex &bottomRight )
{
    if ( topLeft.row() == -1 ) return;
    qDebug() << "roi changed" << topLeft.row() << topLeft.column() << topLeft.internalId();
    int branch = 0;
    int pos = 0;
    if ( topLeft.internalId() == -1 )
    {
        // top level box
        branch = topLeft.row();
    }
    else
    {
        // child box
        branch = topLeft.internalId();
        pos = topLeft.row() + 1;
    }
    updateBox( branch, pos );

}

void FiberRenderer::roiInserted( const QModelIndex &parent, int start, int end )
{
    //qDebug() << "roi inserted" << parent.row() << start << end;
    if ( parent.row() == -1 )
    {
        // inserted top level roi
        QList<QVector<bool> >newBranch;
        QVector<bool>newLeaf( m_numLines );
        newBranch.push_back( newLeaf );
        m_branchfields.push_back( newLeaf );
        m_bitfields.push_back( newBranch );
        updateBox( m_bitfields.size() - 1, 0 );
    }
    else
    {
        // inserted child roi
        QVector<bool>newLeaf( m_numLines );
        m_bitfields[parent.row()].push_back( newLeaf );
        updateBox( parent.row(), m_bitfields[parent.row()].size() - 1 );
    }
}

void FiberRenderer::roiDeleted( const QModelIndex &parent, int start, int end )
{
    qDebug() << "roi deleted" << parent.row() << start << end;
    if ( parent.row() == -1 )
    {
        m_bitfields.removeAt( start );
        m_branchfields.removeAt( start );
        updateRoot();
    }
    else
    {
        m_bitfields[parent.row()].removeAt( start + 1 );
        updateBranch( parent.row() );
    }
}

QModelIndex FiberRenderer::createIndex( int branch, int pos, int column )
{
    int row;
    QModelIndex parent;
    if ( pos == 0 )
    {
        row = branch;
    }
    else
    {
        row = pos - 1;
        parent = m_roiModel->index( branch, 0 );
    }
    return m_roiModel->index( row, column, parent );
}

void FiberRenderer::updateBox( int branch, int pos )
{
    //qDebug() << "update box" << branch << pos;
    float x, y, z, dx, dy, dz;

    if ( m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )
    {
        x = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::X ), Qt::DisplayRole ).toFloat();
        y = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::Y ), Qt::DisplayRole ).toFloat();
        z = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::Z ), Qt::DisplayRole ).toFloat();
        dx = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DX ), Qt::DisplayRole ).toFloat();
        dy = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DY ), Qt::DisplayRole ).toFloat();
        dz = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DZ ), Qt::DisplayRole ).toFloat();
        m_boxMin[0] = x - dx / 2;
        m_boxMax[0] = x + dx / 2;
        m_boxMin[1] = y - dy / 2;
        m_boxMax[1] = y + dy / 2;
        m_boxMin[2] = z - dz / 2;
        m_boxMax[2] = z + dz / 2;

        for ( int i = 0; i < m_numLines; ++i )
        {
            m_bitfields[branch][pos][i] = false;
        }
        boxTest( m_bitfields[branch][pos], 0, m_numPoints - 1, 0 );
    }
    else
    {
        for ( int i = 0; i < m_numLines; ++i )
        {
            m_bitfields[branch][pos][i] = true;
        }
    }

    updateBranch( branch );
    if ( m_isInitialized )
    {
        m_roiModel->setData( createIndex( branch, pos, (int)Fn::ROI::UPDATED ), true, Qt::DisplayRole );
    }
}

void FiberRenderer::boxTest( QVector<bool>& workfield, int left, int right, int axis )
{
    // abort condition
    if ( left > right )
        return;

    int root = left + ( ( right - left ) / 2 );
    int axis1 = ( axis + 1 ) % 3;
    int pointIndex = m_kdTree->m_tree[root] * 3;

    if ( m_kdVerts[pointIndex + axis] < m_boxMin[axis] )
    {
        boxTest( workfield, root + 1, right, axis1 );
    }
    else if ( m_kdVerts[pointIndex + axis] > m_boxMax[axis] )
    {
        boxTest( workfield, left, root - 1, axis1 );
    }
    else
    {
        int axis2 = ( axis + 2 ) % 3;
        if ( m_kdVerts[pointIndex + axis1] <= m_boxMax[axis1] && m_kdVerts[pointIndex + axis1]
                >= m_boxMin[axis1] && m_kdVerts[pointIndex + axis2] <= m_boxMax[axis2]
                && m_kdVerts[pointIndex + axis2] >= m_boxMin[axis2] )
        {
            workfield[m_reverseIndexes[ m_kdTree->m_tree[root] ]] = true;
        }
        boxTest( workfield, left, root - 1, axis1 );
        boxTest( workfield, root + 1, right, axis1 );
    }
}

void FiberRenderer::updateBranch( int branch )
{
    //qDebug() << "update branch" << branch;
    int current = 0;

    bool neg = m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::NEG ), Qt::DisplayRole ).toBool();
    if ( neg )
    {
        for ( int k = 0; k < m_numLines; ++k )
        {
            m_branchfields[branch][k] = !m_bitfields[branch][current][k];
        }
    }
    else
    {
        for ( int k = 0; k < m_numLines; ++k )
        {
            m_branchfields[branch][k] = m_bitfields[branch][current][k];
        }
    }
    ++current;

    while ( current < m_bitfields[branch].size() )
    {
        if ( m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )
        {
            bool neg = m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::NEG ), Qt::DisplayRole ).toBool();
            if ( neg )
            {
                for ( int k = 0; k < m_numLines; ++k )
                {
                    m_branchfields[branch][k] &= !m_bitfields[branch][current][k];
                }
            }
            else
            {
                for ( int k = 0; k < m_numLines; ++k )
                {
                    m_branchfields[branch][k] &= m_bitfields[branch][current][k];
                }
            }
            ++current;
        }
        else
        {
            ++current;
        }
    }
    updateRoot();
}

void FiberRenderer::updateRoot()
{
    qDebug() << "update root";
    if ( m_branchfields.size() > 0 )
    {
        for ( int i = 0; i < m_numLines; ++i )
        {
            m_rootfield[i] = false;
        }

        for ( int i = 0; i < m_branchfields.size(); ++i )
        {
            if ( m_roiModel->data( createIndex( i, 0, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )
            {
                for ( int k = 0; k < m_numLines; ++k )
                {
                    m_rootfield[k] |= m_branchfields[i][k];
                }
            }
        }
    }
    else
    {
        for ( int i = 0; i < m_numLines; ++i )
        {
            m_rootfield[i] = true;
        }
    }
}

<commit_msg>removed debug output<commit_after>/*
 * fiberrenderer.cpp
 *
 *  Created on: 28.12.2012
 *      Author: Ralph
 */
#include "fiberrenderer.h"
#include "fiberrendererthread.h"

#include "glfunctions.h"

#include "../../data/enums.h"

#include <QtOpenGL/QGLShaderProgram>
#include <QtCore/QDebug>

FiberRenderer::FiberRenderer( QAbstractItemModel* roiModel, QVector< QVector< float > >& data )  :
    ObjectRenderer(),
    m_roiModel( roiModel ),
    vboIds( new GLuint[ 2 ] ),
    m_data( data ),
    m_numLines( data.size() ),
    m_numPoints( 0 ),
    m_isInitialized( false ),
    m_colorMode( 0 )
{
    m_boxMin.resize( 3 );
    m_boxMax.resize( 3 );

    connect( m_roiModel, SIGNAL( dataChanged( QModelIndex, QModelIndex ) ), this, SLOT( roiChanged( QModelIndex, QModelIndex ) ) );
    connect( m_roiModel, SIGNAL( rowsInserted( QModelIndex, int, int ) ), this, SLOT( roiInserted( QModelIndex, int, int ) ) );
    connect( m_roiModel, SIGNAL( rowsRemoved( QModelIndex, int, int ) ), this, SLOT( roiDeleted( QModelIndex, int, int ) ) );

    m_rootfield.resize( m_numLines );
    for ( int i = 0; i < m_numLines; ++i )
    {
        m_rootfield[i] = true;
    }
}

FiberRenderer::~FiberRenderer()
{
    glDeleteBuffers(1, &( vboIds[ 0 ] ) );
    glDeleteBuffers(1, &( vboIds[ 1 ] ) );
}

void FiberRenderer::init()
{
    glGenBuffers( 2, vboIds );
}

void FiberRenderer::draw( QMatrix4x4 mvp_matrix, QMatrix4x4 mv_matrixInvert )
{
    GLFunctions::getShader( "fiber" )->bind();
    // Set modelview-projection matrix
    GLFunctions::getShader( "fiber" )->setUniformValue( "mvp_matrix", mvp_matrix );
    GLFunctions::getShader( "fiber" )->setUniformValue( "mv_matrixInvert", mv_matrixInvert );
    GLFunctions::getShader( "fiber" )->setUniformValue( "u_colorMode", m_colorMode );

    initGeometry();

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    setShaderVars();

    for ( int i = 0; i < m_data.size(); ++i )
    {
        if ( m_rootfield[i] )
        {
            glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] );
        }
    }

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}

void FiberRenderer::setupTextures()
{
}

void FiberRenderer::setShaderVars()
{
    GLFunctions::setShaderVars( "fiber", model() );
}

void FiberRenderer::initGeometry()
{
    if ( m_isInitialized )
    {
        return;
    }
    qDebug() << "create fiber vbo's...";
    int numThreads = QThread::idealThreadCount();

    QVector<FiberRendererThread*> threads;
    // create threads
    for ( int i = 0; i < numThreads; ++i )
    {
        threads.push_back( new FiberRendererThread( m_data, i ) );
    }

    // run threads
    for ( int i = 0; i < numThreads; ++i )
    {
        threads[i]->start();
    }

    // wait for all threads to finish
    for ( int i = 0; i < numThreads; ++i )
    {
        threads[i]->wait();
    }

    QVector<float> verts;
    // combine verts from all threads
    for ( int i = 0; i < numThreads; ++i )
    {
        verts += *( threads[i]->getVerts() );
    }

    for ( int i = 0; i < numThreads; ++i )
    {
        delete threads[i];
    }

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 1 ] );
    glBufferData( GL_ELEMENT_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW );

    m_pointsPerLine.resize( m_data.size() );
    m_startIndexes.resize( m_data.size() );

    int currentStart = 0;
    for ( int i = 0; i < m_data.size(); ++i )
    {
        m_pointsPerLine[i] = m_data[i].size() / 3;
        m_startIndexes[i] = currentStart;
        currentStart += m_pointsPerLine[i];
    }
    qDebug() << "create fiber vbo's done";

    qDebug() << "start creating kdtree";
    m_numPoints = verts.size() / 9;
    m_kdVerts.reserve( m_numPoints * 3 );
    m_reverseIndexes.reserve( m_numPoints );
    for ( int i = 0; i < m_numLines; ++i )
    {
        for( int k = 0; k < m_data[i].size() / 3; ++k )
        {
            m_kdVerts.push_back( m_data[i][k * 3    ] );
            m_kdVerts.push_back( m_data[i][k * 3 + 1] );
            m_kdVerts.push_back( m_data[i][k * 3 + 2] );
            m_reverseIndexes.push_back( i );
        }
    }
    m_kdTree = new KdTree( m_numPoints, m_kdVerts.data() );
    qDebug() << "end creating kdtree";

    updatePresentRois();

    m_isInitialized = true;
}

void FiberRenderer::setRenderParams( int colorMode )
{
    m_colorMode = colorMode;
}

void FiberRenderer::updatePresentRois()
{
    int numBranches = m_roiModel->rowCount( QModelIndex() );

    for ( int i = 0; i < numBranches; ++i )
    {
        QList<QVector<bool> >newBranch;
        QVector<bool>newLeaf( m_numLines );
        newBranch.push_back( newLeaf );
        m_branchfields.push_back( newLeaf );
        m_bitfields.push_back( newBranch );
        updateBox( m_bitfields.size() - 1, 0 );

        int leafCount = m_roiModel->rowCount( createIndex( i, 0, 0 ) );

        for ( int k = 0; k < leafCount; ++k )
        {
            // inserted child roi
            QVector<bool>newLeaf( m_numLines );
            m_bitfields[i].push_back( newLeaf );
            updateBox( i, k + 1 );
        }
    }
}

void FiberRenderer::roiChanged( const QModelIndex &topLeft, const QModelIndex &bottomRight )
{
    if ( topLeft.row() == -1 ) return;
    //qDebug() << "roi changed" << topLeft.row() << topLeft.column() << topLeft.internalId();
    int branch = 0;
    int pos = 0;
    if ( topLeft.internalId() == -1 )
    {
        // top level box
        branch = topLeft.row();
    }
    else
    {
        // child box
        branch = topLeft.internalId();
        pos = topLeft.row() + 1;
    }
    updateBox( branch, pos );

}

void FiberRenderer::roiInserted( const QModelIndex &parent, int start, int end )
{
    //qDebug() << "roi inserted" << parent.row() << start << end;
    if ( parent.row() == -1 )
    {
        // inserted top level roi
        QList<QVector<bool> >newBranch;
        QVector<bool>newLeaf( m_numLines );
        newBranch.push_back( newLeaf );
        m_branchfields.push_back( newLeaf );
        m_bitfields.push_back( newBranch );
        updateBox( m_bitfields.size() - 1, 0 );
    }
    else
    {
        // inserted child roi
        QVector<bool>newLeaf( m_numLines );
        m_bitfields[parent.row()].push_back( newLeaf );
        updateBox( parent.row(), m_bitfields[parent.row()].size() - 1 );
    }
}

void FiberRenderer::roiDeleted( const QModelIndex &parent, int start, int end )
{
    //qDebug() << "roi deleted" << parent.row() << start << end;
    if ( parent.row() == -1 )
    {
        m_bitfields.removeAt( start );
        m_branchfields.removeAt( start );
        updateRoot();
    }
    else
    {
        m_bitfields[parent.row()].removeAt( start + 1 );
        updateBranch( parent.row() );
    }
}

QModelIndex FiberRenderer::createIndex( int branch, int pos, int column )
{
    int row;
    QModelIndex parent;
    if ( pos == 0 )
    {
        row = branch;
    }
    else
    {
        row = pos - 1;
        parent = m_roiModel->index( branch, 0 );
    }
    return m_roiModel->index( row, column, parent );
}

void FiberRenderer::updateBox( int branch, int pos )
{
    //qDebug() << "update box" << branch << pos;
    float x, y, z, dx, dy, dz;

    if ( m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )
    {
        x = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::X ), Qt::DisplayRole ).toFloat();
        y = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::Y ), Qt::DisplayRole ).toFloat();
        z = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::Z ), Qt::DisplayRole ).toFloat();
        dx = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DX ), Qt::DisplayRole ).toFloat();
        dy = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DY ), Qt::DisplayRole ).toFloat();
        dz = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DZ ), Qt::DisplayRole ).toFloat();
        m_boxMin[0] = x - dx / 2;
        m_boxMax[0] = x + dx / 2;
        m_boxMin[1] = y - dy / 2;
        m_boxMax[1] = y + dy / 2;
        m_boxMin[2] = z - dz / 2;
        m_boxMax[2] = z + dz / 2;

        for ( int i = 0; i < m_numLines; ++i )
        {
            m_bitfields[branch][pos][i] = false;
        }
        boxTest( m_bitfields[branch][pos], 0, m_numPoints - 1, 0 );
    }
    else
    {
        for ( int i = 0; i < m_numLines; ++i )
        {
            m_bitfields[branch][pos][i] = true;
        }
    }

    updateBranch( branch );
    if ( m_isInitialized )
    {
        m_roiModel->setData( createIndex( branch, pos, (int)Fn::ROI::UPDATED ), true, Qt::DisplayRole );
    }
}

void FiberRenderer::boxTest( QVector<bool>& workfield, int left, int right, int axis )
{
    // abort condition
    if ( left > right )
        return;

    int root = left + ( ( right - left ) / 2 );
    int axis1 = ( axis + 1 ) % 3;
    int pointIndex = m_kdTree->m_tree[root] * 3;

    if ( m_kdVerts[pointIndex + axis] < m_boxMin[axis] )
    {
        boxTest( workfield, root + 1, right, axis1 );
    }
    else if ( m_kdVerts[pointIndex + axis] > m_boxMax[axis] )
    {
        boxTest( workfield, left, root - 1, axis1 );
    }
    else
    {
        int axis2 = ( axis + 2 ) % 3;
        if ( m_kdVerts[pointIndex + axis1] <= m_boxMax[axis1] && m_kdVerts[pointIndex + axis1]
                >= m_boxMin[axis1] && m_kdVerts[pointIndex + axis2] <= m_boxMax[axis2]
                && m_kdVerts[pointIndex + axis2] >= m_boxMin[axis2] )
        {
            workfield[m_reverseIndexes[ m_kdTree->m_tree[root] ]] = true;
        }
        boxTest( workfield, left, root - 1, axis1 );
        boxTest( workfield, root + 1, right, axis1 );
    }
}

void FiberRenderer::updateBranch( int branch )
{
    //qDebug() << "update branch" << branch;
    int current = 0;

    bool neg = m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::NEG ), Qt::DisplayRole ).toBool();
    if ( neg )
    {
        for ( int k = 0; k < m_numLines; ++k )
        {
            m_branchfields[branch][k] = !m_bitfields[branch][current][k];
        }
    }
    else
    {
        for ( int k = 0; k < m_numLines; ++k )
        {
            m_branchfields[branch][k] = m_bitfields[branch][current][k];
        }
    }
    ++current;

    while ( current < m_bitfields[branch].size() )
    {
        if ( m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )
        {
            bool neg = m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::NEG ), Qt::DisplayRole ).toBool();
            if ( neg )
            {
                for ( int k = 0; k < m_numLines; ++k )
                {
                    m_branchfields[branch][k] &= !m_bitfields[branch][current][k];
                }
            }
            else
            {
                for ( int k = 0; k < m_numLines; ++k )
                {
                    m_branchfields[branch][k] &= m_bitfields[branch][current][k];
                }
            }
            ++current;
        }
        else
        {
            ++current;
        }
    }
    updateRoot();
}

void FiberRenderer::updateRoot()
{
    //qDebug() << "update root";
    if ( m_branchfields.size() > 0 )
    {
        for ( int i = 0; i < m_numLines; ++i )
        {
            m_rootfield[i] = false;
        }

        for ( int i = 0; i < m_branchfields.size(); ++i )
        {
            if ( m_roiModel->data( createIndex( i, 0, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )
            {
                for ( int k = 0; k < m_numLines; ++k )
                {
                    m_rootfield[k] |= m_branchfields[i][k];
                }
            }
        }
    }
    else
    {
        for ( int i = 0; i < m_numLines; ++i )
        {
            m_rootfield[i] = true;
        }
    }
}

<|endoftext|>


<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*/

#include "textbrowser.h"
#include <QApplication>
#include <QScrollBar>
#include <QPainter>
#include <QTextBlock>
#include <QAbstractTextDocumentLayout>
#include <qmath.h>

TextBrowser::TextBrowser(QWidget* parent) : QTextBrowser(parent)
{
    d.ub = -1;
    d.bud = 0;
}

QWidget* TextBrowser::buddy() const
{
    return d.bud;
}

void TextBrowser::setBuddy(QWidget* buddy)
{
    d.bud = buddy;
}

void TextBrowser::addMarker(int block)
{
    d.markers.append(block);
    update();
}

void TextBrowser::removeMarker(int block)
{
    if (d.markers.removeOne(block))
        update();
}

QColor TextBrowser::highlightColor() const
{
    return d.highlightColor;
}

void TextBrowser::setHighlightColor(const QColor& color)
{
    if (d.highlightColor != color) {
        d.highlightColor = color;
        update();
    }
}

void TextBrowser::append(const QString& text, bool highlight)
{
    if (!text.isEmpty()) {

        QTextBrowser::append(text);

#if QT_VERSION >= 0x040800
        QTextCursor cursor(document());
        cursor.movePosition(QTextCursor::End);
        QTextBlockFormat format = cursor.blockFormat();
        format.setLineHeight(120, QTextBlockFormat::ProportionalHeight);
        cursor.setBlockFormat(format);
#endif // QT_VERSION

        if (!isVisible() && d.ub == -1)
            d.ub = document()->blockCount() - 1;

        if (highlight)
            d.highlights.append(document()->blockCount() - 1);
    }
}

void TextBrowser::hideEvent(QHideEvent* event)
{
    QTextBrowser::hideEvent(event);
    d.ub = -1;
}

void TextBrowser::keyPressEvent(QKeyEvent* event)
{
    // for example:
    // - Ctrl+C goes to the browser
    // - Ctrl+V goes to the buddy
    // - Shift+7 ("/") goes to the buddy
    switch (event->key()) {
        case Qt::Key_Shift:
        case Qt::Key_Control:
        case Qt::Key_Meta:
        case Qt::Key_Alt:
        case Qt::Key_AltGr:
            break;
        default:
            if (!event->matches(QKeySequence::Copy) && !event->matches(QKeySequence::SelectAll)) {
                QApplication::sendEvent(d.bud, event);
                d.bud->setFocus();
                return;
            }
            break;
    }
    QTextBrowser::keyPressEvent(event);
}

void TextBrowser::resizeEvent(QResizeEvent* event)
{
    QTextBrowser::resizeEvent(event);

    // http://www.qtsoftware.com/developer/task-tracker/index_html?method=entry&id=240940
    QMetaObject::invokeMethod(this, "scrollToBottom", Qt::QueuedConnection);
}

void TextBrowser::scrollToTop()
{
    verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum);
}

void TextBrowser::scrollToBottom()
{
    verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);
}

void TextBrowser::scrollToNextPage()
{
    verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepAdd);
}

void TextBrowser::scrollToPreviousPage()
{
    verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepSub);
}

void TextBrowser::paintEvent(QPaintEvent* event)
{
    const QRect bounds = rect().translated(horizontalScrollBar()->value(),
                                           verticalScrollBar()->value());

    if (!d.highlights.isEmpty()) {
        QPainter painter(viewport());
        painter.translate(-horizontalScrollBar()->value(), -verticalScrollBar()->value());

        int margin = qCeil(document()->documentMargin());
        foreach (int highlight, d.highlights) {
            QTextBlock block = document()->findBlockByNumber(highlight);
            QRectF br = document()->documentLayout()->blockBoundingRect(block);
            if (bounds.intersects(br.toAlignedRect()))
                painter.fillRect(br.adjusted(-margin, 0, margin, 0), d.highlightColor);
        }
    }

    QTextBrowser::paintEvent(event);

    QPainter painter(viewport());
    painter.translate(-horizontalScrollBar()->value(), -verticalScrollBar()->value());

    int last = -1;
    if (!d.markers.isEmpty()) {
        painter.setPen(QPen(Qt::gray, 1, Qt::DashLine));
        foreach (int marker, d.markers) {
            QTextBlock block = document()->findBlockByNumber(marker);
            QRectF br = document()->documentLayout()->blockBoundingRect(block);
            if (bounds.intersects(br.toAlignedRect())) {
                painter.drawLine(br.topLeft(), br.topRight());
                last = qMax(marker, last);
            }
        }
    }

    if (d.ub > 0 && d.ub >= last) {
        painter.setPen(QPen(Qt::black, 1, Qt::DashLine));
        QTextBlock block = document()->findBlockByNumber(d.ub);
        QRectF br = document()->documentLayout()->blockBoundingRect(block);
        if (bounds.intersects(br.toAlignedRect()))
            painter.drawLine(br.topLeft(), br.topRight());
    }

    QLinearGradient gradient(0, 0, 0, 3);
    gradient.setColorAt(0.0, palette().color(QPalette::Dark));
    gradient.setColorAt(1.0, Qt::transparent);
    painter.fillRect(0, 0, width(), 3, gradient);
}

void TextBrowser::wheelEvent(QWheelEvent* event)
{
#ifdef Q_WS_MACX
    // disable cmd+wheel zooming on mac
    QAbstractScrollArea::wheelEvent(event);
#else
    QTextBrowser::wheelEvent(event);
#endif // Q_WS_MACX
}

<commit_msg>TextBrowser: fix the top shadow<commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*/

#include "textbrowser.h"
#include <QApplication>
#include <QScrollBar>
#include <QPainter>
#include <QTextBlock>
#include <QAbstractTextDocumentLayout>
#include <qmath.h>

TextBrowser::TextBrowser(QWidget* parent) : QTextBrowser(parent)
{
    d.ub = -1;
    d.bud = 0;
}

QWidget* TextBrowser::buddy() const
{
    return d.bud;
}

void TextBrowser::setBuddy(QWidget* buddy)
{
    d.bud = buddy;
}

void TextBrowser::addMarker(int block)
{
    d.markers.append(block);
    update();
}

void TextBrowser::removeMarker(int block)
{
    if (d.markers.removeOne(block))
        update();
}

QColor TextBrowser::highlightColor() const
{
    return d.highlightColor;
}

void TextBrowser::setHighlightColor(const QColor& color)
{
    if (d.highlightColor != color) {
        d.highlightColor = color;
        update();
    }
}

void TextBrowser::append(const QString& text, bool highlight)
{
    if (!text.isEmpty()) {

        QTextBrowser::append(text);

#if QT_VERSION >= 0x040800
        QTextCursor cursor(document());
        cursor.movePosition(QTextCursor::End);
        QTextBlockFormat format = cursor.blockFormat();
        format.setLineHeight(120, QTextBlockFormat::ProportionalHeight);
        cursor.setBlockFormat(format);
#endif // QT_VERSION

        if (!isVisible() && d.ub == -1)
            d.ub = document()->blockCount() - 1;

        if (highlight)
            d.highlights.append(document()->blockCount() - 1);
    }
}

void TextBrowser::hideEvent(QHideEvent* event)
{
    QTextBrowser::hideEvent(event);
    d.ub = -1;
}

void TextBrowser::keyPressEvent(QKeyEvent* event)
{
    // for example:
    // - Ctrl+C goes to the browser
    // - Ctrl+V goes to the buddy
    // - Shift+7 ("/") goes to the buddy
    switch (event->key()) {
        case Qt::Key_Shift:
        case Qt::Key_Control:
        case Qt::Key_Meta:
        case Qt::Key_Alt:
        case Qt::Key_AltGr:
            break;
        default:
            if (!event->matches(QKeySequence::Copy) && !event->matches(QKeySequence::SelectAll)) {
                QApplication::sendEvent(d.bud, event);
                d.bud->setFocus();
                return;
            }
            break;
    }
    QTextBrowser::keyPressEvent(event);
}

void TextBrowser::resizeEvent(QResizeEvent* event)
{
    QTextBrowser::resizeEvent(event);

    // http://www.qtsoftware.com/developer/task-tracker/index_html?method=entry&id=240940
    QMetaObject::invokeMethod(this, "scrollToBottom", Qt::QueuedConnection);
}

void TextBrowser::scrollToTop()
{
    verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum);
}

void TextBrowser::scrollToBottom()
{
    verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);
}

void TextBrowser::scrollToNextPage()
{
    verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepAdd);
}

void TextBrowser::scrollToPreviousPage()
{
    verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepSub);
}

void TextBrowser::paintEvent(QPaintEvent* event)
{
    const QRect bounds = rect().translated(horizontalScrollBar()->value(),
                                           verticalScrollBar()->value());

    if (!d.highlights.isEmpty()) {
        QPainter painter(viewport());
        painter.translate(-horizontalScrollBar()->value(), -verticalScrollBar()->value());

        int margin = qCeil(document()->documentMargin());
        foreach (int highlight, d.highlights) {
            QTextBlock block = document()->findBlockByNumber(highlight);
            QRectF br = document()->documentLayout()->blockBoundingRect(block);
            if (bounds.intersects(br.toAlignedRect()))
                painter.fillRect(br.adjusted(-margin, 0, margin, 0), d.highlightColor);
        }
    }

    QTextBrowser::paintEvent(event);

    QPainter painter(viewport());
    painter.save();
    painter.translate(-horizontalScrollBar()->value(), -verticalScrollBar()->value());

    int last = -1;
    if (!d.markers.isEmpty()) {
        painter.setPen(QPen(Qt::gray, 1, Qt::DashLine));
        foreach (int marker, d.markers) {
            QTextBlock block = document()->findBlockByNumber(marker);
            QRectF br = document()->documentLayout()->blockBoundingRect(block);
            if (bounds.intersects(br.toAlignedRect())) {
                painter.drawLine(br.topLeft(), br.topRight());
                last = qMax(marker, last);
            }
        }
    }

    if (d.ub > 0 && d.ub >= last) {
        painter.setPen(QPen(Qt::black, 1, Qt::DashLine));
        QTextBlock block = document()->findBlockByNumber(d.ub);
        QRectF br = document()->documentLayout()->blockBoundingRect(block);
        if (bounds.intersects(br.toAlignedRect()))
            painter.drawLine(br.topLeft(), br.topRight());
    }

    QLinearGradient gradient(0, 0, 0, 3);
    gradient.setColorAt(0.0, palette().color(QPalette::Dark));
    gradient.setColorAt(1.0, Qt::transparent);
    painter.restore();
    painter.fillRect(0, 0, width(), 3, gradient);
}

void TextBrowser::wheelEvent(QWheelEvent* event)
{
#ifdef Q_WS_MACX
    // disable cmd+wheel zooming on mac
    QAbstractScrollArea::wheelEvent(event);
#else
    QTextBrowser::wheelEvent(event);
#endif // Q_WS_MACX
}

<|endoftext|>