<commit_before>/*! \brief serial_controller_node.
 *         Manages serial communications with AVR-Master.
 *
 *  This node manages serial communications with the AVR-Master.
 *  Therefore it first requests all data from AVR-Master and then sends all
 *  commands to AVR-Master in a Loop. Data read is stored in md49_data.txt,
 *  commands to be send are read from md49_commands.txt.
 *
 */

// Includes
// *********************************************************
#include <iostream>                                         /* allows to perform standard input and output operations */
//#include <fstream>                                          /* Input/output stream class to operate on files. */
#include <stdio.h>                                          /* Standard input/output definitions */
#include <stdint.h>                                         /* Standard input/output definitions */
#include <stdlib.h>                                         /* defines several general purpose functions */
//#include <unistd.h>                                         /* UNIX standard function definitions */
#include <fcntl.h>                                          /* File control definitions */
#include <errno.h>                                          /* Error number definitions */
#include <termios.h>                                        /* POSIX terminal control definitions */
//#include <ctype.h>                                          /* isxxx() */
//#include<ros/ros.h>
#include <sqlite3.h>

// Global variables
const char* serialport_name="//dev/ttyAMA0";                   /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/
int serialport_bps=B9600;                                  /* defines used baudrate on serialport */
//int filedesc;                                             /* File descriptor of serial port we will talk to*/
int fd;                                                     /* serial port file descriptor */
int32_t EncoderL;                                           /* stores encoder value left read from md49 */
int32_t EncoderR;                                           /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128;                     /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128;           /* speed to set for MD49 */
unsigned char serialBuffer[16];                             /* Serial buffer to store uart data */
struct termios orig;                                        // backuped port options

// sqlite globals
sqlite3 *db;
char *zErrMsg = 0;
int  rc;
const char *sql;
const char* data = "Callback function called";

using namespace std;

// Declare functions
// *********************************************************
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void open_sqlite_db_md49data(void);
static int sql_callback(void *data, int argc, char **argv, char **azColName);
void read_MD49_Data_serial (void);
void read_md49_commands(void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);

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

    // Init as ROS node
    // ****************
    //ros::init(argc, argv, "serial_controller");
    //ros::NodeHandle n;

    // Open sqlite database md49data.db
    // ********************************
    open_sqlite_db_md49data();

    // Open serial port
    // ****************
    fd = openSerialPort(serialport_name, serialport_bps);
    if (fd == -1) exit(1);
    //ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps);
    usleep(10000);                                          // Sleep for UART to power up and set options

    //ROS_DEBUG("Starting Mainloop...");
    //ROS_DEBUG("reading data from MD49 and pushing commands to MD49 @ 5Hz...");

    // Mainloop
    // ***********************************
    //while(  n.ok() ){
    while( 1 ){
        // Read encodervalues and other data from MD49
        // serial. Data ist stored in md49_data.txt
        // ****************************************
        read_MD49_Data_serial();
        usleep(100000);

        // Read commands from md49_commands.txt:
        // *************************************
        read_md49_commands();

        // Set speed and other commands as
        // read from md49_commands.txt
        // *******************************
        if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
            set_MD49_speed(speed_l, speed_r);
            last_speed_l=speed_l;
            last_speed_r=speed_r;
        }

        usleep(100000);

    }// end.mainloop
    sqlite3_close(db);
    return 1;
} // end.main

void read_MD49_Data_serial (void){
    // Read serial MD49 data from AVR-Master
    // *************************************
    serialBuffer[0] = 82;                                   // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
    writeBytes(fd, 1);
    readBytes(fd, 18);

    // Put toghether encoder values from their
    // corresponding bytes, read from MD49
    // ***************************************
    EncoderL = serialBuffer[0] << 24;                       // Put together first encoder value
    EncoderL |= (serialBuffer[1] << 16);
    EncoderL |= (serialBuffer[2] << 8);
    EncoderL |= (serialBuffer[3]);
    EncoderR = serialBuffer[4] << 24;                       // Put together second encoder value
    EncoderR |= (serialBuffer[5] << 16);
    EncoderR |= (serialBuffer[6] << 8);
    EncoderR |= (serialBuffer[7]);

    // Write data read from MD49 into
    // sqlite3 database md49data.db
    // ******************************
    char sql_buffer[300];
    int cx;
    cx = snprintf (sql_buffer,300,"UPDATE md49data SET Encoderbyte1L, Encoderbyte2L, Encoderbyte3L, Encoderbyte4L," \
                   "Encoderbyte1R, Encoderbyte2R, Encoderbyte3R, Encoderbyte4R, EncoderL=%i, EncoderR=%i, " \
                   " SpeedL, SpeedR, Volts, CurrentL, CurrentR, Error, Acceleration, Mode, Regulator, Timeout" \
                   "WHERE ID=1", serialBuffer[0], serialBuffer[1], serialBuffer[2], serialBuffer[3], \
                    serialBuffer[4], serialBuffer[5], serialBuffer[6], serialBuffer[7], EncoderL, EncoderR, \
                    serialBuffer[8], serialBuffer[9], serialBuffer[10], serialBuffer[11], serialBuffer[12], \
                    serialBuffer[13], serialBuffer[14], serialBuffer[15], serialBuffer[16], serialBuffer[17]);

    rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        //fprintf(stdout, "Operation done successfully\n");
    }

    // Output MD49 data on screen
    // **************************
    printf("\033[2J");                                      //  clear the screen
    printf("\033[H");                                       //  position cursor at top-left corner
    printf ("MD49-Data read from AVR-Master: \n");
    printf("========================================\n");
    printf("Encoder1 Byte1: %i ",serialBuffer[0]);
    printf("Byte2: %i ",serialBuffer[1]);
    printf("Byte3: % i ",serialBuffer[2]);
    printf("Byte4: %i \n",serialBuffer[3]);
    printf("Encoder2 Byte1: %i ",serialBuffer[4]);
    printf("Byte2: %i ",serialBuffer[5]);
    printf("Byte3: %i ",serialBuffer[6]);
    printf("Byte4: %i \n",serialBuffer[7]);
    printf("EncoderL: %i ",EncoderL);
    printf("EncoderR: %i \n",EncoderR);
    printf("========================================\n");
    printf("SpeedL: %i ",serialBuffer[8]);
    printf("SpeedR: %i \n",serialBuffer[9]);
    printf("Volts: %i \n",serialBuffer[10]);
    printf("CurrentL: %i ",serialBuffer[11]);
    printf("CurrentR: %i \n",serialBuffer[12]);
    printf("Error: %i \n",serialBuffer[13]);
    printf("Acceleration: %i \n",serialBuffer[14]);
    printf("Mode: %i \n",serialBuffer[15]);
    printf("Regulator: %i \n",serialBuffer[16]);
    printf("Timeout: %i \n",serialBuffer[17]);

}

// Write serial command to change left and right speed
// ***************************************************
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){

    serialBuffer[0] = 88;                                   // 88 =X Steuerbyte um Commands an MD49 zu senden
    serialBuffer[1] = 115;                                  // 115=s Steuerbyte setSpeed
    serialBuffer[2] = speed_l;                              // set speed1
    serialBuffer[3] = speed_r;                              // set speed2
    writeBytes(fd, 4);
}

// Read SpeedL and SpeedR from
// table md49commands(md49data.db)
// *******************************
void read_md49_commands(void){

   // Create SQL statement
   sql = "SELECT * from md49commands WHERE ID=1";

   // Execute SQL statement
   rc = sqlite3_exec(db, sql, sql_callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL message: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      //fprintf(stdout, "Query done successfully\n");
   }
}

// Open serialport
// ***************
int openSerialPort(const char * device, int bps){

   struct termios neu;
   char buf[128];

   //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
   fd = open(device, O_RDWR | O_NOCTTY);

   if (fd == -1)
   {
      sprintf(buf, "openSerialPort %s error", device);
      perror(buf);
   }
   else
   {
      tcgetattr(fd, &orig);                                 /* save current serial settings */
      tcgetattr(fd, &neu);
      cfmakeraw(&neu);
      cfsetispeed(&neu, bps);
      cfsetospeed(&neu, bps);
      tcflush(fd, TCIFLUSH);
      tcsetattr(fd, TCSANOW, &neu);                         /* set new serial settings */
      fcntl (fd, F_SETFL, O_RDWR);
   }
   return fd;
}

// Write bytes serial to UART
// **************************
void writeBytes(int descriptor, int count) {
    if ((write(descriptor, serialBuffer, count)) == -1) {   // Send data out
        perror("Error writing");
        close(descriptor);                                  // Close port if there is an error
        exit(1);
    }

}

// Read bytes serial from UART
// ***************************
void readBytes(int descriptor, int count) {
    if (read(descriptor, serialBuffer, count) == -1) {      // Read back data into buf[]
        perror("Error reading ");
        close(descriptor);                                  // Close port if there is an error
        exit(1);
    }
}

// Open sqlite db md49data.db and create
// table md49data if not existing
// *************************************
void open_sqlite_db_md49data(void){

    // Open database md49data.db and add table md49data
    // ************************************************
    rc = sqlite3_open("data/md49data.db", &db);
    if( rc ){
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        exit(0);
    }else{
        fprintf(stdout, "Opened database successfully,\n");
    }

    // Create table md49data
    // *********************
    sql = "CREATE TABLE md49data("  \
     "ID INT PRIMARY KEY     NOT NULL," \
     "Encoderbyte1L  INT DEFAULT 0, Encoderbyte2L  INT DEFAULT 0," \
     "Encoderbyte3L  INT DEFAULT 0, Encoderbyte4L  INT DEFAULT 0," \
     "Encoderbyte1R  INT DEFAULT 0, Encoderbyte2R  INT DEFAULT 0," \
     "Encoderbyte3R  INT DEFAULT 0, Encoderbyte4R  INT DEFAULT 0," \
     "EncoderL       INT DEFAULT 0, EncoderR       INT DEFAULT 0," \
     "SpeedL         INT DEFAULT 0, SpeedR         INT DEFAULT 0," \
     "Volts          INT DEFAULT 0," \
     "CurrentL       INT DEFAULT 0, CurrentR       INT DEFAULT 0," \
     "Error          INT DEFAULT 0, Acceleration   INT DEFAULT 0," \
     "Mode           INT DEFAULT 0, Regulator      INT DEFAULT 0," \
     "Timeout        INT DEFAULT 0 );" \
     "INSERT INTO md49data (ID) VALUES (1);";

    /* Execute SQL statement */
    rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        fprintf(stdout, "table created successfully\n");
    }
}

// Callbackfunction executed if table md49commands in md49data.db is queried
// *************************************************************************
static int sql_callback(void *data, int argc, char **argv, char **azColName){
   speed_l= atoi(argv[1]);
   speed_r= atoi(argv[2]);
   return 0;
}

<commit_msg>Remove txt files<commit_after>/*! \brief serial_controller_node.
 *         Manages serial communications with AVR-Master.
 *
 *  This node manages serial communications with the AVR-Master.
 *  Therefore it first requests all data from AVR-Master and then sends all
 *  commands to AVR-Master in a Loop. Data read is stored in md49_data.txt,
 *  commands to be send are read from md49_commands.txt.
 *
 */

