<commit_before>// This file is intended to be included into an array of 'const char*'

#define STRING_CMP_FUNCS(op)                    \
  "(define (string"op"? s1 s2)"                 \
  "  ("op" (%string-strcmp s1 s2) 0))"
STRING_CMP_FUNCS("="),
STRING_CMP_FUNCS("<"),
STRING_CMP_FUNCS(">"),
STRING_CMP_FUNCS("<="),
STRING_CMP_FUNCS(">="),
#undef STRING_CMP_FUNCS

#define STRING_CI_CMP_FUNCS(op)                    \
  "(define (string-ci"op"? s1 s2)"                 \
  "  ("op" (%string-strcasecmp s1 s2) 0))"
STRING_CI_CMP_FUNCS("="),
STRING_CI_CMP_FUNCS("<"),
STRING_CI_CMP_FUNCS(">"),
STRING_CI_CMP_FUNCS("<="),
STRING_CI_CMP_FUNCS(">="),
#undef STRING_CI_CMP_FUNCS

"(define (substring str start end)"
"  (let* ((size (- end start))"
"         (str2 (make-string size)))"
"    (do ((i 0 (+ i 1)))"
"        ((= i size) str2)"
"      (string-set! str2 i (string-ref str (+ i start))))))",

"(define (string-copy str)"
"  (let* ((size (string-length str))"
"         (str2 (make-string size)))"
"    (do ((i 0 (+ i 1)))"
"        ((= i size) str2)"
"      (string-set! str2 i (string-ref str i)))))",

"(define (string-fill! str fill)"
"  (let ((size (string-length str)))"
"    (do ((i 0 (+ i 1)))"
"        ((= i size) str)"
"      (string-set! str i fill))))",
<commit_msg>cleanup string-copy<commit_after>// This file is intended to be included into an array of 'const char*'

#define STRING_CMP_FUNCS(op)                    \
  "(define (string"op"? s1 s2)"                 \
  "  ("op" (%string-strcmp s1 s2) 0))"
STRING_CMP_FUNCS("="),
STRING_CMP_FUNCS("<"),
STRING_CMP_FUNCS(">"),
STRING_CMP_FUNCS("<="),
STRING_CMP_FUNCS(">="),
#undef STRING_CMP_FUNCS

#define STRING_CI_CMP_FUNCS(op)                    \
  "(define (string-ci"op"? s1 s2)"                 \
  "  ("op" (%string-strcasecmp s1 s2) 0))"
STRING_CI_CMP_FUNCS("="),
STRING_CI_CMP_FUNCS("<"),
STRING_CI_CMP_FUNCS(">"),
STRING_CI_CMP_FUNCS("<="),
STRING_CI_CMP_FUNCS(">="),
#undef STRING_CI_CMP_FUNCS

"(define (substring str start end)"
"  (let* ((size (- end start))"
"         (str2 (make-string size)))"
"    (do ((i 0 (+ i 1)))"
"        ((= i size) str2)"
"      (string-set! str2 i (string-ref str (+ i start))))))",

"(define (string-copy str)"
"  (substring str 0 (string-length str)))",

"(define (string-fill! str fill)"
"  (let ((size (string-length str)))"
"    (do ((i 0 (+ i 1)))"
"        ((= i size) str)"
"      (string-set! str i fill))))",
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "CursesMenu.h"
#include "StateDatabase.h"
#include "TextUtils.h"

CursesMenuItem::CursesMenuItem(const std::string& str) : text(str) {

}

CursesMenuItem::~CursesMenuItem() {

}

void CursesMenuItem::showItem(WINDOW* menuWin, int line, int col, int width,
			      bool selected) {
  /* just print the text of the item centered between col and col+width
     if this item is selected, use reverse video */
  wmove(menuWin, line, col);
  if (selected)
    wattron(menuWin, A_REVERSE);
  for (unsigned int i = 0; i < (width - text.size()) / 2; ++i)
    waddstr(menuWin, " ");
  waddstr(menuWin, text.c_str());
  for (int i = (width - text.size()) /2 + text.size(); i < width; ++i)
    waddstr(menuWin, " ");
  if (selected)
    wattroff(menuWin, A_REVERSE);
}

bool CursesMenuItem::handleKey(int, std::string&, CursesMenu&) {
  return false;
}

void CursesMenuItem::deselect() {

}

SubmenuCMItem::SubmenuCMItem(const std::string& str, MenuCallback callback)
  : CursesMenuItem(str), cb(callback) {

}

bool SubmenuCMItem::handleKey(int c, std::string&, CursesMenu& menu) {
  // different key codes for the enter key
  if (c == '\n' || c == 13) {
    menu.setUpdateCallback(cb);
    menu.forceUpdate();
  }
  return false;
}

CallbackCMItem::CallbackCMItem(const std::string& str, MenuCallback callback)
  : CursesMenuItem(str), cb(callback) {

}

bool CallbackCMItem::handleKey(int c, std::string&, CursesMenu& menu) {
  // different key codes for the enter key
  if (c == '\n' || c == 13) {
    cb(menu);
  }
  return false;
}

CommandCMItem::CommandCMItem(const std::string& str, const std::string& cmd,
			     bool update)
  : CursesMenuItem(str), command(cmd), forceUpdate(update) {

}

bool CommandCMItem::handleKey(int c, std::string& str, CursesMenu& menu) {
  // different key codes for the enter key
  if (c == '\n' || c == 13) {
    str = command;
    if (forceUpdate)
      menu.forceUpdate();
    return true;
  }
  return false;
}

BoolCMItem::BoolCMItem(std::string name, bool& variable,  std::string trueText,
			  std::string falseText)
  : CursesMenuItem(name), varRef(variable), trueTxt(trueText),
    falseTxt(falseText) {

}

void BoolCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
			  bool selected) {
  /* print the name of the variable to the left of the center and the
     value to the right, use reverse video if it is selected */
  wmove(menuWin, line, col);
  if (selected)
    wattron(menuWin, A_REVERSE);
  for (unsigned int i = 0; i < width / 2 - text.size() - 1; ++i)
    waddstr(menuWin, " ");
  waddstr(menuWin, text.c_str());
  wmove(menuWin, line, col + width / 2 + 1);
  std::string& value = (varRef ? trueTxt : falseTxt);
  waddstr(menuWin, value.c_str());
  for (int i = width / 2 + 1 + value.size(); i < width; ++i)
    waddstr(menuWin, " ");
  if (selected)
    wattroff(menuWin, A_REVERSE);
}

bool BoolCMItem::handleKey(int c, std::string&, CursesMenu&) {
  if (c == ' ')
    varRef = !varRef;
  return false;
}

BZDBCMItem::BZDBCMItem(const std::string& variable)
  : CursesMenuItem(variable), editing(false) {

}

void BZDBCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
			  bool selected) {
  /* print the name of the variable to the left of the center and the
     value to the right, use reverse video if it is selected, but don't use
     reverse video for the value if we're editing it */
  wmove(menuWin, line, col);
  if (selected)
    wattron(menuWin, A_REVERSE);
  for (unsigned int i = 0; i < width / 2 - text.size() - 1; ++i)
    waddstr(menuWin, " ");
  waddstr(menuWin, text.c_str());
  wmove(menuWin, line, col + width / 2 + 1);
  std::string value = BZDB.get(text);
  if (editing) {
    wattroff(menuWin, A_REVERSE);
    waddstr(menuWin, editString.c_str());
    waddstr(menuWin, "_");
  }
  else
    waddstr(menuWin, value.c_str());
  for (int i = width / 2 + 1 + value.size(); i < width; ++i)
    waddstr(menuWin, " ");
  if (selected && !editing)
    wattroff(menuWin, A_REVERSE);
}

bool BZDBCMItem::handleKey(int c, std::string& str, CursesMenu&) {
  // if we're not editing, start if we get a return key
  if (!editing && (c == '\n' || c == 13)) {
    editing = true;
    editString = BZDB.get(text);
    return false;
  }

  // OK, we're editing
  switch (c) {

    // different codes for the return key - stop and send a /set command
  case '\n':
  case 13:
    editing = false;
    str = "/set ";
    str += text + " \"" + editString + "\"";
    return true;

    // ESC - stop editing, don't touch the BZDB value
  case 27:
    editing = false;
    break;

    // backspace/delete - delete the last character
  case KEY_BACKSPACE:
  case KEY_DC:
  case 127:
    editString = (editString.size() > 0 ?
		  editString.substr(0, editString.size() - 1) : editString);
    break;

    // valid characters - edit the string
  default:
    if (c < 32 || c > 127 || editString.size() > 30)
      return false;
    editString += char(c);
    break;
  }

  return false;
}

void BZDBCMItem::deselect() {
  editing = false;
}

PlayerCMItem::PlayerCMItem(const PlayerIdMap& players, PlayerId playerId)
  : CursesMenuItem(), playerMap(players), id(playerId) {

}

void PlayerCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
			    bool selected) {
  // score (wins-losses)[tks] callsign IP, reverse video if selected
  std::string name, ip;
  int wins, losses, tks;
  PlayerIdMap::const_iterator iter = playerMap.find(id);
  if (iter != playerMap.end()) {
    name = iter->second.name;
    ip = iter->second.ip;
    wins = iter->second.wins;
    losses = iter->second.losses;
    tks = iter->second.tks;
    std::ostringstream oss;
    oss<<(wins - losses)<<" ("<<wins<<"-"<<losses<<")["<<tks<<"]";
    unsigned int scoreLength = oss.str().size();
    for (unsigned int i = 0; i < 21 - scoreLength; ++i)
      oss<<' ';
    oss<<name;
    for (unsigned int i = 0; i < CallSignLen + 1 - name.size(); ++i)
      oss<<' ';
    oss<<ip;
    for (unsigned int i = 0; i < 15 - ip.size(); ++i)
      oss<<' ';
    if (selected)
      wattron(menuWin, A_REVERSE);
    wmove(menuWin, line, col);
    waddstr(menuWin, oss.str().substr(0, width).c_str());
    if (selected)
      wattroff(menuWin, A_REVERSE);
  }
}

CursesMenu::CursesMenu(const PlayerIdMap& p)
  : players(p), dirty(true) {

}

CursesMenu::~CursesMenu() {
  clear();
}

void CursesMenu::setHeader(const std::string& newHeader) {
  header = newHeader;
}

void CursesMenu::addItem(CursesMenuItem* item) {
  items.push_back(item);
}

void CursesMenu::clear() {
  for (unsigned int i = 0; i < items.size(); ++i)
    delete items[i];
  items.clear();
  selection = 0;
}

