<commit_before>// Copyright (c) 2014 Joseph D Poirier
// Distributable under the terms of The New BSD License
// that can be found in the LICENSE file.

#ifdef _WIN32 /* this is set for 64 bit as well */
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif

#ifdef _APPLE_
#include <OpenGl/gl.h>
#else
#include <GL/gl.h>
#endif

#include <math.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "XPLMDefs.h"
#include "XPLMPlugin.h"
#include "XPLMProcessing.h"
#include "XPLMDataAccess.h"
#include "XPLMUtilities.h"
#include "XPLMDisplay.h"
#include "XPLMGraphics.h"

#include "defs.h"
#include "commviewer.h"

static int CommandHandler(XPLMCommandRef inCommand,
                          XPLMCommandPhase inPhase,
                          void* inRefcon);

static void DrawWindowCallback(XPLMWindowID inWindowID,
                               void* inRefcon);

static void HandleKeyCallback(XPLMWindowID inWindowID,
                              char inKey,
                              XPLMKeyFlags inFlags,
                              char inVirtualKey,
                              void* inRefcon,
                              int losingFocus);

static int HandleMouseCallback(XPLMWindowID inWindowID,
                               int x,
                               int y,
                               XPLMMouseStatus inMouse,
                               void* inRefcon);

static void HotKeyCallback(void* inRefcon);

static XPLMWindowID gCommWindow = NULL;
static bool gPluginEnabled = false;
static int gPlaneLoaded = 0;
static const float FL_CB_INTERVAL = -1.0;
static bool gPTT_On = false;
static XPLMHotKeyID gHotKey = NULL;

#define WINDOW_WIDTH (200)
#define WINDOW_HEIGHT (40)
static int gWinPosX;
static int gWinPosY;
static int gLastMouseX;
static int gLastMouseY;

// general & misc
enum {
    PLUGIN_PLANE_ID = 0
    ,CMD_CONTACT_ATC
    ,COMMVIEWER_WINDOW
#ifdef TOGGLE_TEST_FEATURE

#endif
};

// Command Refs
#define sCONTACT_ATC   "sim/operation/contact_atc"

XPLMDataRef avionics_power_on_dataref;
XPLMDataRef audio_selection_com1_dataref;
XPLMDataRef audio_selection_com2_dataref;

#ifdef TOGGLE_TEST_FEATURE
XPLMDataRef artificial_stability_on_dataref;
XPLMDataRef artificial_stability_pitch_on_dataref;
XPLMDataRef artificial_stability_roll_on_dataref;
#endif

XPLMDataRef panel_visible_win_t_dataref;

/*
 *
 *
 */
PLUGIN_API int XPluginStart(char* outName, char* outSig, char* outDesc) {

    LPRINTF("CommView Plugin: XPluginStart\n");
    strcpy(outName, "CommViewer");
    strcpy(outSig , "jdp.comm.viewer");
    strcpy(outDesc, "CommViewer Plugin.");

    // sim/cockpit/switches/audio_panel_out

    // sim/cockpit2/radios/actuators/audio_com_selection
    // sim/cockpit2/radios/actuators/audio_selection_com1 int   y   boolean is com1 selected for listening
    // sim/cockpit2/radios/actuators/audio_selection_com2 int   y   boolean is com2 selected for listening
    // sim/cockpit2/radios/actuators/com1_power int y   boolean Com radio 1 off or on, 0 or 1.
    // sim/cockpit2/radios/actuators/com2_power int y   boolean Com radio 2 off or on, 0 or 1.

    //avionics_power_on_dataref = XPLMFindDataRef("sim/cockpit2/switches/avionics_power_on");
    //LPRINTF("CommView Plugin: data/command refs initialized\n");

    audio_selection_com1_dataref = XPLMFindDataRef("sim/cockpit2/radios/actuators/audio_selection_com1");
    audio_selection_com2_dataref = XPLMFindDataRef("sim/cockpit2/radios/actuators/audio_selection_com2");

#ifdef TOGGLE_TEST_FEATURE
    artificial_stability_on_dataref = XPLMFindDataRef("sim/cockpit2/switches/artificial_stability_on");
    artificial_stability_pitch_on_dataref = XPLMFindDataRef("sim/cockpit2/switches/artificial_stability_pitch_on");
    artificial_stability_roll_on_dataref = XPLMFindDataRef("sim/cockpit2/switches/artificial_stability_roll_on");
    XPLMSetDatai(artificial_stability_on_dataref, 1);
    XPLMSetDatai(artificial_stability_pitch_on_dataref, 1);
    XPLMSetDatai(artificial_stability_roll_on_dataref, 1);
#endif

    XPLMCommandRef cmd_ref;
    cmd_ref = XPLMCreateCommand(sCONTACT_ATC, "Contact ATC");
    XPLMRegisterCommandHandler(cmd_ref,
                               CommandHandler,
                               CMD_HNDLR_EPILOG,
                               (void*)CMD_CONTACT_ATC);

    // XPLMRegisterFlightLoopCallback(FlightLoopCallback, FL_CB_INTERVAL, NULL);
    panel_visible_win_t_dataref = XPLMFindDataRef("sim/graphics/view/panel_visible_win_t");

    int top = (int)XPLMGetDataf(panel_visible_win_t_dataref);
    gWinPosX = 0;
    gWinPosY = top - 200;
    gCommWindow = XPLMCreateWindow(gWinPosX,                // left
                                   gWinPosY,                // top
                                   gWinPosX+WINDOW_WIDTH,   // right
                                   gWinPosY-WINDOW_HEIGHT,  // bottom
                                   true,                    // is visible
                                   DrawWindowCallback,
                                   HandleKeyCallback,
                                   HandleMouseCallback,
                                   (void*)COMMVIEWER_WINDOW);    // Refcon

#ifdef TOGGLE_TEST_FEATURE
    //gHotKey = XPLMRegisterHotKey(XPLM_VK_F3,
    //                             xplm_DownFlag,
    //                             "Toggle Window Ice",
    //                             HotKeyCallback,
    //                             NULL);
#endif

    LPRINTF("CommView Plugin: startup completed\n");

    return PROCESSED_EVENT;
}

#ifdef TOGGLE_TEST_FEATURE
/*
 *
 *
 */
void HotKeyCallback(void* inRefcon) {
    static bool isSaved = false;

    if (isSaved) {
        isSaved = false;
    } else {
        isSaved = true;
    }
}
#endif

/*
 *
 *
 */
float FlightLoopCallback(float inElapsedSinceLastCall,
                         float inElapsedTimeSinceLastFlightLoop,
                         int inCounter,
                         void* inRefcon) {

//   if ((gFlCbCnt % PANEL_CHECK_INTERVAL) == 0) {
//   }

    if (!gPluginEnabled) {

    }

    return 1.0;
}

/*
 *
 *
 */
int CommandHandler(XPLMCommandRef inCommand,
                   XPLMCommandPhase inPhase,
                   void* inRefcon) {

//    if ((gFlCbCnt % PANEL_CHECK_INTERVAL) == 0) {
//    }
//    if (!gPluginEnabled) {
//        return IGNORED_EVENT;
//    }

    switch (reinterpret_cast<uint32_t>(inRefcon)) {
    case CMD_CONTACT_ATC:
        switch (inPhase) {
        case xplm_CommandBegin:
        case xplm_CommandContinue:
            gPTT_On = true;
            break;
        case xplm_CommandEnd:
            gPTT_On = false;
            break;
        default:
            break;
        }
        break;
    default:
        break;
    }

    return IGNORED_EVENT;
}

/*
 *
 */
PLUGIN_API void XPluginStop(void) {

    gPluginEnabled = false;
    //XPLMUnregisterFlightLoopCallback(FlightLoopCallback, NULL);
    LPRINTF("CommView Plugin: XPluginStop\n");
}

/*
 *
 */
PLUGIN_API void XPluginDisable(void) {

    gPluginEnabled = false;
    LPRINTF("CommView Plugin: XPluginDisable\n");
}

/*
 *
 */
PLUGIN_API int XPluginEnable(void) {

    gPluginEnabled = true;
    LPRINTF("CommView Plugin: XPluginEnable\n");

    return PROCESSED_EVENT;
}

/*
 *
 */
PLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFrom,
                                      long inMsg,
                                      void* inParam) {

    if (inFrom == XPLM_PLUGIN_XPLANE) {
        int inparam = reinterpret_cast<int>(inParam);
        switch (inMsg) {
        case XPLM_MSG_PLANE_LOADED:
            if (inparam != PLUGIN_PLANE_ID || gPlaneLoaded) { break; }
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_LOADED\n");
            break;
        case XPLM_MSG_AIRPORT_LOADED:
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_AIRPORT_LOADED\n");
            break;
        case XPLM_MSG_SCENERY_LOADED:
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_SCENERY_LOADED\n");
            break;
        case XPLM_MSG_AIRPLANE_COUNT_CHANGED:
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_AIRPLANE_COUNT_CHANGED\n");
            break;
        // XXX: system state and procedure, what's difference between an unloaded and crashed plane?
        case XPLM_MSG_PLANE_CRASHED:
            if ((int)inParam != PLUGIN_PLANE_ID) { break; }
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_CRASHED\n");
            break;
        case XPLM_MSG_PLANE_UNLOADED:
            if ((int)inParam != PLUGIN_PLANE_ID) { break; }
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_UNLOADED\n");
            break;
        default: // unknown
            break;
        } // switch (inMsg)
    } // if (inFrom == XPLM_PLUGIN_XPLANE)
}

/*
 *
 *
 */