// Includes
// *********************************************************
#include <iostream>                                         /* allows to perform standard input and output operations */
//#include <fstream>                                          /* Input/output stream class to operate on files. */
#include <stdio.h>                                          /* Standard input/output definitions */
#include <stdint.h>                                         /* Standard input/output definitions */
#include <stdlib.h>                                         /* defines several general purpose functions */
//#include <unistd.h>                                         /* UNIX standard function definitions */
#include <fcntl.h>                                          /* File control definitions */
#include <errno.h>                                          /* Error number definitions */
#include <termios.h>                                        /* POSIX terminal control definitions */
//#include <ctype.h>                                          /* isxxx() */
//#include<ros/ros.h>
#include <sqlite3.h>

// Global variables
const char* serialport_name="//dev/ttyAMA0";                   /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/
int serialport_bps=B9600;                                  /* defines used baudrate on serialport */
//int filedesc;                                             /* File descriptor of serial port we will talk to*/
int fd;                                                     /* serial port file descriptor */
int32_t EncoderL;                                           /* stores encoder value left read from md49 */
int32_t EncoderR;                                           /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128;                     /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128;           /* speed to set for MD49 */
unsigned char serialBuffer[16];                             /* Serial buffer to store uart data */
struct termios orig;                                        // backuped port options

// sqlite globals
sqlite3 *db;
char *zErrMsg = 0;
int  rc;
const char *sql;
const char* data = "Callback function called";

using namespace std;

// Declare functions
// *********************************************************
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void open_sqlite_db_md49data(void);
static int sql_callback(void *data, int argc, char **argv, char **azColName);
void read_MD49_Data_serial (void);
void read_md49_commands(void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);

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

    // Init as ROS node
    // ****************
    //ros::init(argc, argv, "serial_controller");
    //ros::NodeHandle n;

    // Open sqlite database md49data.db
    // ********************************
    open_sqlite_db_md49data();

    // Open serial port
    // ****************
    fd = openSerialPort(serialport_name, serialport_bps);
    if (fd == -1) exit(1);
    //ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps);
    usleep(10000);                                          // Sleep for UART to power up and set options

    //ROS_DEBUG("Starting Mainloop...");
    //ROS_DEBUG("reading data from MD49 and pushing commands to MD49 @ 5Hz...");

    // Mainloop
    // ***********************************
    //while(  n.ok() ){
    while( 1 ){
        // Read encodervalues and other data from MD49
        // serial. Data ist stored in md49_data.txt
        // ****************************************
        read_MD49_Data_serial();
        usleep(100000);

        // Read commands from md49_commands.txt:
        // *************************************
        read_md49_commands();

        // Set speed and other commands as
        // read from md49_commands.txt
        // *******************************
        if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
            set_MD49_speed(speed_l, speed_r);
            last_speed_l=speed_l;
            last_speed_r=speed_r;
        }

        usleep(100000);

    }// end.mainloop
    sqlite3_close(db);
    return 1;
} // end.main

void read_MD49_Data_serial (void){
    // Read serial MD49 data from AVR-Master
    // *************************************
    serialBuffer[0] = 82;                                   // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
    writeBytes(fd, 1);
    readBytes(fd, 18);

    // Put toghether encoder values from their
    // corresponding bytes, read from MD49
    // ***************************************
    EncoderL = serialBuffer[0] << 24;                       // Put together first encoder value
    EncoderL |= (serialBuffer[1] << 16);
    EncoderL |= (serialBuffer[2] << 8);
    EncoderL |= (serialBuffer[3]);
    EncoderR = serialBuffer[4] << 24;                       // Put together second encoder value
    EncoderR |= (serialBuffer[5] << 16);
    EncoderR |= (serialBuffer[6] << 8);
    EncoderR |= (serialBuffer[7]);

    // Write data read from MD49 into
    // sqlite3 database md49data.db
    // ******************************
    char sql_buffer[300];
    int cx;
    cx = snprintf (sql_buffer,300,"UPDATE md49data SET Encoderbyte1L, Encoderbyte2L, Encoderbyte3L, Encoderbyte4L," \
                   "Encoderbyte1R, Encoderbyte2R, Encoderbyte3R, Encoderbyte4R, EncoderL=%i, EncoderR=%i, " \
                   " SpeedL, SpeedR, Volts, CurrentL, CurrentR, Error, Acceleration, Mode, Regulator, Timeout" \
                   "WHERE ID=1", serialBuffer[0], serialBuffer[1], serialBuffer[2], serialBuffer[3], serialBuffer[4], serialBuffer[5], serialBuffer[6], serialBuffer[7], EncoderL, EncoderR, serialBuffer[8], serialBuffer[9], serialBuffer[10], serialBuffer[11], serialBuffer[12], serialBuffer[13], serialBuffer[14], serialBuffer[15], serialBuffer[16], serialBuffer[17]);

    rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        //fprintf(stdout, "Operation done successfully\n");
    }

    // Output MD49 data on screen
    // **************************
    printf("\033[2J");                                      //  clear the screen
    printf("\033[H");                                       //  position cursor at top-left corner
    printf ("MD49-Data read from AVR-Master: \n");
    printf("========================================\n");
    printf("Encoder1 Byte1: %i ",serialBuffer[0]);
    printf("Byte2: %i ",serialBuffer[1]);
    printf("Byte3: % i ",serialBuffer[2]);
    printf("Byte4: %i \n",serialBuffer[3]);
    printf("Encoder2 Byte1: %i ",serialBuffer[4]);
    printf("Byte2: %i ",serialBuffer[5]);
    printf("Byte3: %i ",serialBuffer[6]);
    printf("Byte4: %i \n",serialBuffer[7]);
    printf("EncoderL: %i ",EncoderL);
    printf("EncoderR: %i \n",EncoderR);
    printf("========================================\n");
    printf("SpeedL: %i ",serialBuffer[8]);
    printf("SpeedR: %i \n",serialBuffer[9]);
    printf("Volts: %i \n",serialBuffer[10]);
    printf("CurrentL: %i ",serialBuffer[11]);
    printf("CurrentR: %i \n",serialBuffer[12]);
    printf("Error: %i \n",serialBuffer[13]);
    printf("Acceleration: %i \n",serialBuffer[14]);
    printf("Mode: %i \n",serialBuffer[15]);
    printf("Regulator: %i \n",serialBuffer[16]);
    printf("Timeout: %i \n",serialBuffer[17]);

}

// Write serial command to change left and right speed
// ***************************************************
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){

    serialBuffer[0] = 88;                                   // 88 =X Steuerbyte um Commands an MD49 zu senden
    serialBuffer[1] = 115;                                  // 115=s Steuerbyte setSpeed
    serialBuffer[2] = speed_l;                              // set speed1
    serialBuffer[3] = speed_r;                              // set speed2
    writeBytes(fd, 4);
}

// Read SpeedL and SpeedR from
// table md49commands(md49data.db)
// *******************************
void read_md49_commands(void){

   // Create SQL statement
   sql = "SELECT * from md49commands WHERE ID=1";

   // Execute SQL statement
   rc = sqlite3_exec(db, sql, sql_callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL message: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      //fprintf(stdout, "Query done successfully\n");
   }
}

// Open serialport
// ***************
int openSerialPort(const char * device, int bps){

   struct termios neu;
   char buf[128];

   //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
   fd = open(device, O_RDWR | O_NOCTTY);

   if (fd == -1)
   {
      sprintf(buf, "openSerialPort %s error", device);
      perror(buf);
   }
   else
   {
      tcgetattr(fd, &orig);                                 /* save current serial settings */
      tcgetattr(fd, &neu);
      cfmakeraw(&neu);
      cfsetispeed(&neu, bps);
      cfsetospeed(&neu, bps);
      tcflush(fd, TCIFLUSH);
      tcsetattr(fd, TCSANOW, &neu);                         /* set new serial settings */
      fcntl (fd, F_SETFL, O_RDWR);
   }
   return fd;
}

// Write bytes serial to UART
// **************************
void writeBytes(int descriptor, int count) {
    if ((write(descriptor, serialBuffer, count)) == -1) {   // Send data out
        perror("Error writing");
        close(descriptor);                                  // Close port if there is an error
        exit(1);
    }

}

// Read bytes serial from UART
// ***************************
void readBytes(int descriptor, int count) {
    if (read(descriptor, serialBuffer, count) == -1) {      // Read back data into buf[]
        perror("Error reading ");
        close(descriptor);                                  // Close port if there is an error
        exit(1);
    }
}

// Open sqlite db md49data.db and create
// table md49data if not existing
// *************************************
void open_sqlite_db_md49data(void){

    // Open database md49data.db and add table md49data
    // ************************************************
    rc = sqlite3_open("data/md49data.db", &db);
    if( rc ){
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        exit(0);
    }else{
        fprintf(stdout, "Opened database successfully,\n");
    }

    // Create table md49data
    // *********************
    sql = "CREATE TABLE md49data("  \
     "ID INT PRIMARY KEY     NOT NULL," \
     "Encoderbyte1L  INT DEFAULT 0, Encoderbyte2L  INT DEFAULT 0," \
     "Encoderbyte3L  INT DEFAULT 0, Encoderbyte4L  INT DEFAULT 0," \
     "Encoderbyte1R  INT DEFAULT 0, Encoderbyte2R  INT DEFAULT 0," \
     "Encoderbyte3R  INT DEFAULT 0, Encoderbyte4R  INT DEFAULT 0," \
     "EncoderL       INT DEFAULT 0, EncoderR       INT DEFAULT 0," \
     "SpeedL         INT DEFAULT 0, SpeedR         INT DEFAULT 0," \
     "Volts          INT DEFAULT 0," \
     "CurrentL       INT DEFAULT 0, CurrentR       INT DEFAULT 0," \
     "Error          INT DEFAULT 0, Acceleration   INT DEFAULT 0," \
     "Mode           INT DEFAULT 0, Regulator      INT DEFAULT 0," \
     "Timeout        INT DEFAULT 0 );" \
     "INSERT INTO md49data (ID) VALUES (1);";

    /* Execute SQL statement */
    rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        fprintf(stdout, "table created successfully\n");
    }
}