void CursesMenu::showMenu() {
  if (window == NULL)
    return;
  werase(window);

  // update the menu if needed
  rebuild();

  // get the window size
  int x1, x2, y1, y2, w, h;
  getbegyx(window, y1, x1);
  getmaxyx(window, y2, x2);
  w = x2 - x1;
  h = y2 - y1;

  wmove(window, 0, w / 2 - header.size() / 2);
  waddstr(window, header.c_str());

  // this magic should scroll the menu so that the selected menu item
  // always is visible
  int start = selection - (h / 2 - 2);
  start = (start + (h - 3) > (signed)items.size() ?
	   items.size() - (h - 3) : start);
  start = (start < 0 ? 0 : start);
  int end = start + (h - 3);
  end = ((unsigned)end > items.size() ? items.size() : end);

  // show the menu items
  for (int i = start; i < end; ++i)
    items[i]->showItem(window, 2 + (i - start), 10, w - 20, i == selection);

  // draw a line at the bottom of the menu window
  wmove(window, h - 1, 0);
  wattron(window, A_UNDERLINE);
  for (int i = 0; i < COLS; ++i)
    waddstr(window, " ");
  wattroff(window, A_UNDERLINE);

  wrefresh(window);
}

bool CursesMenu::handleKey(int c, std::string& str) {
  bool result = false;
  str = "";
  switch (c) {
  case KEY_UP:
    items[selection]->deselect();
    selection = (selection == 0 ? items.size() - 1 : selection - 1);
    break;
  case KEY_DOWN:
    items[selection]->deselect();
    selection = ((unsigned)selection == items.size() - 1 ? 0 : selection + 1);
    break;
  default:
    result = items[selection]->handleKey(c, str, *this);
  }
  showMenu();
  return result;
}

void CursesMenu::setWindow(WINDOW* win) {
  window = win;
}

void CursesMenu::setUpdateCallback(MenuCallback cb) {
  rebuilder = cb;
}

void CursesMenu::forceUpdate() {
  dirty = true;
}

void CursesMenu::rebuild() {
  if (dirty) {
    dirty = false;
    rebuilder(*this);
  }
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Clean up the playerlist output in the curses menu<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "CursesMenu.h"
#include "StateDatabase.h"
#include "TextUtils.h"

CursesMenuItem::CursesMenuItem(const std::string& str) : text(str) {

}

CursesMenuItem::~CursesMenuItem() {

}

void CursesMenuItem::showItem(WINDOW* menuWin, int line, int col, int width,
			      bool selected) {
  /* just print the text of the item centered between col and col+width
     if this item is selected, use reverse video */
  wmove(menuWin, line, col);
  if (selected)
    wattron(menuWin, A_REVERSE);
  for (unsigned int i = 0; i < (width - text.size()) / 2; ++i)
    waddstr(menuWin, " ");
  waddstr(menuWin, text.c_str());
  for (int i = (width - text.size()) /2 + text.size(); i < width; ++i)
    waddstr(menuWin, " ");
  if (selected)
    wattroff(menuWin, A_REVERSE);
}

bool CursesMenuItem::handleKey(int, std::string&, CursesMenu&) {
  return false;
}

void CursesMenuItem::deselect() {

}

SubmenuCMItem::SubmenuCMItem(const std::string& str, MenuCallback callback)
  : CursesMenuItem(str), cb(callback) {

}

bool SubmenuCMItem::handleKey(int c, std::string&, CursesMenu& menu) {
  // different key codes for the enter key
  if (c == '\n' || c == 13) {
    menu.setUpdateCallback(cb);
    menu.forceUpdate();
  }
  return false;
}

CallbackCMItem::CallbackCMItem(const std::string& str, MenuCallback callback)
  : CursesMenuItem(str), cb(callback) {

}

bool CallbackCMItem::handleKey(int c, std::string&, CursesMenu& menu) {
  // different key codes for the enter key
  if (c == '\n' || c == 13) {
    cb(menu);
  }
  return false;
}

CommandCMItem::CommandCMItem(const std::string& str, const std::string& cmd,
			     bool update)
  : CursesMenuItem(str), command(cmd), forceUpdate(update) {

}

bool CommandCMItem::handleKey(int c, std::string& str, CursesMenu& menu) {
  // different key codes for the enter key
  if (c == '\n' || c == 13) {
    str = command;
    if (forceUpdate)
      menu.forceUpdate();
    return true;
  }
  return false;
}

BoolCMItem::BoolCMItem(std::string name, bool& variable,  std::string trueText,
			  std::string falseText)
  : CursesMenuItem(name), varRef(variable), trueTxt(trueText),
    falseTxt(falseText) {

}

void BoolCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
			  bool selected) {
  /* print the name of the variable to the left of the center and the
     value to the right, use reverse video if it is selected */
  wmove(menuWin, line, col);
  if (selected)
    wattron(menuWin, A_REVERSE);
  for (unsigned int i = 0; i < width / 2 - text.size() - 1; ++i)
    waddstr(menuWin, " ");
  waddstr(menuWin, text.c_str());
  wmove(menuWin, line, col + width / 2 + 1);
  std::string& value = (varRef ? trueTxt : falseTxt);
  waddstr(menuWin, value.c_str());
  for (int i = width / 2 + 1 + value.size(); i < width; ++i)
    waddstr(menuWin, " ");
  if (selected)
    wattroff(menuWin, A_REVERSE);
}

bool BoolCMItem::handleKey(int c, std::string&, CursesMenu&) {
  if (c == ' ')
    varRef = !varRef;
  return false;
}

BZDBCMItem::BZDBCMItem(const std::string& variable)
  : CursesMenuItem(variable), editing(false) {

}

void BZDBCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
			  bool selected) {
  /* print the name of the variable to the left of the center and the
     value to the right, use reverse video if it is selected, but don't use
     reverse video for the value if we're editing it */
  wmove(menuWin, line, col);
  if (selected)
    wattron(menuWin, A_REVERSE);
  for (unsigned int i = 0; i < width / 2 - text.size() - 1; ++i)
    waddstr(menuWin, " ");
  waddstr(menuWin, text.c_str());
  wmove(menuWin, line, col + width / 2 + 1);
  std::string value = BZDB.get(text);
  if (editing) {
    wattroff(menuWin, A_REVERSE);
    waddstr(menuWin, editString.c_str());
    waddstr(menuWin, "_");
  }
  else
    waddstr(menuWin, value.c_str());
  for (int i = width / 2 + 1 + value.size(); i < width; ++i)
    waddstr(menuWin, " ");
  if (selected && !editing)
    wattroff(menuWin, A_REVERSE);
}

bool BZDBCMItem::handleKey(int c, std::string& str, CursesMenu&) {
  // if we're not editing, start if we get a return key
  if (!editing && (c == '\n' || c == 13)) {
    editing = true;
    editString = BZDB.get(text);
    return false;
  }

  // OK, we're editing
  switch (c) {

    // different codes for the return key - stop and send a /set command
  case '\n':
  case 13:
    editing = false;
    str = "/set ";
    str += text + " \"" + editString + "\"";
    return true;

    // ESC - stop editing, don't touch the BZDB value
  case 27:
    editing = false;
    break;

    // backspace/delete - delete the last character
  case KEY_BACKSPACE:
  case KEY_DC:
  case 127:
    editString = (editString.size() > 0 ?
		  editString.substr(0, editString.size() - 1) : editString);
    break;

    // valid characters - edit the string
  default:
    if (c < 32 || c > 127 || editString.size() > 30)
      return false;
    editString += char(c);
    break;
  }

  return false;
}

void BZDBCMItem::deselect() {
  editing = false;
}

PlayerCMItem::PlayerCMItem(const PlayerIdMap& players, PlayerId playerId)
  : CursesMenuItem(), playerMap(players), id(playerId) {

}

void PlayerCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
			    bool selected) {
  // score (wins-losses)[tks] callsign IP, reverse video if selected
  std::string name, ip;
  int wins, losses, tks;
  int scorePad = 17;
  int callsignPad = CallSignLen;
  PlayerIdMap::const_iterator iter = playerMap.find(id);
  if (iter != playerMap.end()) {
    name = iter->second.name;
    ip = iter->second.ip;
    wins = iter->second.wins;
    losses = iter->second.losses;
    tks = iter->second.tks;
    std::ostringstream oss;
    oss<<(wins - losses)<<" ("<<wins<<"-"<<losses<<")["<<tks<<"]";
    unsigned int streamLength = oss.str().size();
    for (unsigned int i = 0; i < scorePad - streamLength; ++i)
      oss<<' ';
    oss<<' '<<name;
    for (unsigned int i = 0; i < callsignPad - name.size(); ++i)
      oss<<' ';
    streamLength = oss.str().size();
    if (selected)
      wattron(menuWin, A_REVERSE);
    wmove(menuWin, line, col);
    waddstr(menuWin,
	    (oss.str().substr(0, width - ip.size() - 1) + " ").c_str());
    waddstr(menuWin, ip.c_str());
    if (selected)
      wattroff(menuWin, A_REVERSE);
  }
}

CursesMenu::CursesMenu(const PlayerIdMap& p)
  : players(p), dirty(true) {

}

CursesMenu::~CursesMenu() {
  clear();
}

void CursesMenu::setHeader(const std::string& newHeader) {
  header = newHeader;
}

void CursesMenu::addItem(CursesMenuItem* item) {
  items.push_back(item);
}

void CursesMenu::clear() {
  for (unsigned int i = 0; i < items.size(); ++i)
    delete items[i];
  items.clear();
  selection = 0;
}

void CursesMenu::showMenu() {
  if (window == NULL)
    return;
  werase(window);

  // update the menu if needed
  rebuild();

  // get the window size
  int x1, x2, y1, y2, w, h;
  getbegyx(window, y1, x1);
  getmaxyx(window, y2, x2);
  w = x2 - x1;
  h = y2 - y1;

  wmove(window, 0, w / 2 - header.size() / 2);
  waddstr(window, header.c_str());

  // this magic should scroll the menu so that the selected menu item
  // always is visible
  int start = selection - (h / 2 - 2);
  start = (start + (h - 3) > (signed)items.size() ?
	   items.size() - (h - 3) : start);
  start = (start < 0 ? 0 : start);
  int end = start + (h - 3);
  end = ((unsigned)end > items.size() ? items.size() : end);

  // show the menu items
  for (int i = start; i < end; ++i)
    items[i]->showItem(window, 2 + (i - start), 10, w - 20, i == selection);

  // draw a line at the bottom of the menu window
  wmove(window, h - 1, 0);
  wattron(window, A_UNDERLINE);
  for (int i = 0; i < COLS; ++i)
    waddstr(window, " ");
  wattroff(window, A_UNDERLINE);

  wrefresh(window);
}

