<commit_before>//
//  nthRoot.cpp
//  Calculator
//
//  Created by Gavin Scheele on 3/27/14.
//  Copyright (c) 2014 Gavin Scheele. All rights reserved.
//

#include "nthRoot.h"
using namespace std;
nthRoot::nthRoot(int root, int operand, int coefficient) {
    this->type = "nthRoot";
    this->operand = operand;
    this->root = root;
    this->coefficient = coefficient;

    if ((root % 2) == 0 && operand < 0) {
        throw runtime_error("unreal answer");
    }
}

nthRoot::~nthRoot() {

}

int* nthRoot::primeFactorization(int n) {
    int k = 0;
    while (n%2 == 0) {
        factors[k] = 2;
        k++;
        n = n/2;
    }
    for (int i = 3; i <= sqrt(n); i = i + 2) {
        if (n%i == 0) {
            while (n%i == 0) {
                factors[k] = i;
                k++;
                n = n/i;
            }
        }
    }
    if (n > 1) {
        factors[k] = n;
    }
    return factors;
    // added bonus: factors should be sorted already
}

Expression* nthRoot::simplify(){
    //if coefficient == 0 then return 0?
    //if operand < 0 throw an error
    if ((root % 2) == 0 && operand < 0) {   //this needs to be made right
        throw runtime_error("unreal answer");
    }
    factors = this->primeFactorization(operand);
    int i = 0;
    int factorsSize = sizeof(factors)/sizeof(factors[0]);

    while (i <= factorsSize) {   //all this takes unnecessary factors out of the operand
        int j = i;               //and puts them into the coefficient
        int count = 0;
        while (j <= factorsSize && factors[j + 1] == factors[j]) {
            count++;
            j++;
        }
        if (count >= root) {
            coefficient *= (factors[i] ^ (count/root));
            operand = operand / (factors[i] ^ (count - (count % root)));
        }
        i = j + 1;
    }
    if (operand == 1) {
        Integer* newInt = new Integer(coefficient);
        return newInt;
    }
    else {
        Expression* newRoot = new nthRoot(root, operand, coefficient);
        delete this;  //is this necessary?
        return newRoot;
    }

}