// Callbackfunction executed if table md49commands in md49data.db is queried
// *************************************************************************
static int sql_callback(void *data, int argc, char **argv, char **azColName){
   speed_l= atoi(argv[1]);
   speed_r= atoi(argv[2]);
   return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: typeselectionpage.cxx,v $
 * $Revision: 1.16 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#include "typeselectionpage.hxx"
#include "addresssettings.hxx"
#include "abspilot.hxx"
#include <vcl/msgbox.hxx>
#include <com/sun/star/sdbc/XDriverAccess.hpp>

//.........................................................................
namespace abp
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::sdbc;

    //=====================================================================
    //= TypeSelectionPage
    //=====================================================================
    //---------------------------------------------------------------------
    TypeSelectionPage::TypeSelectionPage( OAddessBookSourcePilot* _pParent )
        :AddressBookSourcePage(_pParent, ModuleRes(RID_PAGE_SELECTABTYPE))
        ,m_aHint            (this,  ModuleRes(FT_TYPE_HINTS))
        ,m_aTypeSep         (this,  ModuleRes(FL_TYPE))
        ,m_aMORK            (this,  ModuleRes(RB_MORK))
        ,m_aThunderbird     (this,  ModuleRes(RB_THUNDERBIRD))
        ,m_aEvolutionGroupwise (this,   ModuleRes(RB_EVOLUTION_GROUPWISE))
        ,m_aEvolutionLdap      (this,   ModuleRes(RB_EVOLUTION_LDAP))
        ,m_aEvolution       (this,  ModuleRes(RB_EVOLUTION))
        ,m_aKab             (this,  ModuleRes(RB_KAB))
        ,m_aMacab           (this,  ModuleRes(RB_MACAB))
        ,m_aLDAP            (this,  ModuleRes(RB_LDAP))
        ,m_aOutlook         (this,  ModuleRes(RB_OUTLOOK))
        ,m_aOE              (this,  ModuleRes(RB_OUTLOOKEXPRESS))
        ,m_aOther           (this,  ModuleRes(RB_OTHER))
    {
        Point aTopLeft;
        Size  aItemSize;

        FreeResource();

        aTopLeft = m_aMORK.GetPosPixel();
        aItemSize = m_aMORK.GetSizePixel();

        bool bWithMozilla = true, bUnx = true;
        bool bHaveEvolution = true, bHaveKab = true;
        bool bHaveMacab = true;

#ifndef WITH_MOZILLA
        bWithMozilla = false;
#endif
#ifndef UNX
        bUnx = false;
        bHaveEvolution = false;
        bHaveKab = false;
        bHaveMacab = false;
#else
        Reference< XDriverAccess> xManager(_pParent->getORB()->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdbc.DriverManager"))), UNO_QUERY);

        // check whether Evolution is available
        Reference< XDriver > xDriver( xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sdbc:address:evolution:local"))) );
        if ( !xDriver.is() )
            bHaveEvolution = false;

        // check whether KDE address book is available
        xDriver = xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sdbc:address:kab")));
        if ( !xDriver.is() )
            bHaveKab = false;

        // check whether Mac OS X address book is available
        xDriver = xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sdbc:address:macab")));
        if ( !xDriver.is() )
            bHaveMacab = false;
#endif

        // Items are displayed in list order
        m_aAllTypes.push_back( ButtonItem( &m_aEvolution, AST_EVOLUTION, bHaveEvolution ) );
        m_aAllTypes.push_back( ButtonItem( &m_aEvolutionGroupwise, AST_EVOLUTION_GROUPWISE, bHaveEvolution ) );
        m_aAllTypes.push_back( ButtonItem( &m_aEvolutionLdap, AST_EVOLUTION_LDAP, bHaveEvolution ) );
        m_aAllTypes.push_back( ButtonItem( &m_aMORK, AST_MORK, bWithMozilla ) );
        m_aAllTypes.push_back( ButtonItem( &m_aThunderbird, AST_THUNDERBIRD, bWithMozilla ) );
        m_aAllTypes.push_back( ButtonItem( &m_aKab, AST_KAB, bHaveKab ) );
        m_aAllTypes.push_back( ButtonItem( &m_aMacab, AST_MACAB, bHaveMacab ) );
        m_aAllTypes.push_back( ButtonItem( &m_aLDAP, AST_LDAP, bWithMozilla ) );
        m_aAllTypes.push_back( ButtonItem( &m_aOutlook, AST_OUTLOOK, bWithMozilla && !bUnx ) );
        m_aAllTypes.push_back( ButtonItem( &m_aOE, AST_OE, bWithMozilla && !bUnx ) );
        m_aAllTypes.push_back( ButtonItem( &m_aOther, AST_OTHER, true ) );

        Link aTypeSelectionHandler = LINK(this, TypeSelectionPage, OnTypeSelected );
        for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();
              loop != m_aAllTypes.end(); ++loop )
        {
            ButtonItem aItem = *loop;
            if (!aItem.m_bVisible)
                aItem.m_pItem->Hide();
            else
            {
                aItem.m_pItem->SetPosPixel( aTopLeft );
                aTopLeft.Y() += (aItemSize.Height() * 5) / 4;
                aItem.m_pItem->SetClickHdl( aTypeSelectionHandler );
                aItem.m_pItem->Show();
            }
        }
    }

    //---------------------------------------------------------------------
    void TypeSelectionPage::ActivatePage()
    {
        AddressBookSourcePage::ActivatePage();

        for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();
              loop != m_aAllTypes.end(); ++loop )
        {
            ButtonItem aItem = (*loop);
            if( aItem.m_pItem->IsChecked() && aItem.m_bVisible )
            {
                aItem.m_pItem->GrabFocus();
                break;
            }
        }

        getDialog()->enableButtons(WZB_PREVIOUS, sal_False);
    }

    //---------------------------------------------------------------------
    void TypeSelectionPage::DeactivatePage()
    {
        AddressBookSourcePage::DeactivatePage();
        getDialog()->enableButtons(WZB_PREVIOUS, sal_True);
    }

    //---------------------------------------------------------------------
    void TypeSelectionPage::selectType( AddressSourceType _eType )
    {
        for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();
              loop != m_aAllTypes.end(); ++loop )
        {
            ButtonItem aItem = (*loop);
            aItem.m_pItem->Check( _eType == aItem.m_eType );
        }
    }

    //---------------------------------------------------------------------
    AddressSourceType TypeSelectionPage::getSelectedType() const
    {
        for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();
              loop != m_aAllTypes.end(); ++loop )
        {
            ButtonItem aItem = (*loop);
            if ( aItem.m_pItem->IsChecked() )
                return aItem.m_eType;
        }

        return AST_INVALID;
    }

    //---------------------------------------------------------------------
    void TypeSelectionPage::initializePage()
    {
        AddressBookSourcePage::initializePage();

        const AddressSettings& rSettings = getSettings();
        selectType(rSettings.eType);
    }

    //---------------------------------------------------------------------
    sal_Bool TypeSelectionPage::commitPage( CommitPageReason _eReason )
    {
        if (!AddressBookSourcePage::commitPage(_eReason))
            return sal_False;

        if (AST_INVALID == getSelectedType( ))
        {
            if ( _eReason != eValidateNoUI )
            {
                ErrorBox aError(this, ModuleRes(RID_ERR_NEEDTYPESELECTION));
                aError.Execute();
            }
            return sal_False;
        }

        AddressSettings& rSettings = getSettings();
        rSettings.eType = getSelectedType();

        return sal_True;
    }

    //---------------------------------------------------------------------
    bool TypeSelectionPage::canAdvance() const
    {
        return  AddressBookSourcePage::canAdvance()
            &&  (AST_INVALID != getSelectedType());
    }

    //---------------------------------------------------------------------
    IMPL_LINK( TypeSelectionPage, OnTypeSelected, void*, /*NOTINTERESTEDIN*/ )
    {
        getDialog()->typeSelectionChanged( getSelectedType() );
        updateDialogTravelUI();
        return 0L;
    }

//.........................................................................
}   // namespace abp
//.........................................................................

<commit_msg>INTEGRATION: CWS nomacmozab (1.16.50); FILE MERGED 2008/07/01 20:01:31 fs 1.16.50.1: #i91209# no Mozilla-based address books on mac OS X<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: typeselectionpage.cxx,v $
 * $Revision: 1.17 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#include "typeselectionpage.hxx"
#include "addresssettings.hxx"
#include "abspilot.hxx"
#include <vcl/msgbox.hxx>
#include <com/sun/star/sdbc/XDriverAccess.hpp>