bool CursesMenu::handleKey(int c, std::string& str) {
  bool result = false;
  str = "";
  switch (c) {
  case KEY_UP:
    items[selection]->deselect();
    selection = (selection == 0 ? items.size() - 1 : selection - 1);
    break;
  case KEY_DOWN:
    items[selection]->deselect();
    selection = ((unsigned)selection == items.size() - 1 ? 0 : selection + 1);
    break;
  default:
    result = items[selection]->handleKey(c, str, *this);
  }
  showMenu();
  return result;
}

void CursesMenu::setWindow(WINDOW* win) {
  window = win;
}

void CursesMenu::setUpdateCallback(MenuCallback cb) {
  rebuilder = cb;
}

void CursesMenu::forceUpdate() {
  dirty = true;
}

void CursesMenu::rebuild() {
  if (dirty) {
    dirty = false;
    rebuilder(*this);
  }
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/**************************************************************************/
/*!
    @file     Adafruit_MCP9808.cpp
    @author   K.Townsend (Adafruit Industries)
	@license  BSD (see license.txt)

	I2C Driver for Microchip's MCP9808 I2C Temp sensor

	This is a library for the Adafruit MCP9808 breakout
	----> http://www.adafruit.com/products/1782

	Adafruit invests time and resources providing this open source code,
	please support Adafruit and open-source hardware by purchasing
	products from Adafruit!

	@section  HISTORY

    v1.0 - First release
*/
/**************************************************************************/
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

#ifdef __AVR_ATtiny85__
 #include "TinyWireM.h"
 #define Wire TinyWireM
#else
 #include <Wire.h>
#endif

#include "Adafruit_MCP9808.h"

/**************************************************************************/
/*!
    @brief  Instantiates a new MCP9808 class
*/
/**************************************************************************/
Adafruit_MCP9808::Adafruit_MCP9808() {
}

/**************************************************************************/
/*!
    @brief  Setups the HW
*/
/**************************************************************************/
boolean Adafruit_MCP9808::begin(uint8_t addr) {
  _i2caddr = addr;
  Wire.begin();

  if (read16(MCP9808_REG_MANUF_ID) != 0x0054) return false;
  if (read16(MCP9808_REG_DEVICE_ID) != 0x0400) return false;

  return true;
}

/**************************************************************************/
/*!
    @brief  Reads the 16-bit temperature register and returns the Centigrade
            temperature as a float.

*/
/**************************************************************************/
float Adafruit_MCP9808::readTempC( void )
{
  uint16_t t = read16(MCP9808_REG_AMBIENT_TEMP);

  float temp = t & 0x0FFF;
  temp /=  16.0;
  if (t & 0x1000) temp -= 256;

  return temp;
}

/**************************************************************************/
/*!
    @brief  Low level 16 bit read and write procedures!
*/
/**************************************************************************/

void Adafruit_MCP9808::write16(uint8_t reg, uint16_t value) {
    Wire.beginTransmission(_i2caddr);
    Wire.write((uint8_t)reg);
    Wire.write(value >> 8);
    Wire.write(value & 0xFF);
    Wire.endTransmission();
}

uint16_t Adafruit_MCP9808::read16(uint8_t reg) {
  uint16_t val;

  Wire.beginTransmission(_i2caddr);
  Wire.write((uint8_t)reg);
  Wire.endTransmission();

  Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
  val = Wire.read();
  val <<= 8;
  val |= Wire.read();
  return val;
}
<commit_msg>Added attribute to Adafruit_MCP9808 initializer list, added implementation for Adafruit_MCP9808::readTempF() method.<commit_after>/**************************************************************************/
/*!
    @file     Adafruit_MCP9808.cpp
    @author   K.Townsend (Adafruit Industries)
	@license  BSD (see license.txt)

	I2C Driver for Microchip's MCP9808 I2C Temp sensor

	This is a library for the Adafruit MCP9808 breakout
	----> http://www.adafruit.com/products/1782

	Adafruit invests time and resources providing this open source code,
	please support Adafruit and open-source hardware by purchasing
	products from Adafruit!

	@section  HISTORY

    v1.0 - First release
*/
/**************************************************************************/
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

#ifdef __AVR_ATtiny85__
 #include "TinyWireM.h"
 #define Wire TinyWireM
#else
 #include <Wire.h>
#endif

#include "Adafruit_MCP9808.h"

/**************************************************************************/
/*!
    @brief  Instantiates a new MCP9808 class
*/
/**************************************************************************/
Adafruit_MCP9808::Adafruit_MCP9808()
: _i2caddr(0)
{ }

/**************************************************************************/
/*!
    @brief  Setups the HW
*/
/**************************************************************************/
boolean Adafruit_MCP9808::begin(uint8_t addr) {
  _i2caddr = addr;
  Wire.begin();

  if (read16(MCP9808_REG_MANUF_ID) != 0x0054) return false;
  if (read16(MCP9808_REG_DEVICE_ID) != 0x0400) return false;

  return true;
}

/**************************************************************************/
/*!
    @brief  Reads the 16-bit temperature register and returns the Fahrenheit
            temperature as a float.

*/
/**************************************************************************/
float Adafruit_MCP9808::readTempF( void )
{
  uint16_t t = read16(MCP9808_REG_AMBIENT_TEMP);

  float temp = t & 0x0FFF;
  temp /=  16.0;
  if (t & 0x1000) temp -= 256;

  temp = temp * 9.0 / 5.0 + 32;

  return temp;
}

/**************************************************************************/
/*!
    @brief  Reads the 16-bit temperature register and returns the Centigrade
            temperature as a float.

*/
/**************************************************************************/
float Adafruit_MCP9808::readTempC( void )
{
  uint16_t t = read16(MCP9808_REG_AMBIENT_TEMP);

  float temp = t & 0x0FFF;
  temp /=  16.0;
  if (t & 0x1000) temp -= 256;

  return temp;
}

/**************************************************************************/
/*!
    @brief  Low level 16 bit read and write procedures!
*/
/**************************************************************************/

void Adafruit_MCP9808::write16(uint8_t reg, uint16_t value) {
    Wire.beginTransmission(_i2caddr);
    Wire.write((uint8_t)reg);
    Wire.write(value >> 8);
    Wire.write(value & 0xFF);
    Wire.endTransmission();
}

uint16_t Adafruit_MCP9808::read16(uint8_t reg) {
  uint16_t val;

  Wire.beginTransmission(_i2caddr);
  Wire.write((uint8_t)reg);
  Wire.endTransmission();

  Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
  val = Wire.read();
  val <<= 8;
  val |= Wire.read();
  return val;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ListBox.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-04-02 10:54:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FORMS_LISTBOX_HXX_
#define _FORMS_LISTBOX_HXX_

#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif

#ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_
#include <com/sun/star/util/XRefreshable.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLERRORBROADCASTER_HPP_
#include <com/sun/star/sdb/XSQLErrorBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_LISTSOURCETYPE_HPP_
#include <com/sun/star/form/ListSourceType.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XITEMLISTENER_HPP_
#include <com/sun/star/awt/XItemListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_
#include <com/sun/star/awt/XFocusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XCHANGEBROADCASTER_HPP_
#include <com/sun/star/form/XChangeBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYSINK_HDL_
#include <com/sun/star/form/binding/XListEntrySink.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYLISTENER_HDL_
#include <com/sun/star/form/binding/XListEntryListener.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef FORMS_ERRORBROADCASTER_HXX
#include "errorbroadcaster.hxx"
#endif
#ifndef FORMS_ENTRYLISTHELPER_HXX
#include "entrylisthelper.hxx"
#endif

//.........................................................................
namespace frm
{

//==================================================================
//= OListBoxModel
//==================================================================
typedef ::cppu::ImplHelper1 <   ::com::sun::star::util::XRefreshable
                            >   OListBoxModel_BASE;

class OListBoxModel :public OBoundControlModel
                    ,public OListBoxModel_BASE
                    ,public OEntryListHelper
                    ,public OErrorBroadcaster
                    ,public ::comphelper::OAggregationArrayUsageHelper< OListBoxModel >
{
    ::com::sun::star::uno::Any                  m_aSaveValue;

    // <properties>
    ::com::sun::star::form::ListSourceType      m_eListSourceType;      // type der list source
    ::com::sun::star::uno::Any                  m_aBoundColumn;
    StringSequence                              m_aListSourceSeq;       //
    StringSequence                              m_aValueSeq;            // alle Werte, readonly
    ::com::sun::star::uno::Sequence<sal_Int16>  m_aDefaultSelectSeq;    // DefaultSelected
    // </properties>

    ::cppu::OInterfaceContainerHelper           m_aRefreshListeners;

    sal_Int16                                   m_nNULLPos;             // position of the NULL value in our list
    sal_Bool                                    m_bBoundComponent : 1;

    /** type how we should transfer our selection to external value bindings
    */
    enum TransferSelection
    {
        tsIndexList,        /// as list of indexes of selected entries
        tsIndex,            /// as index of the selected entry
        tsEntryList,        /// as list of string representations of selected entries
        tsEntry             /// as string representation of the selected entry
    };
    TransferSelection                           m_eTransferSelectionAs;

private:
    // Helper functions
    StringSequence GetCurValueSeq() const;

    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>   _getTypes();

public:
    DECLARE_DEFAULT_LEAF_XTOR( OListBoxModel );

// XServiceInfo
    IMPLEMENTATION_NAME(OListBoxModel);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

// UNO Anbindung
    DECLARE_UNO3_AGG_DEFAULTS(OListBoxModel, OBoundControlModel);
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);

// OComponentHelper
    virtual void SAL_CALL disposing();

// OPropertySetHelper
    virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
    virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
                throw (::com::sun::star::uno::Exception);
    virtual sal_Bool SAL_CALL convertFastPropertyValue(
                ::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
                throw (::com::sun::star::lang::IllegalArgumentException);

protected:
    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    // XPersistObject
    virtual ::rtl::OUString SAL_CALL    getServiceName() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

    // XRefreshable
    virtual void SAL_CALL refresh() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addRefreshListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XRefreshListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeRefreshListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XRefreshListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);

    // OAggregationArrayUsageHelper
    virtual void fillProperties(
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
        ) const;
    IMPLEMENT_INFO_SERVICE()

    // XEventListener
    virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw (::com::sun::star::uno::RuntimeException);

protected:
    // OBoundControlModel overridables
    virtual ::com::sun::star::uno::Any
                            translateDbColumnToControlValue( );
    virtual ::com::sun::star::uno::Any
                            translateExternalValueToControlValue( );
    virtual ::com::sun::star::uno::Any
                            translateControlValueToExternalValue( );
    virtual sal_Bool        commitControlValueToDbColumn( bool _bPostReset );

    virtual void            onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
    virtual void            onDisconnectedDbColumn();
    virtual void            onConnectedExternalValue( );

    virtual ::com::sun::star::uno::Any
                            getDefaultForReset() const;

    virtual sal_Bool        approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );

    // OEntryListHelper overriables
    virtual void    stringItemListChanged( );
    virtual void    connectedExternalListSource( );
    virtual void    disconnectedExternalListSource( );

protected:
    DECLARE_XCLONEABLE();

private:
    void        loadData();

    /**
    @precond we don't actually have an external list source
    */
    void        implRefreshListFromDbBinding( );
};

//==================================================================
//= OListBoxControl
//==================================================================
typedef ::cppu::ImplHelper3<    ::com::sun::star::awt::XFocusListener,
                                ::com::sun::star::awt::XItemListener,
                                ::com::sun::star::form::XChangeBroadcaster > OListBoxControl_BASE;

class OListBoxControl   :public OBoundControl
                        ,public OListBoxControl_BASE
{
    ::cppu::OInterfaceContainerHelper       m_aChangeListeners;

    ::com::sun::star::uno::Any              m_aCurrentSelection;
    Timer                                   m_aChangeTimer;

protected:
    // UNO Anbindung
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>   _getTypes();

public:
    OListBoxControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
    virtual ~OListBoxControl();

    // UNO Anbindung
    DECLARE_UNO3_AGG_DEFAULTS(OListBoxControl, OBoundControl);
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);

// XServiceInfo
    IMPLEMENTATION_NAME(OListBoxControl);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

// XChangeBroadcaster
    virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);