Expression* nthRoot::add(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asCoefficient = b->getCoefficient();
    int asOperand = b->getOperand();
    int asRoot = b->getRoot();
    if (root == asRoot && operand == asOperand) {
        int newCoefficient = asCoefficient + coefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

Expression* nthRoot::subtract(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asCoefficient = b->getCoefficient();
    int asOperand = b->getOperand();
    int asRoot = b->getRoot();
    if (root == asRoot && operand == asOperand) {
        int newCoefficient = coefficient - asCoefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

Expression* nthRoot::multiply(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asCoefficient = b->getCoefficient();
    int asOperand = b->getOperand();
    int asRoot = b->getRoot();
    if (root == asRoot) {
        int newCoefficient = asCoefficient * coefficient;
        int newOperand = operand * asOperand;       //asOperand doesnt exist?
        nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

Expression* nthRoot::divide(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asRoot = b->getRoot();
    int asOperand = b->getOperand();
    int asCoefficient = b->getCoefficient();
    if (root == asRoot && ((double)coefficient / (double)asCoefficient) % 1 == 0 && ((double)operand / (double)asOperand) % 1 == 0) {
        int newCoefficient = coefficient / asCoefficient;
        int newOperand = operand / asOperand;
        nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
   else if (((double)coefficient / (double)asCoefficient) % 1 == 0) {
        int newCoefficient = coefficient / asCoefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

int nthRoot::getRoot() {
    return root;
}

int nthRoot::getOperand() {
    return operand;
}

int nthRoot::getCoefficient() {
    return coefficient;
}

void nthRoot::setCoefficient(int n) {
    this->coefficient = n;
}

void nthRoot::setOperand(int n) {
    this->operand = n;
}

void nthRoot::setRoot(int n) {
    this->root = n;
}
ostream& nthRoot::print(std::ostream& output) const {
    output << this->coefficient  << "*" << this->root << "rt:" << this->operand;
    return output;
}

string nthRoot::toString() {
    stringstream s;
    s << coefficient << "*" << root << "rt:" << operand;
    return s.str();
}
<commit_msg>changed % to fmod() for doubles<commit_after>//
//  nthRoot.cpp
//  Calculator
//
//  Created by Gavin Scheele on 3/27/14.
//  Copyright (c) 2014 Gavin Scheele. All rights reserved.
//

#include "nthRoot.h"
using namespace std;
nthRoot::nthRoot(int root, int operand, int coefficient) {
    this->type = "nthRoot";
    this->operand = operand;
    this->root = root;
    this->coefficient = coefficient;

    if ((root % 2) == 0 && operand < 0) {
        throw runtime_error("unreal answer");
    }
}

nthRoot::~nthRoot() {

}

int* nthRoot::primeFactorization(int n) {
    int k = 0;
    while (n%2 == 0) {
        factors[k] = 2;
        k++;
        n = n/2;
    }
    for (int i = 3; i <= sqrt(n); i = i + 2) {
        if (n%i == 0) {
            while (n%i == 0) {
                factors[k] = i;
                k++;
                n = n/i;
            }
        }
    }
    if (n > 1) {
        factors[k] = n;
    }
    return factors;
    // added bonus: factors should be sorted already
}

Expression* nthRoot::simplify(){
    //if coefficient == 0 then return 0?
    //if operand < 0 throw an error
    if ((root % 2) == 0 && operand < 0) {   //this needs to be made right
        throw runtime_error("unreal answer");
    }
    factors = this->primeFactorization(operand);
    int i = 0;
    int factorsSize = sizeof(factors)/sizeof(factors[0]);

    while (i <= factorsSize) {   //all this takes unnecessary factors out of the operand
        int j = i;               //and puts them into the coefficient
        int count = 0;
        while (j <= factorsSize && factors[j + 1] == factors[j]) {
            count++;
            j++;
        }
        if (count >= root) {
            coefficient *= (factors[i] ^ (count/root));
            operand = operand / (factors[i] ^ (count - (count % root)));
        }
        i = j + 1;
    }
    if (operand == 1) {
        Integer* newInt = new Integer(coefficient);
        return newInt;
    }
    else {
        Expression* newRoot = new nthRoot(root, operand, coefficient);
        delete this;  //is this necessary?
        return newRoot;
    }

}

Expression* nthRoot::add(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asCoefficient = b->getCoefficient();
    int asOperand = b->getOperand();
    int asRoot = b->getRoot();
    if (root == asRoot && operand == asOperand) {
        int newCoefficient = asCoefficient + coefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

Expression* nthRoot::subtract(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asCoefficient = b->getCoefficient();
    int asOperand = b->getOperand();
    int asRoot = b->getRoot();
    if (root == asRoot && operand == asOperand) {
        int newCoefficient = coefficient - asCoefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

Expression* nthRoot::multiply(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asCoefficient = b->getCoefficient();
    int asOperand = b->getOperand();
    int asRoot = b->getRoot();
    if (root == asRoot) {
        int newCoefficient = asCoefficient * coefficient;
        int newOperand = operand * asOperand;       //asOperand doesnt exist?
        nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

Expression* nthRoot::divide(Expression* a) {
    nthRoot *b = (nthRoot *)a;
    int asRoot = b->getRoot();
    int asOperand = b->getOperand();
    int asCoefficient = b->getCoefficient();
    if (root == asRoot && fmod( ((double)coefficient / (double)asCoefficient), 1) == 0 && fmod(((double)operand / (double)asOperand), 1) == 0) {
        int newCoefficient = coefficient / asCoefficient;
        int newOperand = operand / asOperand;
        nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
   else if (fmod( ((double)coefficient / (double)asCoefficient),1) == 0) {
        int newCoefficient = coefficient / asCoefficient;
        nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
        nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
        return simplifiedVersion;
    }
    else {
        return this;
    }
}

int nthRoot::getRoot() {
    return root;
}

int nthRoot::getOperand() {
    return operand;
}

int nthRoot::getCoefficient() {
    return coefficient;
}

void nthRoot::setCoefficient(int n) {
    this->coefficient = n;
}

void nthRoot::setOperand(int n) {
    this->operand = n;
}

void nthRoot::setRoot(int n) {
    this->root = n;
}
ostream& nthRoot::print(std::ostream& output) const {
    output << this->coefficient  << "*" << this->root << "rt:" << this->operand;
    return output;
}

string nthRoot::toString() {
    stringstream s;
    s << coefficient << "*" << root << "rt:" << operand;
    return s.str();
}
<|endoftext|>


<commit_before>#include "x11api.h"

#ifdef __LINUX__
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xos.h>
#include <X11/keysymdef.h>
#include <X11/Xutil.h>
//#include <GL/glx.h> //FIXME

#include <Tempest/Event>
#include <Tempest/TextCodec>
#include <Tempest/Window>

#include <atomic>
#include <stdexcept>
#include <cstring>
#include <thread>
#include <unordered_map>

struct HWND final {
  ::Window wnd;
  HWND()=default;
  HWND(::Window w):wnd(w) {
    }
  HWND(Tempest::SystemApi::Window* p) {
    std::memcpy(&wnd,&p,sizeof(wnd));
    }

  HWND& operator = (::Window w) { wnd = w; return *this; }

  operator ::Window() { return wnd; }

  Tempest::SystemApi::Window* ptr() {
    static_assert (sizeof(::Window)<=sizeof(void*),"cannot map X11 window handle to pointer");
    Tempest::SystemApi::Window* ret=nullptr;
    std::memcpy(&ret,&wnd,sizeof(wnd));
    return ret;
    }
  };

using namespace Tempest;

static const char*      wndClassName="Tempest.Window";
static Display*         dpy  = nullptr;
static ::Window         root = {};
static std::atomic_bool isExit{0};

static std::unordered_map<SystemApi::Window*,Tempest::Window*> windows;

static Atom& wmDeleteMessage(){
  static Atom w  = XInternAtom( dpy, "WM_DELETE_WINDOW", 0);
  return w;
  }

static Atom& _NET_WM_STATE(){
  static Atom w  = XInternAtom( dpy, "_NET_WM_STATE", 0);
  return w;
  }

static Atom& _NET_WM_STATE_MAXIMIZED_HORZ(){
  static Atom w  = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", 0);
  return w;
  }

static Atom& _NET_WM_STATE_MAXIMIZED_VERT(){
  static Atom w  = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_VERT", 0);
  return w;
  }

static Atom& _NET_WM_STATE_FULLSCREEN(){
  static Atom w  = XInternAtom( dpy, "_NET_WM_STATE_FULLSCREEN", 0);
  return w;
  }

static Event::MouseButton toButton( XButtonEvent& msg ){
  if( msg.button==Button1 )
    return Event::ButtonLeft;

  if( msg.button==Button3 )
    return Event::ButtonRight;

  if( msg.button==Button2 )
    return Event::ButtonMid;

  return Event::ButtonNone;
  }

static void maximizeWindow(HWND& w) {
  Atom a[2];
  a[0] = _NET_WM_STATE_MAXIMIZED_HORZ();
  a[1] = _NET_WM_STATE_MAXIMIZED_VERT();

  XChangeProperty ( dpy, w, _NET_WM_STATE(),
    XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 2);
  XSync(dpy,False);
  }

static void alignGeometry(::Window w,Tempest::Window& owner) {
  XWindowAttributes xwa={};
  if(XGetWindowAttributes(dpy, HWND(w), &xwa)){
    owner.resize(xwa.width, xwa.height);
    }
  }

X11Api::X11Api() {
  dpy = XOpenDisplay(nullptr);

  if(dpy == nullptr)
    throw std::runtime_error("cannot connect to X server!");

  root = DefaultRootWindow(dpy);

  static const TranslateKeyPair k[] = {
    { XK_KP_Left,   Event::K_Left     },
    { XK_KP_Right,  Event::K_Right    },
    { XK_KP_Up,     Event::K_Up       },
    { XK_KP_Down,   Event::K_Down     },

    { XK_Shift_L,   Event::K_LShift   },
    { XK_Shift_R,   Event::K_RShift   },

    { XK_Control_L, Event::K_LControl },
    { XK_Control_R, Event::K_RControl },

    { XK_Escape,    Event::K_ESCAPE   },
    { XK_Tab,       Event::K_Tab      },
    { XK_BackSpace, Event::K_Back     },
    { XK_Delete,    Event::K_Delete   },
    { XK_Insert,    Event::K_Insert   },
    { XK_Home,      Event::K_Home     },
    { XK_End,       Event::K_End      },
    { XK_Pause,     Event::K_Pause    },
    { XK_Return,    Event::K_Return   },

    { XK_F1,        Event::K_F1       },
    {   48,         Event::K_0        },
    {   97,         Event::K_A        },

    { 0,            Event::K_NoKey    }
    };

  setupKeyTranslate(k,24);
  }

void *X11Api::display() {
  return dpy;
  }

SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, uint32_t w, uint32_t h) {
  //GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
  //XVisualInfo * vi = glXChooseVisual(dpy, 0, att);

  long visualMask = VisualScreenMask;
  int numberOfVisuals;
  XVisualInfo vInfoTemplate = {};
  vInfoTemplate.screen = DefaultScreen(dpy);
  XVisualInfo * vi = XGetVisualInfo(dpy, visualMask, &vInfoTemplate, &numberOfVisuals);

  Colormap cmap;
  cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);

  XSetWindowAttributes swa={};
  swa.colormap   = cmap;
  swa.event_mask = PointerMotionMask | ExposureMask |
                   ButtonPressMask | ButtonReleaseMask |
                   KeyPressMask | KeyReleaseMask;

  HWND win = XCreateWindow( dpy, root, 0, 0, w, h,
                            0, vi->depth, InputOutput, vi->visual,
                            CWColormap | CWEventMask, &swa );
  XSetWMProtocols(dpy, win, &wmDeleteMessage(), 1);
  XStoreName(dpy, win, wndClassName);

  XFreeColormap( dpy, cmap );
  XFree(vi);

  auto ret = reinterpret_cast<SystemApi::Window*>(win.ptr());
  windows[ret] = owner;
  //maximizeWindow(win);
  XMapWindow(dpy, win);
  XSync(dpy,False);
  alignGeometry(win,*owner);
  return ret;
  }

SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, SystemApi::ShowMode sm) {
  return implCreateWindow(owner,800,600); //TODO
  }

void X11Api::implDestroyWindow(SystemApi::Window *w) {
  windows.erase(w);
  XDestroyWindow(dpy, HWND(w));
  }

bool X11Api::implSetAsFullscreen(SystemApi::Window *w, bool fullScreen) {
  return false;
  }

bool X11Api::implIsFullscreen(SystemApi::Window *w) {
  return false;
  }

void X11Api::implSetCursorPosition(int x, int y) {
  // TODO
  }

void X11Api::implShowCursor(bool show) {
  // TODO
  }

Rect X11Api::implWindowClientRect(SystemApi::Window *w) {
  XWindowAttributes xwa;
  XGetWindowAttributes(dpy, HWND(w), &xwa);

  return Rect( xwa.x, xwa.y, xwa.width, xwa.height );
  }

void X11Api::implExit() {
  isExit.store(true);
  }

int X11Api::implExec(SystemApi::AppCallBack &cb) {
  // main message loop
  while (!isExit.load()) {
    if(XPending(dpy)>0) {
      XEvent xev={};
      XNextEvent(dpy, &xev);

      HWND hWnd = xev.xclient.window;
      Tempest::Window* cb = windows.find(hWnd.ptr())->second; //TODO: validation
      switch( xev.type ) {
        case ClientMessage: {
          if( xev.xclient.data.l[0] == long(wmDeleteMessage()) ){
            SystemApi::exit();
            }
          break;
          }
        case ButtonPress:
        case ButtonRelease: {
          if(cb) {
            bool isWheel = false;
            if( xev.type==ButtonPress && XPending(dpy) &&
                (xev.xbutton.button == Button4 || xev.xbutton.button == Button5) ){
              XEvent ev;
              XNextEvent(dpy, &ev);
              isWheel = (ev.type==ButtonRelease);
              }

            if( isWheel ){
              int ticks = 0;
              if( xev.xbutton.button == Button4 ) {
                ticks = 100;
                }
              else if ( xev.xbutton.button == Button5 ) {
                ticks = -100;
                }
              Tempest::MouseEvent e( xev.xbutton.x,
                                     xev.xbutton.y,
                                     Tempest::Event::ButtonNone,
                                     ticks,
                                     0,
                                     Event::MouseWheel );
              SystemApi::dispatchMouseWheel(*cb, e);
              } else {
              MouseEvent e( xev.xbutton.x,
                            xev.xbutton.y,
                            toButton( xev.xbutton ),
                            0,
                            0,
                            xev.type==ButtonPress ? Event::MouseDown : Event::MouseUp );
              if(xev.type==ButtonPress)
                SystemApi::dispatchMouseDown(*cb, e); else
                SystemApi::dispatchMouseUp(*cb, e);
              }
            }
          break;
          }
        case MotionNotify: {
          MouseEvent e( xev.xmotion.x,
                        xev.xmotion.y,
                        Event::ButtonNone,
                        0,
                        0,
                        Event::MouseMove  );
          SystemApi::dispatchMouseMove(*cb, e);
          break;
          }
        case KeyPress:
        case KeyRelease: {
          if(cb) {
            int keysyms_per_keycode_return = 0;
            KeySym *ksym = XGetKeyboardMapping( dpy, KeyCode(xev.xkey.keycode),
                                                1,
                                                &keysyms_per_keycode_return );

            char txt[10]={};
            XLookupString(&xev.xkey, txt, sizeof(txt)-1, ksym, nullptr );

            auto u16 = TextCodec::toUtf16(txt); // TODO: remove dynamic allocation
            auto key = SystemApi::translateKey(*ksym);

            uint32_t scan = xev.xkey.keycode;

            Tempest::KeyEvent e(Event::KeyType(key),uint32_t(u16.size()>0 ? u16[0] : 0),(xev.type==KeyPress) ? Event::KeyDown : Event::KeyUp);
            if(xev.type==KeyPress)
              SystemApi::dispatchKeyDown(*cb,e,scan); else
              SystemApi::dispatchKeyUp  (*cb,e,scan);
              }
          break;
          }
        }

      std::this_thread::yield();
      } else {
      if(cb.onTimer()==0)
        std::this_thread::yield();
      for(auto& i:windows) {
        ::Window hWnd = HWND(i.first);
        // artificial move/resize event
        alignGeometry(hWnd,*i.second);
        SystemApi::dispatchRender(*i.second);
        }
      }
    }

  return 0;
  }

#endif
<commit_msg>x11 fixup<commit_after>#include "x11api.h"

#ifdef __LINUX__
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xos.h>
#include <X11/keysymdef.h>
#include <X11/Xutil.h>
//#include <GL/glx.h> //FIXME

#include <Tempest/Event>
#include <Tempest/TextCodec>
#include <Tempest/Window>

#include <atomic>
#include <stdexcept>
#include <cstring>
#include <thread>
#include <unordered_map>

struct HWND final {
  ::Window wnd;
  HWND()=default;
  HWND(::Window w):wnd(w) {
    }
  HWND(Tempest::SystemApi::Window* p) {
    std::memcpy(&wnd,&p,sizeof(wnd));
    }

  HWND& operator = (::Window w) { wnd = w; return *this; }

  operator ::Window() { return wnd; }

  Tempest::SystemApi::Window* ptr() {
    static_assert (sizeof(::Window)<=sizeof(void*),"cannot map X11 window handle to pointer");
    Tempest::SystemApi::Window* ret=nullptr;
    std::memcpy(&ret,&wnd,sizeof(wnd));
    return ret;
    }
  };

using namespace Tempest;

static const char*      wndClassName="Tempest.Window";
static Display*         dpy  = nullptr;
static ::Window         root = {};
static std::atomic_bool isExit{0};

static std::unordered_map<SystemApi::Window*,Tempest::Window*> windows;

static Atom& wmDeleteMessage(){
  static Atom w  = XInternAtom( dpy, "WM_DELETE_WINDOW", 0);
  return w;
  }

static Atom& _NET_WM_STATE(){
  static Atom w  = XInternAtom( dpy, "_NET_WM_STATE", 0);
  return w;
  }

static Atom& _NET_WM_STATE_MAXIMIZED_HORZ(){
  static Atom w  = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", 0);
  return w;
  }

static Atom& _NET_WM_STATE_MAXIMIZED_VERT(){
  static Atom w  = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_VERT", 0);
  return w;
  }

static Atom& _NET_WM_STATE_FULLSCREEN(){
  static Atom w  = XInternAtom( dpy, "_NET_WM_STATE_FULLSCREEN", 0);
  return w;
  }

static Event::MouseButton toButton( XButtonEvent& msg ){
  if( msg.button==Button1 )
    return Event::ButtonLeft;

  if( msg.button==Button3 )
    return Event::ButtonRight;

  if( msg.button==Button2 )
    return Event::ButtonMid;

  return Event::ButtonNone;
  }

static void maximizeWindow(HWND& w) {
  Atom a[2];
  a[0] = _NET_WM_STATE_MAXIMIZED_HORZ();
  a[1] = _NET_WM_STATE_MAXIMIZED_VERT();

  XChangeProperty ( dpy, w, _NET_WM_STATE(),
    XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 2);
  XSync(dpy,False);
  }

static void alignGeometry(::Window w,Tempest::Window& owner) {
  XWindowAttributes xwa={};
  if(XGetWindowAttributes(dpy, HWND(w), &xwa)){
    owner.resize(xwa.width, xwa.height);
    }
  }

X11Api::X11Api() {
  dpy = XOpenDisplay(nullptr);

  if(dpy == nullptr)
    throw std::runtime_error("cannot connect to X server!");

  root = DefaultRootWindow(dpy);

  static const TranslateKeyPair k[] = {
    { XK_KP_Left,   Event::K_Left     },
    { XK_KP_Right,  Event::K_Right    },
    { XK_KP_Up,     Event::K_Up       },
    { XK_KP_Down,   Event::K_Down     },

    { XK_Shift_L,   Event::K_LShift   },
    { XK_Shift_R,   Event::K_RShift   },

    { XK_Control_L, Event::K_LControl },
    { XK_Control_R, Event::K_RControl },

    { XK_Escape,    Event::K_ESCAPE   },
    { XK_Tab,       Event::K_Tab      },
    { XK_BackSpace, Event::K_Back     },
    { XK_Delete,    Event::K_Delete   },
    { XK_Insert,    Event::K_Insert   },
    { XK_Home,      Event::K_Home     },
    { XK_End,       Event::K_End      },
    { XK_Pause,     Event::K_Pause    },
    { XK_Return,    Event::K_Return   },

    { XK_F1,        Event::K_F1       },
    {   48,         Event::K_0        },
    {   97,         Event::K_A        },

    { 0,            Event::K_NoKey    }
    };

  setupKeyTranslate(k,24);
  }

void *X11Api::display() {
  return dpy;
  }

SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, uint32_t w, uint32_t h) {
  //GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
  //XVisualInfo * vi = glXChooseVisual(dpy, 0, att);

  long visualMask = VisualScreenMask;
  int numberOfVisuals;
  XVisualInfo vInfoTemplate = {};
  vInfoTemplate.screen = DefaultScreen(dpy);
  XVisualInfo * vi = XGetVisualInfo(dpy, visualMask, &vInfoTemplate, &numberOfVisuals);

  Colormap cmap;
  cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);

  XSetWindowAttributes swa={};
  swa.colormap   = cmap;
  swa.event_mask = PointerMotionMask | ExposureMask |
                   ButtonPressMask | ButtonReleaseMask |
                   KeyPressMask | KeyReleaseMask;

  HWND win = XCreateWindow( dpy, root, 0, 0, w, h,
                            0, vi->depth, InputOutput, vi->visual,
                            CWColormap | CWEventMask, &swa );
  XSetWMProtocols(dpy, win, &wmDeleteMessage(), 1);
  XStoreName(dpy, win, wndClassName);

  XFreeColormap( dpy, cmap );
  XFree(vi);

  auto ret = reinterpret_cast<SystemApi::Window*>(win.ptr());
  windows[ret] = owner;
  //maximizeWindow(win);
  XMapWindow(dpy, win);
  XSync(dpy,False);
  alignGeometry(win,*owner);
  return ret;
  }

SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, SystemApi::ShowMode sm) {
  return implCreateWindow(owner,800,600); //TODO
  }

void X11Api::implDestroyWindow(SystemApi::Window *w) {
  windows.erase(w);
  XDestroyWindow(dpy, HWND(w));
  }

bool X11Api::implSetAsFullscreen(SystemApi::Window *w, bool fullScreen) {
  return false;
  }

bool X11Api::implIsFullscreen(SystemApi::Window *w) {
  return false;
  }

void X11Api::implSetCursorPosition(int x, int y) {
  // TODO
  }

void X11Api::implShowCursor(bool show) {
  // TODO
  }

Rect X11Api::implWindowClientRect(SystemApi::Window *w) {
  XWindowAttributes xwa;
  XGetWindowAttributes(dpy, HWND(w), &xwa);

  return Rect( xwa.x, xwa.y, xwa.width, xwa.height );
  }

void X11Api::implExit() {
  isExit.store(true);
  }

int X11Api::implExec(SystemApi::AppCallBack &cb) {
  // main message loop
  while (!isExit.load()) {
    if(XPending(dpy)>0) {
      XEvent xev={};
      XNextEvent(dpy, &xev);

      HWND hWnd = xev.xclient.window;
      Tempest::Window* cb = windows.find(hWnd.ptr())->second; //TODO: validation
      switch( xev.type ) {
        case ClientMessage: {
          if( xev.xclient.data.l[0] == long(wmDeleteMessage()) ){
            SystemApi::exit();
            }
          break;
          }
        case ButtonPress:
        case ButtonRelease: {
          if(cb) {
            bool isWheel = false;
            if( xev.type==ButtonPress && XPending(dpy) &&
                (xev.xbutton.button == Button4 || xev.xbutton.button == Button5) ){
              XEvent ev;
              XNextEvent(dpy, &ev);
              isWheel = (ev.type==ButtonRelease);
              }

            if( isWheel ){
              int ticks = 0;
              if( xev.xbutton.button == Button4 ) {
                ticks = 100;
                }
              else if ( xev.xbutton.button == Button5 ) {
                ticks = -100;
                }
              Tempest::MouseEvent e( xev.xbutton.x,
                                     xev.xbutton.y,
                                     Tempest::Event::ButtonNone,
                                     ticks,
                                     0,
                                     Event::MouseWheel );
              SystemApi::dispatchMouseWheel(*cb, e);
              } else {
              MouseEvent e( xev.xbutton.x,
                            xev.xbutton.y,
                            toButton( xev.xbutton ),
                            0,
                            0,
                            xev.type==ButtonPress ? Event::MouseDown : Event::MouseUp );
              if(xev.type==ButtonPress)
                SystemApi::dispatchMouseDown(*cb, e); else
                SystemApi::dispatchMouseUp(*cb, e);
              }
            }
          break;
          }
        case MotionNotify: {
          MouseEvent e( xev.xmotion.x,
                        xev.xmotion.y,
                        Event::ButtonNone,
                        0,
                        0,
                        Event::MouseMove  );
          SystemApi::dispatchMouseMove(*cb, e);
          break;
          }
        case KeyPress:
        case KeyRelease: {
          if(cb) {
            int keysyms_per_keycode_return = 0;
            KeySym *ksym = XGetKeyboardMapping( dpy, KeyCode(xev.xkey.keycode),
                                                1,
                                                &keysyms_per_keycode_return );

            char txt[10]={};
            XLookupString(&xev.xkey, txt, sizeof(txt)-1, ksym, nullptr );

            auto u16 = TextCodec::toUtf16(txt); // TODO: remove dynamic allocation
            auto key = SystemApi::translateKey(*ksym);

            uint32_t scan = xev.xkey.keycode;

            Tempest::KeyEvent e(Event::KeyType(key),uint32_t(u16.size()>0 ? u16[0] : 0),Event::M_NoModifier,(xev.type==KeyPress) ? Event::KeyDown : Event::KeyUp);
            if(xev.type==KeyPress)
              SystemApi::dispatchKeyDown(*cb,e,scan); else
              SystemApi::dispatchKeyUp  (*cb,e,scan);
              }
          break;
          }
        }

      std::this_thread::yield();
      } else {
      if(cb.onTimer()==0)
        std::this_thread::yield();
      for(auto& i:windows) {
        ::Window hWnd = HWND(i.first);
        // artificial move/resize event
        alignGeometry(hWnd,*i.second);
        SystemApi::dispatchRender(*i.second);
        }
      }
    }

  return 0;
  }

#endif
<|endoftext|>


<commit_before>#include <sys/types.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <CoreFoundation/CoreFoundation.h>
#include <SystemConfiguration/SystemConfiguration.h>

namespace {
  bool
  verifyUser(void)
  {
    uid_t consoleUID;
    CFStringRef result = SCDynamicStoreCopyConsoleUser(NULL, &consoleUID, NULL);
    if (! result) return false;
    CFRelease(result);

    return (getuid() == consoleUID);
  }
}

int
main(int argc, char **argv)
{
  if (argc != 3) {
    fprintf(stderr, "Usage: %s key value\n", argv[0]);
    return 1;
  }

  if (! verifyUser()) {
    fprintf(stderr, "Permission denied\n");
    return 1;
  }

  char name[512];
  snprintf(name, sizeof(name), "pckeyboardhack.%s", argv[1]);

  int value = atoi(argv[2]);

  size_t oldlen = 0;
  size_t newlen = sizeof(value);
  int error = sysctlbyname(name, NULL, &oldlen, &value, newlen);

  if (error) {
    perror("sysctl");
    return 1;
  }

  fprintf(stderr, "%s -> %d\n", name, value);

  return 0;
}
<commit_msg>update src/bin/sysctl_set<commit_after>#include <sys/types.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <CoreFoundation/CoreFoundation.h>
#include <SystemConfiguration/SystemConfiguration.h>

namespace {
  bool
  verifyUser(void)
  {
    uid_t consoleUID;
    CFStringRef result = SCDynamicStoreCopyConsoleUser(NULL, &consoleUID, NULL);
    if (! result) return false;
    CFRelease(result);

    return (getuid() == consoleUID);
  }
}

int
main(int argc, char** argv)
{
  if (argc != 3) {
    fprintf(stderr, "Usage: %s key value\n", argv[0]);
    return 1;
  }

  if (! verifyUser()) {
    return 1;
  }

  char name[512];
  snprintf(name, sizeof(name), "pckeyboardhack.%s", argv[1]);

  int value = atoi(argv[2]);

  size_t oldlen = 0;
  size_t newlen = sizeof(value);
  int error = sysctlbyname(name, NULL, &oldlen, &value, newlen);

  if (error) {
    perror("sysctl");
    return 1;
  }

  return 0;
}
<|endoftext|>


<commit_before>// CToolDlg.cpp
// Copyright (c) 2014, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include "CToolDlg.h"
#include "interface/NiceTextCtrl.h"

enum
{
    ID_TITLE_TYPE = 100,
    ID_TOOL_TYPE,
    ID_MATERIAL,
    ID_DIRECTION,
};

BEGIN_EVENT_TABLE(CToolDlg, HeeksObjDlg)
    EVT_COMBOBOX(ID_TITLE_TYPE,CToolDlg::OnComboTitleType)
    EVT_COMBOBOX(ID_TOOL_TYPE, CToolDlg::OnComboToolType)
    EVT_COMBOBOX(ID_MATERIAL, CToolDlg::OnComboMaterial)
    EVT_TEXT(wxID_ANY,CToolDlg::OnTextCtrlEvent)
    EVT_BUTTON(wxID_HELP, CToolDlg::OnHelp)
END_EVENT_TABLE()

CToolDlg::CToolDlg(wxWindow *parent, CTool* object, const wxString& title, bool top_level)
             : HeeksObjDlg(parent, object, title, false)
{
	// add some of the controls to the right side
	rightControls.push_back(MakeLabelAndControl(_("Title"), m_txtTitle = new wxTextCtrl(this, wxID_ANY)));
	wxString title_choices[] = {_("Leave manually assigned title"), _("Automatically Generate Title")};
	rightControls.push_back(MakeLabelAndControl(_("Title Type"), m_cmbTitleType = new wxComboBox(this, ID_TITLE_TYPE, _T(""), wxDefaultPosition, wxDefaultSize, 2, title_choices)));

	// add all the controls to the left side
	leftControls.push_back(MakeLabelAndControl(_("Tool Number"), m_dlbToolNumber = new wxTextCtrl(this, wxID_ANY)));
	wxString materials[] = {_("High Speed Steel"),_("Carbide") };
	leftControls.push_back(MakeLabelAndControl(_("Tool Material"), m_cmbMaterial = new wxComboBox(this, ID_MATERIAL, _T(""), wxDefaultPosition, wxDefaultSize, 2, materials)));
	wxString tool_types[] = {_("Drill Bit"), _("Centre Drill Bit"), _("End Mill"), _("Slot Cutter"), _("Ball End Mill"), _("Chamfer"), _("Engraving Bit")};
	leftControls.push_back(MakeLabelAndControl(_("Tool Type"), m_cmbToolType = new wxComboBox(this, ID_TOOL_TYPE, _T(""), wxDefaultPosition, wxDefaultSize, sizeof(tool_types)/sizeof(CToolParams::eToolType), tool_types)));
	leftControls.push_back(MakeLabelAndControl(_("Diameter"), m_dblDiameter = new CLengthCtrl(this)));
	leftControls.push_back(MakeLabelAndControl(_("Tool Length Offset"), m_dblToolLengthOffset = new CLengthCtrl(this)));
	leftControls.push_back(MakeLabelAndControl(_("Flat Radius"), m_dblFlatRadius = new CLengthCtrl(this)));
	leftControls.push_back(MakeLabelAndControl(_("Corner Radius"), m_dblCornerRadius = new CLengthCtrl(this)));
	leftControls.push_back(MakeLabelAndControl(_("Cutting Edge Angle"), m_dblCuttingEdgeAngle = new CDoubleCtrl(this)));
	leftControls.push_back(MakeLabelAndControl(_("Cutting Edge Height"), m_dblCuttingEdgeHeight = new CLengthCtrl(this)));

	if(top_level)
	{
		HeeksObjDlg::AddControlsAndCreate();
		m_dblDiameter->SetFocus();
	}
}

void CToolDlg::GetDataRaw(HeeksObj* object)
{
	long i = 0;
	m_dlbToolNumber->GetValue().ToLong(&i);
	((CTool*)object)->m_tool_number = i;
	((CTool*)object)->m_params.m_material = m_cmbMaterial->GetSelection();
	((CTool*)object)->m_params.m_type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());
	((CTool*)object)->m_params.m_diameter = m_dblDiameter->GetValue();
	((CTool*)object)->m_params.m_tool_length_offset = m_dblToolLengthOffset->GetValue();
	((CTool*)object)->m_params.m_flat_radius = m_dblFlatRadius->GetValue();
	((CTool*)object)->m_params.m_corner_radius = m_dblCornerRadius->GetValue();
	((CTool*)object)->m_params.m_cutting_edge_angle = m_dblCuttingEdgeAngle->GetValue();
	((CTool*)object)->m_params.m_cutting_edge_height = m_dblCuttingEdgeHeight->GetValue();
	((CTool*)object)->m_title = m_txtTitle->GetValue();
	((CTool*)object)->m_params.m_automatically_generate_title = (m_cmbTitleType->GetSelection() != 0);
}

void CToolDlg::SetFromDataRaw(HeeksObj* object)
{
	m_dlbToolNumber->SetValue(wxString::Format(_T("%d"), ((CTool*)object)->m_tool_number));
	m_txtTitle->SetValue(((CTool*)object)->m_title);
	m_cmbMaterial->SetSelection(((CTool*)object)->m_params.m_material);
	m_cmbToolType->SetSelection(((CTool*)object)->m_params.m_type);
	m_dblDiameter->SetValue(((CTool*)object)->m_params.m_diameter);
	m_dblToolLengthOffset->SetValue(((CTool*)object)->m_params.m_tool_length_offset);
	m_dblCuttingEdgeHeight->SetValue(((CTool*)object)->m_params.m_cutting_edge_height);
	m_txtTitle->SetValue(((CTool*)object)->m_title);
	m_cmbTitleType->SetSelection(((CTool*)object)->m_params.m_automatically_generate_title ? 1:0);

	EnableAndSetCornerFlatAndAngle(((CTool*)object)->m_params.m_type);
}

void CToolDlg::SetPicture(const wxString& name)
{
	HeeksObjDlg::SetPicture(name, _T("ctool"));
}

void CToolDlg::SetPictureByWindow(wxWindow* w)
{
	CToolParams::eToolType type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());

	switch(type)
	{
		case CToolParams::eDrill:
			if(w == m_dblDiameter)SetPicture(_T("drill_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("drill_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("drill_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("drill_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("drill_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("drill_height"));
			else SetPicture(_T("drill"));
			break;
		case CToolParams::eCentreDrill:
			if(w == m_dblDiameter)SetPicture(_T("centre_drill_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("centre_drill_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("centre_drill_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("centre_drill_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("centre_drill_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("centre_drill_height"));
			else SetPicture(_T("centre_drill"));
			break;
		case CToolParams::eEndmill:
		case CToolParams::eSlotCutter:
			if(w == m_dblDiameter)SetPicture(_T("end_mill_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("end_mill_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("end_mill_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("end_mill_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("end_mill_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("end_mill_height"));
			else SetPicture(_T("end_mill"));
			break;
		case CToolParams::eBallEndMill:
			if(w == m_dblDiameter)SetPicture(_T("ball_mill_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("ball_mill_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("ball_mill_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("ball_mill_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("ball_mill_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("ball_mill_height"));
			else SetPicture(_T("ball_mill"));
			break;
		case CToolParams::eChamfer:
			if(w == m_dblDiameter)SetPicture(_T("chamfer_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("chamfer_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("chamfer_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("chamfer_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("chamfer_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("chamfer_height"));
			else SetPicture(_T("chamfer"));
			break;
		case CToolParams::eEngravingTool:
			if(w == m_dblDiameter)SetPicture(_T("engraver_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("engraver_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("engraver_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("engraver_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("engraver_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("engraver_height"));
			else SetPicture(_T("engraver"));
			break;
		default:
			SetPicture(_T("undefined"));
			break;
	}
}

void CToolDlg::OnComboTitleType( wxCommandEvent& event )
{
	if(m_ignore_event_functions)return;
//	SetPicture();
}

void CToolDlg::OnComboMaterial( wxCommandEvent& event )
{
	if(m_ignore_event_functions)return;
//	//SetPicture();
}

void CToolDlg::OnTextCtrlEvent(wxCommandEvent& event)
{
	if(m_ignore_event_functions)return;

	// something's changed, recalculate the title
	CTool* object = (CTool*)(m_object->MakeACopy());
	GetData(object);
	m_ignore_event_functions = true;
	object->ResetTitle();
	m_txtTitle->SetValue(object->m_title);
	delete object;

	m_ignore_event_functions = false;
}

void CToolDlg::OnComboToolType(wxCommandEvent& event)
{
	if(m_ignore_event_functions)return;
	CToolParams::eToolType type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());
	EnableAndSetCornerFlatAndAngle(type);
	HeeksObjDlg::SetPicture();
}

void CToolDlg::EnableAndSetCornerFlatAndAngle(CToolParams::eToolType type)
{
	switch(type)
	{
		case CToolParams::eDrill:
		case CToolParams::eCentreDrill:
			m_dblCornerRadius->Enable(false);
			m_dblCornerRadius->SetLabel(_T(""));
			m_dblFlatRadius->Enable(false);
			m_dblFlatRadius->SetLabel(_T(""));
			m_dblCuttingEdgeAngle->Enable();
			m_dblCuttingEdgeAngle->SetValue(((CTool*)m_object)->m_params.m_cutting_edge_angle);
			break;
		case CToolParams::eEndmill:
		case CToolParams::eSlotCutter:
			m_dblCornerRadius->Enable();
			m_dblCornerRadius->SetValue(((CTool*)m_object)->m_params.m_corner_radius);
			m_dblFlatRadius->Enable(false);
			m_dblFlatRadius->SetLabel(_T(""));
			m_dblCuttingEdgeAngle->Enable(false);
			m_dblCuttingEdgeAngle->SetLabel(_T(""));
			break;
		case CToolParams::eBallEndMill:
			m_dblCornerRadius->Enable(false);
			m_dblCornerRadius->SetLabel(_T(""));
			m_dblFlatRadius->Enable(false);
			m_dblFlatRadius->SetLabel(_T(""));
			m_dblCuttingEdgeAngle->Enable(false);
			m_dblCuttingEdgeAngle->SetLabel(_T(""));
			break;
		case CToolParams::eChamfer:
		case CToolParams::eEngravingTool:
			m_dblCornerRadius->Enable(false);
			m_dblCornerRadius->SetLabel(_T(""));
			m_dblFlatRadius->Enable();
			m_dblFlatRadius->SetValue(((CTool*)m_object)->m_params.m_flat_radius);
			m_dblCuttingEdgeAngle->Enable();
			m_dblCuttingEdgeAngle->SetValue(((CTool*)m_object)->m_params.m_cutting_edge_angle);
			break;
		default:
			break;
	}
}

void CToolDlg::OnHelp( wxCommandEvent& event )
{
	::wxLaunchDefaultBrowser(_T("http://heeks.net/help/tool"));
}
<commit_msg>Fix crash while editing tools under 64 bits arch.<commit_after>// CToolDlg.cpp
// Copyright (c) 2014, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include "CToolDlg.h"
#include "interface/NiceTextCtrl.h"

enum
{
    ID_TITLE_TYPE = 100,
    ID_TOOL_TYPE,
    ID_MATERIAL,
    ID_DIRECTION,
};

BEGIN_EVENT_TABLE(CToolDlg, HeeksObjDlg)
    EVT_COMBOBOX(ID_TITLE_TYPE,CToolDlg::OnComboTitleType)
    EVT_COMBOBOX(ID_TOOL_TYPE, CToolDlg::OnComboToolType)
    EVT_COMBOBOX(ID_MATERIAL, CToolDlg::OnComboMaterial)
    EVT_TEXT(wxID_ANY,CToolDlg::OnTextCtrlEvent)
    EVT_BUTTON(wxID_HELP, CToolDlg::OnHelp)
END_EVENT_TABLE()

CToolDlg::CToolDlg(wxWindow *parent, CTool* object, const wxString& title, bool top_level)
             : HeeksObjDlg(parent, object, title, false)
{
	// add some of the controls to the right side
	rightControls.push_back(MakeLabelAndControl(_("Title"), m_txtTitle = new wxTextCtrl(this, wxID_ANY)));
	wxString title_choices[] = {_("Leave manually assigned title"), _("Automatically Generate Title")};
	rightControls.push_back(MakeLabelAndControl(_("Title Type"), m_cmbTitleType = new wxComboBox(this, ID_TITLE_TYPE, _T(""), wxDefaultPosition, wxDefaultSize, 2, title_choices)));

	// add all the controls to the left side
	leftControls.push_back(MakeLabelAndControl(_("Tool Number"), m_dlbToolNumber = new wxTextCtrl(this, wxID_ANY)));
	wxString materials[] = {_("High Speed Steel"),_("Carbide") };
	leftControls.push_back(MakeLabelAndControl(_("Tool Material"), m_cmbMaterial = new wxComboBox(this, ID_MATERIAL, _T(""), wxDefaultPosition, wxDefaultSize, 2, materials)));
	wxString tool_types[] = {_("Drill Bit"), _("Centre Drill Bit"), _("End Mill"), _("Slot Cutter"), _("Ball End Mill"), _("Chamfer"), _("Engraving Bit")};
	leftControls.push_back(MakeLabelAndControl(_("Tool Type"), m_cmbToolType = new wxComboBox(this, ID_TOOL_TYPE, _T(""), wxDefaultPosition, wxDefaultSize, sizeof(tool_types)/sizeof(wxString), tool_types)));
	leftControls.push_back(MakeLabelAndControl(_("Diameter"), m_dblDiameter = new CLengthCtrl(this)));
	leftControls.push_back(MakeLabelAndControl(_("Tool Length Offset"), m_dblToolLengthOffset = new CLengthCtrl(this)));
	leftControls.push_back(MakeLabelAndControl(_("Flat Radius"), m_dblFlatRadius = new CLengthCtrl(this)));
	leftControls.push_back(MakeLabelAndControl(_("Corner Radius"), m_dblCornerRadius = new CLengthCtrl(this)));
	leftControls.push_back(MakeLabelAndControl(_("Cutting Edge Angle"), m_dblCuttingEdgeAngle = new CDoubleCtrl(this)));
	leftControls.push_back(MakeLabelAndControl(_("Cutting Edge Height"), m_dblCuttingEdgeHeight = new CLengthCtrl(this)));

	if(top_level)
	{
		HeeksObjDlg::AddControlsAndCreate();
		m_dblDiameter->SetFocus();
	}
}

void CToolDlg::GetDataRaw(HeeksObj* object)
{
	long i = 0;
	m_dlbToolNumber->GetValue().ToLong(&i);
	((CTool*)object)->m_tool_number = i;
	((CTool*)object)->m_params.m_material = m_cmbMaterial->GetSelection();
	((CTool*)object)->m_params.m_type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());
	((CTool*)object)->m_params.m_diameter = m_dblDiameter->GetValue();
	((CTool*)object)->m_params.m_tool_length_offset = m_dblToolLengthOffset->GetValue();
	((CTool*)object)->m_params.m_flat_radius = m_dblFlatRadius->GetValue();
	((CTool*)object)->m_params.m_corner_radius = m_dblCornerRadius->GetValue();
	((CTool*)object)->m_params.m_cutting_edge_angle = m_dblCuttingEdgeAngle->GetValue();
	((CTool*)object)->m_params.m_cutting_edge_height = m_dblCuttingEdgeHeight->GetValue();
	((CTool*)object)->m_title = m_txtTitle->GetValue();
	((CTool*)object)->m_params.m_automatically_generate_title = (m_cmbTitleType->GetSelection() != 0);
}

void CToolDlg::SetFromDataRaw(HeeksObj* object)
{
	m_dlbToolNumber->SetValue(wxString::Format(_T("%d"), ((CTool*)object)->m_tool_number));
	m_txtTitle->SetValue(((CTool*)object)->m_title);
	m_cmbMaterial->SetSelection(((CTool*)object)->m_params.m_material);
	m_cmbToolType->SetSelection(((CTool*)object)->m_params.m_type);
	m_dblDiameter->SetValue(((CTool*)object)->m_params.m_diameter);
	m_dblToolLengthOffset->SetValue(((CTool*)object)->m_params.m_tool_length_offset);
	m_dblCuttingEdgeHeight->SetValue(((CTool*)object)->m_params.m_cutting_edge_height);
	m_txtTitle->SetValue(((CTool*)object)->m_title);
	m_cmbTitleType->SetSelection(((CTool*)object)->m_params.m_automatically_generate_title ? 1:0);

	EnableAndSetCornerFlatAndAngle(((CTool*)object)->m_params.m_type);
}

void CToolDlg::SetPicture(const wxString& name)
{
	HeeksObjDlg::SetPicture(name, _T("ctool"));
}

void CToolDlg::SetPictureByWindow(wxWindow* w)
{
	CToolParams::eToolType type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());

	switch(type)
	{
		case CToolParams::eDrill:
			if(w == m_dblDiameter)SetPicture(_T("drill_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("drill_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("drill_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("drill_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("drill_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("drill_height"));
			else SetPicture(_T("drill"));
			break;
		case CToolParams::eCentreDrill:
			if(w == m_dblDiameter)SetPicture(_T("centre_drill_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("centre_drill_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("centre_drill_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("centre_drill_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("centre_drill_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("centre_drill_height"));
			else SetPicture(_T("centre_drill"));
			break;
		case CToolParams::eEndmill:
		case CToolParams::eSlotCutter:
			if(w == m_dblDiameter)SetPicture(_T("end_mill_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("end_mill_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("end_mill_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("end_mill_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("end_mill_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("end_mill_height"));
			else SetPicture(_T("end_mill"));
			break;
		case CToolParams::eBallEndMill:
			if(w == m_dblDiameter)SetPicture(_T("ball_mill_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("ball_mill_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("ball_mill_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("ball_mill_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("ball_mill_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("ball_mill_height"));
			else SetPicture(_T("ball_mill"));
			break;
		case CToolParams::eChamfer:
			if(w == m_dblDiameter)SetPicture(_T("chamfer_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("chamfer_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("chamfer_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("chamfer_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("chamfer_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("chamfer_height"));
			else SetPicture(_T("chamfer"));
			break;
		case CToolParams::eEngravingTool:
			if(w == m_dblDiameter)SetPicture(_T("engraver_diameter"));
			else if(w == m_dblToolLengthOffset)SetPicture(_T("engraver_offset"));
			else if(w == m_dblFlatRadius)SetPicture(_T("engraver_flat"));
			else if(w == m_dblCornerRadius)SetPicture(_T("engraver_corner"));
			else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("engraver_angle"));
			else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("engraver_height"));
			else SetPicture(_T("engraver"));
			break;
		default:
			SetPicture(_T("undefined"));
			break;
	}
}

void CToolDlg::OnComboTitleType( wxCommandEvent& event )
{
	if(m_ignore_event_functions)return;
//	SetPicture();
}

void CToolDlg::OnComboMaterial( wxCommandEvent& event )
{
	if(m_ignore_event_functions)return;
//	//SetPicture();
}

void CToolDlg::OnTextCtrlEvent(wxCommandEvent& event)
{
	if(m_ignore_event_functions)return;

	// something's changed, recalculate the title
	CTool* object = (CTool*)(m_object->MakeACopy());
	GetData(object);
	m_ignore_event_functions = true;
	object->ResetTitle();
	m_txtTitle->SetValue(object->m_title);
	delete object;

	m_ignore_event_functions = false;
}

void CToolDlg::OnComboToolType(wxCommandEvent& event)
{
	if(m_ignore_event_functions)return;
	CToolParams::eToolType type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());
	EnableAndSetCornerFlatAndAngle(type);
	HeeksObjDlg::SetPicture();
}

void CToolDlg::EnableAndSetCornerFlatAndAngle(CToolParams::eToolType type)
{
	switch(type)
	{
		case CToolParams::eDrill:
		case CToolParams::eCentreDrill:
			m_dblCornerRadius->Enable(false);
			m_dblCornerRadius->SetLabel(_T(""));
			m_dblFlatRadius->Enable(false);
			m_dblFlatRadius->SetLabel(_T(""));
			m_dblCuttingEdgeAngle->Enable();
			m_dblCuttingEdgeAngle->SetValue(((CTool*)m_object)->m_params.m_cutting_edge_angle);
			break;
		case CToolParams::eEndmill:
		case CToolParams::eSlotCutter:
			m_dblCornerRadius->Enable();
			m_dblCornerRadius->SetValue(((CTool*)m_object)->m_params.m_corner_radius);
			m_dblFlatRadius->Enable(false);
			m_dblFlatRadius->SetLabel(_T(""));
			m_dblCuttingEdgeAngle->Enable(false);
			m_dblCuttingEdgeAngle->SetLabel(_T(""));
			break;
		case CToolParams::eBallEndMill:
			m_dblCornerRadius->Enable(false);
			m_dblCornerRadius->SetLabel(_T(""));
			m_dblFlatRadius->Enable(false);
			m_dblFlatRadius->SetLabel(_T(""));
			m_dblCuttingEdgeAngle->Enable(false);
			m_dblCuttingEdgeAngle->SetLabel(_T(""));
			break;
		case CToolParams::eChamfer:
		case CToolParams::eEngravingTool:
			m_dblCornerRadius->Enable(false);
			m_dblCornerRadius->SetLabel(_T(""));
			m_dblFlatRadius->Enable();
			m_dblFlatRadius->SetValue(((CTool*)m_object)->m_params.m_flat_radius);
			m_dblCuttingEdgeAngle->Enable();
			m_dblCuttingEdgeAngle->SetValue(((CTool*)m_object)->m_params.m_cutting_edge_angle);
			break;
		default:
			break;
	}
}

void CToolDlg::OnHelp( wxCommandEvent& event )
{
	::wxLaunchDefaultBrowser(_T("http://heeks.net/help/tool"));
}
<|endoftext|>


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

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

#include "taskpane/TitledControl.hxx"

#include "AccessibleTreeNode.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"

#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

namespace sd { namespace toolpanel {

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<TreeNode> pControl,
    const String& rTitle,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle(rTitle),
      mbVisible(true),
      mpUserData(NULL),
      mpControlFactory(NULL),
      mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
    if (pControl.get() != NULL)
    {
        mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
            new TitleBar (this, rTitle, eType, pControl->IsExpandable())));
        pControl->SetParentNode (this);
    }
    mpControlContainer->AddControl (pControl);

    FocusManager::Instance().RegisterDownLink(this, GetControl()->GetWindow());
    FocusManager::Instance().RegisterUpLink(GetControl()->GetWindow(), this);

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<ControlFactory> pControlFactory,
    const String& rTitle,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle (rTitle),
      mbVisible (true),
      mpUserData (NULL),
      mpControlFactory(pControlFactory),
      mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
    mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
        new TitleBar (this, rTitle, eType, true)));

    // The second control is created on demand, i.e. when GetControl(true)
    // is called the first time.

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::~TitledControl (void)
{
    GetTitleBar()->GetWindow()->RemoveEventListener (
        LINK(this,TitledControl,WindowEventListener));
}

Size TitledControl::GetPreferredSize (void)
{
    Size aPreferredSize;
    if (GetControl(false) != NULL)
    {
        aPreferredSize = GetControl()->GetPreferredSize();
        if ( ! IsExpanded())
            aPreferredSize.Height() = 0;
    }
    else
        aPreferredSize = Size (GetSizePixel().Width(), 0);
    if (aPreferredSize.Width() == 0)
        aPreferredSize.Width() = 300;
    aPreferredSize.Height() += GetTitleBar()->GetPreferredHeight(
        aPreferredSize.Width());

    return aPreferredSize;
}

sal_Int32 TitledControl::GetPreferredWidth (sal_Int32 nHeight)
{
    int nPreferredWidth = 0;
    if (GetControl(false) != NULL)
        nPreferredWidth = GetControl()->GetPreferredWidth(
            nHeight - GetTitleBar()->GetWindow()->GetSizePixel().Height());
    else
        nPreferredWidth = GetSizePixel().Width();
    if (nPreferredWidth == 0)
        nPreferredWidth = 300;

    return nPreferredWidth;
}

sal_Int32 TitledControl::GetPreferredHeight (sal_Int32 nWidth)
{
    int nPreferredHeight = 0;
    if (IsExpanded() && GetControl(false)!=NULL)
        nPreferredHeight = GetControl()->GetPreferredHeight(nWidth);
    nPreferredHeight += GetTitleBar()->GetPreferredHeight(nWidth);

    return nPreferredHeight;
}

bool TitledControl::IsResizable (void)
{
    return IsExpanded()
        && GetControl()->IsResizable();
}

::Window* TitledControl::GetWindow (void)
{
    return this;
}

void TitledControl::Resize (void)
{
    Size aWindowSize (GetOutputSizePixel());

    int nTitleBarHeight
        = GetTitleBar()->GetPreferredHeight(aWindowSize.Width());
    GetTitleBar()->GetWindow()->SetPosSizePixel (
        Point (0,0),
        Size (aWindowSize.Width(), nTitleBarHeight));

    TreeNode* pControl = GetControl(false);
    if (pControl != NULL
        && pControl->GetWindow() != NULL
        && pControl->GetWindow()->IsVisible())
    {
        pControl->GetWindow()->SetPosSizePixel (
            Point (0,nTitleBarHeight),
            Size (aWindowSize.Width(), aWindowSize.Height()-nTitleBarHeight));
    }
}

void TitledControl::GetFocus (void)
{
    ::Window::GetFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (true);
}

void TitledControl::LoseFocus (void)
{
    ::Window::LoseFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (false);
}

void TitledControl::KeyInput (const KeyEvent& rEvent)
{
    KeyCode nCode = rEvent.GetKeyCode();
    if (nCode == KEY_SPACE)
    {
        // Toggle the expansion state of the control (when toggling is
        // supported.)  The focus remains on this control.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_TOGGLE);
    }
    else if (nCode == KEY_RETURN)
    {
        // Return, also called enter, enters the control and puts the
        // focus to the first child.  If the control is not yet
        // expanded then do that first.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_EXPAND);

        if ( ! FocusManager::Instance().TransferFocus(this,nCode))
        {
            // When already expanded then put focus on first child.
            TreeNode* pControl = GetControl(false);
            if (pControl!=NULL && IsExpanded())
                if (pControl->GetWindow() != NULL)
                    pControl->GetWindow()->GrabFocus();
        }
    }
    else if (nCode == KEY_ESCAPE)
    {
        if ( ! FocusManager::Instance().TransferFocus(this,nCode))
            // Put focus to parent.
            GetParent()->GrabFocus();
    }
    else
        Window::KeyInput (rEvent);
}

const String& TitledControl::GetTitle (void) const
{
    return msTitle;
}

bool TitledControl::Expand (bool bExpanded)
{
    bool bExpansionStateChanged (false);

    if (IsExpandable())
    {
        if (GetTitleBar()->IsExpanded() != bExpanded)
            bExpansionStateChanged |= GetTitleBar()->Expand (bExpanded);
        // Get the control.  Use the bExpanded parameter as argument to
        // indicate that a control is created via its factory only when it
        // is to be expanded.  When it is collapsed this is not necessary.
        TreeNode* pControl = GetControl(bExpanded);
        if (pControl != NULL
            && GetControl()->IsExpanded() != bExpanded)
        {
            bExpansionStateChanged |= pControl->Expand (bExpanded);
        }
        if (bExpansionStateChanged)
            UpdateStates();
    }

    return bExpansionStateChanged;
}

bool TitledControl::IsExpandable (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpandable();
    else
        // When a control factory is given but the control has not yet been
        // created we assume that the control is expandable.
        return true;
}

bool TitledControl::IsExpanded (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpanded();
    else
        return false;
}

void TitledControl::SetUserData (void* pUserData)
{
    mpUserData = pUserData;
}

void* TitledControl::GetUserData (void) const
{
    return mpUserData;
}

bool TitledControl::IsShowing (void) const
{
    return mbVisible;
}

void TitledControl::Show (bool bVisible)
{
    if (mbVisible != bVisible)
    {
        mbVisible = bVisible;
        UpdateStates ();
    }
}

void TitledControl::UpdateStates (void)
{
    if (mbVisible)
        GetWindow()->Show();
    else
        GetWindow()->Hide();

    TreeNode* pControl = GetControl(false);
    if (pControl!=NULL  &&  pControl->GetWindow() != NULL)
        if (IsVisible() && IsExpanded())
            pControl->GetWindow()->Show();
        else
            pControl->GetWindow()->Hide();
}

IMPL_LINK(TitledControl, WindowEventListener,
    VclSimpleEvent*, pEvent)
{
    if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
    {
        VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
        switch (pWindowEvent->GetId())
        {
            case VCLEVENT_WINDOW_MOUSEBUTTONUP:
                // Toggle expansion.
                GetParentNode()->GetControlContainer().SetExpansionState (
                    this,
                    mbExpansionModeIsToggle ? ControlContainer::ES_TOGGLE
                                            : ControlContainer::ES_EXPAND);
                break;
        }
    }
    return 0;
}

TreeNode* TitledControl::GetControl (bool bCreate)
{
    TreeNode* pNode = mpControlContainer->GetControl(1);
    if (pNode==NULL && mpControlFactory.get()!=NULL && bCreate)
    {
        // We have to create the control with the factory object.
        ::std::auto_ptr<TreeNode> pControl (mpControlFactory->CreateControl(this));//GetParentNode()));
        if (pControl.get() != NULL)
        {
            pControl->SetParentNode(this);
            mpControlContainer->AddControl(pControl);

            pNode = mpControlContainer->GetControl(1);
            FocusManager::Instance().RegisterDownLink(this, pNode->GetWindow());
            FocusManager::Instance().RegisterUpLink(pNode->GetWindow(), this);
        }
    }

    return pNode;
}

const TreeNode* TitledControl::GetConstControl (bool bCreate) const
{
    return const_cast<TitledControl*>(this)->GetControl(bCreate);
}

TitleBar* TitledControl::GetTitleBar (void)
{
    return static_cast<TitleBar*>(mpControlContainer->GetControl(0));
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> TitledControl::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& )
{
    return new ::accessibility::AccessibleTreeNode(
        *this,
        GetTitle(),
        GetTitle(),
        ::com::sun::star::accessibility::AccessibleRole::LIST_ITEM);
}

} } // end of namespace ::sd::toolpanel
<commit_msg>INTEGRATION: CWS components1 (1.11.14); FILE MERGED 2007/01/25 15:24:19 af 1.11.14.2: RESYNC: (1.11-1.12); FILE MERGED 2007/01/24 17:51:21 af 1.11.14.1: #i68075# The click handler can now be supplied along with a control.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TitledControl.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 16:21:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "taskpane/TitledControl.hxx"

#include "AccessibleTreeNode.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"

#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

namespace sd { namespace toolpanel {

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<TreeNode> pControl,
    const String& rTitle,
    const ClickHandler& rClickHandler,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle(rTitle),
      mbVisible(true),
      mpUserData(NULL),
      mpControlFactory(NULL),
      mpClickHandler(new ClickHandler(rClickHandler)),
      mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
    if (pControl.get() != NULL)
    {
        mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
            new TitleBar (this, rTitle, eType, pControl->IsExpandable())));
        pControl->SetParentNode (this);
    }
    mpControlContainer->AddControl (pControl);

    FocusManager::Instance().RegisterDownLink(this, GetControl()->GetWindow());
    FocusManager::Instance().RegisterUpLink(GetControl()->GetWindow(), this);

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<ControlFactory> pControlFactory,
    const String& rTitle,
    const ClickHandler& rClickHandler,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle (rTitle),
      mbVisible (true),
      mpUserData (NULL),
      mpControlFactory(pControlFactory),
      mpClickHandler(new ClickHandler(rClickHandler)),
      mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
    mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
        new TitleBar (this, rTitle, eType, true)));

    // The second control is created on demand, i.e. when GetControl(true)
    // is called the first time.

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::~TitledControl (void)
{
    GetTitleBar()->GetWindow()->RemoveEventListener (
        LINK(this,TitledControl,WindowEventListener));
}

Size TitledControl::GetPreferredSize (void)
{
    Size aPreferredSize;
    if (GetControl(false) != NULL)
    {
        aPreferredSize = GetControl()->GetPreferredSize();
        if ( ! IsExpanded())
            aPreferredSize.Height() = 0;
    }
    else
        aPreferredSize = Size (GetSizePixel().Width(), 0);
    if (aPreferredSize.Width() == 0)
        aPreferredSize.Width() = 300;
    aPreferredSize.Height() += GetTitleBar()->GetPreferredHeight(
        aPreferredSize.Width());

    return aPreferredSize;
}

sal_Int32 TitledControl::GetPreferredWidth (sal_Int32 nHeight)
{
    int nPreferredWidth = 0;
    if (GetControl(false) != NULL)
        nPreferredWidth = GetControl()->GetPreferredWidth(
            nHeight - GetTitleBar()->GetWindow()->GetSizePixel().Height());
    else
        nPreferredWidth = GetSizePixel().Width();
    if (nPreferredWidth == 0)
        nPreferredWidth = 300;

    return nPreferredWidth;
}

sal_Int32 TitledControl::GetPreferredHeight (sal_Int32 nWidth)
{
    int nPreferredHeight = 0;
    if (IsExpanded() && GetControl(false)!=NULL)
        nPreferredHeight = GetControl()->GetPreferredHeight(nWidth);
    nPreferredHeight += GetTitleBar()->GetPreferredHeight(nWidth);

    return nPreferredHeight;
}

bool TitledControl::IsResizable (void)
{
    return IsExpanded()
        && GetControl()->IsResizable();
}

::Window* TitledControl::GetWindow (void)
{
    return this;
}

void TitledControl::Resize (void)
{
    Size aWindowSize (GetOutputSizePixel());

    int nTitleBarHeight
        = GetTitleBar()->GetPreferredHeight(aWindowSize.Width());
    GetTitleBar()->GetWindow()->SetPosSizePixel (
        Point (0,0),
        Size (aWindowSize.Width(), nTitleBarHeight));

    TreeNode* pControl = GetControl(false);
    if (pControl != NULL
        && pControl->GetWindow() != NULL
        && pControl->GetWindow()->IsVisible())
    {
        pControl->GetWindow()->SetPosSizePixel (
            Point (0,nTitleBarHeight),
            Size (aWindowSize.Width(), aWindowSize.Height()-nTitleBarHeight));
    }
}

void TitledControl::GetFocus (void)
{
    ::Window::GetFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (true);
}

void TitledControl::LoseFocus (void)
{
    ::Window::LoseFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (false);
}

void TitledControl::KeyInput (const KeyEvent& rEvent)
{
    KeyCode nCode = rEvent.GetKeyCode();
    if (nCode == KEY_SPACE)
    {
        // Toggle the expansion state of the control (when toggling is
        // supported.)  The focus remains on this control.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_TOGGLE);
    }
    else if (nCode == KEY_RETURN)
    {
        // Return, also called enter, enters the control and puts the
        // focus to the first child.  If the control is not yet
        // expanded then do that first.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_EXPAND);

        if ( ! FocusManager::Instance().TransferFocus(this,nCode))
        {
            // When already expanded then put focus on first child.
            TreeNode* pControl = GetControl(false);
            if (pControl!=NULL && IsExpanded())
                if (pControl->GetWindow() != NULL)
                    pControl->GetWindow()->GrabFocus();
        }
    }
    else if (nCode == KEY_ESCAPE)
    {
        if ( ! FocusManager::Instance().TransferFocus(this,nCode))
            // Put focus to parent.
            GetParent()->GrabFocus();
    }
    else
        Window::KeyInput (rEvent);
}

const String& TitledControl::GetTitle (void) const
{
    return msTitle;
}

bool TitledControl::Expand (bool bExpanded)
{
    bool bExpansionStateChanged (false);

    if (IsExpandable())
    {
        if (GetTitleBar()->IsExpanded() != bExpanded)
            bExpansionStateChanged |= GetTitleBar()->Expand (bExpanded);
        // Get the control.  Use the bExpanded parameter as argument to
        // indicate that a control is created via its factory only when it
        // is to be expanded.  When it is collapsed this is not necessary.
        TreeNode* pControl = GetControl(bExpanded);
        if (pControl != NULL
            && GetControl()->IsExpanded() != bExpanded)
        {
            bExpansionStateChanged |= pControl->Expand (bExpanded);
        }
        if (bExpansionStateChanged)
            UpdateStates();
    }

    return bExpansionStateChanged;
}

bool TitledControl::IsExpandable (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpandable();
    else
        // When a control factory is given but the control has not yet been
        // created we assume that the control is expandable.
        return true;
}

bool TitledControl::IsExpanded (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpanded();
    else
        return false;
}

void TitledControl::SetUserData (void* pUserData)
{
    mpUserData = pUserData;
}

void* TitledControl::GetUserData (void) const
{
    return mpUserData;
}

bool TitledControl::IsShowing (void) const
{
    return mbVisible;
}

void TitledControl::Show (bool bVisible)
{
    if (mbVisible != bVisible)
    {
        mbVisible = bVisible;
        UpdateStates ();
    }
}

void TitledControl::UpdateStates (void)
{
    if (mbVisible)
        GetWindow()->Show();
    else
        GetWindow()->Hide();

    TreeNode* pControl = GetControl(false);
    if (pControl!=NULL  &&  pControl->GetWindow() != NULL)
        if (IsVisible() && IsExpanded())
            pControl->GetWindow()->Show();
        else
            pControl->GetWindow()->Hide();
}

IMPL_LINK(TitledControl, WindowEventListener,
    VclSimpleEvent*, pEvent)
{
    if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
    {
        VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
        switch (pWindowEvent->GetId())
        {
            case VCLEVENT_WINDOW_MOUSEBUTTONUP:
                (*mpClickHandler)(*this);
                break;
        }
    }
    return 0;
}

TreeNode* TitledControl::GetControl (bool bCreate)
{
    TreeNode* pNode = mpControlContainer->GetControl(1);
    if (pNode==NULL && mpControlFactory.get()!=NULL && bCreate)
    {
        // We have to create the control with the factory object.
        ::std::auto_ptr<TreeNode> pControl (mpControlFactory->CreateControl(this));//GetParentNode()));
        if (pControl.get() != NULL)
        {
            pControl->SetParentNode(this);
            mpControlContainer->AddControl(pControl);

            pNode = mpControlContainer->GetControl(1);
            FocusManager::Instance().RegisterDownLink(this, pNode->GetWindow());
            FocusManager::Instance().RegisterUpLink(pNode->GetWindow(), this);
        }
    }

    return pNode;
}

const TreeNode* TitledControl::GetConstControl (bool bCreate) const
{
    return const_cast<TitledControl*>(this)->GetControl(bCreate);
}

TitleBar* TitledControl::GetTitleBar (void)
{
    return static_cast<TitleBar*>(mpControlContainer->GetControl(0));
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> TitledControl::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& )
{
    return new ::accessibility::AccessibleTreeNode(
        *this,
        GetTitle(),
        GetTitle(),
        ::com::sun::star::accessibility::AccessibleRole::LIST_ITEM);
}

//===== TitledControlStandardClickHandler =====================================

TitledControlStandardClickHandler::TitledControlStandardClickHandler (
    ControlContainer& rControlContainer,
    ControlContainer::ExpansionState eExpansionState)
    : mrControlContainer(rControlContainer),
      meExpansionState(eExpansionState)
{
}

void TitledControlStandardClickHandler::operator () (TitledControl& rTitledControl)
{
    // Toggle expansion.
    mrControlContainer.SetExpansionState (&rTitledControl, meExpansionState);
}

} } // end of namespace ::sd::toolpanel
<|endoftext|>


<commit_before>//
//  nif_cass_uuid.cpp
//  erlcass
//
//  Created by silviu on 6/2/15.
//
//

#include "nif_cass_uuid.h"
#include "erlcass.h"
#include "utils.h"

typedef struct
{
    CassUuidGen* gen;
}
EnifCassUuidGen;

ERL_NIF_TERM nif_cass_uuid_gen_new(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    cassandra_data* data = (cassandra_data*) enif_priv_data(env);

    EnifCassUuidGen *enif_gen = (EnifCassUuidGen*) enif_alloc_resource(data->resCassUuidGen, sizeof(EnifCassUuidGen));

    if(enif_gen == NULL)
        return make_error(env, "enif_alloc_resource failed");

    enif_gen->gen = cass_uuid_gen_new();

    ERL_NIF_TERM term = enif_make_resource(env, enif_gen);
    enif_release_resource(enif_gen);

    return enif_make_tuple2(env, ATOMS.atomOk, term);
}

void nif_cass_uuid_gen_free(ErlNifEnv* env, void* obj)
{
    EnifCassUuidGen *enif_gen = (EnifCassUuidGen*) obj;

    if(enif_gen->gen != NULL)
        cass_uuid_gen_free(enif_gen->gen);
}

ERL_NIF_TERM cass_uuid_to_nif(ErlNifEnv* env, const CassUuid& obj)
{
    char buffer[CASS_UUID_STRING_LENGTH];
    cass_uuid_string(obj, buffer);

    return enif_make_tuple2(env, ATOMS.atomOk, make_binary(env, buffer, CASS_UUID_STRING_LENGTH - 1));
}

ERL_NIF_TERM nif_cass_uuid_gen_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    cassandra_data* data = (cassandra_data*) enif_priv_data(env);

    EnifCassUuidGen * enif_gen = NULL;

    if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
        return enif_make_badarg(env);

    CassUuid obj;
    cass_uuid_gen_time(enif_gen->gen, &obj);
    return cass_uuid_to_nif(env, obj);
}

ERL_NIF_TERM nif_cass_uuid_gen_random(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    cassandra_data* data = (cassandra_data*) enif_priv_data(env);

    EnifCassUuidGen * enif_gen = NULL;

    if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
        return enif_make_badarg(env);

    CassUuid obj;
    cass_uuid_gen_random(enif_gen->gen, &obj);
    return cass_uuid_to_nif(env, obj);
}

ERL_NIF_TERM nif_cass_uuid_gen_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    cassandra_data* data = (cassandra_data*) enif_priv_data(env);

    EnifCassUuidGen * enif_gen = NULL;

    if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
        return enif_make_badarg(env);

    unsigned long timestamp;

    if(!enif_get_uint64(env, argv[1], &timestamp))
        return enif_make_badarg(env);

    CassUuid obj;
    cass_uuid_gen_from_time(enif_gen->gen, timestamp, &obj);
    return cass_uuid_to_nif(env, obj);
}

ERL_NIF_TERM nif_cass_uuid_min_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    unsigned long timestamp;

    if(!enif_get_uint64(env, argv[1], &timestamp))
        return enif_make_badarg(env);

    CassUuid obj;
    cass_uuid_min_from_time(timestamp, &obj);
    return cass_uuid_to_nif(env, obj);
}

ERL_NIF_TERM nif_cass_uuid_max_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    unsigned long timestamp;

    if(!enif_get_uint64(env, argv[1], &timestamp))
        return enif_make_badarg(env);

    CassUuid obj;
    cass_uuid_max_from_time(timestamp, &obj);
    return cass_uuid_to_nif(env, obj);
}

ERL_NIF_TERM nif_cass_uuid_timestamp(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    std::string str_value;

    if(!get_string(env, argv[1], str_value))
        return enif_make_badarg(env);

    CassUuid uuid;
    if(cass_uuid_from_string(str_value.c_str(), &uuid) != CASS_OK)
        return enif_make_badarg(env);

    return enif_make_tuple2(env, ATOMS.atomOk, enif_make_uint64(env, cass_uuid_timestamp(uuid)));
}

ERL_NIF_TERM nif_cass_uuid_version(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    std::string str_value;

    if(!get_string(env, argv[1], str_value))
        return enif_make_badarg(env);

    CassUuid uuid;
    if(cass_uuid_from_string(str_value.c_str(), &uuid) != CASS_OK)
        return enif_make_badarg(env);

    return enif_make_tuple2(env, ATOMS.atomOk, enif_make_int(env,cass_uuid_version(uuid)));
}

<commit_msg>Fix for uuid functions<commit_after>//
//  nif_cass_uuid.cpp
//  erlcass
//
//  Created by silviu on 6/2/15.
//
//

#include "nif_cass_uuid.h"
#include "erlcass.h"
#include "utils.h"

typedef struct
{
    CassUuidGen* gen;
}
EnifCassUuidGen;

ERL_NIF_TERM nif_cass_uuid_gen_new(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    cassandra_data* data = (cassandra_data*) enif_priv_data(env);

    EnifCassUuidGen *enif_gen = (EnifCassUuidGen*) enif_alloc_resource(data->resCassUuidGen, sizeof(EnifCassUuidGen));

    if(enif_gen == NULL)
        return make_error(env, "enif_alloc_resource failed");

    enif_gen->gen = cass_uuid_gen_new();

    ERL_NIF_TERM term = enif_make_resource(env, enif_gen);
    enif_release_resource(enif_gen);

    return enif_make_tuple2(env, ATOMS.atomOk, term);
}

void nif_cass_uuid_gen_free(ErlNifEnv* env, void* obj)
{
    EnifCassUuidGen *enif_gen = (EnifCassUuidGen*) obj;

    if(enif_gen->gen != NULL)
        cass_uuid_gen_free(enif_gen->gen);
}

ERL_NIF_TERM cass_uuid_to_nif(ErlNifEnv* env, const CassUuid& obj)
{
    char buffer[CASS_UUID_STRING_LENGTH];
    cass_uuid_string(obj, buffer);

    return enif_make_tuple2(env, ATOMS.atomOk, make_binary(env, buffer, CASS_UUID_STRING_LENGTH - 1));
}

ERL_NIF_TERM nif_cass_uuid_gen_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    cassandra_data* data = (cassandra_data*) enif_priv_data(env);

    EnifCassUuidGen * enif_gen = NULL;

    if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
        return enif_make_badarg(env);

    CassUuid obj;
    cass_uuid_gen_time(enif_gen->gen, &obj);
    return cass_uuid_to_nif(env, obj);
}

ERL_NIF_TERM nif_cass_uuid_gen_random(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    cassandra_data* data = (cassandra_data*) enif_priv_data(env);

    EnifCassUuidGen * enif_gen = NULL;

    if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
        return enif_make_badarg(env);

    CassUuid obj;
    cass_uuid_gen_random(enif_gen->gen, &obj);
    return cass_uuid_to_nif(env, obj);
}

ERL_NIF_TERM nif_cass_uuid_gen_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    cassandra_data* data = (cassandra_data*) enif_priv_data(env);

    EnifCassUuidGen * enif_gen = NULL;

    if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
        return enif_make_badarg(env);

    unsigned long timestamp;

    if(!enif_get_uint64(env, argv[1], &timestamp))
        return enif_make_badarg(env);

    CassUuid obj;
    cass_uuid_gen_from_time(enif_gen->gen, timestamp, &obj);
    return cass_uuid_to_nif(env, obj);
}

ERL_NIF_TERM nif_cass_uuid_min_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    unsigned long timestamp;

    if(!enif_get_uint64(env, argv[0], &timestamp))
        return enif_make_badarg(env);

    CassUuid obj;
    cass_uuid_min_from_time(timestamp, &obj);
    return cass_uuid_to_nif(env, obj);
}

ERL_NIF_TERM nif_cass_uuid_max_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    unsigned long timestamp;

    if(!enif_get_uint64(env, argv[0], &timestamp))
        return enif_make_badarg(env);

    CassUuid obj;
    cass_uuid_max_from_time(timestamp, &obj);
    return cass_uuid_to_nif(env, obj);
}

ERL_NIF_TERM nif_cass_uuid_timestamp(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    std::string str_value;

    if(!get_string(env, argv[0], str_value))
        return enif_make_badarg(env);

    CassUuid uuid;
    if(cass_uuid_from_string(str_value.c_str(), &uuid) != CASS_OK)
        return enif_make_badarg(env);

    return enif_make_tuple2(env, ATOMS.atomOk, enif_make_uint64(env, cass_uuid_timestamp(uuid)));
}

ERL_NIF_TERM nif_cass_uuid_version(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    std::string str_value;

    if(!get_string(env, argv[0], str_value))
        return enif_make_badarg(env);

    CassUuid uuid;
    if(cass_uuid_from_string(str_value.c_str(), &uuid) != CASS_OK)
        return enif_make_badarg(env);

    return enif_make_tuple2(env, ATOMS.atomOk, enif_make_int(env,cass_uuid_version(uuid)));
}

<|endoftext|>


<commit_before>#ifdef USE_SDL
#include <SDL.h>
#endif
#include "bitmap.h"
#include "events.h"
#include "exceptions/shutdown_exception.h"
#include "funcs.h"
#include "thread.h"

namespace Util{

EventManager::EventManager(){
}

#ifdef USE_SDL
void EventManager::runSDL(){
    SDL_Event event;
    while (SDL_PollEvent(&event) == 1){
        switch (event.type){
            case SDL_QUIT : {
                dispatch(CloseWindow);
                break;
            }
            case SDL_VIDEORESIZE : {
                dispatch(ResizeScreen, event.resize.w, event.resize.h);
                break;
            }
            default : {
                break;
            }
        }
    }
}
#endif

void EventManager::run(){
#ifdef USE_SDL
    runSDL();
#endif
}

/* kill the program if the user requests */
void EventManager::waitForThread(WaitThread & thread){
    while (!thread.isRunning()){
        try{
            run();
        } catch (const ShutdownException & death){
            thread.kill();
            throw death;
        }
        Util::rest(10);
    }
}

EventManager::~EventManager(){
}

void EventManager::dispatch(Event type, int arg1, int arg2){
    switch (type){
        case ResizeScreen : {
            Bitmap::setGraphicsMode(0, arg1, arg2);
            break;
        }
        default : break;
    }
}

void EventManager::dispatch(Event type){
    switch (type){
        case CloseWindow : {
            throw ShutdownException();
        }
        default : break;
    }
}

}
<commit_msg>enforce aspect ratios<commit_after>#ifdef USE_SDL
#include <SDL.h>
#endif
#include "bitmap.h"
#include "events.h"
#include "exceptions/shutdown_exception.h"
#include "funcs.h"
#include "thread.h"

namespace Util{

EventManager::EventManager(){
}

#ifdef USE_SDL
void EventManager::runSDL(){
    SDL_Event event;
    while (SDL_PollEvent(&event) == 1){
        switch (event.type){
            case SDL_QUIT : {
                dispatch(CloseWindow);
                break;
            }
            case SDL_VIDEORESIZE : {
                int width = event.resize.w;
                int height = event.resize.h;
                /* to keep the perspective correct
                 * 640/480 = 1.33333
                 */
                if (width > height){
                    height = (int)((double) width / 1.3333333333);
                } else {
                    width = (int)((double) height * 1.3333333333);
                }
                dispatch(ResizeScreen, width, height);
                break;
            }
            default : {
                break;
            }
        }
    }
}
#endif

void EventManager::run(){
#ifdef USE_SDL
    runSDL();
#endif
}

/* kill the program if the user requests */
void EventManager::waitForThread(WaitThread & thread){
    while (!thread.isRunning()){
        try{
            run();
        } catch (const ShutdownException & death){
            thread.kill();
            throw death;
        }
        Util::rest(10);
    }
}

EventManager::~EventManager(){
}

void EventManager::dispatch(Event type, int arg1, int arg2){
    switch (type){
        case ResizeScreen : {
            Bitmap::setGraphicsMode(0, arg1, arg2);
            break;
        }
        default : break;
    }
}

void EventManager::dispatch(Event type){
    switch (type){
        case CloseWindow : {
            throw ShutdownException();
        }
        default : break;
    }
}

}
<|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: statusbarcontroller.hxx,v $
 * $Revision: 1.2 $
 *
 * 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.
 *
 ************************************************************************/
#ifndef RPTUI_STATUSBARCONTROLLER_HXX
#define RPTUI_STATUSBARCONTROLLER_HXX

#include <svtools/statusbarcontroller.hxx>
#include <comphelper/uno3.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <cppuhelper/implbase1.hxx>
#include <comphelper/implementationreference.hxx>

class SfxStatusBarControl;
namespace rptui
{
    typedef ::comphelper::ImplementationReference<SfxStatusBarControl,::com::sun::star::frame::XStatusbarController> TStatusbarHelper;

    typedef ::cppu::ImplHelper1 <   ::com::sun::star::lang::XServiceInfo> OStatusbarController_BASE;
    class OStatusbarController : public ::svt::StatusbarController,
                                 public OStatusbarController_BASE
    {
        TStatusbarHelper m_pController;
        sal_uInt16       m_nSlotId;
        sal_uInt16       m_nId;
    public:
        OStatusbarController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);

        static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
            create(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext);

    private:
        void SAL_CALL OStatusbarController::dispose() throw (::com::sun::star::uno::RuntimeException);
        // XInterface
        DECLARE_XINTERFACE( )
        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
        // need by registration

        virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

        // XUpdatable
        virtual void SAL_CALL update() throw (::com::sun::star::uno::RuntimeException);

        // XStatusListener
        virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );

        // XStatusbarController
        virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos,
                                       ::sal_Int32 nCommand,
                                       ::sal_Bool bMouseEvent,
                                       const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics,
                                     const ::com::sun::star::awt::Rectangle& rOutputRectangle,
                                     ::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException);
    };
}
#endif // DBAUI_STATUSBARCONTROLLER_HXX

<commit_msg>#i10000# removed extra qualification<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: statusbarcontroller.hxx,v $
 * $Revision: 1.2 $
 *
 * 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.
 *
 ************************************************************************/
#ifndef RPTUI_STATUSBARCONTROLLER_HXX
#define RPTUI_STATUSBARCONTROLLER_HXX

#include <svtools/statusbarcontroller.hxx>
#include <comphelper/uno3.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <cppuhelper/implbase1.hxx>
#include <comphelper/implementationreference.hxx>

class SfxStatusBarControl;
namespace rptui
{
    typedef ::comphelper::ImplementationReference<SfxStatusBarControl,::com::sun::star::frame::XStatusbarController> TStatusbarHelper;

    typedef ::cppu::ImplHelper1 <   ::com::sun::star::lang::XServiceInfo> OStatusbarController_BASE;
    class OStatusbarController : public ::svt::StatusbarController,
                                 public OStatusbarController_BASE
    {
        TStatusbarHelper m_pController;
        sal_uInt16       m_nSlotId;
        sal_uInt16       m_nId;
    public:
        OStatusbarController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);

        static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
            create(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext);

    private:
        void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
        // XInterface
        DECLARE_XINTERFACE( )
        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
        // need by registration

        virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

        // XUpdatable
        virtual void SAL_CALL update() throw (::com::sun::star::uno::RuntimeException);

        // XStatusListener
        virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );

        // XStatusbarController
        virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos,
                                       ::sal_Int32 nCommand,
                                       ::sal_Bool bMouseEvent,
                                       const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics,
                                     const ::com::sun::star::awt::Rectangle& rOutputRectangle,
                                     ::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException);
    };
}
#endif // DBAUI_STATUSBARCONTROLLER_HXX

<|endoftext|>