//.........................................................................
namespace abp
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::sdbc;

    //=====================================================================
    //= TypeSelectionPage
    //=====================================================================
    //---------------------------------------------------------------------
    TypeSelectionPage::TypeSelectionPage( OAddessBookSourcePilot* _pParent )
        :AddressBookSourcePage(_pParent, ModuleRes(RID_PAGE_SELECTABTYPE))
        ,m_aHint            (this,  ModuleRes(FT_TYPE_HINTS))
        ,m_aTypeSep         (this,  ModuleRes(FL_TYPE))
        ,m_aMORK            (this,  ModuleRes(RB_MORK))
        ,m_aThunderbird     (this,  ModuleRes(RB_THUNDERBIRD))
        ,m_aEvolutionGroupwise (this,   ModuleRes(RB_EVOLUTION_GROUPWISE))
        ,m_aEvolutionLdap      (this,   ModuleRes(RB_EVOLUTION_LDAP))
        ,m_aEvolution       (this,  ModuleRes(RB_EVOLUTION))
        ,m_aKab             (this,  ModuleRes(RB_KAB))
        ,m_aMacab           (this,  ModuleRes(RB_MACAB))
        ,m_aLDAP            (this,  ModuleRes(RB_LDAP))
        ,m_aOutlook         (this,  ModuleRes(RB_OUTLOOK))
        ,m_aOE              (this,  ModuleRes(RB_OUTLOOKEXPRESS))
        ,m_aOther           (this,  ModuleRes(RB_OTHER))
    {
        Point aTopLeft;
        Size  aItemSize;

        FreeResource();

        aTopLeft = m_aMORK.GetPosPixel();
        aItemSize = m_aMORK.GetSizePixel();

        bool bWithMozilla = true, bUnx = true;
        bool bHaveEvolution = true, bHaveKab = true;
        bool bHaveMacab = true;

#if !defined WITH_MOZILLA || defined MACOSX
        bWithMozilla = false;
#endif
#ifndef UNX
        bUnx = false;
        bHaveEvolution = false;
        bHaveKab = false;
        bHaveMacab = false;
#else
        Reference< XDriverAccess> xManager(_pParent->getORB()->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdbc.DriverManager"))), UNO_QUERY);

        // check whether Evolution is available
        Reference< XDriver > xDriver( xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sdbc:address:evolution:local"))) );
        if ( !xDriver.is() )
            bHaveEvolution = false;

        // check whether KDE address book is available
        xDriver = xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sdbc:address:kab")));
        if ( !xDriver.is() )
            bHaveKab = false;

        // check whether Mac OS X address book is available
        xDriver = xManager->getDriverByURL(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("sdbc:address:macab")));
        if ( !xDriver.is() )
            bHaveMacab = false;
#endif

        // Items are displayed in list order
        m_aAllTypes.push_back( ButtonItem( &m_aEvolution, AST_EVOLUTION, bHaveEvolution ) );
        m_aAllTypes.push_back( ButtonItem( &m_aEvolutionGroupwise, AST_EVOLUTION_GROUPWISE, bHaveEvolution ) );
        m_aAllTypes.push_back( ButtonItem( &m_aEvolutionLdap, AST_EVOLUTION_LDAP, bHaveEvolution ) );
        m_aAllTypes.push_back( ButtonItem( &m_aMORK, AST_MORK, bWithMozilla ) );
        m_aAllTypes.push_back( ButtonItem( &m_aThunderbird, AST_THUNDERBIRD, bWithMozilla ) );
        m_aAllTypes.push_back( ButtonItem( &m_aKab, AST_KAB, bHaveKab ) );
        m_aAllTypes.push_back( ButtonItem( &m_aMacab, AST_MACAB, bHaveMacab ) );
        m_aAllTypes.push_back( ButtonItem( &m_aLDAP, AST_LDAP, bWithMozilla ) );
        m_aAllTypes.push_back( ButtonItem( &m_aOutlook, AST_OUTLOOK, bWithMozilla && !bUnx ) );
        m_aAllTypes.push_back( ButtonItem( &m_aOE, AST_OE, bWithMozilla && !bUnx ) );
        m_aAllTypes.push_back( ButtonItem( &m_aOther, AST_OTHER, true ) );

        Link aTypeSelectionHandler = LINK(this, TypeSelectionPage, OnTypeSelected );
        for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();
              loop != m_aAllTypes.end(); ++loop )
        {
            ButtonItem aItem = *loop;
            if (!aItem.m_bVisible)
                aItem.m_pItem->Hide();
            else
            {
                aItem.m_pItem->SetPosPixel( aTopLeft );
                aTopLeft.Y() += (aItemSize.Height() * 5) / 4;
                aItem.m_pItem->SetClickHdl( aTypeSelectionHandler );
                aItem.m_pItem->Show();
            }
        }
    }

    //---------------------------------------------------------------------
    void TypeSelectionPage::ActivatePage()
    {
        AddressBookSourcePage::ActivatePage();

        for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();
              loop != m_aAllTypes.end(); ++loop )
        {
            ButtonItem aItem = (*loop);
            if( aItem.m_pItem->IsChecked() && aItem.m_bVisible )
            {
                aItem.m_pItem->GrabFocus();
                break;
            }
        }

        getDialog()->enableButtons(WZB_PREVIOUS, sal_False);
    }

    //---------------------------------------------------------------------
    void TypeSelectionPage::DeactivatePage()
    {
        AddressBookSourcePage::DeactivatePage();
        getDialog()->enableButtons(WZB_PREVIOUS, sal_True);
    }

    //---------------------------------------------------------------------
    void TypeSelectionPage::selectType( AddressSourceType _eType )
    {
        for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();
              loop != m_aAllTypes.end(); ++loop )
        {
            ButtonItem aItem = (*loop);
            aItem.m_pItem->Check( _eType == aItem.m_eType );
        }
    }

    //---------------------------------------------------------------------
    AddressSourceType TypeSelectionPage::getSelectedType() const
    {
        for ( ::std::vector< ButtonItem >::const_iterator loop = m_aAllTypes.begin();
              loop != m_aAllTypes.end(); ++loop )
        {
            ButtonItem aItem = (*loop);
            if ( aItem.m_pItem->IsChecked() )
                return aItem.m_eType;
        }

        return AST_INVALID;
    }

    //---------------------------------------------------------------------
    void TypeSelectionPage::initializePage()
    {
        AddressBookSourcePage::initializePage();

        const AddressSettings& rSettings = getSettings();
        selectType(rSettings.eType);
    }

    //---------------------------------------------------------------------
    sal_Bool TypeSelectionPage::commitPage( CommitPageReason _eReason )
    {
        if (!AddressBookSourcePage::commitPage(_eReason))
            return sal_False;

        if (AST_INVALID == getSelectedType( ))
        {
            if ( _eReason != eValidateNoUI )
            {
                ErrorBox aError(this, ModuleRes(RID_ERR_NEEDTYPESELECTION));
                aError.Execute();
            }
            return sal_False;
        }

        AddressSettings& rSettings = getSettings();
        rSettings.eType = getSelectedType();

        return sal_True;
    }

    //---------------------------------------------------------------------
    bool TypeSelectionPage::canAdvance() const
    {
        return  AddressBookSourcePage::canAdvance()
            &&  (AST_INVALID != getSelectedType());
    }

    //---------------------------------------------------------------------
    IMPL_LINK( TypeSelectionPage, OnTypeSelected, void*, /*NOTINTERESTEDIN*/ )
    {
        getDialog()->typeSelectionChanged( getSelectedType() );
        updateDialogTravelUI();
        return 0L;
    }

//.........................................................................
}   // namespace abp
//.........................................................................

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_utils_to_throttle.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_utils_to_throttle.C
/// @brief Sets throttles
/// TMGT will call this procedure to set the N address operations (commands)
/// allowed within a window of M DRAM clocks given the minimum dram data bus utilization.
///

// *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB

#include <p9_mss_utils_to_throttle.H>

// fapi2
#include <fapi2.H>

// mss lib
#include <lib/power_thermal/throttle.H>
#include <lib/utils/index.H>
#include <lib/utils/find.H>
#include <lib/utils/conversions.H>
#include <lib/mss_attribute_accessors.H>

using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;

extern "C"
{

///
/// @brief Sets number commands allowed within a given data bus utilization.
/// @param[in] i_targets vector of MCS on the same VDDR domain
/// @return FAPI2_RC_SUCCESS iff ok
/// @note throttle_per_slot will be equalized so all throttles coming out will be equal to worst case
///
    fapi2::ReturnCode p9_mss_utils_to_throttle( const std::vector< fapi2::Target<TARGET_TYPE_MCS> >& i_targets )
    {
        for( const auto& l_mcs : i_targets )
        {
            //TODO RTC 160048 Complete implementing (calculating power and per slot throttles) - JLH
            uint32_t l_databus_util [mss::PORTS_PER_MCS];
            uint32_t l_throttled_cmds_port[mss::PORTS_PER_MCS];
            uint32_t l_throttled_cmds_slot[mss::PORTS_PER_MCS];
            uint32_t l_max_power[mss::PORTS_PER_MCS];

            uint32_t l_dram_clocks = 0;
            FAPI_TRY( mss::mrw_mem_m_dram_clocks(l_dram_clocks) );

            FAPI_TRY( mss::databus_util(l_mcs, l_databus_util) );

            for( const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(l_mcs) )
            {
                const auto l_port_num = mss::index( l_mca );

                FAPI_INF( "MRW dram clock window: %d, databus utilization: %d",
                          l_dram_clocks,
                          l_databus_util );

                // Calculate programmable N address operations within M dram clock window
                l_throttled_cmds_port[l_port_num] = mss::power_thermal::throttled_cmds( l_databus_util[l_port_num], l_dram_clocks );
                l_throttled_cmds_slot[l_port_num] = mss::power_thermal::throttled_cmds( l_databus_util[l_port_num], l_dram_clocks );
                //TK - actually implement function - JLH
                //Quick hard code for API purposes
                l_max_power[l_port_num] = 2088;
                FAPI_INF( "Calculated N commands per port [%d] = %d",
                          l_port_num,
                          l_throttled_cmds_port[l_port_num]);
            }// end for

            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_PORT_MAXPOWER,
                                    l_mcs,
                                    l_max_power) );
            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_RUNTIME_MEM_THROTTLED_N_COMMANDS_PER_SLOT,
                                    l_mcs,
                                    l_throttled_cmds_slot) );
            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_RUNTIME_MEM_THROTTLED_N_COMMANDS_PER_PORT,
                                    l_mcs,
                                    l_throttled_cmds_port) );
        }

    fapi_try_exit:
        return fapi2::current_err;
    }

}// extern C
<commit_msg>Implement L2 eff_config_thermal, bulk_pwr_throttle<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_utils_to_throttle.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_utils_to_throttle.C
/// @brief Sets throttles
/// TMGT will call this procedure to set the N address operations (commands)
/// allowed within a window of M DRAM clocks given the minimum dram data bus utilization.
///

// *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <p9_mss_utils_to_throttle.H>

// fapi2
#include <fapi2.H>

// mss lib
#include <lib/power_thermal/throttle.H>
#include <lib/utils/index.H>
#include <lib/utils/find.H>
#include <lib/utils/conversions.H>
#include <lib/power_thermal/throttle.H>
#include <lib/mss_attribute_accessors.H>

using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;

extern "C"
{

///
/// @brief Sets number commands allowed within a given data bus utilization.
/// @param[in] i_targets vector of MCS on the same VDDR domain
/// @return FAPI2_RC_SUCCESS iff ok
/// @note throttle_per_slot will be equalized so all throttles coming out will be equal to worst case
///
    fapi2::ReturnCode p9_mss_utils_to_throttle( const std::vector< fapi2::Target<TARGET_TYPE_MCS> >& i_targets )
    {
        for( const auto& l_mcs : i_targets )
        {
            uint32_t l_databus_util [mss::PORTS_PER_MCS];
            uint32_t l_dram_clocks = 0;

            uint16_t l_throttled_cmds_port[mss::PORTS_PER_MCS];
            uint16_t l_throttled_cmds_slot[mss::PORTS_PER_MCS];
            uint32_t l_max_power[mss::PORTS_PER_MCS];

            FAPI_TRY( mss::mrw_mem_m_dram_clocks(l_dram_clocks) );
            //Util attribute set by OCC
            FAPI_TRY( mss::databus_util(l_mcs, l_databus_util) );

            for( const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(l_mcs) )
            {
                const auto l_port_num = mss::index( l_mca );
                //Make a throttle object in order to calculate the port power
                fapi2::ReturnCode l_rc;
                mss::power_thermal::throttle l_throttle (l_mca, l_rc);
                FAPI_TRY(l_rc, "Error calculating mss::power_thermal::throttle constructor in p9_mss_utils_to_throttles");

                FAPI_INF( "MRW dram clock window: %d, databus utilization: %d",
                          l_dram_clocks,
                          l_databus_util);

                //Calculate programmable N address operations within M dram clock window
                l_throttled_cmds_port[l_port_num] = mss::power_thermal::throttled_cmds(l_databus_util[l_port_num],
                                                    l_dram_clocks );
                l_throttled_cmds_slot[l_port_num] = l_throttled_cmds_port[l_port_num];
                //Calculate the port power needed to reach the calculated N value
                l_max_power[l_port_num] = l_throttle.calc_power_from_n(l_throttled_cmds_slot[l_port_num]);

                FAPI_INF( "Calculated N commands per port [%d] = %d commands, maxpower is %d",
                          l_port_num,
                          l_throttled_cmds_port[l_port_num],
                          l_max_power[l_port_num]);
            }// end for

            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_PORT_MAXPOWER,
                                    l_mcs,
                                    l_max_power) );
            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT,
                                    l_mcs,
                                    l_throttled_cmds_slot) );
            FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_PORT,
                                    l_mcs,
                                    l_throttled_cmds_port) );
        }

    fapi_try_exit:
        return fapi2::current_err;
    }

}// extern C
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "maintenancecontroller.h"
#include "maintenancejobrunner.h"
#include "document_db_maintenance_config.h"
#include "i_blockable_maintenance_job.h"
#include <vespa/searchcorespi/index/i_thread_service.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <vespa/vespalib/util/scheduledexecutor.h>

#include <vespa/log/log.h>
LOG_SETUP(".proton.server.maintenancecontroller");

using document::BucketId;
using vespalib::Executor;
using vespalib::makeLambdaTask;