// XFocusListener
    virtual void SAL_CALL focusGained(const ::com::sun::star::awt::FocusEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL focusLost(const ::com::sun::star::awt::FocusEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);

// XItemListener
    virtual void SAL_CALL itemStateChanged(const ::com::sun::star::awt::ItemEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);

// XEventListener
    virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw (::com::sun::star::uno::RuntimeException);

// OComponentHelper
    virtual void SAL_CALL disposing();

private:
    DECL_LINK( OnTimeout, void* );
};

//.........................................................................
}
//.........................................................................

#endif // _FORMS_LISTBOX_HXX_

<commit_msg>INTEGRATION: CWS dba09 (1.7.44); FILE MERGED 2004/04/27 06:15:59 fs 1.7.44.2: RESYNC: (1.7-1.8); FILE MERGED 2004/04/05 12:05:47 fs 1.7.44.1: #i27024# +setPropertyValues<commit_after>/*************************************************************************
 *
 *  $RCSfile: ListBox.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2004-05-10 12:46:33 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FORMS_LISTBOX_HXX_
#define _FORMS_LISTBOX_HXX_

#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif

#ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_
#include <com/sun/star/util/XRefreshable.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLERRORBROADCASTER_HPP_
#include <com/sun/star/sdb/XSQLErrorBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_LISTSOURCETYPE_HPP_
#include <com/sun/star/form/ListSourceType.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XITEMLISTENER_HPP_
#include <com/sun/star/awt/XItemListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_
#include <com/sun/star/awt/XFocusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XCHANGEBROADCASTER_HPP_
#include <com/sun/star/form/XChangeBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYSINK_HDL_
#include <com/sun/star/form/binding/XListEntrySink.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYLISTENER_HDL_
#include <com/sun/star/form/binding/XListEntryListener.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef FORMS_ERRORBROADCASTER_HXX
#include "errorbroadcaster.hxx"
#endif
#ifndef FORMS_ENTRYLISTHELPER_HXX
#include "entrylisthelper.hxx"
#endif

//.........................................................................
namespace frm
{

//==================================================================
//= OListBoxModel
//==================================================================
typedef ::cppu::ImplHelper1 <   ::com::sun::star::util::XRefreshable
                            >   OListBoxModel_BASE;

class OListBoxModel :public OBoundControlModel
                    ,public OListBoxModel_BASE
                    ,public OEntryListHelper
                    ,public OErrorBroadcaster
                    ,public ::comphelper::OAggregationArrayUsageHelper< OListBoxModel >
{
    ::com::sun::star::uno::Any                  m_aSaveValue;

    // <properties>
    ::com::sun::star::form::ListSourceType      m_eListSourceType;      // type der list source
    ::com::sun::star::uno::Any                  m_aBoundColumn;
    StringSequence                              m_aListSourceSeq;       //
    StringSequence                              m_aValueSeq;            // alle Werte, readonly
    ::com::sun::star::uno::Sequence<sal_Int16>  m_aDefaultSelectSeq;    // DefaultSelected
    // </properties>

    ::cppu::OInterfaceContainerHelper           m_aRefreshListeners;

    sal_Int16                                   m_nNULLPos;             // position of the NULL value in our list
    sal_Bool                                    m_bBoundComponent : 1;

    /** type how we should transfer our selection to external value bindings
    */
    enum TransferSelection
    {
        tsIndexList,        /// as list of indexes of selected entries
        tsIndex,            /// as index of the selected entry
        tsEntryList,        /// as list of string representations of selected entries
        tsEntry             /// as string representation of the selected entry
    };
    TransferSelection                           m_eTransferSelectionAs;

private:
    // Helper functions
    StringSequence GetCurValueSeq() const;

    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>   _getTypes();

public:
    DECLARE_DEFAULT_LEAF_XTOR( OListBoxModel );

// XServiceInfo
    IMPLEMENTATION_NAME(OListBoxModel);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

// UNO Anbindung
    DECLARE_UNO3_AGG_DEFAULTS(OListBoxModel, OBoundControlModel);
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);

// OComponentHelper
    virtual void SAL_CALL disposing();

// OPropertySetHelper
    virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
    virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
                throw (::com::sun::star::uno::Exception);
    virtual sal_Bool SAL_CALL convertFastPropertyValue(
                ::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
                throw (::com::sun::star::lang::IllegalArgumentException);

protected:
    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    // XMultiPropertySet
    virtual void SAL_CALL   setPropertyValues(const ::com::sun::star::uno::Sequence< ::rtl::OUString >& PropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Values) throw(::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XPersistObject
    virtual ::rtl::OUString SAL_CALL    getServiceName() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
        read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

    // XRefreshable
    virtual void SAL_CALL refresh() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addRefreshListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XRefreshListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeRefreshListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XRefreshListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);

    // OAggregationArrayUsageHelper
    virtual void fillProperties(
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
        ) const;
    IMPLEMENT_INFO_SERVICE()

    // XEventListener
    virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw (::com::sun::star::uno::RuntimeException);

protected:
    // OBoundControlModel overridables
    virtual ::com::sun::star::uno::Any
                            translateDbColumnToControlValue( );
    virtual ::com::sun::star::uno::Any
                            translateExternalValueToControlValue( );
    virtual ::com::sun::star::uno::Any
                            translateControlValueToExternalValue( );
    virtual sal_Bool        commitControlValueToDbColumn( bool _bPostReset );

    virtual void            onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
    virtual void            onDisconnectedDbColumn();
    virtual void            onConnectedExternalValue( );

    virtual ::com::sun::star::uno::Any
                            getDefaultForReset() const;

    virtual sal_Bool        approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );

    // OEntryListHelper overriables
    virtual void    stringItemListChanged( );
    virtual void    connectedExternalListSource( );
    virtual void    disconnectedExternalListSource( );

protected:
    DECLARE_XCLONEABLE();

private:
    void        loadData();

    /**
    @precond we don't actually have an external list source
    */
    void        implRefreshListFromDbBinding( );
};

//==================================================================
//= OListBoxControl
//==================================================================
typedef ::cppu::ImplHelper3<    ::com::sun::star::awt::XFocusListener,
                                ::com::sun::star::awt::XItemListener,
                                ::com::sun::star::form::XChangeBroadcaster > OListBoxControl_BASE;

class OListBoxControl   :public OBoundControl
                        ,public OListBoxControl_BASE
{
    ::cppu::OInterfaceContainerHelper       m_aChangeListeners;

    ::com::sun::star::uno::Any              m_aCurrentSelection;
    Timer                                   m_aChangeTimer;

protected:
    // UNO Anbindung
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>   _getTypes();

public:
    OListBoxControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
    virtual ~OListBoxControl();

    // UNO Anbindung
    DECLARE_UNO3_AGG_DEFAULTS(OListBoxControl, OBoundControl);
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);

// XServiceInfo
    IMPLEMENTATION_NAME(OListBoxControl);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

// XChangeBroadcaster
    virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);

// XFocusListener
    virtual void SAL_CALL focusGained(const ::com::sun::star::awt::FocusEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL focusLost(const ::com::sun::star::awt::FocusEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);

// XItemListener
    virtual void SAL_CALL itemStateChanged(const ::com::sun::star::awt::ItemEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);

// XEventListener
    virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw (::com::sun::star::uno::RuntimeException);

// OComponentHelper
    virtual void SAL_CALL disposing();

private:
    DECL_LINK( OnTimeout, void* );
};

//.........................................................................
}
//.........................................................................

#endif // _FORMS_LISTBOX_HXX_

<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// object that creates and contains a spawn position

#include "common.h"

#include <string>

#include "SpawnPosition.h"
#include "DropGeometry.h"
#include "Obstacle.h"
#include "FlagInfo.h"
#include "TeamBases.h"
#include "WorldInfo.h"
#include "PlayerInfo.h"
#include "PlayerState.h"
#include "GameKeeper.h"
#include "BZDBCache.h"

// FIXME: from bzfs.cxx
extern int getCurMaxPlayers();
extern bool areFoes(TeamColor team1, TeamColor team2);
extern BasesList bases;
extern WorldInfo *world;
extern PlayerState lastState[];

SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :
		curMaxPlayers(getCurMaxPlayers())
{
  GameKeeper::Player *playerData
    = GameKeeper::Player::getPlayerByIndex(playerId);
  if (!playerData)
    return;

  team = playerData->player.getTeam();
  azimuth = (float)(bzfrand() * 2.0 * M_PI);

  if (playerData->player.shouldRestartAtBase() &&
      (team >= RedTeam) && (team <= PurpleTeam) &&
      (bases.find(team) != bases.end())) {
    TeamBases &teamBases = bases[team];
    const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));
    base.getRandomPosition(pos[0], pos[1], pos[2]);
    playerData->player.setRestartOnBase(false);
  } else {
    const float tankRadius = BZDBCache::tankRadius;
    safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDBCache::tankRadius) * 1.5);
    safeDistance = tankRadius * 20; // FIXME: is this a good value?
    const float size = BZDBCache::worldSize;
    const float maxWorldHeight = world->getMaxWorldHeight();

    // keep track of how much time we spend searching for a location
    TimeKeeper start = TimeKeeper::getCurrent();

    int tries = 0;
    float minProximity = size / 3.0f;
    float bestDist = -1.0f;
    bool foundspot = false;
    while (!foundspot) {
      if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {
	if (notNearEdges) {
	  // don't spawn close to map edges in CTF mode
	  testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;
	  testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;
	} else {
	  testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
	  testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
	}
	testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);
      }
      tries++;

      const float waterLevel = world->getWaterLevel();
      float minZ = 0.0f;
      if (waterLevel > minZ) {
	minZ = waterLevel;
      }
      float maxZ = maxWorldHeight;
      if (onGroundOnly) {
	maxZ = 0.0f;
      }

      if (DropGeometry::dropPlayer(testPos, minZ, maxZ)) {
	foundspot = true;
      }

      // check every now and then if we have already used up 10ms of time
      if (tries >= 50) {
	tries = 0;
	if (TimeKeeper::getCurrent() - start > 0.01f) {
	  if (bestDist < 0.0f) { // haven't found a single spot
	    //Just drop the sucka in, and pray
	    pos[0] = testPos[0];
	    pos[1] = testPos[1];
	    pos[2] = maxWorldHeight;
	    DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n");
	  }
	  break;
	}
      }

      // check if spot is safe enough
      bool dangerous = isImminentlyDangerous();
      if (foundspot && !dangerous) {
	float enemyAngle;
	float dist = enemyProximityCheck(enemyAngle);
	if (dist > bestDist) { // best so far
	  bestDist = dist;
	  pos[0] = testPos[0];
	  pos[1] = testPos[1];
	  pos[2] = testPos[2];
	  azimuth = fmod((float)(enemyAngle + M_PI), (float)(2.0 * M_PI));
	}
	if (bestDist < minProximity) { // not good enough, keep looking
	  foundspot = false;
	  minProximity *= 0.99f; // relax requirements a little
	}
      } else if (dangerous) {
	foundspot = false;
      }
    }
  }
}

SpawnPosition::~SpawnPosition()
{
}

const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth,
				   const float deviation) const
{
  // vector points from test to enemy
  float dx = enemyPos[0] - testPos[0];
  float dy = enemyPos[0] - testPos[1];
  float angActual = atan2f (dy, dx);
  float diff = fmodf(enemyAzimuth - angActual, (float)M_PI * 2.0f);

  // now diff is between {-PI*2 and +PI*2}, and we're looking for values around
  // -PI or +PI, because that's when the enemy is facing the source.
  diff = fabsf (diff); // between {0 and +PI*2}
  diff = fabsf ((float)(diff - M_PI));

  if (diff < (deviation / 2.0f)) {
    return true;
  } else {
    return false;
  }
}

const bool SpawnPosition::isImminentlyDangerous() const
{
  GameKeeper::Player *playerData;
  for (int i = 0; i < curMaxPlayers; i++) {
    playerData = GameKeeper::Player::getPlayerByIndex(i);
    if (!playerData)
      continue;
    if (playerData->player.isAlive()) {
      float *enemyPos = lastState[i].pos;
      float enemyAngle = lastState[i].azimuth;
      if (playerData->player.getFlag() >= 0) {
	// check for dangerous flags
	const FlagInfo *finfo = FlagInfo::get(playerData->player.getFlag());
	const FlagType *ftype = finfo->flag.type;
	// FIXME: any more?
	if (ftype == Flags::Laser) {  // don't spawn in the line of sight of an L
	  if (isFacing(enemyPos, enemyAngle, (float)(M_PI / 9.0))) { // he's looking within 20 degrees of spawn point
	    return true;	// eek, don't spawn here
	  }
	} else if (ftype == Flags::ShockWave) {  // don't spawn next to a SW
	  if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW
	    return true;	// eek, don't spawn here
	  }
	}
      }
      // don't spawn in the line of sight of a normal-shot tank within a certain distance
      if (distanceFrom(enemyPos) < safeDistance) { // within danger zone?
	if (isFacing(enemyPos, enemyAngle, (float)(M_PI / 9.0))) { //and he's looking at me
	  return true;
	}
      }
    }
  }

  // TODO: should check world weapons also

  return false;
}

const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const
{
  GameKeeper::Player *playerData;
  float worstDist = 1e12f; // huge number
  bool noEnemy    = true;

  for (int i = 0; i < curMaxPlayers; i++) {
    playerData = GameKeeper::Player::getPlayerByIndex(i);
    if (!playerData)
      continue;
    if (playerData->player.isAlive()
	&& areFoes(playerData->player.getTeam(), team)) {
      float *enemyPos = lastState[i].pos;
      if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {
	float x = enemyPos[0] - testPos[0];
	float y = enemyPos[1] - testPos[1];
	float distSq = x * x + y * y;
	if (distSq < worstDist) {
	  worstDist  = distSq;
	  enemyAngle = lastState[i].azimuth;
	  noEnemy    = false;
	}
      }
    }
  }
  if (noEnemy)
    enemyAngle = (float)(bzfrand() * 2.0 * M_PI);
  return sqrtf(worstDist);
}

const float SpawnPosition::distanceFrom(const float* farPos) const
{
  float dx = farPos[0] - testPos[0];
  float dy = farPos[1] - testPos[1];
  float dz = farPos[2] - testPos[2];
  return (float)sqrt(dx*dx + dy*dy + dz*dz);
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>make SpawnPosition use playerData->lastState rather than directly accessing the lastState[] array<commit_after>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// object that creates and contains a spawn position

#include "common.h"

#include <string>

#include "SpawnPosition.h"
#include "DropGeometry.h"
#include "Obstacle.h"
#include "FlagInfo.h"
#include "TeamBases.h"
#include "WorldInfo.h"
#include "PlayerInfo.h"
#include "PlayerState.h"
#include "GameKeeper.h"
#include "BZDBCache.h"

// FIXME: from bzfs.cxx
extern int getCurMaxPlayers();
extern bool areFoes(TeamColor team1, TeamColor team2);
extern BasesList bases;
extern WorldInfo *world;

SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :
		curMaxPlayers(getCurMaxPlayers())
{
  GameKeeper::Player *playerData
    = GameKeeper::Player::getPlayerByIndex(playerId);
  if (!playerData)
    return;

  team = playerData->player.getTeam();
  azimuth = (float)(bzfrand() * 2.0 * M_PI);

  if (playerData->player.shouldRestartAtBase() &&
      (team >= RedTeam) && (team <= PurpleTeam) &&
      (bases.find(team) != bases.end())) {
    TeamBases &teamBases = bases[team];
    const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));
    base.getRandomPosition(pos[0], pos[1], pos[2]);
    playerData->player.setRestartOnBase(false);
  } else {
    const float tankRadius = BZDBCache::tankRadius;
    safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDBCache::tankRadius) * 1.5);
    safeDistance = tankRadius * 20; // FIXME: is this a good value?
    const float size = BZDBCache::worldSize;
    const float maxWorldHeight = world->getMaxWorldHeight();

    // keep track of how much time we spend searching for a location
    TimeKeeper start = TimeKeeper::getCurrent();

    int tries = 0;
    float minProximity = size / 3.0f;
    float bestDist = -1.0f;
    bool foundspot = false;
    while (!foundspot) {
      if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {
	if (notNearEdges) {
	  // don't spawn close to map edges in CTF mode
	  testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;
	  testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;
	} else {
	  testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
	  testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
	}
	testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);
      }
      tries++;

      const float waterLevel = world->getWaterLevel();
      float minZ = 0.0f;
      if (waterLevel > minZ) {
	minZ = waterLevel;
      }
      float maxZ = maxWorldHeight;
      if (onGroundOnly) {
	maxZ = 0.0f;
      }

      if (DropGeometry::dropPlayer(testPos, minZ, maxZ)) {
	foundspot = true;
      }

      // check every now and then if we have already used up 10ms of time
      if (tries >= 50) {
	tries = 0;
	if (TimeKeeper::getCurrent() - start > 0.01f) {
	  if (bestDist < 0.0f) { // haven't found a single spot
	    //Just drop the sucka in, and pray
	    pos[0] = testPos[0];
	    pos[1] = testPos[1];
	    pos[2] = maxWorldHeight;
	    DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n");
	  }
	  break;
	}
      }

      // check if spot is safe enough
      bool dangerous = isImminentlyDangerous();
      if (foundspot && !dangerous) {
	float enemyAngle;
	float dist = enemyProximityCheck(enemyAngle);
	if (dist > bestDist) { // best so far
	  bestDist = dist;
	  pos[0] = testPos[0];
	  pos[1] = testPos[1];
	  pos[2] = testPos[2];
	  azimuth = fmod((float)(enemyAngle + M_PI), (float)(2.0 * M_PI));
	}
	if (bestDist < minProximity) { // not good enough, keep looking
	  foundspot = false;
	  minProximity *= 0.99f; // relax requirements a little
	}
      } else if (dangerous) {
	foundspot = false;
      }
    }
  }
}

SpawnPosition::~SpawnPosition()
{
}

const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth,
				   const float deviation) const
{
  // vector points from test to enemy
  float dx = enemyPos[0] - testPos[0];
  float dy = enemyPos[0] - testPos[1];
  float angActual = atan2f (dy, dx);
  float diff = fmodf(enemyAzimuth - angActual, (float)M_PI * 2.0f);

  // now diff is between {-PI*2 and +PI*2}, and we're looking for values around
  // -PI or +PI, because that's when the enemy is facing the source.
  diff = fabsf (diff); // between {0 and +PI*2}
  diff = fabsf ((float)(diff - M_PI));

  if (diff < (deviation / 2.0f)) {
    return true;
  } else {
    return false;
  }
}

const bool SpawnPosition::isImminentlyDangerous() const
{
  GameKeeper::Player *playerData;
  for (int i = 0; i < curMaxPlayers; i++) {
    playerData = GameKeeper::Player::getPlayerByIndex(i);
    if (!playerData)
      continue;
    if (playerData->player.isAlive()) {
      float *enemyPos = playerData->lastState->pos;
      float enemyAngle = playerData->lastState->azimuth;
      if (playerData->player.getFlag() >= 0) {
	// check for dangerous flags
	const FlagInfo *finfo = FlagInfo::get(playerData->player.getFlag());
	const FlagType *ftype = finfo->flag.type;
	// FIXME: any more?
	if (ftype == Flags::Laser) {  // don't spawn in the line of sight of an L
	  if (isFacing(enemyPos, enemyAngle, (float)(M_PI / 9.0))) { // he's looking within 20 degrees of spawn point
	    return true;	// eek, don't spawn here
	  }
	} else if (ftype == Flags::ShockWave) {  // don't spawn next to a SW
	  if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW
	    return true;	// eek, don't spawn here
	  }
	}
      }
      // don't spawn in the line of sight of a normal-shot tank within a certain distance
      if (distanceFrom(enemyPos) < safeDistance) { // within danger zone?
	if (isFacing(enemyPos, enemyAngle, (float)(M_PI / 9.0))) { //and he's looking at me
	  return true;
	}
      }
    }
  }

  // TODO: should check world weapons also

  return false;
}