void DrawWindowCallback(XPLMWindowID inWindowID, void* inRefcon) {

    int left;
    int top;
    int right;
    int bottom;
    static char str[100];
    static float commviewer_color[] = {1.0, 1.0, 1.0};  // RGB White

    // XXX: are inWindowIDs our XPLMCreateWindow return pointers
    XPLMGetWindowGeometry(inWindowID, &left, &top, &right, &bottom);
    XPLMDrawTranslucentDarkBox(left, top, right, bottom);

    switch (reinterpret_cast<uint32_t>(inRefcon)) {
    case COMMVIEWER_WINDOW:
        // text to window, NULL indicates no word wrap
        sprintf(str,"%s\t\t\tCOM1: %d\t\t\tCOM2: %d",
                (char*)(gPTT_On ? "PTT: ON" : "PTT: OFF"),
                XPLMGetDatai(audio_selection_com1_dataref),
                XPLMGetDatai(audio_selection_com2_dataref));
        XPLMDrawString(commviewer_color,
                       left+5,
                       top-20,
                       str,
                       NULL,
                       xplmFont_Basic);
        break;
    default:
        break;
    }

    //glDisable(GL_TEXTURE_2D);
    //glColor3f(0.7, 0.7, 0.7);
    //glBegin(GL_LINES);
    //    glVertex2i(right-1, top-1);
    //    glVertex2i(right-7, top-7);
    //    glVertex2i(right-7, top-1);
    //    glVertex2i(right-1, top-7);
    //glEnd();
    //glEnable(GL_TEXTURE_2D);
}

/*
 *
 *
 */
void HandleKeyCallback(XPLMWindowID inWindowID,
                         char inKey,
                         XPLMKeyFlags inFlags,
                         char inVirtualKey,
                         void* inRefcon,
                         int losingFocus) {

    // nothing to do here
}

/*
 *
 *
 */
 #define COMS_UNCHANGED     (0)
 #define COM1_CHANGED       (1)
 #define COM2_CHANGED       (2)
 #define COMM_UNSELECTED    (0)
 #define COMM_SELECTED      (1)
int HandleMouseCallback(XPLMWindowID inWindowID,
                        int x,
                        int y,
                        XPLMMouseStatus inMouse,
                        void* inRefcon) {

    static int com_changed = COMS_UNCHANGED;
    static int MouseDownX;
    static int MouseDownY;

    switch (inMouse) {
    case xplm_MouseDown:
        // if ((x >= gWinPosX+WINDOW_WIDTH-8) &&
        //     (x <= gWinPosX+WINDOW_WIDTH) &&
        //     (y <= gWinPosY) && (y >= gWinPosY-8)) {
        //         windowCloseRequest = 1;
        //     } else {
                MouseDownX = gLastMouseX = x;
                MouseDownY = gLastMouseY = y;
        // }
        break;
    case xplm_MouseDrag:
        // this event fires while xplm_MouseDown
        // and whether the window is being dragged or not
        gWinPosX += (x - gLastMouseX);
        gWinPosY += (y - gLastMouseY);
        XPLMSetWindowGeometry(gWindow,
                              gWinPosX,
                              gWinPosY,
                              gWinPosX+WINDOW_WIDTH,
                              gWinPosY-WINDOW_HEIGHT);
        gLastMouseX = x;
        gLastMouseY = y;
        break;
    case xplm_MouseUp:
        if (MouseDownX == x || MouseDownY == y) {
            int com1 = XPLMGetDatai(audio_selection_com1_dataref);
            int com2 = XPLMGetDatai(audio_selection_com2_dataref);

            if (com1 && com2 && com_changed) {
                switch (com_changed) {
                case COM1_CHANGED:
                    XPLMSetDatai(audio_selection_com1_dataref, COMM_UNSELECTED);
                    break;
                case COM2_CHANGED:
                    XPLMSetDatai(audio_selection_com2_dataref, COMM_UNSELECTED);
                    break;
                default:
                    break;
                }
                com_changed = COMS_UNCHANGED;
            } else if (!com1 && com2) {
                com_changed = COM1_CHANGED;
                XPLMSetDatai(audio_selection_com1_dataref, COMM_SELECTED);
            }  else if (com1 && !com2) {
                com_changed = COM2_CHANGED;
                XPLMSetDatai(audio_selection_com2_dataref, COMM_SELECTED);
            }
        }
        break;
    } // switch (inMouse)

    return PROCESSED_EVENT;
}
<commit_msg>minor nitpicks fixed<commit_after>// Copyright (c) 2014 Joseph D Poirier
// Distributable under the terms of The New BSD License
// that can be found in the LICENSE file.

#ifdef _WIN32 /* this is set for 64 bit as well */
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif

#ifdef _APPLE_
#include <OpenGl/gl.h>
#else
#include <GL/gl.h>
#endif

#include <math.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "XPLMDefs.h"
#include "XPLMPlugin.h"
#include "XPLMProcessing.h"
#include "XPLMDataAccess.h"
#include "XPLMUtilities.h"
#include "XPLMDisplay.h"
#include "XPLMGraphics.h"

#include "defs.h"
#include "commviewer.h"

static int CommandHandler(XPLMCommandRef inCommand,
                          XPLMCommandPhase inPhase,
                          void* inRefcon);

static void DrawWindowCallback(XPLMWindowID inWindowID,
                               void* inRefcon);

static void HandleKeyCallback(XPLMWindowID inWindowID,
                              char inKey,
                              XPLMKeyFlags inFlags,
                              char inVirtualKey,
                              void* inRefcon,
                              int losingFocus);

static int HandleMouseCallback(XPLMWindowID inWindowID,
                               int x,
                               int y,
                               XPLMMouseStatus inMouse,
                               void* inRefcon);

static void HotKeyCallback(void* inRefcon);

static XPLMWindowID gCommWindow = NULL;
static bool gPluginEnabled = false;
static int gPlaneLoaded = 0;
static const float FL_CB_INTERVAL = -1.0;
static bool gPTT_On = false;
static XPLMHotKeyID gHotKey = NULL;

#define WINDOW_WIDTH (200)
#define WINDOW_HEIGHT (40)
static int gWinPosX;
static int gWinPosY;
static int gLastMouseX;
static int gLastMouseY;

// general & misc
enum {
    PLUGIN_PLANE_ID = 0
    ,CMD_CONTACT_ATC
    ,COMMVIEWER_WINDOW
#ifdef TOGGLE_TEST_FEATURE

#endif
};

// Command Refs
#define sCONTACT_ATC   "sim/operation/contact_atc"

XPLMDataRef avionics_power_on_dataref;
XPLMDataRef audio_selection_com1_dataref;
XPLMDataRef audio_selection_com2_dataref;

#ifdef TOGGLE_TEST_FEATURE
XPLMDataRef artificial_stability_on_dataref;
XPLMDataRef artificial_stability_pitch_on_dataref;
XPLMDataRef artificial_stability_roll_on_dataref;
#endif

XPLMDataRef panel_visible_win_t_dataref;

/*
 *
 *
 */
PLUGIN_API int XPluginStart(char* outName, char* outSig, char* outDesc) {

    LPRINTF("CommView Plugin: XPluginStart\n");
    strcpy(outName, "CommViewer");
    strcpy(outSig , "jdp.comm.viewer");
    strcpy(outDesc, "CommViewer Plugin.");

    // sim/cockpit/switches/audio_panel_out

    // sim/cockpit2/radios/actuators/audio_com_selection
    // sim/cockpit2/radios/actuators/audio_selection_com1 int   y   boolean is com1 selected for listening
    // sim/cockpit2/radios/actuators/audio_selection_com2 int   y   boolean is com2 selected for listening
    // sim/cockpit2/radios/actuators/com1_power int y   boolean Com radio 1 off or on, 0 or 1.
    // sim/cockpit2/radios/actuators/com2_power int y   boolean Com radio 2 off or on, 0 or 1.

    //avionics_power_on_dataref = XPLMFindDataRef("sim/cockpit2/switches/avionics_power_on");
    //LPRINTF("CommView Plugin: data/command refs initialized\n");

    audio_selection_com1_dataref = XPLMFindDataRef("sim/cockpit2/radios/actuators/audio_selection_com1");
    audio_selection_com2_dataref = XPLMFindDataRef("sim/cockpit2/radios/actuators/audio_selection_com2");

#ifdef TOGGLE_TEST_FEATURE
    artificial_stability_on_dataref = XPLMFindDataRef("sim/cockpit2/switches/artificial_stability_on");
    artificial_stability_pitch_on_dataref = XPLMFindDataRef("sim/cockpit2/switches/artificial_stability_pitch_on");
    artificial_stability_roll_on_dataref = XPLMFindDataRef("sim/cockpit2/switches/artificial_stability_roll_on");
    XPLMSetDatai(artificial_stability_on_dataref, 1);
    XPLMSetDatai(artificial_stability_pitch_on_dataref, 1);
    XPLMSetDatai(artificial_stability_roll_on_dataref, 1);
#endif

    XPLMCommandRef cmd_ref;
    cmd_ref = XPLMCreateCommand(sCONTACT_ATC, "Contact ATC");
    XPLMRegisterCommandHandler(cmd_ref,
                               CommandHandler,
                               CMD_HNDLR_EPILOG,
                               (void*)CMD_CONTACT_ATC);

    // XPLMRegisterFlightLoopCallback(FlightLoopCallback, FL_CB_INTERVAL, NULL);
    panel_visible_win_t_dataref = XPLMFindDataRef("sim/graphics/view/panel_visible_win_t");

    int top = (int)XPLMGetDataf(panel_visible_win_t_dataref);
    gWinPosX = 0;
    gWinPosY = top - 200;
    gCommWindow = XPLMCreateWindow(gWinPosX,                // left
                                   gWinPosY,                // top
                                   gWinPosX+WINDOW_WIDTH,   // right
                                   gWinPosY-WINDOW_HEIGHT,  // bottom
                                   true,                    // is visible
                                   DrawWindowCallback,
                                   HandleKeyCallback,
                                   HandleMouseCallback,
                                   (void*)COMMVIEWER_WINDOW);    // Refcon

#ifdef TOGGLE_TEST_FEATURE
    //gHotKey = XPLMRegisterHotKey(XPLM_VK_F3,
    //                             xplm_DownFlag,
    //                             "Toggle Window Ice",
    //                             HotKeyCallback,
    //                             NULL);
#endif

    LPRINTF("CommView Plugin: startup completed\n");

    return PROCESSED_EVENT;
}