namespace proton {

namespace {

class JobWrapperTask : public Executor::Task
{
private:
    MaintenanceJobRunner *_job;
public:
    JobWrapperTask(MaintenanceJobRunner *job) : _job(job) {}
    void run() override { _job->run(); }
};

}

MaintenanceController::MaintenanceController(IThreadService &masterThread,
                                             vespalib::Executor & defaultExecutor,
                                             const DocTypeName &docTypeName)
    : IBucketFreezeListener(),
      _masterThread(masterThread),
      _defaultExecutor(defaultExecutor),
      _readySubDB(),
      _remSubDB(),
      _notReadySubDB(),
      _periodicTimer(),
      _config(),
      _frozenBuckets(masterThread),
      _state(State::INITIALIZING),
      _docTypeName(docTypeName),
      _jobs(),
      _jobsLock()
{
    _frozenBuckets.addListener(this); // forward freeze/thaw to bmc
}

MaintenanceController::~MaintenanceController()
{
    kill();
    _frozenBuckets.removeListener(this);
}

void
MaintenanceController::registerJobInMasterThread(IMaintenanceJob::UP job)
{
    // Called by master write thread
    registerJob(_masterThread, std::move(job));
}

void
MaintenanceController::registerJobInDefaultPool(IMaintenanceJob::UP job)
{
    // Called by master write thread
    registerJob(_defaultExecutor, std::move(job));
}

void
MaintenanceController::registerJob(Executor & executor, IMaintenanceJob::UP job)
{
    // Called by master write thread
    Guard guard(_jobsLock);
    _jobs.push_back(std::make_shared<MaintenanceJobRunner>(executor, std::move(job)));
}

void
MaintenanceController::killJobs()
{
    if (_state == State::STARTED) {
        _state = State::PAUSED;
    }
    // Called by master write thread
    assert(_masterThread.isCurrentThread());
    LOG(debug, "killJobs(): threadId=%zu", (size_t)FastOS_Thread::GetCurrentThreadId());
    _periodicTimer.reset();
    // No need to take _jobsLock as modification of _jobs also happens in master write thread.
    for (auto &job : _jobs) {
        job->stop(); // Make sure no more tasks are added to the executor
    }
    for (auto &job : _jobs) {
        while (job->isRunning()) {
            std::this_thread::sleep_for(1ms);
        }
    }
    JobList tmpJobs = _jobs;
    {
        Guard guard(_jobsLock);
        _jobs.clear();
    }
    // Hold jobs until existing tasks have been drained
    _masterThread.execute(makeLambdaTask([this, jobs=std::move(tmpJobs)]() {
        performHoldJobs(std::move(jobs));
    }));
}

void
MaintenanceController::updateMetrics(DocumentDBTaggedMetrics & metrics)
{
    Guard guard(_jobsLock);
    for (auto &job : _jobs) {
        job->getJob().updateMetrics(metrics); // Make sure no more tasks are added to the executor
    }
}

void
MaintenanceController::performHoldJobs(JobList jobs)
{
    // Called by master write thread
    LOG(debug, "performHoldJobs(): threadId=%zu", (size_t)FastOS_Thread::GetCurrentThreadId());
    (void) jobs;
}

void
MaintenanceController::stop()
{
    assert(!_masterThread.isCurrentThread());
    _masterThread.execute(makeLambdaTask([this]() { _state = State::STOPPING; killJobs(); }));
    _masterThread.sync();  // Wait for killJobs()
    _masterThread.sync();  // Wait for already scheduled maintenance jobs and performHoldJobs
}

void
MaintenanceController::kill()
{
    stop();
    _readySubDB.clear();
    _remSubDB.clear();
    _notReadySubDB.clear();
}

void
MaintenanceController::start(const DocumentDBMaintenanceConfig::SP &config)
{
    // Called by master write thread
    assert(_state == State::INITIALIZING);
    _config = config;
    _state = State::STARTED;
    restart();
}

void
MaintenanceController::restart()
{
    // Called by master write thread
    if (!getStarted() || getStopping() || !_readySubDB.valid()) {
        return;
    }
    _periodicTimer = std::make_unique<vespalib::ScheduledExecutor>();

    addJobsToPeriodicTimer();
}

void
MaintenanceController::addJobsToPeriodicTimer()
{
    // No need to take _jobsLock as modification of _jobs also happens in master write thread.
    for (const auto &jw : _jobs) {
        const IMaintenanceJob &job = jw->getJob();
        LOG(debug, "addJobsToPeriodicTimer(): docType='%s', job.name='%s', job.delay=%f, job.interval=%f",
                _docTypeName.getName().c_str(), job.getName().c_str(), vespalib::to_s(job.getDelay()), vespalib::to_s(job.getInterval()));
        if (job.getInterval() == vespalib::duration::zero()) {
            jw->run();
            continue;
        }
        _periodicTimer->scheduleAtFixedRate(std::make_unique<JobWrapperTask>(jw.get()),
                                            job.getDelay(), job.getInterval());
    }
}

void
MaintenanceController::newConfig(const DocumentDBMaintenanceConfig::SP &config)
{
    // Called by master write thread
    _config = config;
    restart();
}

namespace {

void
assert_equal_meta_store_instances(const MaintenanceDocumentSubDB& old_db,
                                  const MaintenanceDocumentSubDB& new_db)
{
    if (old_db.valid() && new_db.valid()) {
        assert(old_db.meta_store().get() == new_db.meta_store().get());
    }
}

}

void
MaintenanceController::syncSubDBs(const MaintenanceDocumentSubDB &readySubDB,
                                  const MaintenanceDocumentSubDB &remSubDB,
                                  const MaintenanceDocumentSubDB &notReadySubDB)
{
    // Called by master write thread
    bool oldValid = _readySubDB.valid();
    assert(readySubDB.valid());
    assert(remSubDB.valid());
    // Document meta store instances should not change. Maintenance jobs depend on this fact.
    assert_equal_meta_store_instances(_readySubDB, readySubDB);
    assert_equal_meta_store_instances(_remSubDB, remSubDB);
    assert_equal_meta_store_instances(_notReadySubDB, notReadySubDB);
    _readySubDB = readySubDB;
    _remSubDB = remSubDB;
    _notReadySubDB = notReadySubDB;
    if (!oldValid && getStarted()) {
        restart();
    }
}

void
MaintenanceController::notifyThawedBucket(const BucketId &bucket)
{
    (void) bucket;
    // No need to take _jobsLock as modification of _jobs also happens in master write thread.
    for (const auto &jw : _jobs) {
        IBlockableMaintenanceJob *job = jw->getJob().asBlockable();
        if (job && job->isBlocked()) {
            job->unBlock(IBlockableMaintenanceJob::BlockedReason::FROZEN_BUCKET);
        }
    }
}

} // namespace proton
<commit_msg>Include thread when needed.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "maintenancecontroller.h"
#include "maintenancejobrunner.h"
#include "document_db_maintenance_config.h"
#include "i_blockable_maintenance_job.h"
#include <vespa/searchcorespi/index/i_thread_service.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <vespa/vespalib/util/scheduledexecutor.h>
#include <thread>

#include <vespa/log/log.h>
LOG_SETUP(".proton.server.maintenancecontroller");

using document::BucketId;
using vespalib::Executor;
using vespalib::makeLambdaTask;

namespace proton {

namespace {

class JobWrapperTask : public Executor::Task
{
private:
    MaintenanceJobRunner *_job;
public:
    JobWrapperTask(MaintenanceJobRunner *job) : _job(job) {}
    void run() override { _job->run(); }
};

}

MaintenanceController::MaintenanceController(IThreadService &masterThread,
                                             vespalib::Executor & defaultExecutor,
                                             const DocTypeName &docTypeName)
    : IBucketFreezeListener(),
      _masterThread(masterThread),
      _defaultExecutor(defaultExecutor),
      _readySubDB(),
      _remSubDB(),
      _notReadySubDB(),
      _periodicTimer(),
      _config(),
      _frozenBuckets(masterThread),
      _state(State::INITIALIZING),
      _docTypeName(docTypeName),
      _jobs(),
      _jobsLock()
{
    _frozenBuckets.addListener(this); // forward freeze/thaw to bmc
}

MaintenanceController::~MaintenanceController()
{
    kill();
    _frozenBuckets.removeListener(this);
}

void
MaintenanceController::registerJobInMasterThread(IMaintenanceJob::UP job)
{
    // Called by master write thread
    registerJob(_masterThread, std::move(job));
}

void
MaintenanceController::registerJobInDefaultPool(IMaintenanceJob::UP job)
{
    // Called by master write thread
    registerJob(_defaultExecutor, std::move(job));
}

void
MaintenanceController::registerJob(Executor & executor, IMaintenanceJob::UP job)
{
    // Called by master write thread
    Guard guard(_jobsLock);
    _jobs.push_back(std::make_shared<MaintenanceJobRunner>(executor, std::move(job)));
}

void
MaintenanceController::killJobs()
{
    if (_state == State::STARTED) {
        _state = State::PAUSED;
    }
    // Called by master write thread
    assert(_masterThread.isCurrentThread());
    LOG(debug, "killJobs(): threadId=%zu", (size_t)FastOS_Thread::GetCurrentThreadId());
    _periodicTimer.reset();
    // No need to take _jobsLock as modification of _jobs also happens in master write thread.
    for (auto &job : _jobs) {
        job->stop(); // Make sure no more tasks are added to the executor
    }
    for (auto &job : _jobs) {
        while (job->isRunning()) {
            std::this_thread::sleep_for(1ms);
        }
    }
    JobList tmpJobs = _jobs;
    {
        Guard guard(_jobsLock);
        _jobs.clear();
    }
    // Hold jobs until existing tasks have been drained
    _masterThread.execute(makeLambdaTask([this, jobs=std::move(tmpJobs)]() {
        performHoldJobs(std::move(jobs));
    }));
}

void
MaintenanceController::updateMetrics(DocumentDBTaggedMetrics & metrics)
{
    Guard guard(_jobsLock);
    for (auto &job : _jobs) {
        job->getJob().updateMetrics(metrics); // Make sure no more tasks are added to the executor
    }
}

void
MaintenanceController::performHoldJobs(JobList jobs)
{
    // Called by master write thread
    LOG(debug, "performHoldJobs(): threadId=%zu", (size_t)FastOS_Thread::GetCurrentThreadId());
    (void) jobs;
}

void
MaintenanceController::stop()
{
    assert(!_masterThread.isCurrentThread());
    _masterThread.execute(makeLambdaTask([this]() { _state = State::STOPPING; killJobs(); }));
    _masterThread.sync();  // Wait for killJobs()
    _masterThread.sync();  // Wait for already scheduled maintenance jobs and performHoldJobs
}

void
MaintenanceController::kill()
{
    stop();
    _readySubDB.clear();
    _remSubDB.clear();
    _notReadySubDB.clear();
}

void
MaintenanceController::start(const DocumentDBMaintenanceConfig::SP &config)
{
    // Called by master write thread
    assert(_state == State::INITIALIZING);
    _config = config;
    _state = State::STARTED;
    restart();
}

void
MaintenanceController::restart()
{
    // Called by master write thread
    if (!getStarted() || getStopping() || !_readySubDB.valid()) {
        return;
    }
    _periodicTimer = std::make_unique<vespalib::ScheduledExecutor>();

    addJobsToPeriodicTimer();
}

void
MaintenanceController::addJobsToPeriodicTimer()
{
    // No need to take _jobsLock as modification of _jobs also happens in master write thread.
    for (const auto &jw : _jobs) {
        const IMaintenanceJob &job = jw->getJob();
        LOG(debug, "addJobsToPeriodicTimer(): docType='%s', job.name='%s', job.delay=%f, job.interval=%f",
                _docTypeName.getName().c_str(), job.getName().c_str(), vespalib::to_s(job.getDelay()), vespalib::to_s(job.getInterval()));
        if (job.getInterval() == vespalib::duration::zero()) {
            jw->run();
            continue;
        }
        _periodicTimer->scheduleAtFixedRate(std::make_unique<JobWrapperTask>(jw.get()),
                                            job.getDelay(), job.getInterval());
    }
}

void
MaintenanceController::newConfig(const DocumentDBMaintenanceConfig::SP &config)
{
    // Called by master write thread
    _config = config;
    restart();
}

namespace {

void
assert_equal_meta_store_instances(const MaintenanceDocumentSubDB& old_db,
                                  const MaintenanceDocumentSubDB& new_db)
{
    if (old_db.valid() && new_db.valid()) {
        assert(old_db.meta_store().get() == new_db.meta_store().get());
    }
}

}

void
MaintenanceController::syncSubDBs(const MaintenanceDocumentSubDB &readySubDB,
                                  const MaintenanceDocumentSubDB &remSubDB,
                                  const MaintenanceDocumentSubDB &notReadySubDB)
{
    // Called by master write thread
    bool oldValid = _readySubDB.valid();
    assert(readySubDB.valid());
    assert(remSubDB.valid());
    // Document meta store instances should not change. Maintenance jobs depend on this fact.
    assert_equal_meta_store_instances(_readySubDB, readySubDB);
    assert_equal_meta_store_instances(_remSubDB, remSubDB);
    assert_equal_meta_store_instances(_notReadySubDB, notReadySubDB);
    _readySubDB = readySubDB;
    _remSubDB = remSubDB;
    _notReadySubDB = notReadySubDB;
    if (!oldValid && getStarted()) {
        restart();
    }
}

void
MaintenanceController::notifyThawedBucket(const BucketId &bucket)
{
    (void) bucket;
    // No need to take _jobsLock as modification of _jobs also happens in master write thread.
    for (const auto &jw : _jobs) {
        IBlockableMaintenanceJob *job = jw->getJob().asBlockable();
        if (job && job->isBlocked()) {
            job->unBlock(IBlockableMaintenanceJob::BlockedReason::FROZEN_BUCKET);
        }
    }
}

} // namespace proton
<|endoftext|>