const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const
{
  GameKeeper::Player *playerData;
  float worstDist = 1e12f; // huge number
  bool noEnemy    = true;

  for (int i = 0; i < curMaxPlayers; i++) {
    playerData = GameKeeper::Player::getPlayerByIndex(i);
    if (!playerData)
      continue;
    if (playerData->player.isAlive()
	&& areFoes(playerData->player.getTeam(), team)) {
      float *enemyPos = playerData->lastState->pos;
      if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {
	float x = enemyPos[0] - testPos[0];
	float y = enemyPos[1] - testPos[1];
	float distSq = x * x + y * y;
	if (distSq < worstDist) {
	  worstDist  = distSq;
	  enemyAngle = playerData->lastState->azimuth;
	  noEnemy    = false;
	}
      }
    }
  }
  if (noEnemy)
    enemyAngle = (float)(bzfrand() * 2.0 * M_PI);
  return sqrtf(worstDist);
}

const float SpawnPosition::distanceFrom(const float* farPos) const
{
  float dx = farPos[0] - testPos[0];
  float dy = farPos[1] - testPos[1];
  float dz = farPos[2] - testPos[2];
  return (float)sqrt(dx*dx + dy*dy + dz*dz);
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


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

#include "chrome/browser/bookmarks/bookmark_context_menu_controller.h"

#include "base/compiler_specific.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/bookmarks/bookmark_editor.h"
#include "chrome/browser/bookmarks/bookmark_folder_editor_controller.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/page_navigator.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

BookmarkContextMenuController::BookmarkContextMenuController(
    gfx::NativeWindow parent_window,
    BookmarkContextMenuControllerDelegate* delegate,
    Profile* profile,
    PageNavigator* navigator,
    const BookmarkNode* parent,
    const std::vector<const BookmarkNode*>& selection)
    : parent_window_(parent_window),
      delegate_(delegate),
      profile_(profile),
      navigator_(navigator),
      parent_(parent),
      selection_(selection),
      model_(profile->GetBookmarkModel()) {
  DCHECK(profile_);
  DCHECK(model_->IsLoaded());
  menu_model_.reset(new ui::SimpleMenuModel(this));
  model_->AddObserver(this);

  BuildMenu();
}

BookmarkContextMenuController::~BookmarkContextMenuController() {
  if (model_)
    model_->RemoveObserver(this);
}

void BookmarkContextMenuController::BuildMenu() {
  if (selection_.size() == 1 && selection_[0]->is_url()) {
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL,
            IDS_BOOMARK_BAR_OPEN_IN_NEW_TAB);
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
            IDS_BOOMARK_BAR_OPEN_IN_NEW_WINDOW);
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
            IDS_BOOMARK_BAR_OPEN_INCOGNITO);
  } else {
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL, IDS_BOOMARK_BAR_OPEN_ALL);
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
        IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW);
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
        IDS_BOOMARK_BAR_OPEN_ALL_INCOGNITO);
  }

  AddSeparator();
  if (selection_.size() == 1 && selection_[0]->is_folder()) {
    AddItem(IDC_BOOKMARK_BAR_RENAME_FOLDER, IDS_BOOKMARK_BAR_RENAME_FOLDER);
  } else {
    AddItem(IDC_BOOKMARK_BAR_EDIT, IDS_BOOKMARK_BAR_EDIT);
  }

  AddSeparator();
  AddItem(IDC_CUT, IDS_CUT);
  AddItem(IDC_COPY, IDS_COPY);
  AddItem(IDC_PASTE, IDS_PASTE);

  AddSeparator();
  AddItem(IDC_BOOKMARK_BAR_REMOVE, IDS_BOOKMARK_BAR_REMOVE);

  AddSeparator();
  AddItem(IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK, IDS_BOOMARK_BAR_ADD_NEW_BOOKMARK);
  AddItem(IDC_BOOKMARK_BAR_NEW_FOLDER, IDS_BOOMARK_BAR_NEW_FOLDER);

  AddSeparator();
  AddItem(IDC_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER);
  AddCheckboxItem(IDC_BOOKMARK_BAR_ALWAYS_SHOW, IDS_BOOMARK_BAR_ALWAYS_SHOW);
}

void BookmarkContextMenuController::AddItem(int id, int localization_id) {
  menu_model_->AddItemWithStringId(id, localization_id);
}

void BookmarkContextMenuController::AddSeparator() {
  menu_model_->AddSeparator();
}

void BookmarkContextMenuController::AddCheckboxItem(int id,
                                                    int localization_id) {
  menu_model_->AddCheckItemWithStringId(id, localization_id);
}

void BookmarkContextMenuController::ExecuteCommand(int id) {
  if (delegate_)
    delegate_->WillExecuteCommand();

  switch (id) {
    case IDC_BOOKMARK_BAR_OPEN_ALL:
    case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
    case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW: {
      WindowOpenDisposition initial_disposition;
      if (id == IDC_BOOKMARK_BAR_OPEN_ALL) {
        initial_disposition = NEW_FOREGROUND_TAB;
        UserMetrics::RecordAction(
            UserMetricsAction("BookmarkBar_ContextMenu_OpenAll"),
            profile_);
      } else if (id == IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW) {
        initial_disposition = NEW_WINDOW;
        UserMetrics::RecordAction(
                UserMetricsAction("BookmarkBar_ContextMenu_OpenAllInNewWindow"),
                profile_);
      } else {
        initial_disposition = OFF_THE_RECORD;
        UserMetrics::RecordAction(
            UserMetricsAction("BookmarkBar_ContextMenu_OpenAllIncognito"),
            profile_);
      }
      bookmark_utils::OpenAll(parent_window_, profile_, navigator_, selection_,
                              initial_disposition);
      break;
    }

    case IDC_BOOKMARK_BAR_RENAME_FOLDER:
    case IDC_BOOKMARK_BAR_EDIT:
      UserMetrics::RecordAction(
          UserMetricsAction("BookmarkBar_ContextMenu_Edit"),
          profile_);

      if (selection_.size() != 1) {
        NOTREACHED();
        break;
      }

      if (selection_[0]->is_url()) {
        BookmarkEditor::Show(parent_window_, profile_, parent_,
                             BookmarkEditor::EditDetails(selection_[0]),
                             BookmarkEditor::SHOW_TREE);
      } else {
        BookmarkFolderEditorController::Show(profile_, parent_window_,
            selection_[0], -1,
            BookmarkFolderEditorController::EXISTING_BOOKMARK);
      }
      break;

    case IDC_BOOKMARK_BAR_REMOVE: {
      UserMetrics::RecordAction(
          UserMetricsAction("BookmarkBar_ContextMenu_Remove"),
          profile_);

      for (size_t i = 0; i < selection_.size(); ++i) {
        model_->Remove(selection_[i]->GetParent(),
                      selection_[i]->GetParent()->IndexOfChild(selection_[i]));
      }
      selection_.clear();
      break;
    }

    case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK: {
      UserMetrics::RecordAction(
          UserMetricsAction("BookmarkBar_ContextMenu_Add"),
          profile_);

      // TODO: this should honor the index from GetParentForNewNodes.
      BookmarkEditor::Show(
          parent_window_, profile_,
          bookmark_utils::GetParentForNewNodes(parent_, selection_, NULL),
          BookmarkEditor::EditDetails(), BookmarkEditor::SHOW_TREE);
      break;
    }

    case IDC_BOOKMARK_BAR_NEW_FOLDER: {
      UserMetrics::RecordAction(
          UserMetricsAction("BookmarkBar_ContextMenu_NewFolder"),
          profile_);
      int index;
      const BookmarkNode* parent =
          bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
      BookmarkFolderEditorController::Show(profile_, parent_window_, parent,
          index, BookmarkFolderEditorController::NEW_BOOKMARK);
      break;
    }

    case IDC_BOOKMARK_BAR_ALWAYS_SHOW:
      bookmark_utils::ToggleWhenVisible(profile_);
      break;

    case IDC_BOOKMARK_MANAGER:
      UserMetrics::RecordAction(UserMetricsAction("ShowBookmarkManager"),
                                profile_);
      {
        Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
        if (browser)
          browser->OpenBookmarkManager();
        else
          NOTREACHED();
      }
      break;

    case IDC_CUT:
      bookmark_utils::CopyToClipboard(model_, selection_, true);
      break;

    case IDC_COPY:
      bookmark_utils::CopyToClipboard(model_, selection_, false);
      break;

    case IDC_PASTE: {
      int index;
      const BookmarkNode* paste_target =
          bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
      if (!paste_target)
        return;

      bookmark_utils::PasteFromClipboard(model_, paste_target, index);
      break;
    }

    default:
      NOTREACHED();
  }

  if (delegate_)
    delegate_->DidExecuteCommand();
}

bool BookmarkContextMenuController::IsCommandIdChecked(int command_id) const {
  DCHECK(command_id == IDC_BOOKMARK_BAR_ALWAYS_SHOW);
  return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
}

bool BookmarkContextMenuController::IsCommandIdEnabled(int command_id) const {
  bool is_root_node =
      (selection_.size() == 1 &&
       selection_[0]->GetParent() == model_->root_node());
  switch (command_id) {
    case IDC_BOOKMARK_BAR_OPEN_INCOGNITO:
      return !profile_->IsOffTheRecord();

    case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
      return HasURLs() && !profile_->IsOffTheRecord();

    case IDC_BOOKMARK_BAR_OPEN_ALL:
    case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW:
      return HasURLs();

    case IDC_BOOKMARK_BAR_RENAME_FOLDER:
    case IDC_BOOKMARK_BAR_EDIT:
      return selection_.size() == 1 && !is_root_node;

    case IDC_BOOKMARK_BAR_REMOVE:
      return !selection_.empty() && !is_root_node;

    case IDC_BOOKMARK_BAR_NEW_FOLDER:
    case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK:
      return bookmark_utils::GetParentForNewNodes(
          parent_, selection_, NULL) != NULL;

    case IDC_COPY:
    case IDC_CUT:
      return selection_.size() > 0 && !is_root_node;

    case IDC_PASTE:
      // Paste to selection from the Bookmark Bar, to parent_ everywhere else
      return (!selection_.empty() &&
              bookmark_utils::CanPasteFromClipboard(selection_[0])) ||
             bookmark_utils::CanPasteFromClipboard(parent_);
  }
  return true;
}