#ifdef TOGGLE_TEST_FEATURE
/*
 *
 *
 */
void HotKeyCallback(void* inRefcon) {
    static bool isSaved = false;

    if (isSaved) {
        isSaved = false;
    } else {
        isSaved = true;
    }
}
#endif

/*
 *
 *
 */
float FlightLoopCallback(float inElapsedSinceLastCall,
                         float inElapsedTimeSinceLastFlightLoop,
                         int inCounter,
                         void* inRefcon) {

//   if ((gFlCbCnt % PANEL_CHECK_INTERVAL) == 0) {
//   }

    if (!gPluginEnabled) {

    }

    return 1.0;
}

/*
 *
 *
 */
int CommandHandler(XPLMCommandRef inCommand,
                   XPLMCommandPhase inPhase,
                   void* inRefcon) {

//    if ((gFlCbCnt % PANEL_CHECK_INTERVAL) == 0) {
//    }
//    if (!gPluginEnabled) {
//        return IGNORED_EVENT;
//    }

    switch (reinterpret_cast<uint32_t>(inRefcon)) {
    case CMD_CONTACT_ATC:
        switch (inPhase) {
        case xplm_CommandBegin:
        case xplm_CommandContinue:
            gPTT_On = true;
            break;
        case xplm_CommandEnd:
            gPTT_On = false;
            break;
        default:
            break;
        }
        break;
    default:
        break;
    }

    return IGNORED_EVENT;
}

/*
 *
 */
PLUGIN_API void XPluginStop(void) {

    gPluginEnabled = false;
    //XPLMUnregisterFlightLoopCallback(FlightLoopCallback, NULL);
    LPRINTF("CommView Plugin: XPluginStop\n");
}

/*
 *
 */
PLUGIN_API void XPluginDisable(void) {

    gPluginEnabled = false;
    LPRINTF("CommView Plugin: XPluginDisable\n");
}

/*
 *
 */
PLUGIN_API int XPluginEnable(void) {

    gPluginEnabled = true;
    LPRINTF("CommView Plugin: XPluginEnable\n");

    return PROCESSED_EVENT;
}

/*
 *
 */
PLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFrom,
                                      long inMsg,
                                      void* inParam) {

    if (inFrom == XPLM_PLUGIN_XPLANE) {
        int inparam = reinterpret_cast<int>(inParam);
        switch (inMsg) {
        case XPLM_MSG_PLANE_LOADED:
            if (inparam != PLUGIN_PLANE_ID || gPlaneLoaded) { break; }
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_LOADED\n");
            break;
        case XPLM_MSG_AIRPORT_LOADED:
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_AIRPORT_LOADED\n");
            break;
        case XPLM_MSG_SCENERY_LOADED:
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_SCENERY_LOADED\n");
            break;
        case XPLM_MSG_AIRPLANE_COUNT_CHANGED:
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_AIRPLANE_COUNT_CHANGED\n");
            break;
        // XXX: system state and procedure, what's difference between an unloaded and crashed plane?
        case XPLM_MSG_PLANE_CRASHED:
            if ((int)inParam != PLUGIN_PLANE_ID) { break; }
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_CRASHED\n");
            break;
        case XPLM_MSG_PLANE_UNLOADED:
            if ((int)inParam != PLUGIN_PLANE_ID) { break; }
            LPRINTF("CommView Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_UNLOADED\n");
            break;
        default:
            // unknown, anything to do?
            break;
        } // switch (inMsg)
    } // if (inFrom == XPLM_PLUGIN_XPLANE)
}

/*
 *
 *
 */
void DrawWindowCallback(XPLMWindowID inWindowID, void* inRefcon) {

    int left;
    int top;
    int right;
    int bottom;
    static char str[100];
    static float commviewer_color[] = {1.0, 1.0, 1.0};  // RGB White

    // XXX: are inWindowIDs our XPLMCreateWindow return pointers
    XPLMGetWindowGeometry(inWindowID, &left, &top, &right, &bottom);
    XPLMDrawTranslucentDarkBox(left, top, right, bottom);

    switch (reinterpret_cast<uint32_t>(inRefcon)) {
    case COMMVIEWER_WINDOW:
        // text to window, NULL indicates no word wrap
        sprintf(str,"%s\t\t\tCOM1: %d\t\t\tCOM2: %d",
                (char*)(gPTT_On ? "PTT: ON" : "PTT: OFF"),
                XPLMGetDatai(audio_selection_com1_dataref),
                XPLMGetDatai(audio_selection_com2_dataref));
        XPLMDrawString(commviewer_color,
                       left+5,
                       top-20,
                       str,
                       NULL,
                       xplmFont_Basic);
        break;
    default:
        break;
    }

    //glDisable(GL_TEXTURE_2D);
    //glColor3f(0.7, 0.7, 0.7);
    //glBegin(GL_LINES);
    //    glVertex2i(right-1, top-1);
    //    glVertex2i(right-7, top-7);
    //    glVertex2i(right-7, top-1);
    //    glVertex2i(right-1, top-7);
    //glEnd();
    //glEnable(GL_TEXTURE_2D);
}

/*
 *
 *
 */
void HandleKeyCallback(XPLMWindowID inWindowID,
                       char inKey,
                       XPLMKeyFlags inFlags,
                       char inVirtualKey,
                       void* inRefcon,
                       int losingFocus) {

    // nothing to do here
}

/*
 *
 *
 */
 #define COMMS_UNCHANGED    (0)
 #define COM1_CHANGED       (1)
 #define COM2_CHANGED       (2)
 #define COMM_UNSELECTED    (0)
 #define COMM_SELECTED      (1)