<commit_before>#ifndef ORG_PQRS_TYPES_HPP
#define ORG_PQRS_TYPES_HPP

#include <IOKit/IOLib.h>
#include <IOKit/IOTimerEventSource.h>
#include "bridge.h"
#include "Vector.hpp"

namespace org_pqrs_Karabiner {
class AddDataType final {
public:
  AddDataType(void) : value_(BRIDGE_DATATYPE_NONE) {}
  explicit AddDataType(unsigned int v) : value_(v) {}
  operator unsigned int(void) {
    return value_;
  }

private:
  unsigned int value_;
};

class AddValue final {
public:
  AddValue(void) : value_(0) {}
  explicit AddValue(unsigned int v) : value_(v) {}
  operator unsigned int(void) {
    return value_;
  }

private:
  unsigned int value_;
};
DECLARE_VECTOR(AddValue);

class AddValueWithDataType final {
public:
  AddValueWithDataType(void) {}
  AddValueWithDataType(AddDataType d, AddValue v) : dataType(d), value(v) {}
  AddDataType dataType;
  AddValue value;
};
DECLARE_VECTOR(AddValueWithDataType);
}

class AutogenId final {
public:
  explicit AutogenId(uint64_t v) : value_(v) {}
  operator uint64_t(void) {
    return value_;
  }
  bool operator>(AutogenId other) const { return value_ > other.value_; }
  bool operator>=(AutogenId other) const { return value_ >= other.value_; }
  bool operator<(AutogenId other) const { return value_ < other.value_; }
  bool operator<=(AutogenId other) const { return value_ <= other.value_; }

  static AutogenId maxValue(void) {
    //       1234567812345678
    return AutogenId(0xffffffffffffffff);
  }

private:
  uint64_t value_;
};

#endif
<commit_msg>add PhysicalEventType<commit_after>#ifndef ORG_PQRS_TYPES_HPP
#define ORG_PQRS_TYPES_HPP

#include <IOKit/IOLib.h>
#include <IOKit/IOTimerEventSource.h>
#include "bridge.h"
#include "Vector.hpp"

namespace org_pqrs_Karabiner {
class AddDataType final {
public:
  AddDataType(void) : value_(BRIDGE_DATATYPE_NONE) {}
  explicit AddDataType(unsigned int v) : value_(v) {}
  operator unsigned int(void) {
    return value_;
  }

private:
  unsigned int value_;
};

class AddValue final {
public:
  AddValue(void) : value_(0) {}
  explicit AddValue(unsigned int v) : value_(v) {}
  operator unsigned int(void) {
    return value_;
  }

private:
  unsigned int value_;
};
DECLARE_VECTOR(AddValue);

class AddValueWithDataType final {
public:
  AddValueWithDataType(void) {}
  AddValueWithDataType(AddDataType d, AddValue v) : dataType(d), value(v) {}
  AddDataType dataType;
  AddValue value;
};
DECLARE_VECTOR(AddValueWithDataType);
}

class AutogenId final {
public:
  explicit AutogenId(uint64_t v) : value_(v) {}
  operator uint64_t(void) {
    return value_;
  }
  bool operator>(AutogenId other) const { return value_ > other.value_; }
  bool operator>=(AutogenId other) const { return value_ >= other.value_; }
  bool operator<(AutogenId other) const { return value_ < other.value_; }
  bool operator<=(AutogenId other) const { return value_ <= other.value_; }

  static AutogenId maxValue(void) {
    //       1234567812345678
    return AutogenId(0xffffffffffffffff);
  }

private:
  uint64_t value_;
};

enum class PhysicalEventType {
  DOWN,
  UP,
  // We do not provide PhysicalEventType::MODIFY. Use DOWN or UP for modifier events.
};

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include "folderlistmodel.h"
#include <QMailAccount>
#include <QMailFolder>
#include <QMailMessage>
#include <QMailMessageKey>
#include <QMailStore>
#include <QDateTime>
#include <QTimer>
#include <QProcess>
#include <qmailnamespace.h>
#include <libedataserver/e-account-list.h>
#include <libedataserver/e-list.h>
#include <gconf/gconf-client.h>

FolderListModel::FolderListModel(QObject *parent) :
    QAbstractListModel(parent)
{
    QHash<int, QByteArray> roles;
    roles.insert(FolderName, "folderName");
    roles.insert(FolderId, "folderId");
    roles.insert(FolderUnreadCount, "folderUnreadCount");
    roles.insert(FolderServerCount, "folderServerCount");
    setRoleNames(roles);
    m_outbox_proxy = NULL;
    m_sent_proxy = NULL;
    m_drafts_proxy = NULL;
}

FolderListModel::~FolderListModel()
{
}

int FolderListModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_folderlist.count();
}

QVariant FolderListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() > m_folderlist.count())
        return QVariant();

    CamelFolderInfoVariant  folder(m_folderlist[index.row()]);
    if (role == FolderName)
    {
	QString displayName;

        if (folder.full_name == ".#evolution/Junk")
                displayName = QString ("Junk");
        else if (folder.full_name == ".#evolution/Trash")
                displayName = QString ("Trash");
        else {
                displayName = QString (folder.full_name);
                displayName.replace (QString("/"), QString(" / "));
        }

        return QVariant(displayName);
    }
    else if (role == FolderId)
    {
        return QVariant(folder.uri);
    }
    else if (role == FolderUnreadCount)
    {
        return QVariant ((folder.unread_count == -1) ? 0 : folder.unread_count );
    }
    else if (role == FolderServerCount)
    {
        return QVariant ((folder.total_mail_count == -1) ? 0 : folder.total_mail_count);
    }

    return QVariant();
}

EAccount * FolderListModel::getAccountById(EAccountList *account_list, char *id)
{
    EIterator *iter;
    EAccount *account = NULL;

    iter = e_list_get_iterator (E_LIST (account_list));
    while (e_iterator_is_valid (iter)) {
        account = (EAccount *) e_iterator_get (iter);
        if (strcmp (id, account->uid) == 0)
             return account;
        e_iterator_next (iter);
    }

    g_object_unref (iter);

    return NULL;
}

void FolderListModel::setAccountKey(QVariant id)
{
    GConfClient *client;
    EAccountList *account_list;
    QString quid;
    const char *url;

    client = gconf_client_get_default ();
    account_list = e_account_list_new (client);
    g_object_unref (client);

    quid = id.value<QString>();
    m_account = getAccountById (account_list, (char *)quid.toLocal8Bit().constData());
    url = e_account_get_string (m_account, E_ACCOUNT_SOURCE_URL);

    g_print ("fetching store: %s\n", url);
    OrgGnomeEvolutionDataserverMailSessionInterface *instance = OrgGnomeEvolutionDataserverMailSessionInterface::instance(this);
    if (instance && instance->isValid()) {
	QDBusPendingReply<QDBusObjectPath> reply = instance->getStore (QString(url));
        reply.waitForFinished();
        m_store_proxy_id = reply.value();
	g_print ("Store PATH: %s\n", (char *) m_store_proxy_id.path().toLocal8Bit().constData());
        m_store_proxy = new OrgGnomeEvolutionDataserverMailStoreInterface (QString ("org.gnome.evolution.dataserver.Mail"),
									m_store_proxy_id.path(),
									QDBusConnection::sessionBus(), this);

	if (m_store_proxy && m_store_proxy->isValid()) {
		QDBusPendingReply<CamelFolderInfoArrayVariant> reply = m_store_proxy->getFolderInfo (QString(""),
									CAMEL_STORE_FOLDER_INFO_RECURSIVE|CAMEL_STORE_FOLDER_INFO_FAST | CAMEL_STORE_FOLDER_INFO_SUBSCRIBED);
		reply.waitForFinished();
		m_folderlist = reply.value ();
	g_print ("Got folder list....\n");

	}

	if (!m_outbox_proxy) {
		reply = instance->getLocalFolder (QString("Outbox"));
		reply.waitForFinished();
        	m_outbox_proxy_id = reply.value();

		m_outbox_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString ("org.gnome.evolution.dataserver.Mail"),
										     m_outbox_proxy_id.path(),
										     QDBusConnection::sessionBus(), this);
	}

	reply = instance->getFolderFromUri (QString(m_account->sent_folder_uri));
        reply.waitForFinished();
        m_sent_proxy_id = reply.value();
	m_sent_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString ("org.gnome.evolution.dataserver.Mail"),
									     m_sent_proxy_id.path(),
									     QDBusConnection::sessionBus(), this);

	reply = instance->getFolderFromUri (QString(m_account->drafts_folder_uri));
        reply.waitForFinished();
        m_drafts_proxy_id = reply.value();
	m_drafts_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString ("org.gnome.evolution.dataserver.Mail"),
									     m_drafts_proxy_id.path(),
									     QDBusConnection::sessionBus(), this);
    }
}