bool BookmarkContextMenuController::GetAcceleratorForCommandId(
    int command_id,
    ui::Accelerator* accelerator) {
  return false;
}

void BookmarkContextMenuController::BookmarkModelChanged() {
  if (delegate_)
    delegate_->CloseMenu();
}

bool BookmarkContextMenuController::HasURLs() const {
  for (size_t i = 0; i < selection_.size(); ++i) {
    if (bookmark_utils::NodeHasURLs(selection_[i]))
      return true;
  }
  return false;
}
<commit_msg>GTK uses a different controller for the bookmark bar view context menu than toolkit_views and this adds the same check for incognito pref that I added for views.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/bookmarks/bookmark_context_menu_controller.h"

#include "base/compiler_specific.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/bookmarks/bookmark_editor.h"
#include "chrome/browser/bookmarks/bookmark_folder_editor_controller.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/page_navigator.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

BookmarkContextMenuController::BookmarkContextMenuController(
    gfx::NativeWindow parent_window,
    BookmarkContextMenuControllerDelegate* delegate,
    Profile* profile,
    PageNavigator* navigator,
    const BookmarkNode* parent,
    const std::vector<const BookmarkNode*>& selection)
    : parent_window_(parent_window),
      delegate_(delegate),
      profile_(profile),
      navigator_(navigator),
      parent_(parent),
      selection_(selection),
      model_(profile->GetBookmarkModel()) {
  DCHECK(profile_);
  DCHECK(model_->IsLoaded());
  menu_model_.reset(new ui::SimpleMenuModel(this));
  model_->AddObserver(this);

  BuildMenu();
}

BookmarkContextMenuController::~BookmarkContextMenuController() {
  if (model_)
    model_->RemoveObserver(this);
}

void BookmarkContextMenuController::BuildMenu() {
  if (selection_.size() == 1 && selection_[0]->is_url()) {
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL,
            IDS_BOOMARK_BAR_OPEN_IN_NEW_TAB);
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
            IDS_BOOMARK_BAR_OPEN_IN_NEW_WINDOW);
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
            IDS_BOOMARK_BAR_OPEN_INCOGNITO);
  } else {
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL, IDS_BOOMARK_BAR_OPEN_ALL);
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
        IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW);
    AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
        IDS_BOOMARK_BAR_OPEN_ALL_INCOGNITO);
  }

  AddSeparator();
  if (selection_.size() == 1 && selection_[0]->is_folder()) {
    AddItem(IDC_BOOKMARK_BAR_RENAME_FOLDER, IDS_BOOKMARK_BAR_RENAME_FOLDER);
  } else {
    AddItem(IDC_BOOKMARK_BAR_EDIT, IDS_BOOKMARK_BAR_EDIT);
  }

  AddSeparator();
  AddItem(IDC_CUT, IDS_CUT);
  AddItem(IDC_COPY, IDS_COPY);
  AddItem(IDC_PASTE, IDS_PASTE);

  AddSeparator();
  AddItem(IDC_BOOKMARK_BAR_REMOVE, IDS_BOOKMARK_BAR_REMOVE);

  AddSeparator();
  AddItem(IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK, IDS_BOOMARK_BAR_ADD_NEW_BOOKMARK);
  AddItem(IDC_BOOKMARK_BAR_NEW_FOLDER, IDS_BOOMARK_BAR_NEW_FOLDER);

  AddSeparator();
  AddItem(IDC_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER);
  AddCheckboxItem(IDC_BOOKMARK_BAR_ALWAYS_SHOW, IDS_BOOMARK_BAR_ALWAYS_SHOW);
}

void BookmarkContextMenuController::AddItem(int id, int localization_id) {
  menu_model_->AddItemWithStringId(id, localization_id);
}

void BookmarkContextMenuController::AddSeparator() {
  menu_model_->AddSeparator();
}

void BookmarkContextMenuController::AddCheckboxItem(int id,
                                                    int localization_id) {
  menu_model_->AddCheckItemWithStringId(id, localization_id);
}

void BookmarkContextMenuController::ExecuteCommand(int id) {
  if (delegate_)
    delegate_->WillExecuteCommand();

  switch (id) {
    case IDC_BOOKMARK_BAR_OPEN_ALL:
    case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
    case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW: {
      WindowOpenDisposition initial_disposition;
      if (id == IDC_BOOKMARK_BAR_OPEN_ALL) {
        initial_disposition = NEW_FOREGROUND_TAB;
        UserMetrics::RecordAction(
            UserMetricsAction("BookmarkBar_ContextMenu_OpenAll"),
            profile_);
      } else if (id == IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW) {
        initial_disposition = NEW_WINDOW;
        UserMetrics::RecordAction(
                UserMetricsAction("BookmarkBar_ContextMenu_OpenAllInNewWindow"),
                profile_);
      } else {
        initial_disposition = OFF_THE_RECORD;
        UserMetrics::RecordAction(
            UserMetricsAction("BookmarkBar_ContextMenu_OpenAllIncognito"),
            profile_);
      }
      bookmark_utils::OpenAll(parent_window_, profile_, navigator_, selection_,
                              initial_disposition);
      break;
    }

    case IDC_BOOKMARK_BAR_RENAME_FOLDER:
    case IDC_BOOKMARK_BAR_EDIT:
      UserMetrics::RecordAction(
          UserMetricsAction("BookmarkBar_ContextMenu_Edit"),
          profile_);

      if (selection_.size() != 1) {
        NOTREACHED();
        break;
      }

      if (selection_[0]->is_url()) {
        BookmarkEditor::Show(parent_window_, profile_, parent_,
                             BookmarkEditor::EditDetails(selection_[0]),
                             BookmarkEditor::SHOW_TREE);
      } else {
        BookmarkFolderEditorController::Show(profile_, parent_window_,
            selection_[0], -1,
            BookmarkFolderEditorController::EXISTING_BOOKMARK);
      }
      break;

    case IDC_BOOKMARK_BAR_REMOVE: {
      UserMetrics::RecordAction(
          UserMetricsAction("BookmarkBar_ContextMenu_Remove"),
          profile_);

      for (size_t i = 0; i < selection_.size(); ++i) {
        model_->Remove(selection_[i]->GetParent(),
                      selection_[i]->GetParent()->IndexOfChild(selection_[i]));
      }
      selection_.clear();
      break;
    }

    case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK: {
      UserMetrics::RecordAction(
          UserMetricsAction("BookmarkBar_ContextMenu_Add"),
          profile_);

      // TODO: this should honor the index from GetParentForNewNodes.
      BookmarkEditor::Show(
          parent_window_, profile_,
          bookmark_utils::GetParentForNewNodes(parent_, selection_, NULL),
          BookmarkEditor::EditDetails(), BookmarkEditor::SHOW_TREE);
      break;
    }

    case IDC_BOOKMARK_BAR_NEW_FOLDER: {
      UserMetrics::RecordAction(
          UserMetricsAction("BookmarkBar_ContextMenu_NewFolder"),
          profile_);
      int index;
      const BookmarkNode* parent =
          bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
      BookmarkFolderEditorController::Show(profile_, parent_window_, parent,
          index, BookmarkFolderEditorController::NEW_BOOKMARK);
      break;
    }

    case IDC_BOOKMARK_BAR_ALWAYS_SHOW:
      bookmark_utils::ToggleWhenVisible(profile_);
      break;

    case IDC_BOOKMARK_MANAGER:
      UserMetrics::RecordAction(UserMetricsAction("ShowBookmarkManager"),
                                profile_);
      {
        Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
        if (browser)
          browser->OpenBookmarkManager();
        else
          NOTREACHED();
      }
      break;

    case IDC_CUT:
      bookmark_utils::CopyToClipboard(model_, selection_, true);
      break;

    case IDC_COPY:
      bookmark_utils::CopyToClipboard(model_, selection_, false);
      break;

    case IDC_PASTE: {
      int index;
      const BookmarkNode* paste_target =
          bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
      if (!paste_target)
        return;

      bookmark_utils::PasteFromClipboard(model_, paste_target, index);
      break;
    }

    default:
      NOTREACHED();
  }

  if (delegate_)
    delegate_->DidExecuteCommand();
}

bool BookmarkContextMenuController::IsCommandIdChecked(int command_id) const {
  DCHECK(command_id == IDC_BOOKMARK_BAR_ALWAYS_SHOW);
  return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
}

bool BookmarkContextMenuController::IsCommandIdEnabled(int command_id) const {
  bool is_root_node =
      (selection_.size() == 1 &&
       selection_[0]->GetParent() == model_->root_node());
  switch (command_id) {
    case IDC_BOOKMARK_BAR_OPEN_INCOGNITO:
      return !profile_->IsOffTheRecord() &&
             profile_->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled);

    case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
      return HasURLs() && !profile_->IsOffTheRecord() &&
             profile_->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled);

    case IDC_BOOKMARK_BAR_OPEN_ALL:
    case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW:
      return HasURLs();

    case IDC_BOOKMARK_BAR_RENAME_FOLDER:
    case IDC_BOOKMARK_BAR_EDIT:
      return selection_.size() == 1 && !is_root_node;

    case IDC_BOOKMARK_BAR_REMOVE:
      return !selection_.empty() && !is_root_node;

    case IDC_BOOKMARK_BAR_NEW_FOLDER:
    case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK:
      return bookmark_utils::GetParentForNewNodes(
          parent_, selection_, NULL) != NULL;

    case IDC_COPY:
    case IDC_CUT:
      return selection_.size() > 0 && !is_root_node;

    case IDC_PASTE:
      // Paste to selection from the Bookmark Bar, to parent_ everywhere else
      return (!selection_.empty() &&
              bookmark_utils::CanPasteFromClipboard(selection_[0])) ||
             bookmark_utils::CanPasteFromClipboard(parent_);
  }
  return true;
}

bool BookmarkContextMenuController::GetAcceleratorForCommandId(
    int command_id,
    ui::Accelerator* accelerator) {
  return false;
}

void BookmarkContextMenuController::BookmarkModelChanged() {
  if (delegate_)
    delegate_->CloseMenu();
}

bool BookmarkContextMenuController::HasURLs() const {
  for (size_t i = 0; i < selection_.size(); ++i) {
    if (bookmark_utils::NodeHasURLs(selection_[i]))
      return true;
  }
  return false;
}
<|endoftext|>