int HandleMouseCallback(XPLMWindowID inWindowID,
                        int x,
                        int y,
                        XPLMMouseStatus inMouse,
                        void* inRefcon) {

    static int com_changed = COMMS_UNCHANGED;
    static int MouseDownX;
    static int MouseDownY;

    switch (inMouse) {
    case xplm_MouseDown:
        // if ((x >= gWinPosX+WINDOW_WIDTH-8) &&
        //     (x <= gWinPosX+WINDOW_WIDTH) &&
        //     (y <= gWinPosY) && (y >= gWinPosY-8)) {
        //         windowCloseRequest = 1;
        //     } else {
                MouseDownX = gLastMouseX = x;
                MouseDownY = gLastMouseY = y;
        // }
        break;
    case xplm_MouseDrag:
        // this event fires while xplm_MouseDown
        // and whether the window is being dragged or not
        gWinPosX += (x - gLastMouseX);
        gWinPosY += (y - gLastMouseY);
        XPLMSetWindowGeometry(gWindow,
                              gWinPosX,
                              gWinPosY,
                              gWinPosX+WINDOW_WIDTH,
                              gWinPosY-WINDOW_HEIGHT);
        gLastMouseX = x;
        gLastMouseY = y;
        break;
    case xplm_MouseUp:
        if (MouseDownX == x || MouseDownY == y) {
            int com1 = XPLMGetDatai(audio_selection_com1_dataref);
            int com2 = XPLMGetDatai(audio_selection_com2_dataref);

            if (com1 && com2 && com_changed) {
                switch (com_changed) {
                case COM1_CHANGED:
                    XPLMSetDatai(audio_selection_com1_dataref, COMM_UNSELECTED);
                    break;
                case COM2_CHANGED:
                    XPLMSetDatai(audio_selection_com2_dataref, COMM_UNSELECTED);
                    break;
                default:
                    break;
                }
                com_changed = COMMS_UNCHANGED;
            } else if (!com1 && com2) {
                com_changed = COM1_CHANGED;
                XPLMSetDatai(audio_selection_com1_dataref, COMM_SELECTED);
            }  else if (com1 && !com2) {
                com_changed = COM2_CHANGED;
                XPLMSetDatai(audio_selection_com2_dataref, COMM_SELECTED);
            }
        }
        break;
    } // switch (inMouse)

    return PROCESSED_EVENT;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/autofill/name_field.h"

#include "base/string_util.h"
#include "chrome/browser/autofill/autofill_type.h"

NameField* NameField::Parse(std::vector<AutoFillField*>::const_iterator* iter,
                            bool is_ecml) {
  // Try FirstLastNameField first since it's more specific.
  NameField* field = FirstLastNameField::Parse(iter, is_ecml);
  if (field == NULL && !is_ecml)
    field = FullNameField::Parse(iter);
  return field;
}

FullNameField* FullNameField::Parse(
    std::vector<AutoFillField*>::const_iterator* iter) {
  // Exclude labels containing the string "username", which typically
  // denotes a login ID rather than the user's actual name.
  AutoFillField* field = **iter;
  if (Match(field, ASCIIToUTF16("username"), false))
    return NULL;

  // Searching for any label containing the word "name" is too general;
  // for example, Travelocity_Edit travel profile.html contains a field
  // "Travel Profile Name".
  const string16 name_match =
      ASCIIToUTF16("^name|full name|fullname|your name|customer name");
  if (ParseText(iter, name_match, &field))
    return new FullNameField(field);

  return NULL;
}

FirstLastNameField* FirstLastNameField::Parse1(
    std::vector<AutoFillField*>::const_iterator* iter) {
  // Some pages (e.g. Overstock_comBilling.html, SmithsonianCheckout.html)
  // have the label "Name" followed by two or three text fields.
  FirstLastNameField v;
  std::vector<AutoFillField*>::const_iterator q = *iter;

  AutoFillField* next;
  if (ParseText(&q, ASCIIToUTF16("^name"), &v.first_name_) &&
      ParseText(&q, ASCIIToUTF16(""), &next)) {
    if (ParseText(&q, ASCIIToUTF16(""), &v.last_name_)) {
      // There are three name fields; assume that the middle one is a
      // middle initial (it is, at least, on SmithsonianCheckout.html).
      v.middle_name_ = next;
      v.middle_initial_ = true;
    } else {  // only two name fields
      v.last_name_ = next;
    }

    *iter = q;
    return new FirstLastNameField(v);
  }

  return NULL;
}

FirstLastNameField* FirstLastNameField::Parse2(
    std::vector<AutoFillField*>::const_iterator* iter) {
  FirstLastNameField v;
  std::vector<AutoFillField*>::const_iterator q = *iter;

  // A fair number of pages use the names "fname" and "lname" for naming
  // first and last name fields (examples from the test suite:
  // BESTBUY_COM - Sign In2.html; Crate and Barrel Check Out.html;
  // dell_checkout1.html).  At least one UK page (The China Shop2.html)
  // asks, in stuffy English style, for just initials and a surname,
  // so we match "initials" here (and just fill in a first name there,
  // American-style).
  // The ".*first$" matches fields ending in "first" (example in sample8.html).
  if (!ParseText(&q,
                 ASCIIToUTF16("first name|firstname|initials|fname|.*first$"),
                 &v.first_name_))
    return NULL;

  // We check for a middle initial before checking for a middle name
  // because at least one page (PC Connection.html) has a field marked
  // as both (the label text is "MI" and the element name is
  // "txtmiddlename"); such a field probably actually represents a
  // middle initial.
  if (ParseText(&q,
                ASCIIToUTF16("^mi|middle initial|middleinitial|m.i."),
                &v.middle_name_)) {
    v.middle_initial_ = true;
  } else {
    ParseText(&q, ASCIIToUTF16("middle name|mname"), &v.middle_name_);
  }

  // The ".*last$" matches fields ending in "last" (example in sample8.html).
  if (!ParseText(&q,
                 ASCIIToUTF16("last name|lastname|lname|surname|.*last$"),
                 &v.last_name_))
    return NULL;

  *iter = q;
  return new FirstLastNameField(v);
}

FirstLastNameField* FirstLastNameField::ParseEcmlName(
    std::vector<AutoFillField*>::const_iterator* iter) {
  FirstLastNameField field;
  std::vector<AutoFillField*>::const_iterator q = *iter;

  string16 pattern = GetEcmlPattern(kEcmlShipToFirstName,
                                    kEcmlBillToFirstName, '|');
  if (!ParseText(&q, pattern, &field.first_name_))
    return NULL;

  pattern = GetEcmlPattern(kEcmlShipToMiddleName, kEcmlBillToMiddleName, '|');
  ParseText(&q, pattern, &field.middle_name_);

  pattern = GetEcmlPattern(kEcmlShipToLastName, kEcmlBillToLastName, '|');
  if (ParseText(&q, pattern, &field.last_name_)) {
    *iter = q;
    return new FirstLastNameField(field);
  }

  return NULL;
}

FirstLastNameField* FirstLastNameField::Parse(
    std::vector<AutoFillField*>::const_iterator* iter,
    bool is_ecml) {
  if (is_ecml) {
    return ParseEcmlName(iter);
  } else {
    FirstLastNameField* v = Parse1(iter);
    if (v != NULL)
      return v;

    return Parse2(iter);
  }
}

bool FirstLastNameField::GetFieldInfo(FieldTypeMap* field_type_map) const {
  bool ok = Add(field_type_map, first_name_, AutoFillType(NAME_FIRST));
  DCHECK(ok);
  ok = ok && Add(field_type_map, last_name_, AutoFillType(NAME_LAST));
  DCHECK(ok);
  AutoFillType type = middle_initial_ ?
      AutoFillType(NAME_MIDDLE_INITIAL) : AutoFillType(NAME_MIDDLE);
  ok = ok && Add(field_type_map, middle_name_, type);
  DCHECK(ok);

  return ok;
}

FirstLastNameField::FirstLastNameField()
    : first_name_(NULL),
      middle_name_(NULL),
      last_name_(NULL),
      middle_initial_(false) {
}

FirstLastNameField::FirstLastNameField(const FirstLastNameField& field)
    : NameField(),
      first_name_(field.first_name_),
      middle_name_(field.middle_name_),
      last_name_(field.last_name_),
      middle_initial_(field.middle_initial_) {
}
<commit_msg>Fix form heuristic for registration.crgevents.com.  Match on 'mi' anywhere in the field name.  It's safe to assume that if we match both the first and last name, it's safe to match mi anywhere in the field name.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/autofill/name_field.h"

#include "base/string_util.h"
#include "chrome/browser/autofill/autofill_type.h"

NameField* NameField::Parse(std::vector<AutoFillField*>::const_iterator* iter,
                            bool is_ecml) {
  // Try FirstLastNameField first since it's more specific.
  NameField* field = FirstLastNameField::Parse(iter, is_ecml);
  if (field == NULL && !is_ecml)
    field = FullNameField::Parse(iter);
  return field;
}

FullNameField* FullNameField::Parse(
    std::vector<AutoFillField*>::const_iterator* iter) {
  // Exclude labels containing the string "username", which typically
  // denotes a login ID rather than the user's actual name.
  AutoFillField* field = **iter;
  if (Match(field, ASCIIToUTF16("username"), false))
    return NULL;

  // Searching for any label containing the word "name" is too general;
  // for example, Travelocity_Edit travel profile.html contains a field
  // "Travel Profile Name".
  const string16 name_match =
      ASCIIToUTF16("^name|full name|fullname|your name|customer name");
  if (ParseText(iter, name_match, &field))
    return new FullNameField(field);

  return NULL;
}

FirstLastNameField* FirstLastNameField::Parse1(
    std::vector<AutoFillField*>::const_iterator* iter) {
  // Some pages (e.g. Overstock_comBilling.html, SmithsonianCheckout.html)
  // have the label "Name" followed by two or three text fields.
  FirstLastNameField v;
  std::vector<AutoFillField*>::const_iterator q = *iter;

  AutoFillField* next;
  if (ParseText(&q, ASCIIToUTF16("^name"), &v.first_name_) &&
      ParseText(&q, ASCIIToUTF16(""), &next)) {
    if (ParseText(&q, ASCIIToUTF16(""), &v.last_name_)) {
      // There are three name fields; assume that the middle one is a
      // middle initial (it is, at least, on SmithsonianCheckout.html).
      v.middle_name_ = next;
      v.middle_initial_ = true;
    } else {  // only two name fields
      v.last_name_ = next;
    }

    *iter = q;
    return new FirstLastNameField(v);
  }

  return NULL;
}

FirstLastNameField* FirstLastNameField::Parse2(
    std::vector<AutoFillField*>::const_iterator* iter) {
  FirstLastNameField v;
  std::vector<AutoFillField*>::const_iterator q = *iter;

  // A fair number of pages use the names "fname" and "lname" for naming
  // first and last name fields (examples from the test suite:
  // BESTBUY_COM - Sign In2.html; Crate and Barrel Check Out.html;
  // dell_checkout1.html).  At least one UK page (The China Shop2.html)
  // asks, in stuffy English style, for just initials and a surname,
  // so we match "initials" here (and just fill in a first name there,
  // American-style).
  // The ".*first$" matches fields ending in "first" (example in sample8.html).
  if (!ParseText(&q,
                 ASCIIToUTF16("first name|firstname|initials|fname|.*first$"),
                 &v.first_name_))
    return NULL;

  // We check for a middle initial before checking for a middle name
  // because at least one page (PC Connection.html) has a field marked
  // as both (the label text is "MI" and the element name is
  // "txtmiddlename"); such a field probably actually represents a
  // middle initial.
  if (ParseText(&q,
                ASCIIToUTF16("mi|middle initial|middleinitial|m.i."),
                &v.middle_name_)) {
    v.middle_initial_ = true;
  } else {
    ParseText(&q, ASCIIToUTF16("middle name|mname"), &v.middle_name_);
  }

  // The ".*last$" matches fields ending in "last" (example in sample8.html).
  if (!ParseText(&q,
                 ASCIIToUTF16("last name|lastname|lname|surname|.*last$"),
                 &v.last_name_))
    return NULL;

  *iter = q;
  return new FirstLastNameField(v);
}

FirstLastNameField* FirstLastNameField::ParseEcmlName(
    std::vector<AutoFillField*>::const_iterator* iter) {
  FirstLastNameField field;
  std::vector<AutoFillField*>::const_iterator q = *iter;

  string16 pattern = GetEcmlPattern(kEcmlShipToFirstName,
                                    kEcmlBillToFirstName, '|');
  if (!ParseText(&q, pattern, &field.first_name_))
    return NULL;

  pattern = GetEcmlPattern(kEcmlShipToMiddleName, kEcmlBillToMiddleName, '|');
  ParseText(&q, pattern, &field.middle_name_);

  pattern = GetEcmlPattern(kEcmlShipToLastName, kEcmlBillToLastName, '|');
  if (ParseText(&q, pattern, &field.last_name_)) {
    *iter = q;
    return new FirstLastNameField(field);
  }

  return NULL;
}

FirstLastNameField* FirstLastNameField::Parse(
    std::vector<AutoFillField*>::const_iterator* iter,
    bool is_ecml) {
  if (is_ecml) {
    return ParseEcmlName(iter);
  } else {
    FirstLastNameField* v = Parse1(iter);
    if (v != NULL)
      return v;

    return Parse2(iter);
  }
}

bool FirstLastNameField::GetFieldInfo(FieldTypeMap* field_type_map) const {
  bool ok = Add(field_type_map, first_name_, AutoFillType(NAME_FIRST));
  DCHECK(ok);
  ok = ok && Add(field_type_map, last_name_, AutoFillType(NAME_LAST));
  DCHECK(ok);
  AutoFillType type = middle_initial_ ?
      AutoFillType(NAME_MIDDLE_INITIAL) : AutoFillType(NAME_MIDDLE);
  ok = ok && Add(field_type_map, middle_name_, type);
  DCHECK(ok);

  return ok;
}

FirstLastNameField::FirstLastNameField()
    : first_name_(NULL),
      middle_name_(NULL),
      last_name_(NULL),
      middle_initial_(false) {
}

FirstLastNameField::FirstLastNameField(const FirstLastNameField& field)
    : NameField(),
      first_name_(field.first_name_),
      middle_name_(field.middle_name_),
      last_name_(field.last_name_),
      middle_initial_(field.middle_initial_) {
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: viewcontainer.cxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: hr $ $Date: 2005-09-23 12:03:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DBA_CORE_VIEWCONTAINER_HXX_
#include "viewcontainer.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
#ifndef _COMPHELPER_ENUMHELPER_HXX_
#include <comphelper/enumhelper.hxx>
#endif
#ifndef _DBA_CORE_RESOURCE_HXX_
#include "core_resource.hxx"
#endif
#ifndef _DBA_CORE_RESOURCE_HRC_
#include "core_resource.hrc"
#endif

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

#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _CONNECTIVITY_SDBCX_VIEW_HXX_
#include <connectivity/sdbcx/VView.hxx>
#endif

using namespace dbaccess;
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;

//==========================================================================
//= OViewContainer
//==========================================================================
DBG_NAME(OViewContainer)
//------------------------------------------------------------------------------
OViewContainer::OViewContainer(::cppu::OWeakObject& _rParent,
                                 ::osl::Mutex& _rMutex,
                                 const Reference< XConnection >& _xCon,
                                 sal_Bool _bCase,
                                 IRefreshListener*  _pRefreshListener,
                                 IWarningsContainer* _pWarningsContainer)
    :OFilteredContainer(_rParent,_rMutex,_xCon,_bCase,_pRefreshListener,_pWarningsContainer)
{
    DBG_CTOR(OViewContainer, NULL);
}

//------------------------------------------------------------------------------
OViewContainer::~OViewContainer()
{
    //  dispose();
    DBG_DTOR(OViewContainer, NULL);
}
//------------------------------------------------------------------------------
// XServiceInfo
//------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO2(OViewContainer, "com.sun.star.sdb.dbaccess.OViewContainer", SERVICE_SDBCX_CONTAINER, SERVICE_SDBCX_TABLES)
// -----------------------------------------------------------------------------
ObjectType OViewContainer::createObject(const ::rtl::OUString& _rName)
{
    ObjectType xProp;
    if ( m_xMasterContainer.is() && m_xMasterContainer->hasByName(_rName) )
        xProp.set(m_xMasterContainer->getByName(_rName),UNO_QUERY);

    if ( !xProp.is() )
    {
        ::rtl::OUString sCatalog,sSchema,sTable;
        ::dbtools::qualifiedNameComponents(m_xMetaData,
                                            _rName,
                                            sCatalog,
                                            sSchema,
                                            sTable,
                                            ::dbtools::eInDataManipulation);
        return new ::connectivity::sdbcx::OView(isCaseSensitive(),
                                sTable,
                                m_xMetaData,
                                0,
                                ::rtl::OUString(),
                                sSchema,
                                sCatalog
                                );
    }

    return xProp;
}
// -----------------------------------------------------------------------------
Reference< XPropertySet > OViewContainer::createEmptyObject()
{
    Reference< XPropertySet > xRet;
    // frist we have to look if the master tables does support this
    // and if then create a table object as well with the master tables
    Reference<XColumnsSupplier > xMasterColumnsSup;
    Reference<XDataDescriptorFactory> xDataFactory(m_xMasterContainer,UNO_QUERY);
    if(xDataFactory.is())
        xRet = xDataFactory->createDataDescriptor();
    else
        xRet = new ::connectivity::sdbcx::OView(isCaseSensitive(),m_xMetaData);

    return xRet;
}
// -----------------------------------------------------------------------------
// XAppend
void OViewContainer::appendObject( const Reference< XPropertySet >& descriptor )
{
    // append the new table with a create stmt
    ::rtl::OUString aName = getString(descriptor->getPropertyValue(PROPERTY_NAME));

    Reference<XAppend> xAppend(m_xMasterContainer,UNO_QUERY);
    Reference< XPropertySet > xProp = descriptor;
    if(xAppend.is())
    {
        xAppend->appendByDescriptor(descriptor);
        if(m_xMasterContainer->hasByName(aName))
            xProp.set(m_xMasterContainer->getByName(aName),UNO_QUERY);
    }
    else
    {
        ::rtl::OUString aSql    = ::rtl::OUString::createFromAscii("CREATE VIEW ");
        ::rtl::OUString sComposedName = ::dbtools::composeTableName(m_xMetaData,descriptor,sal_True,::dbtools::eInTableDefinitions);
        if(!sComposedName.getLength())
            ::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(static_cast<OFilteredContainer*>(this)));

        aSql += sComposedName + ::rtl::OUString::createFromAscii(" AS ");
        ::rtl::OUString sCommand;
        descriptor->getPropertyValue(PROPERTY_COMMAND)          >>= sCommand;
        aSql += sCommand;

        Reference<XConnection> xCon = m_xConnection;
        OSL_ENSURE(xCon.is(),"Connection is null!");
        if ( xCon.is() )
        {
            Reference< XStatement > xStmt = xCon->createStatement(  );
            if ( xStmt.is() )
                xStmt->execute(aSql);
            ::comphelper::disposeComponent(xStmt);
        }
    }
}
// -------------------------------------------------------------------------
// XDrop
void OViewContainer::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
    Reference< XDrop > xDrop(m_xMasterContainer,UNO_QUERY);
    if(xDrop.is())
        xDrop->dropByName(_sElementName);
    else
    {
        ::rtl::OUString sCatalog,sSchema,sTable,sComposedName;

        Reference<XPropertySet> xTable(getObject(_nPos),UNO_QUERY);
        if ( xTable.is() )
        {
            xTable->getPropertyValue(PROPERTY_CATALOGNAME)  >>= sCatalog;
            xTable->getPropertyValue(PROPERTY_SCHEMANAME)   >>= sSchema;
            xTable->getPropertyValue(PROPERTY_NAME)         >>= sTable;

            ::dbtools::composeTableName(m_xMetaData,sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInTableDefinitions);
        }

        if(!sComposedName.getLength())
            ::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(static_cast<OFilteredContainer*>(this)));

        ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP VIEW ");
        aSql += sComposedName;
        Reference<XConnection> xCon = m_xConnection;
        OSL_ENSURE(xCon.is(),"Connection is null!");
        if ( xCon.is() )
        {
            Reference< XStatement > xStmt = xCon->createStatement(  );
            if(xStmt.is())
                xStmt->execute(aSql);
            ::comphelper::disposeComponent(xStmt);
        }
    }
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementInserted( const ContainerEvent& Event ) throw (RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    ::rtl::OUString sName;
    if ( (Event.Accessor >>= sName) && !hasByName(sName) )
    {
        Reference<XPropertySet> xProp(Event.Element,UNO_QUERY);
        ::rtl::OUString sType;
        xProp->getPropertyValue(PROPERTY_TYPE) >>= sType;
        if ( sType == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VIEW")) )
            insertElement(sName,createObject(sName));
    }
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementRemoved( const ContainerEvent& Event ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::disposing( const ::com::sun::star::lang::EventObject& Source ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementReplaced( const ContainerEvent& Event ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > OViewContainer::getTableTypeFilter(const Sequence< ::rtl::OUString >& _rTableTypeFilter) const
{
    static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW"));

    if(_rTableTypeFilter.getLength() != 0)
    {
        const ::rtl::OUString* pBegin = _rTableTypeFilter.getConstArray();
        const ::rtl::OUString* pEnd   = pBegin + _rTableTypeFilter.getLength();
        for(;pBegin != pEnd;++pBegin)
        {
            if ( *pBegin == s_sTableTypeView )
                break;
        }
        if ( pBegin != pEnd )
        { // view are filtered out
            m_bConstructed = sal_True;
            return Sequence< ::rtl::OUString >();
        }
    }
    // we want all catalogues, all schemas, all tables
    Sequence< ::rtl::OUString > sTableTypes(1);
    sTableTypes[0] = s_sTableTypeView;
    return sTableTypes;
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS warnings01 (1.22.74); FILE MERGED 2006/03/24 15:35:50 fs 1.22.74.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: viewcontainer.cxx,v $
 *
 *  $Revision: 1.23 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 02:42:19 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DBA_CORE_VIEWCONTAINER_HXX_
#include "viewcontainer.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
#ifndef _COMPHELPER_ENUMHELPER_HXX_
#include <comphelper/enumhelper.hxx>
#endif
#ifndef _DBA_CORE_RESOURCE_HXX_
#include "core_resource.hxx"
#endif
#ifndef _DBA_CORE_RESOURCE_HRC_
#include "core_resource.hrc"
#endif

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

#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _CONNECTIVITY_SDBCX_VIEW_HXX_
#include <connectivity/sdbcx/VView.hxx>
#endif

using namespace dbaccess;
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;

//==========================================================================
//= OViewContainer
//==========================================================================
DBG_NAME(OViewContainer)
//------------------------------------------------------------------------------
OViewContainer::OViewContainer(::cppu::OWeakObject& _rParent,
                                 ::osl::Mutex& _rMutex,
                                 const Reference< XConnection >& _xCon,
                                 sal_Bool _bCase,
                                 IRefreshListener*  _pRefreshListener,
                                 IWarningsContainer* _pWarningsContainer)
    :OFilteredContainer(_rParent,_rMutex,_xCon,_bCase,_pRefreshListener,_pWarningsContainer)
{
    DBG_CTOR(OViewContainer, NULL);
}

//------------------------------------------------------------------------------
OViewContainer::~OViewContainer()
{
    //  dispose();
    DBG_DTOR(OViewContainer, NULL);
}
//------------------------------------------------------------------------------
// XServiceInfo
//------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO2(OViewContainer, "com.sun.star.sdb.dbaccess.OViewContainer", SERVICE_SDBCX_CONTAINER, SERVICE_SDBCX_TABLES)
// -----------------------------------------------------------------------------
ObjectType OViewContainer::createObject(const ::rtl::OUString& _rName)
{
    ObjectType xProp;
    if ( m_xMasterContainer.is() && m_xMasterContainer->hasByName(_rName) )
        xProp.set(m_xMasterContainer->getByName(_rName),UNO_QUERY);

    if ( !xProp.is() )
    {
        ::rtl::OUString sCatalog,sSchema,sTable;
        ::dbtools::qualifiedNameComponents(m_xMetaData,
                                            _rName,
                                            sCatalog,
                                            sSchema,
                                            sTable,
                                            ::dbtools::eInDataManipulation);
        return new ::connectivity::sdbcx::OView(isCaseSensitive(),
                                sTable,
                                m_xMetaData,
                                0,
                                ::rtl::OUString(),
                                sSchema,
                                sCatalog
                                );
    }

    return xProp;
}
// -----------------------------------------------------------------------------
Reference< XPropertySet > OViewContainer::createEmptyObject()
{
    Reference< XPropertySet > xRet;
    // frist we have to look if the master tables does support this
    // and if then create a table object as well with the master tables
    Reference<XColumnsSupplier > xMasterColumnsSup;
    Reference<XDataDescriptorFactory> xDataFactory(m_xMasterContainer,UNO_QUERY);
    if(xDataFactory.is())
        xRet = xDataFactory->createDataDescriptor();
    else
        xRet = new ::connectivity::sdbcx::OView(isCaseSensitive(),m_xMetaData);

    return xRet;
}
// -----------------------------------------------------------------------------
// XAppend
void OViewContainer::appendObject( const Reference< XPropertySet >& descriptor )
{
    // append the new table with a create stmt
    ::rtl::OUString aName = getString(descriptor->getPropertyValue(PROPERTY_NAME));

    Reference<XAppend> xAppend(m_xMasterContainer,UNO_QUERY);
    Reference< XPropertySet > xProp = descriptor;
    if(xAppend.is())
    {
        xAppend->appendByDescriptor(descriptor);
        if(m_xMasterContainer->hasByName(aName))
            xProp.set(m_xMasterContainer->getByName(aName),UNO_QUERY);
    }
    else
    {
        ::rtl::OUString aSql    = ::rtl::OUString::createFromAscii("CREATE VIEW ");
        ::rtl::OUString sComposedName = ::dbtools::composeTableName(m_xMetaData,descriptor,sal_True,::dbtools::eInTableDefinitions);
        if(!sComposedName.getLength())
            ::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(static_cast<OFilteredContainer*>(this)));

        aSql += sComposedName + ::rtl::OUString::createFromAscii(" AS ");
        ::rtl::OUString sCommand;
        descriptor->getPropertyValue(PROPERTY_COMMAND)          >>= sCommand;
        aSql += sCommand;

        Reference<XConnection> xCon = m_xConnection;
        OSL_ENSURE(xCon.is(),"Connection is null!");
        if ( xCon.is() )
        {
            Reference< XStatement > xStmt = xCon->createStatement(  );
            if ( xStmt.is() )
                xStmt->execute(aSql);
            ::comphelper::disposeComponent(xStmt);
        }
    }
}
// -------------------------------------------------------------------------
// XDrop
void OViewContainer::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
    Reference< XDrop > xDrop(m_xMasterContainer,UNO_QUERY);
    if(xDrop.is())
        xDrop->dropByName(_sElementName);
    else
    {
        ::rtl::OUString sCatalog,sSchema,sTable,sComposedName;

        Reference<XPropertySet> xTable(getObject(_nPos),UNO_QUERY);
        if ( xTable.is() )
        {
            xTable->getPropertyValue(PROPERTY_CATALOGNAME)  >>= sCatalog;
            xTable->getPropertyValue(PROPERTY_SCHEMANAME)   >>= sSchema;
            xTable->getPropertyValue(PROPERTY_NAME)         >>= sTable;

            ::dbtools::composeTableName(m_xMetaData,sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInTableDefinitions);
        }

        if(!sComposedName.getLength())
            ::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(static_cast<OFilteredContainer*>(this)));

        ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP VIEW ");
        aSql += sComposedName;
        Reference<XConnection> xCon = m_xConnection;
        OSL_ENSURE(xCon.is(),"Connection is null!");
        if ( xCon.is() )
        {
            Reference< XStatement > xStmt = xCon->createStatement(  );
            if(xStmt.is())
                xStmt->execute(aSql);
            ::comphelper::disposeComponent(xStmt);
        }
    }
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementInserted( const ContainerEvent& Event ) throw (RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    ::rtl::OUString sName;
    if ( (Event.Accessor >>= sName) && !hasByName(sName) )
    {
        Reference<XPropertySet> xProp(Event.Element,UNO_QUERY);
        ::rtl::OUString sType;
        xProp->getPropertyValue(PROPERTY_TYPE) >>= sType;
        if ( sType == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VIEW")) )
            insertElement(sName,createObject(sName));
    }
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementRemoved( const ContainerEvent& /*Event*/ ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::disposing( const ::com::sun::star::lang::EventObject& /*Source*/ ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
void SAL_CALL OViewContainer::elementReplaced( const ContainerEvent& /*Event*/ ) throw (RuntimeException)
{
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > OViewContainer::getTableTypeFilter(const Sequence< ::rtl::OUString >& _rTableTypeFilter) const
{
    static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW"));

    if(_rTableTypeFilter.getLength() != 0)
    {
        const ::rtl::OUString* pBegin = _rTableTypeFilter.getConstArray();
        const ::rtl::OUString* pEnd   = pBegin + _rTableTypeFilter.getLength();
        for(;pBegin != pEnd;++pBegin)
        {
            if ( *pBegin == s_sTableTypeView )
                break;
        }
        if ( pBegin != pEnd )
        { // view are filtered out
            m_bConstructed = sal_True;
            return Sequence< ::rtl::OUString >();
        }
    }
    // we want all catalogues, all schemas, all tables
    Sequence< ::rtl::OUString > sTableTypes(1);
    sTableTypes[0] = s_sTableTypeView;
    return sTableTypes;
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TableDesignView.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 15:36:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBAUI_TABLEDESIGNVIEW_HXX
#define DBAUI_TABLEDESIGNVIEW_HXX

#ifndef DBAUI_DATAVIEW_HXX
#include "dataview.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX
#include "IClipBoardTest.hxx"
#endif

namespace dbaui
{
    class OTableController;
    class OTableFieldDescWin;
    class OTableDescWin;
    class OTableEditorCtrl;
    //==================================================================
    class OTableBorderWindow : public Window
    {
        Splitter                            m_aHorzSplitter;
        OTableFieldDescWin*                 m_pFieldDescWin;
        OTableEditorCtrl*                   m_pEditorCtrl;

        void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
        void ArrangeChilds( long nSplitPos ,Rectangle& rRect);
        DECL_LINK( SplitHdl, Splitter* );
    protected:
        virtual void DataChanged(const DataChangedEvent& rDCEvt);
    public:
        OTableBorderWindow(Window* pParent);
        ~OTableBorderWindow();
        // window overloads
        virtual void Resize();
        virtual void GetFocus();

        OTableEditorCtrl*       GetEditorCtrl() const { return m_pEditorCtrl; }
        OTableFieldDescWin*     GetDescWin()    const { return m_pFieldDescWin; }
    };
    //==================================================================
    class OTableDesignView : public ODataView
                            ,public IClipboardTest
    {
        enum ChildFocusState
        {
            DESCRIPTION,
            EDITOR,
            NONE
        };
    private:
        ::com::sun::star::lang::Locale      m_aLocale;
        OTableBorderWindow*                 m_pWin;
        OTableController*                   m_pController;
        ChildFocusState                     m_eChildFocus;

        IClipboardTest* getActiveChild() const;
    protected:

        // return the Rectangle where I can paint myself
        virtual void resizeDocumentView(Rectangle& rRect);

    public:
        OTableDesignView(   Window* pParent,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&,
                            OTableController* _pController);
        virtual ~OTableDesignView();

        // window overloads
        virtual long            PreNotify( NotifyEvent& rNEvt );
        virtual void            GetFocus();

        OTableEditorCtrl*       GetEditorCtrl() const { return m_pWin ? m_pWin->GetEditorCtrl() : NULL; }
        OTableFieldDescWin*     GetDescWin()    const { return m_pWin ? m_pWin->GetDescWin() : NULL; }
        OTableController*       getController() const { return m_pController; }

        ::com::sun::star::lang::Locale      getLocale() const { return m_aLocale;}

        // IClipboardTest
        virtual sal_Bool isCutAllowed();
        virtual sal_Bool isCopyAllowed();
        virtual sal_Bool isPasteAllowed();
        virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); }
        virtual void copy();
        virtual void cut();
        virtual void paste();

        // set the view readonly or not
        virtual void setReadOnly(sal_Bool _bReadOnly);

        virtual void initialize();
        void reSync(); // resync window data with realdata

        DECL_LINK( SwitchHdl, Accelerator* );
    };
}
#endif // DBAUI_TABLEDESIGNVIEW_HXX

<commit_msg>INTEGRATION: CWS dba203a (1.10.94); FILE MERGED 2006/03/09 08:20:02 fs 1.10.94.1: removed obsolete files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TableDesignView.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2006-03-29 12:39:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBAUI_TABLEDESIGNVIEW_HXX
#define DBAUI_TABLEDESIGNVIEW_HXX

#ifndef DBAUI_DATAVIEW_HXX
#include "dataview.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX
#include "IClipBoardTest.hxx"
#endif

namespace dbaui
{
    class OTableController;
    class OTableFieldDescWin;
    class OTableEditorCtrl;
    //==================================================================
    class OTableBorderWindow : public Window
    {
        Splitter                            m_aHorzSplitter;
        OTableFieldDescWin*                 m_pFieldDescWin;
        OTableEditorCtrl*                   m_pEditorCtrl;

        void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
        void ArrangeChilds( long nSplitPos ,Rectangle& rRect);
        DECL_LINK( SplitHdl, Splitter* );
    protected:
        virtual void DataChanged(const DataChangedEvent& rDCEvt);
    public:
        OTableBorderWindow(Window* pParent);
        ~OTableBorderWindow();
        // window overloads
        virtual void Resize();
        virtual void GetFocus();

        OTableEditorCtrl*       GetEditorCtrl() const { return m_pEditorCtrl; }
        OTableFieldDescWin*     GetDescWin()    const { return m_pFieldDescWin; }
    };
    //==================================================================
    class OTableDesignView : public ODataView
                            ,public IClipboardTest
    {
        enum ChildFocusState
        {
            DESCRIPTION,
            EDITOR,
            NONE
        };
    private:
        ::com::sun::star::lang::Locale      m_aLocale;
        OTableBorderWindow*                 m_pWin;
        OTableController*                   m_pController;
        ChildFocusState                     m_eChildFocus;

        IClipboardTest* getActiveChild() const;
    protected:

        // return the Rectangle where I can paint myself
        virtual void resizeDocumentView(Rectangle& rRect);

    public:
        OTableDesignView(   Window* pParent,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&,
                            OTableController* _pController);
        virtual ~OTableDesignView();

        // window overloads
        virtual long            PreNotify( NotifyEvent& rNEvt );
        virtual void            GetFocus();

        OTableEditorCtrl*       GetEditorCtrl() const { return m_pWin ? m_pWin->GetEditorCtrl() : NULL; }
        OTableFieldDescWin*     GetDescWin()    const { return m_pWin ? m_pWin->GetDescWin() : NULL; }
        OTableController*       getController() const { return m_pController; }

        ::com::sun::star::lang::Locale      getLocale() const { return m_aLocale;}

        // IClipboardTest
        virtual sal_Bool isCutAllowed();
        virtual sal_Bool isCopyAllowed();
        virtual sal_Bool isPasteAllowed();
        virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); }
        virtual void copy();
        virtual void cut();
        virtual void paste();

        // set the view readonly or not
        virtual void setReadOnly(sal_Bool _bReadOnly);

        virtual void initialize();
        void reSync(); // resync window data with realdata

        DECL_LINK( SwitchHdl, Accelerator* );
    };
}
#endif // DBAUI_TABLEDESIGNVIEW_HXX

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2009 Daniël de Kok
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA
 */

#include <fstream>
#include <iostream>
#include <limits>

#include "FeatureSqueeze/stringutil.hh"
#include "FeatureSqueeze/DataSet.hh"
#include "FeatureSqueeze/Logger.hh"
#include "FeatureSqueeze/corr_selection.hh"
#include "FeatureSqueeze/feature_selection.hh"

#include "ProgramOptions.hh"

using namespace std;

void usage(string const &programName)
{
	cerr << "Usage: " << programName << " [OPTION] dataset" << endl << endl <<
		"  -a val\t Alpha convergence threshold (default: 1e-6)" << endl <<
		"  -c\t\t Correlation selection" << endl <<
		"  -f\t\t Fast maxent selection (do not recalculate all gains)" << endl <<
		"  -g val\t Gain threshold (default: 1e-20)" << endl <<
		"  -n val\t Maximum number of features" << endl <<
		"  -o\t\t Find overlap (incompatible with -f)" << endl <<
		"  -r val\t Correlation exclusion threshold (default: 0.9)" << endl <<
		"  -s val\t L2 prior variance (default: 0.0)" << endl << endl;
}

int main(int argc, char *argv[])
{
	fsqueeze::ProgramOptions programOptions(argc, argv, "a:cfg:n:or:s:");

	if (programOptions.arguments().size() != 1)
	{
		usage(programOptions.programName());
		return 1;
	}

	if (programOptions.option('o') && programOptions.option('f'))
	{
		cerr << "Overlap detection (-o) and fast selection(-f) cannot be used " <<
			"simultaneously!" << endl << endl;
		return 1;
	}

	if (programOptions.option('r') && !programOptions.option('c'))
	{
		cerr << "Minimal correlation specification (-r) can only be used " <<
			"with correlation" << endl << "selection (-c)!" << endl;
		return 1;
	}

	double alphaThreshold = 1e-6;
	if (programOptions.option('a'))
		alphaThreshold = fsqueeze::parseString<double>(programOptions.optionValue('a'));

	double gradientThreshold = 1e-20;
	if (programOptions.option('g'))
		gradientThreshold = fsqueeze::parseString<double>(programOptions.optionValue('g'));

	size_t nFeatures = numeric_limits<size_t>::max();
	if (programOptions.option('n'))
		nFeatures = fsqueeze::parseString<size_t>(programOptions.optionValue('n'));

	double minCorrelation = 0.9;
	if (programOptions.option('r'))
		minCorrelation = fsqueeze::parseString<double>(programOptions.optionValue('r'));

	double gaussianVariance = 0.0;
	if (programOptions.option('s'))
		gaussianVariance = 1.0 / fsqueeze::parseString<double>(programOptions.optionValue('s'));

	cerr << "Reading data... ";

	ifstream dataStream(programOptions.arguments()[0].c_str());
	if (!dataStream)
	{
		cerr << "Error opening input file!" << endl;
		return 1;
	}

	fsqueeze::DataSet ds = fsqueeze::DataSet::readTADMDataSet(dataStream);

	cerr << "done!" << endl;

	fsqueeze::Logger logger(cout, cerr);
	logger.error() << "Dynamic features: "<< ds.features().size() << "/" <<
		ds.nFeatures() << endl;

	if (programOptions.option('c'))
		fsqueeze::corrFeatureSelection(ds, logger, minCorrelation, nFeatures);
	else if (programOptions.option('f'))
		fsqueeze::fastFeatureSelection(ds, logger, alphaThreshold, gradientThreshold, gaussianVariance, nFeatures);
	else
		fsqueeze::featureSelection(ds, logger, alphaThreshold, gradientThreshold, gaussianVariance, nFeatures,
			programOptions.option('o'));

	return 0;
}
<commit_msg>Revert "Improve the synopsis of the '-s' flag (L2 prior)."<commit_after>/*
 * Copyright (c) 2009 Daniël de Kok
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA
 */

#include <fstream>
#include <iostream>
#include <limits>

#include "FeatureSqueeze/stringutil.hh"
#include "FeatureSqueeze/DataSet.hh"
#include "FeatureSqueeze/Logger.hh"
#include "FeatureSqueeze/corr_selection.hh"
#include "FeatureSqueeze/feature_selection.hh"

#include "ProgramOptions.hh"

using namespace std;

void usage(string const &programName)
{
	cerr << "Usage: " << programName << " [OPTION] dataset" << endl << endl <<
		"  -a val\t Alpha convergence threshold (default: 1e-6)" << endl <<
		"  -c\t\t Correlation selection" << endl <<
		"  -f\t\t Fast maxent selection (do not recalculate all gains)" << endl <<
		"  -g val\t Gain threshold (default: 1e-20)" << endl <<
		"  -n val\t Maximum number of features" << endl <<
		"  -o\t\t Find overlap (incompatible with -f)" << endl <<
		"  -r val\t Correlation exclusion threshold (default: 0.9)" << endl <<
		"  -s val\t Variance for L2 prior (default: 0.0)" << endl << endl;
}

int main(int argc, char *argv[])
{
	fsqueeze::ProgramOptions programOptions(argc, argv, "a:cfg:n:or:s:");

	if (programOptions.arguments().size() != 1)
	{
		usage(programOptions.programName());
		return 1;
	}

	if (programOptions.option('o') && programOptions.option('f'))
	{
		cerr << "Overlap detection (-o) and fast selection(-f) cannot be used " <<
			"simultaneously!" << endl << endl;
		return 1;
	}

	if (programOptions.option('r') && !programOptions.option('c'))
	{
		cerr << "Minimal correlation specification (-r) can only be used " <<
			"with correlation" << endl << "selection (-c)!" << endl;
		return 1;
	}

	double alphaThreshold = 1e-6;
	if (programOptions.option('a'))
		alphaThreshold = fsqueeze::parseString<double>(programOptions.optionValue('a'));

	double gradientThreshold = 1e-20;
	if (programOptions.option('g'))
		gradientThreshold = fsqueeze::parseString<double>(programOptions.optionValue('g'));

	size_t nFeatures = numeric_limits<size_t>::max();
	if (programOptions.option('n'))
		nFeatures = fsqueeze::parseString<size_t>(programOptions.optionValue('n'));

	double minCorrelation = 0.9;
	if (programOptions.option('r'))
		minCorrelation = fsqueeze::parseString<double>(programOptions.optionValue('r'));

	double gaussianVariance = 0.0;
	if (programOptions.option('s'))
		gaussianVariance = 1.0 / fsqueeze::parseString<double>(programOptions.optionValue('s'));

	cerr << "Reading data... ";

	ifstream dataStream(programOptions.arguments()[0].c_str());
	if (!dataStream)
	{
		cerr << "Error opening input file!" << endl;
		return 1;
	}

	fsqueeze::DataSet ds = fsqueeze::DataSet::readTADMDataSet(dataStream);

	cerr << "done!" << endl;

	fsqueeze::Logger logger(cout, cerr);
	logger.error() << "Dynamic features: "<< ds.features().size() << "/" <<
		ds.nFeatures() << endl;

	if (programOptions.option('c'))
		fsqueeze::corrFeatureSelection(ds, logger, minCorrelation, nFeatures);
	else if (programOptions.option('f'))
		fsqueeze::fastFeatureSelection(ds, logger, alphaThreshold, gradientThreshold, gaussianVariance, nFeatures);
	else
		fsqueeze::featureSelection(ds, logger, alphaThreshold, gradientThreshold, gaussianVariance, nFeatures,
			programOptions.option('o'));

	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/dom_ui/tips_handler.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/web_resource/web_resource_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/web_resource/web_resource_unpacker.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/gurl.h"

DOMMessageHandler* TipsHandler::Attach(DOMUI* dom_ui) {
  dom_ui_ = dom_ui;
  tips_cache_ = dom_ui_->GetProfile()->GetPrefs()->
      GetMutableDictionary(prefs::kNTPTipsCache);
  return DOMMessageHandler::Attach(dom_ui);
}

void TipsHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback("getTips",
      NewCallback(this, &TipsHandler::HandleGetTips));
}

void TipsHandler::HandleGetTips(const Value* content) {
  // List containing the tips to be displayed.
  ListValue list_value;

  // Holds the web resource data found in the preferences cache.
  ListValue* wr_list;

  // These values hold the data for each web resource item.
  int current_tip_index;
  std::string current_tip;

  // If tips are not correct for our locale, do not send.  Wait for update.
  // We need to check here because the new tab page calls for tips before
  // the tip service starts up.
  PrefService* current_prefs = dom_ui_->GetProfile()->GetPrefs();
  if (current_prefs->HasPrefPath(prefs::kNTPTipsServer)) {
    std::wstring server = current_prefs->GetString(prefs::kNTPTipsServer);
    std::wstring locale = ASCIIToWide(
        g_browser_process->GetApplicationLocale());
    if (!EndsWith(server, locale, false)) {
      dom_ui_->CallJavascriptFunction(L"tips", list_value);
      return;
    }
  }

  if (tips_cache_ != NULL && tips_cache_->GetSize() >= 0) {
    if (tips_cache_->GetInteger(
        WebResourceService::kCurrentTipPrefName, &current_tip_index) &&
        tips_cache_->GetList(
        WebResourceService::kTipCachePrefName, &wr_list)) {
      if (wr_list && wr_list->GetSize() > 0)
      if (wr_list->GetSize() <= static_cast<size_t>(current_tip_index))
        current_tip_index = 0;
      if (wr_list->GetString(current_tip_index, &current_tip)) {
        DictionaryValue* tip_dict = new DictionaryValue();
        tip_dict->SetString(L"tip_html_text", current_tip);
        list_value.Append(tip_dict);
        tips_cache_->SetInteger(WebResourceService::kCurrentTipPrefName,
                                current_tip_index + 1);
      }
    }
  }

  // Send list of web resource items back out to the DOM.
  dom_ui_->CallJavascriptFunction(L"tips", list_value);
}

// static
void TipsHandler::RegisterUserPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kNTPTipsCache);
  prefs->RegisterStringPref(prefs::kNTPTipsServer,
                            WebResourceService::kDefaultResourceServer);
}

bool TipsHandler::IsValidURL(const std::wstring& url_string) {
  GURL url(WideToUTF8(url_string));
  return !url.is_empty() && (url.SchemeIs(chrome::kHttpScheme) ||
                             url.SchemeIs(chrome::kHttpsScheme));
}

<commit_msg>Fix check for wr_list validity not covering entire use.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/dom_ui/tips_handler.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/web_resource/web_resource_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/web_resource/web_resource_unpacker.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/gurl.h"

DOMMessageHandler* TipsHandler::Attach(DOMUI* dom_ui) {
  dom_ui_ = dom_ui;
  tips_cache_ = dom_ui_->GetProfile()->GetPrefs()->
      GetMutableDictionary(prefs::kNTPTipsCache);
  return DOMMessageHandler::Attach(dom_ui);
}

void TipsHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback("getTips",
      NewCallback(this, &TipsHandler::HandleGetTips));
}

void TipsHandler::HandleGetTips(const Value* content) {
  // List containing the tips to be displayed.
  ListValue list_value;

  // Holds the web resource data found in the preferences cache.
  ListValue* wr_list;

  // These values hold the data for each web resource item.
  int current_tip_index;
  std::string current_tip;

  // If tips are not correct for our locale, do not send.  Wait for update.
  // We need to check here because the new tab page calls for tips before
  // the tip service starts up.
  PrefService* current_prefs = dom_ui_->GetProfile()->GetPrefs();
  if (current_prefs->HasPrefPath(prefs::kNTPTipsServer)) {
    std::wstring server = current_prefs->GetString(prefs::kNTPTipsServer);
    std::wstring locale = ASCIIToWide(
        g_browser_process->GetApplicationLocale());
    if (!EndsWith(server, locale, false)) {
      dom_ui_->CallJavascriptFunction(L"tips", list_value);
      return;
    }
  }

  if (tips_cache_ != NULL && tips_cache_->GetSize() >= 0) {
    if (tips_cache_->GetInteger(
        WebResourceService::kCurrentTipPrefName, &current_tip_index) &&
        tips_cache_->GetList(
        WebResourceService::kTipCachePrefName, &wr_list) &&
        wr_list && wr_list->GetSize() > 0) {
      if (wr_list->GetSize() <= static_cast<size_t>(current_tip_index))
        current_tip_index = 0;
      if (wr_list->GetString(current_tip_index, &current_tip)) {
        DictionaryValue* tip_dict = new DictionaryValue();
        tip_dict->SetString(L"tip_html_text", current_tip);
        list_value.Append(tip_dict);
        tips_cache_->SetInteger(WebResourceService::kCurrentTipPrefName,
                                current_tip_index + 1);
      }
    }
  }

  // Send list of web resource items back out to the DOM.
  dom_ui_->CallJavascriptFunction(L"tips", list_value);
}

// static
void TipsHandler::RegisterUserPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kNTPTipsCache);
  prefs->RegisterStringPref(prefs::kNTPTipsServer,
                            WebResourceService::kDefaultResourceServer);
}

bool TipsHandler::IsValidURL(const std::wstring& url_string) {
  GURL url(WideToUTF8(url_string));
  return !url.is_empty() && (url.SchemeIs(chrome::kHttpScheme) ||
                             url.SchemeIs(chrome::kHttpsScheme));
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/configuration_policy_pref_store.h"
#include "chrome/browser/policy/cloud_policy_subsystem.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/policy/profile_policy_connector_factory.h"

// Policies are optionally built, hence the following stubs.

namespace policy {

// static
BrowserPolicyConnector* BrowserPolicyConnector::Create() {
  return NULL;
}

// static
BrowserPolicyConnector* BrowserPolicyConnector::CreateForTests() {
  return NULL;
}

BrowserPolicyConnector::~BrowserPolicyConnector() {
}

// static
const ConfigurationPolicyProvider::PolicyDefinitionList*
ConfigurationPolicyPrefStore::GetChromePolicyDefinitionList() {
  return NULL;
}

// static
ConfigurationPolicyPrefStore* ConfigurationPolicyPrefStore::Create(
    ConfigurationPolicyProvider* provider) {
  return NULL;
}

// static
ConfigurationPolicyPrefStore*
ConfigurationPolicyPrefStore::CreateManagedPlatformPolicyPrefStore() {
  return NULL;
}

// static
ConfigurationPolicyPrefStore*
ConfigurationPolicyPrefStore::CreateManagedCloudPolicyPrefStore(
    Profile* profile) {
  return NULL;
}

// static
ConfigurationPolicyPrefStore*
ConfigurationPolicyPrefStore::CreateRecommendedPlatformPolicyPrefStore() {
  return NULL;
}

// static
ConfigurationPolicyPrefStore*
ConfigurationPolicyPrefStore::CreateRecommendedCloudPolicyPrefStore(
    Profile* profile) {
  return NULL;
}

// static
void CloudPolicySubsystem::RegisterPrefs(PrefService* local_state) {
  // don't need prefs for things we don't use.
}

// static
void ProfilePolicyConnector::Initialize() {
}

// static
ProfilePolicyConnector*
ProfilePolicyConnectorFactory::GetForProfile(Profile* profile) {
  return NULL;
}

}  // namespace policy
<commit_msg>Follow-up on http://codereview.chromium.org/7147015/ Removes unnecessary stubs for ProfilePolicyConnector and ProfilePolicyConnectorFactory.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/configuration_policy_pref_store.h"
#include "chrome/browser/policy/cloud_policy_subsystem.h"

// Policies are optionally built, hence the following stubs.

namespace policy {

// static
BrowserPolicyConnector* BrowserPolicyConnector::Create() {
  return NULL;
}

// static
BrowserPolicyConnector* BrowserPolicyConnector::CreateForTests() {
  return NULL;
}

BrowserPolicyConnector::~BrowserPolicyConnector() {
}

// static
const ConfigurationPolicyProvider::PolicyDefinitionList*
ConfigurationPolicyPrefStore::GetChromePolicyDefinitionList() {
  return NULL;
}

// static
ConfigurationPolicyPrefStore* ConfigurationPolicyPrefStore::Create(
    ConfigurationPolicyProvider* provider) {
  return NULL;
}

// static
ConfigurationPolicyPrefStore*
ConfigurationPolicyPrefStore::CreateManagedPlatformPolicyPrefStore() {
  return NULL;
}

// static
ConfigurationPolicyPrefStore*
ConfigurationPolicyPrefStore::CreateManagedCloudPolicyPrefStore(
    Profile* profile) {
  return NULL;
}

// static
ConfigurationPolicyPrefStore*
ConfigurationPolicyPrefStore::CreateRecommendedPlatformPolicyPrefStore() {
  return NULL;
}

// static
ConfigurationPolicyPrefStore*
ConfigurationPolicyPrefStore::CreateRecommendedCloudPolicyPrefStore(
    Profile* profile) {
  return NULL;
}

// static
void CloudPolicySubsystem::RegisterPrefs(PrefService* local_state) {
  // don't need prefs for things we don't use.
}

}  // namespace policy
<|endoftext|>