QStringList FolderListModel::folderNames()
{
    QStringList folderNames;

    foreach (CamelFolderInfoVariant fInfo, m_folderlist)
    {
        QString displayName;

	if (fInfo.full_name == ".#evolution/Junk")
		displayName = QString ("Junk");
	else if (fInfo.full_name == ".#evolution/Trash")
		displayName = QString ("Trash");
	else {
		displayName = QString (fInfo.full_name);
		displayName.replace (QString("/"), QString(" / "));
	}

        if (fInfo.unread_count > 0)
        {
            displayName = displayName + " (" + QString::number(fInfo.unread_count) + ")";
        }

        folderNames << displayName;
	g_print("FOLDER: %s\n", (char *)displayName.toLocal8Bit().constData());
    }
    return folderNames;
}

QVariant FolderListModel::folderId(int index)
{
    if (index < 0 || index >= m_folderlist.count())
        return QVariant();

    return m_folderlist[index].uri;
}

int FolderListModel::indexFromFolderId(QVariant vFolderId)
{

    QString uri = vFolderId.toString();
    g_print ("Entering FolderListModel::indexFromFolderId: %s\n", (char *)uri.toLocal8Bit().constData());
    for (int i = 0; i < m_folderlist.size(); i ++)
    {
        if (vFolderId == 0) {
	        CamelFolderInfoVariant folder(m_folderlist[i]);
        	if (QString::compare(folder.full_name, "INBOX", Qt::CaseInsensitive) == 0)
			return i;

	} else {
        	if (uri == m_folderlist[i].uri)
            		return i;
	}
    }
    return -1;
}

QVariant FolderListModel::folderServerCount(QVariant vFolderId)
{
    QString uri = vFolderId.toString();

    for (int i = 0; i < m_folderlist.size(); i ++)
    {
        if (uri == m_folderlist[i].uri)
            return QVariant(m_folderlist[i].total_mail_count);
    }
    return QVariant(-1);
}

QVariant FolderListModel::inboxFolderId()
{
    for (int i = 0; i < m_folderlist.size(); i++)
    {
        CamelFolderInfoVariant folder(m_folderlist[i]);
        if (QString::compare(folder.full_name, "INBOX", Qt::CaseInsensitive) == 0) {
	    g_print ("Returning INBOX URI: %s\n", (char *)folder.uri.toLocal8Bit().constData());
            return QVariant(folder.uri);
	}
    }

    return QVariant();
}

QVariant FolderListModel::inboxFolderName()
{
    for (int i = 0; i < m_folderlist.size(); i++)
    {
        CamelFolderInfoVariant folder(m_folderlist[i]);

       if (QString::compare(folder.full_name, "INBOX", Qt::CaseInsensitive) == 0) {
            g_print ("Returning INBOX URI: %s\n", (char *)folder.uri.toLocal8Bit().constData());
            return QVariant(folder.folder_name);
        }
    }
    return QVariant("");
}

int FolderListModel::totalNumberOfFolders()
{
    return m_folderlist.size();
}
<commit_msg>Dont set the same account key again.<commit_after>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include "folderlistmodel.h"
#include <QMailAccount>
#include <QMailFolder>
#include <QMailMessage>
#include <QMailMessageKey>
#include <QMailStore>
#include <QDateTime>
#include <QTimer>
#include <QProcess>
#include <qmailnamespace.h>
#include <libedataserver/e-account-list.h>
#include <libedataserver/e-list.h>
#include <gconf/gconf-client.h>

FolderListModel::FolderListModel(QObject *parent) :
    QAbstractListModel(parent)
{
    QHash<int, QByteArray> roles;
    roles.insert(FolderName, "folderName");
    roles.insert(FolderId, "folderId");
    roles.insert(FolderUnreadCount, "folderUnreadCount");
    roles.insert(FolderServerCount, "folderServerCount");
    setRoleNames(roles);
    m_outbox_proxy = NULL;
    m_sent_proxy = NULL;
    m_drafts_proxy = NULL;
}

FolderListModel::~FolderListModel()
{
}

int FolderListModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_folderlist.count();
}

QVariant FolderListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() > m_folderlist.count())
        return QVariant();

    CamelFolderInfoVariant  folder(m_folderlist[index.row()]);
    if (role == FolderName)
    {
	QString displayName;

        if (folder.full_name == ".#evolution/Junk")
                displayName = QString ("Junk");
        else if (folder.full_name == ".#evolution/Trash")
                displayName = QString ("Trash");
        else {
                displayName = QString (folder.full_name);
                displayName.replace (QString("/"), QString(" / "));
        }

        return QVariant(displayName);
    }
    else if (role == FolderId)
    {
        return QVariant(folder.uri);
    }
    else if (role == FolderUnreadCount)
    {
        return QVariant ((folder.unread_count == -1) ? 0 : folder.unread_count );
    }
    else if (role == FolderServerCount)
    {
        return QVariant ((folder.total_mail_count == -1) ? 0 : folder.total_mail_count);
    }

    return QVariant();
}

EAccount * FolderListModel::getAccountById(EAccountList *account_list, char *id)
{
    EIterator *iter;
    EAccount *account = NULL;

    iter = e_list_get_iterator (E_LIST (account_list));
    while (e_iterator_is_valid (iter)) {
        account = (EAccount *) e_iterator_get (iter);
        if (strcmp (id, account->uid) == 0)
             return account;
        e_iterator_next (iter);
    }

    g_object_unref (iter);

    return NULL;
}

void FolderListModel::setAccountKey(QVariant id)
{
    GConfClient *client;
    EAccountList *account_list;
    QString quid;
    const char *url;

    if (m_account && m_account->uid && strcmp (m_account->uid, (const char *)id.toString().toLocal8Bit().constData()) == 0) {
	return;
    }

    client = gconf_client_get_default ();
    account_list = e_account_list_new (client);
    g_object_unref (client);

    quid = id.value<QString>();
    m_account = getAccountById (account_list, (char *)quid.toLocal8Bit().constData());
    url = e_account_get_string (m_account, E_ACCOUNT_SOURCE_URL);

    g_print ("fetching store: %s\n", url);
    OrgGnomeEvolutionDataserverMailSessionInterface *instance = OrgGnomeEvolutionDataserverMailSessionInterface::instance(this);
    if (instance && instance->isValid()) {
	QDBusPendingReply<QDBusObjectPath> reply = instance->getStore (QString(url));
        reply.waitForFinished();
        m_store_proxy_id = reply.value();
	g_print ("Store PATH: %s\n", (char *) m_store_proxy_id.path().toLocal8Bit().constData());
        m_store_proxy = new OrgGnomeEvolutionDataserverMailStoreInterface (QString ("org.gnome.evolution.dataserver.Mail"),
									m_store_proxy_id.path(),
									QDBusConnection::sessionBus(), this);

	if (m_store_proxy && m_store_proxy->isValid()) {
		QDBusPendingReply<CamelFolderInfoArrayVariant> reply = m_store_proxy->getFolderInfo (QString(""),
									CAMEL_STORE_FOLDER_INFO_RECURSIVE|CAMEL_STORE_FOLDER_INFO_FAST | CAMEL_STORE_FOLDER_INFO_SUBSCRIBED);
		reply.waitForFinished();
		m_folderlist = reply.value ();
	g_print ("Got folder list....\n");

	}

	if (!m_outbox_proxy) {
		reply = instance->getLocalFolder (QString("Outbox"));
		reply.waitForFinished();
        	m_outbox_proxy_id = reply.value();

		m_outbox_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString ("org.gnome.evolution.dataserver.Mail"),
										     m_outbox_proxy_id.path(),
										     QDBusConnection::sessionBus(), this);
	}

	reply = instance->getFolderFromUri (QString(m_account->sent_folder_uri));
        reply.waitForFinished();
        m_sent_proxy_id = reply.value();
	m_sent_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString ("org.gnome.evolution.dataserver.Mail"),
									     m_sent_proxy_id.path(),
									     QDBusConnection::sessionBus(), this);

	reply = instance->getFolderFromUri (QString(m_account->drafts_folder_uri));
        reply.waitForFinished();
        m_drafts_proxy_id = reply.value();
	m_drafts_proxy = new OrgGnomeEvolutionDataserverMailFolderInterface (QString ("org.gnome.evolution.dataserver.Mail"),
									     m_drafts_proxy_id.path(),
									     QDBusConnection::sessionBus(), this);
    }
}

QStringList FolderListModel::folderNames()
{
    QStringList folderNames;

    foreach (CamelFolderInfoVariant fInfo, m_folderlist)
    {
        QString displayName;

	if (fInfo.full_name == ".#evolution/Junk")
		displayName = QString ("Junk");
	else if (fInfo.full_name == ".#evolution/Trash")
		displayName = QString ("Trash");
	else {
		displayName = QString (fInfo.full_name);
		displayName.replace (QString("/"), QString(" / "));
	}

        if (fInfo.unread_count > 0)
        {
            displayName = displayName + " (" + QString::number(fInfo.unread_count) + ")";
        }

        folderNames << displayName;
	g_print("FOLDER: %s\n", (char *)displayName.toLocal8Bit().constData());
    }
    return folderNames;
}

QVariant FolderListModel::folderId(int index)
{
    if (index < 0 || index >= m_folderlist.count())
        return QVariant();

    return m_folderlist[index].uri;
}

int FolderListModel::indexFromFolderId(QVariant vFolderId)
{

    QString uri = vFolderId.toString();
    g_print ("Entering FolderListModel::indexFromFolderId: %s\n", (char *)uri.toLocal8Bit().constData());
    for (int i = 0; i < m_folderlist.size(); i ++)
    {
        if (vFolderId == 0) {
	        CamelFolderInfoVariant folder(m_folderlist[i]);
        	if (QString::compare(folder.full_name, "INBOX", Qt::CaseInsensitive) == 0)
			return i;

	} else {
        	if (uri == m_folderlist[i].uri)
            		return i;
	}
    }
    return -1;
}

QVariant FolderListModel::folderServerCount(QVariant vFolderId)
{
    QString uri = vFolderId.toString();

    for (int i = 0; i < m_folderlist.size(); i ++)
    {
        if (uri == m_folderlist[i].uri)
            return QVariant(m_folderlist[i].total_mail_count);
    }
    return QVariant(-1);
}

QVariant FolderListModel::inboxFolderId()
{
    for (int i = 0; i < m_folderlist.size(); i++)
    {
        CamelFolderInfoVariant folder(m_folderlist[i]);
        if (QString::compare(folder.full_name, "INBOX", Qt::CaseInsensitive) == 0) {
	    g_print ("Returning INBOX URI: %s\n", (char *)folder.uri.toLocal8Bit().constData());
            return QVariant(folder.uri);
	}
    }

    return QVariant();
}