<commit_before>#include "cef/cef_app_handler.h"

#include "cosmetic_blocker.h"

namespace doogie {

CefAppHandler::CefAppHandler() {}

bool CefAppHandler::OnBeforeNavigation(
    CefRefPtr<CefBrowser> browser,
    CefRefPtr<CefFrame> frame,
    CefRefPtr<CefRequest> request,
    CefRenderProcessHandler::NavigationType navigation_type,
    bool is_redirect) {
  if (before_nav_callback_) {
    return before_nav_callback_(browser, frame, request,
                                navigation_type, is_redirect);
  }
  return false;
}

void CefAppHandler::OnContextCreated(CefRefPtr<CefBrowser> browser,
                                     CefRefPtr<CefFrame> frame,
                                     CefRefPtr<CefV8Context> context) {
  // Prevent document.webkitExitFullscreen from being mutated because
  //  we need to call it internally in Doogie.
  // TODO(cretz): Find a better way, ref:
  //  http://www.magpcss.org/ceforum/viewtopic.php?f=6&t=13642#p35988
  frame->ExecuteJavaScript(
      "Object.defineProperty(document, 'webkitExitFullscreen', { "
      "  value: document.webkitExitFullscreen, "
      "  writable: false "
      "});",
      "<doogie>",
      0);

  blocker_.OnFrameCreated(browser, frame, context);
}

void CefAppHandler::OnWebKitInitialized() {
}

}  // namespace doogie
<commit_msg>Remove top level SharedArrayBuffer object. Fixes #68.<commit_after>#include "cef/cef_app_handler.h"

#include "cosmetic_blocker.h"

namespace doogie {

CefAppHandler::CefAppHandler() {}

bool CefAppHandler::OnBeforeNavigation(
    CefRefPtr<CefBrowser> browser,
    CefRefPtr<CefFrame> frame,
    CefRefPtr<CefRequest> request,
    CefRenderProcessHandler::NavigationType navigation_type,
    bool is_redirect) {
  if (before_nav_callback_) {
    return before_nav_callback_(browser, frame, request,
                                navigation_type, is_redirect);
  }
  return false;
}

void CefAppHandler::OnContextCreated(CefRefPtr<CefBrowser> browser,
                                     CefRefPtr<CefFrame> frame,
                                     CefRefPtr<CefV8Context> context) {
  // Prevent document.webkitExitFullscreen from being mutated because
  //  we need to call it internally in Doogie.
  // TODO(cretz): Find a better way, ref:
  //  http://www.magpcss.org/ceforum/viewtopic.php?f=6&t=13642#p35988
  frame->ExecuteJavaScript(
      "Object.defineProperty(document, 'webkitExitFullscreen', { "
      "  value: document.webkitExitFullscreen, "
      "  writable: false "
      "});",
      "<doogie>",
      0);

  // Temporarily disable SharedArrayBuffer, ref: https://github.com/cretz/doogie/issues/68
  frame->ExecuteJavaScript("delete window.SharedArrayBuffer", "<doogie>", 0);

  blocker_.OnFrameCreated(browser, frame, context);
}

void CefAppHandler::OnWebKitInitialized() {
}

}  // namespace doogie
<|endoftext|>


<commit_before>//===-- IndirectCallPromotionAnalysis.cpp - Find promotion candidates ===//
//
//                      The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Helper methods for identifying profitable indirect call promotion
// candidates for an instruction when the indirect-call value profile metadata
// is available.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/IndirectCallSiteVisitor.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/ProfileData/InstrProf.h"
#include "llvm/Support/Debug.h"
#include <string>
#include <utility>
#include <vector>

using namespace llvm;

#define DEBUG_TYPE "pgo-icall-prom-analysis"

// The minimum call count for the direct-call target to be considered as the
// promotion candidate.
static cl::opt<unsigned>
    ICPCountThreshold("icp-count-threshold", cl::Hidden, cl::ZeroOrMore,
                      cl::init(1000),
                      cl::desc("The minimum count to the direct call target "
                               "for the promotion"));

// The percent threshold for the direct-call target (this call site vs the
// total call count) for it to be considered as the promotion target.
static cl::opt<unsigned>
    ICPPercentThreshold("icp-percent-threshold", cl::init(33), cl::Hidden,
                        cl::ZeroOrMore,
                        cl::desc("The percentage threshold for the promotion"));

// Set the maximum number of targets to promote for a single indirect-call
// callsite.
static cl::opt<unsigned>
    MaxNumPromotions("icp-max-prom", cl::init(2), cl::Hidden, cl::ZeroOrMore,
                     cl::desc("Max number of promotions for a single indirect "
                              "call callsite"));

ICallPromotionAnalysis::ICallPromotionAnalysis() {
  ValueDataArray = llvm::make_unique<InstrProfValueData[]>(MaxNumPromotions);
}

bool ICallPromotionAnalysis::isPromotionProfitable(uint64_t Count,
                                                   uint64_t TotalCount) {
  if (Count < ICPCountThreshold)
    return false;

  unsigned Percentage = (Count * 100) / TotalCount;
  return (Percentage >= ICPPercentThreshold);
}

// Indirect-call promotion heuristic. The direct targets are sorted based on
// the count. Stop at the first target that is not promoted. Returns the
// number of candidates deemed profitable.
uint32_t ICallPromotionAnalysis::getProfitablePromotionCandidates(
    const Instruction *Inst, uint32_t NumVals, uint64_t TotalCount) {
  ArrayRef<InstrProfValueData> ValueDataRef(ValueDataArray.get(), NumVals);

  DEBUG(dbgs() << " \nWork on callsite " << *Inst << " Num_targets: " << NumVals
               << "\n");

  uint32_t I = 0;
  for (; I < MaxNumPromotions && I < NumVals; I++) {
    uint64_t Count = ValueDataRef[I].Count;
    assert(Count <= TotalCount);
    DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
                 << "  Target_func: " << ValueDataRef[I].Value << "\n");

    if (!isPromotionProfitable(Count, TotalCount)) {
      DEBUG(dbgs() << " Not promote: Cold target.\n");
      return I;
    }
    TotalCount -= Count;
  }
  return I;
}

ArrayRef<InstrProfValueData>
ICallPromotionAnalysis::getPromotionCandidatesForInstruction(
    const Instruction *I, uint32_t &NumVals, uint64_t &TotalCount,
    uint32_t &NumCandidates) {
  bool Res =
      getValueProfDataFromInst(*I, IPVK_IndirectCallTarget, MaxNumPromotions,
                               ValueDataArray.get(), NumVals, TotalCount);
  if (!Res) {
    NumCandidates = 0;
    return ArrayRef<InstrProfValueData>();
  }
  NumCandidates = getProfitablePromotionCandidates(I, NumVals, TotalCount);
  return ArrayRef<InstrProfValueData>(ValueDataArray.get(), NumVals);
}
<commit_msg>[PGO] Adjust indirect call promotion threshold<commit_after>//===-- IndirectCallPromotionAnalysis.cpp - Find promotion candidates ===//
//
//                      The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Helper methods for identifying profitable indirect call promotion
// candidates for an instruction when the indirect-call value profile metadata
// is available.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/IndirectCallSiteVisitor.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/ProfileData/InstrProf.h"
#include "llvm/Support/Debug.h"
#include <string>
#include <utility>
#include <vector>

using namespace llvm;

#define DEBUG_TYPE "pgo-icall-prom-analysis"

// The minimum call count for the direct-call target to be considered as the
// promotion candidate.
static cl::opt<unsigned>
    ICPCountThreshold("icp-count-threshold", cl::Hidden, cl::ZeroOrMore,
                      cl::init(1000),
                      cl::desc("The minimum count to the direct call target "
                               "for the promotion"));

// The percent threshold for the direct-call target (this call site vs the
// total call count) for it to be considered as the promotion target.
static cl::opt<unsigned>
    ICPPercentThreshold("icp-percent-threshold", cl::init(30), cl::Hidden,
                        cl::ZeroOrMore,
                        cl::desc("The percentage threshold for the promotion"));

// Set the maximum number of targets to promote for a single indirect-call
// callsite.
static cl::opt<unsigned>
    MaxNumPromotions("icp-max-prom", cl::init(2), cl::Hidden, cl::ZeroOrMore,
                     cl::desc("Max number of promotions for a single indirect "
                              "call callsite"));

ICallPromotionAnalysis::ICallPromotionAnalysis() {
  ValueDataArray = llvm::make_unique<InstrProfValueData[]>(MaxNumPromotions);
}

bool ICallPromotionAnalysis::isPromotionProfitable(uint64_t Count,
                                                   uint64_t TotalCount) {
  if (Count < ICPCountThreshold)
    return false;

  unsigned Percentage = (Count * 100) / TotalCount;
  return (Percentage >= ICPPercentThreshold);
}

// Indirect-call promotion heuristic. The direct targets are sorted based on
// the count. Stop at the first target that is not promoted. Returns the
// number of candidates deemed profitable.
uint32_t ICallPromotionAnalysis::getProfitablePromotionCandidates(
    const Instruction *Inst, uint32_t NumVals, uint64_t TotalCount) {
  ArrayRef<InstrProfValueData> ValueDataRef(ValueDataArray.get(), NumVals);

  DEBUG(dbgs() << " \nWork on callsite " << *Inst << " Num_targets: " << NumVals
               << "\n");

  uint32_t I = 0;
  for (; I < MaxNumPromotions && I < NumVals; I++) {
    uint64_t Count = ValueDataRef[I].Count;
    assert(Count <= TotalCount);
    DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
                 << "  Target_func: " << ValueDataRef[I].Value << "\n");

    if (!isPromotionProfitable(Count, TotalCount)) {
      DEBUG(dbgs() << " Not promote: Cold target.\n");
      return I;
    }
    TotalCount -= Count;
  }
  return I;
}

ArrayRef<InstrProfValueData>
ICallPromotionAnalysis::getPromotionCandidatesForInstruction(
    const Instruction *I, uint32_t &NumVals, uint64_t &TotalCount,
    uint32_t &NumCandidates) {
  bool Res =
      getValueProfDataFromInst(*I, IPVK_IndirectCallTarget, MaxNumPromotions,
                               ValueDataArray.get(), NumVals, TotalCount);
  if (!Res) {
    NumCandidates = 0;
    return ArrayRef<InstrProfValueData>();
  }
  NumCandidates = getProfitablePromotionCandidates(I, NumVals, TotalCount);
  return ArrayRef<InstrProfValueData>(ValueDataArray.get(), NumVals);
}
<|endoftext|>