QVariant FolderListModel::inboxFolderName()
{
    for (int i = 0; i < m_folderlist.size(); i++)
    {
        CamelFolderInfoVariant folder(m_folderlist[i]);

       if (QString::compare(folder.full_name, "INBOX", Qt::CaseInsensitive) == 0) {
            g_print ("Returning INBOX URI: %s\n", (char *)folder.uri.toLocal8Bit().constData());
            return QVariant(folder.folder_name);
        }
    }
    return QVariant("");
}

int FolderListModel::totalNumberOfFolders()
{
    return m_folderlist.size();
}
<|endoftext|>


<commit_before>// SciTE - Scintilla based Text Editor
/** @file GUIGTK.cxx
 ** Interface to platform GUI facilities.
 ** Split off from Scintilla's Platform.h to avoid SciTE depending on implementation of Scintilla.
 **/
// Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <time.h>

#include <string>

#include <gtk/gtk.h>

#include "Scintilla.h"
#include "ScintillaWidget.h"

#include "GUI.h"

namespace GUI {

gui_string StringFromUTF8(const char *s) {
	return gui_string(s);
}

std::string UTF8FromString(const gui_string &s) {
	return s;
}

gui_string StringFromInteger(int i) {
	char number[32];
	sprintf(number, "%0d", i);
	return gui_string(number);
}

static GtkWidget *PWidget(WindowID wid) {
	return reinterpret_cast<GtkWidget *>(wid);
}

void Window::Destroy() {
	if (wid)
		gtk_widget_destroy(GTK_WIDGET(wid));
	wid = 0;
}

bool Window::HasFocus() {
	return GTK_WIDGET_HAS_FOCUS(wid);
}

Rectangle Window::GetPosition() {
	// Before any size allocated pretend its 1000 wide so not scrolled
	Rectangle rc(0, 0, 1000, 1000);
	if (wid) {
		rc.left = PWidget(wid)->allocation.x;
		rc.top = PWidget(wid)->allocation.y;
		if (PWidget(wid)->allocation.width > 20) {
			rc.right = rc.left + PWidget(wid)->allocation.width;
			rc.bottom = rc.top + PWidget(wid)->allocation.height;
		}
	}
	return rc;
}

void Window::SetPosition(Rectangle rc) {
	GtkAllocation alloc;
	alloc.x = rc.left;
	alloc.y = rc.top;
	alloc.width = rc.Width();
	alloc.height = rc.Height();
	gtk_widget_size_allocate(PWidget(wid), &alloc);
}

Rectangle Window::GetClientPosition() {
	// On GTK+, the client position is the window position
	return GetPosition();
}

void Window::Show(bool show) {
	if (show)
		gtk_widget_show(PWidget(wid));
}

void Window::InvalidateAll() {
	if (wid) {
		gtk_widget_queue_draw(PWidget(wid));
	}
}

void Window::SetTitle(const char *s) {
	gtk_window_set_title(GTK_WINDOW(wid), s);
}

void Menu::CreatePopUp() {
	Destroy();
	mid = gtk_item_factory_new(GTK_TYPE_MENU, "<main>", NULL);
}

void Menu::Destroy() {
	if (mid)
		g_object_unref(G_OBJECT(mid));
	mid = 0;
}

void Menu::Show(Point pt, Window &) {
	int screenHeight = gdk_screen_height();
	int screenWidth = gdk_screen_width();
	GtkItemFactory *factory = reinterpret_cast<GtkItemFactory *>(mid);
	GtkWidget *widget = gtk_item_factory_get_widget(factory, "<main>");
	gtk_widget_show_all(widget);
	GtkRequisition requisition;
	gtk_widget_size_request(widget, &requisition);
	if ((pt.x + requisition.width) > screenWidth) {
		pt.x = screenWidth - requisition.width;
	}
	if ((pt.y + requisition.height) > screenHeight) {
		pt.y = screenHeight - requisition.height;
	}
	gtk_item_factory_popup(factory, pt.x - 4, pt.y - 4, 3,
		gtk_get_current_event_time());
}

ElapsedTime::ElapsedTime() {
	GTimeVal curTime;
	g_get_current_time(&curTime);
	bigBit = curTime.tv_sec;
	littleBit = curTime.tv_usec;
}

double ElapsedTime::Duration(bool reset) {
	GTimeVal curTime;
	g_get_current_time(&curTime);
	long endBigBit = curTime.tv_sec;
	long endLittleBit = curTime.tv_usec;
	double result = 1000000.0 * (endBigBit - bigBit);
	result += endLittleBit - littleBit;
	result /= 1000000.0;
	if (reset) {
		bigBit = endBigBit;
		littleBit = endLittleBit;
	}
	return result;
}

long ScintillaWindow::Send(unsigned int msg, unsigned long wParam, long lParam) {
	return scintilla_send_message(SCINTILLA(GetID()), msg, wParam, lParam);
}

long ScintillaWindow::SendPointer(unsigned int msg, unsigned long wParam, void *lParam) {
	return scintilla_send_message(SCINTILLA(GetID()), msg, wParam, reinterpret_cast<sptr_t>(lParam));
}

bool IsDBCSLeadByte(int codePage, char ch) {
	// Byte ranges found in Wikipedia articles with relevant search strings in each case
	unsigned char uch = static_cast<unsigned char>(ch);
	switch (codePage) {
		case 932:
			// Shift_jis
			return ((uch >= 0x81) && (uch <= 0x9F)) ||
				((uch >= 0xE0) && (uch <= 0xEF));
		case 936:
			// GBK
			return (uch >= 0x81) && (uch <= 0xFE);
		case 950:
			// Big5
			return (uch >= 0x81) && (uch <= 0xFE);
		// Korean EUC-KR may be code page 949.
	}
	return false;
}

}
<commit_msg>Fixed crash when creating a GUI::gui_string from NULL.<commit_after>// SciTE - Scintilla based Text Editor
/** @file GUIGTK.cxx
 ** Interface to platform GUI facilities.
 ** Split off from Scintilla's Platform.h to avoid SciTE depending on implementation of Scintilla.
 **/
// Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <time.h>

#include <string>

#include <gtk/gtk.h>

#include "Scintilla.h"
#include "ScintillaWidget.h"

#include "GUI.h"

namespace GUI {

gui_string StringFromUTF8(const char *s) {
	if (s)
		return gui_string(s);
	else
		return gui_string("");
}

std::string UTF8FromString(const gui_string &s) {
	return s;
}

gui_string StringFromInteger(int i) {
	char number[32];
	sprintf(number, "%0d", i);
	return gui_string(number);
}

static GtkWidget *PWidget(WindowID wid) {
	return reinterpret_cast<GtkWidget *>(wid);
}

void Window::Destroy() {
	if (wid)
		gtk_widget_destroy(GTK_WIDGET(wid));
	wid = 0;
}

bool Window::HasFocus() {
	return GTK_WIDGET_HAS_FOCUS(wid);
}

Rectangle Window::GetPosition() {
	// Before any size allocated pretend its 1000 wide so not scrolled
	Rectangle rc(0, 0, 1000, 1000);
	if (wid) {
		rc.left = PWidget(wid)->allocation.x;
		rc.top = PWidget(wid)->allocation.y;
		if (PWidget(wid)->allocation.width > 20) {
			rc.right = rc.left + PWidget(wid)->allocation.width;
			rc.bottom = rc.top + PWidget(wid)->allocation.height;
		}
	}
	return rc;
}

void Window::SetPosition(Rectangle rc) {
	GtkAllocation alloc;
	alloc.x = rc.left;
	alloc.y = rc.top;
	alloc.width = rc.Width();
	alloc.height = rc.Height();
	gtk_widget_size_allocate(PWidget(wid), &alloc);
}

Rectangle Window::GetClientPosition() {
	// On GTK+, the client position is the window position
	return GetPosition();
}

void Window::Show(bool show) {
	if (show)
		gtk_widget_show(PWidget(wid));
}

void Window::InvalidateAll() {
	if (wid) {
		gtk_widget_queue_draw(PWidget(wid));
	}
}

void Window::SetTitle(const char *s) {
	gtk_window_set_title(GTK_WINDOW(wid), s);
}

void Menu::CreatePopUp() {
	Destroy();
	mid = gtk_item_factory_new(GTK_TYPE_MENU, "<main>", NULL);
}

void Menu::Destroy() {
	if (mid)
		g_object_unref(G_OBJECT(mid));
	mid = 0;
}

void Menu::Show(Point pt, Window &) {
	int screenHeight = gdk_screen_height();
	int screenWidth = gdk_screen_width();
	GtkItemFactory *factory = reinterpret_cast<GtkItemFactory *>(mid);
	GtkWidget *widget = gtk_item_factory_get_widget(factory, "<main>");
	gtk_widget_show_all(widget);
	GtkRequisition requisition;
	gtk_widget_size_request(widget, &requisition);
	if ((pt.x + requisition.width) > screenWidth) {
		pt.x = screenWidth - requisition.width;
	}
	if ((pt.y + requisition.height) > screenHeight) {
		pt.y = screenHeight - requisition.height;
	}
	gtk_item_factory_popup(factory, pt.x - 4, pt.y - 4, 3,
		gtk_get_current_event_time());
}

ElapsedTime::ElapsedTime() {
	GTimeVal curTime;
	g_get_current_time(&curTime);
	bigBit = curTime.tv_sec;
	littleBit = curTime.tv_usec;
}

double ElapsedTime::Duration(bool reset) {
	GTimeVal curTime;
	g_get_current_time(&curTime);
	long endBigBit = curTime.tv_sec;
	long endLittleBit = curTime.tv_usec;
	double result = 1000000.0 * (endBigBit - bigBit);
	result += endLittleBit - littleBit;
	result /= 1000000.0;
	if (reset) {
		bigBit = endBigBit;
		littleBit = endLittleBit;
	}
	return result;
}

long ScintillaWindow::Send(unsigned int msg, unsigned long wParam, long lParam) {
	return scintilla_send_message(SCINTILLA(GetID()), msg, wParam, lParam);
}

long ScintillaWindow::SendPointer(unsigned int msg, unsigned long wParam, void *lParam) {
	return scintilla_send_message(SCINTILLA(GetID()), msg, wParam, reinterpret_cast<sptr_t>(lParam));
}

bool IsDBCSLeadByte(int codePage, char ch) {
	// Byte ranges found in Wikipedia articles with relevant search strings in each case
	unsigned char uch = static_cast<unsigned char>(ch);
	switch (codePage) {
		case 932:
			// Shift_jis
			return ((uch >= 0x81) && (uch <= 0x9F)) ||
				((uch >= 0xE0) && (uch <= 0xEF));
		case 936:
			// GBK
			return (uch >= 0x81) && (uch <= 0xFE);
		case 950:
			// Big5
			return (uch >= 0x81) && (uch <= 0xFE);
		// Korean EUC-KR may be code page 949.
	}
	return false;
}

}
<|endoftext|>