text:
namespace chromeos {

static DBusThreadManager* g_dbus_thread_manager = NULL;

// The DBusThreadManager implementation used in production.
class DBusThreadManagerImpl : public DBusThreadManager {
 public:
  DBusThreadManagerImpl() {
    // Create the D-Bus thread.
    base::Thread::Options thread_options;
    thread_options.message_loop_type = MessageLoop::TYPE_IO;
    dbus_thread_.reset(new base::Thread("D-Bus thread"));
    dbus_thread_->StartWithOptions(thread_options);

    // Create the connection to the system bus.
    dbus::Bus::Options system_bus_options;
    system_bus_options.bus_type = dbus::Bus::SYSTEM;
    system_bus_options.connection_type = dbus::Bus::PRIVATE;
    system_bus_options.dbus_thread_message_loop_proxy =
        dbus_thread_->message_loop_proxy();
    system_bus_ = new dbus::Bus(system_bus_options);

    // Determine whether we use stub or real client implementations.
    const DBusClientImplementationType client_type =
        base::chromeos::IsRunningOnChromeOS() ?
        REAL_DBUS_CLIENT_IMPLEMENTATION : STUB_DBUS_CLIENT_IMPLEMENTATION;

    // Create the bluetooth clients.
    bluetooth_manager_client_.reset(BluetoothManagerClient::Create(
        client_type, system_bus_.get()));
    bluetooth_adapter_client_.reset(BluetoothAdapterClient::Create(
        client_type, system_bus_.get(), bluetooth_manager_client_.get()));
    bluetooth_device_client_.reset(BluetoothDeviceClient::Create(
        client_type, system_bus_.get(), bluetooth_adapter_client_.get()));
    bluetooth_input_client_.reset(BluetoothInputClient::Create(
        client_type, system_bus_.get(), bluetooth_adapter_client_.get()));
    bluetooth_node_client_.reset(BluetoothNodeClient::Create(
        client_type, system_bus_.get(), bluetooth_device_client_.get()));
    // Create the Cashew client.
    cashew_client_.reset(CashewClient::Create(client_type, system_bus_.get()));
    // Create the cros-disks client.
    cros_disks_client_.reset(
        CrosDisksClient::Create(client_type, system_bus_.get()));
    // Create the Cryptohome client.
    cryptohome_client_.reset(
        CryptohomeClient::Create(client_type, system_bus_.get()));
    // Create the debugdaemon client.
    debugdaemon_client_.reset(
        DebugDaemonClient::Create(client_type, system_bus_.get()));
    // Create the Flimflam Device client.
    flimflam_device_client_.reset(
        FlimflamDeviceClient::Create(client_type, system_bus_.get()));
    // Create the Flimflam IPConfig client.
    flimflam_ipconfig_client_.reset(
        FlimflamIPConfigClient::Create(client_type, system_bus_.get()));
    // Create the Flimflam Manager client.
    flimflam_manager_client_.reset(
        FlimflamManagerClient::Create(client_type, system_bus_.get()));
    // Create the Flimflam Network client.
    flimflam_network_client_.reset(
        FlimflamNetworkClient::Create(client_type, system_bus_.get()));
    // Create the Flimflam Profile client.
    flimflam_profile_client_.reset(
        FlimflamProfileClient::Create(client_type, system_bus_.get()));
    // Create the Flimflam Service client.
    flimflam_service_client_.reset(
        FlimflamServiceClient::Create(client_type, system_bus_.get()));
    // Create the SMS cilent.
    gsm_sms_client_.reset(
        GsmSMSClient::Create(client_type, system_bus_.get()));
    // Create the image burner client.
    image_burner_client_.reset(ImageBurnerClient::Create(client_type,
                                                         system_bus_.get()));
    // Create the introspectable object client.
    introspectable_client_.reset(
        IntrospectableClient::Create(client_type, system_bus_.get()));
    // Create the power manager client.
    power_manager_client_.reset(PowerManagerClient::Create(client_type,
                                                           system_bus_.get()));
    // Create the session manager client.
    session_manager_client_.reset(
        SessionManagerClient::Create(client_type, system_bus_.get()));
    // Create the speech synthesizer client.
    speech_synthesizer_client_.reset(
        SpeechSynthesizerClient::Create(client_type, system_bus_.get()));
    // Create the update engine client.
    update_engine_client_.reset(
        UpdateEngineClient::Create(client_type, system_bus_.get()));
  }

  virtual ~DBusThreadManagerImpl() {
    // Shut down the bus. During the browser shutdown, it's ok to shut down
    // the bus synchronously.
    system_bus_->ShutdownOnDBusThreadAndBlock();

    // Stop the D-Bus thread.
    dbus_thread_->Stop();
  }

  // DBusThreadManager override.
  virtual dbus::Bus* GetSystemBus() OVERRIDE {
    return system_bus_.get();
  }

  // DBusThreadManager override.
  virtual BluetoothAdapterClient* GetBluetoothAdapterClient() OVERRIDE {
    return bluetooth_adapter_client_.get();
  }

  // DBusThreadManager override.
  virtual BluetoothDeviceClient* GetBluetoothDeviceClient() OVERRIDE {
    return bluetooth_device_client_.get();
  }

  // DBusThreadManager override.
  virtual BluetoothInputClient* GetBluetoothInputClient() OVERRIDE {
    return bluetooth_input_client_.get();
  }

  // DBusThreadManager override.
  virtual BluetoothManagerClient* GetBluetoothManagerClient() OVERRIDE {
    return bluetooth_manager_client_.get();
  }

  // DBusThreadManager override.
  virtual BluetoothNodeClient* GetBluetoothNodeClient() OVERRIDE {
    return bluetooth_node_client_.get();
  }

  // DBusThreadManager override.
  virtual CashewClient* GetCashewClient() OVERRIDE {
    return cashew_client_.get();
  }

  // DBusThreadManager override.
  virtual CrosDisksClient* GetCrosDisksClient() OVERRIDE {
    return cros_disks_client_.get();
  }

  // DBusThreadManager override.
  virtual CryptohomeClient* GetCryptohomeClient() OVERRIDE {
    return cryptohome_client_.get();
  }

  // DBusThreadManager override.
  virtual DebugDaemonClient* GetDebugDaemonClient() OVERRIDE {
    return debugdaemon_client_.get();
  }

  // DBusThreadManager override.
  virtual FlimflamDeviceClient* GetFlimflamDeviceClient() OVERRIDE {
    return flimflam_device_client_.get();
  }

  // DBusThreadManager override.
  virtual FlimflamIPConfigClient* GetFlimflamIPConfigClient() OVERRIDE {
    return flimflam_ipconfig_client_.get();
  }

  // DBusThreadManager override.
  virtual FlimflamManagerClient* GetFlimflamManagerClient() OVERRIDE {
    return flimflam_manager_client_.get();
  }

  // DBusThreadManager override.
  virtual FlimflamNetworkClient* GetFlimflamNetworkClient() OVERRIDE {
    return flimflam_network_client_.get();
  }

  // DBusThreadManager override.
  virtual FlimflamProfileClient* GetFlimflamProfileClient() OVERRIDE {
    return flimflam_profile_client_.get();
  }

  // DBusThreadManager override.
  virtual FlimflamServiceClient* GetFlimflamServiceClient() OVERRIDE {
    return flimflam_service_client_.get();
  }

  // DBusThreadManager override.
  virtual GsmSMSClient* GetGsmSMSClient() OVERRIDE {
    return gsm_sms_client_.get();
  }

  // DBusThreadManager override.
  virtual ImageBurnerClient* GetImageBurnerClient() OVERRIDE {
    return image_burner_client_.get();
  }

  // DBusThreadManager override.
  virtual IntrospectableClient* GetIntrospectableClient() OVERRIDE {
    return introspectable_client_.get();
  }

  // DBusThreadManager override.
  virtual PowerManagerClient* GetPowerManagerClient() OVERRIDE {
    return power_manager_client_.get();
  }

  // DBusThreadManager override.
  virtual SessionManagerClient* GetSessionManagerClient() OVERRIDE {
    return session_manager_client_.get();
  }

  // DBusThreadManager override.
  virtual SpeechSynthesizerClient* GetSpeechSynthesizerClient() OVERRIDE {
    return speech_synthesizer_client_.get();
  }

  // DBusThreadManager override.
  virtual UpdateEngineClient* GetUpdateEngineClient() OVERRIDE {
    return update_engine_client_.get();
  }

  scoped_ptr<base::Thread> dbus_thread_;
  scoped_refptr<dbus::Bus> system_bus_;
  scoped_ptr<BluetoothAdapterClient> bluetooth_adapter_client_;
  scoped_ptr<BluetoothDeviceClient> bluetooth_device_client_;
  scoped_ptr<BluetoothInputClient> bluetooth_input_client_;
  scoped_ptr<BluetoothManagerClient> bluetooth_manager_client_;
  scoped_ptr<BluetoothNodeClient> bluetooth_node_client_;
  scoped_ptr<CashewClient> cashew_client_;
  scoped_ptr<CrosDisksClient> cros_disks_client_;
  scoped_ptr<CryptohomeClient> cryptohome_client_;
  scoped_ptr<DebugDaemonClient> debugdaemon_client_;
  scoped_ptr<FlimflamDeviceClient> flimflam_device_client_;
  scoped_ptr<FlimflamIPConfigClient> flimflam_ipconfig_client_;
  scoped_ptr<FlimflamManagerClient> flimflam_manager_client_;
  scoped_ptr<FlimflamNetworkClient> flimflam_network_client_;
  scoped_ptr<FlimflamProfileClient> flimflam_profile_client_;
  scoped_ptr<FlimflamServiceClient> flimflam_service_client_;
  scoped_ptr<GsmSMSClient> gsm_sms_client_;
  scoped_ptr<ImageBurnerClient> image_burner_client_;
  scoped_ptr<IntrospectableClient> introspectable_client_;
  scoped_ptr<PowerManagerClient> power_manager_client_;
  scoped_ptr<SessionManagerClient> session_manager_client_;
  scoped_ptr<SpeechSynthesizerClient> speech_synthesizer_client_;
  scoped_ptr<UpdateEngineClient> update_engine_client_;
};

// static
void DBusThreadManager::Initialize() {
  if (g_dbus_thread_manager) {
    LOG(WARNING) << "DBusThreadManager was already initialized";
    return;
  }
  g_dbus_thread_manager = new DBusThreadManagerImpl;
  VLOG(1) << "DBusThreadManager initialized";
}

// static
void DBusThreadManager::InitializeForTesting(
    DBusThreadManager* dbus_thread_manager) {
  if (g_dbus_thread_manager) {
    LOG(WARNING) << "DBusThreadManager was already initialized";
    return;
  }
  g_dbus_thread_manager = dbus_thread_manager;
  VLOG(1) << "DBusThreadManager initialized";
}

// static
void DBusThreadManager::Shutdown() {
  if (!g_dbus_thread_manager) {
    // TODO(satorux): Make it a DCHECK() once it's ready.
    LOG(WARNING) << "DBusThreadManager::Shutdown() called with NULL manager";
    return;
  }
  delete g_dbus_thread_manager;
  g_dbus_thread_manager = NULL;
  VLOG(1) << "DBusThreadManager Shutdown completed";
}

DBusThreadManager::DBusThreadManager() {
}

DBusThreadManager::~DBusThreadManager() {
}

// static
DBusThreadManager* DBusThreadManager::Get() {
  CHECK(g_dbus_thread_manager)
      << "DBusThreadManager::Get() called before Initialize()";
  return g_dbus_thread_manager;
}

}  // namespace chromeos


text:
package com.google.idea.common.experiments;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.truth.Truth.assertThat;

import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link ExperimentServiceImpl}. */
@RunWith(JUnit4.class)
public class ExperimentServiceImplTest {

  @Test
  public void testBooleanPropertyTrue() {
    ExperimentService experimentService =
        new ExperimentServiceImpl(new MapExperimentLoader("test.property", "1"));
    assertThat(experimentService.getExperiment("test.property", false)).isTrue();
  }

  @Test
  public void testBooleanPropertyFalse() {
    ExperimentService experimentService =
        new ExperimentServiceImpl(new MapExperimentLoader("test.property", "0"));
    assertThat(experimentService.getExperiment("test.property", true)).isFalse();
  }

  @Test
  public void testBooleanPropertyReturnsDefaultWhenMissing() {
    ExperimentService experimentService = new ExperimentServiceImpl(new MapExperimentLoader());
    assertThat(experimentService.getExperiment("test.notthere", true)).isTrue();
  }

  @Test
  public void testStringProperty() {
    ExperimentService experimentService =
        new ExperimentServiceImpl(new MapExperimentLoader("test.property", "hi"));
    assertThat(experimentService.getExperimentString("test.property", null)).isEqualTo("hi");
  }

  @Test
  public void testStringPropertyReturnsDefaultWhenMissing() {
    ExperimentService experimentService = new ExperimentServiceImpl(new MapExperimentLoader());
    assertThat(experimentService.getExperimentString("test.property", "bye")).isEqualTo("bye");
  }

  @Test
  public void testFirstLoaderOverridesSecond() {
    ExperimentService experimentService =
        new ExperimentServiceImpl(
            new MapExperimentLoader("test.property", "1"),
            new MapExperimentLoader("test.property", "0"));
    assertThat(experimentService.getExperiment("test.property", false)).isTrue();
  }

  @Test
  public void testOnlyInSecondLoader() {
    ExperimentService experimentService =
        new ExperimentServiceImpl(
            new MapExperimentLoader(), new MapExperimentLoader("test.property", "1"));
    assertThat(experimentService.getExperiment("test.property", false)).isTrue();
  }

  @Test
  public void testIntProperty() {
    ExperimentService experimentService =
        new ExperimentServiceImpl(new MapExperimentLoader("test.property", "10"));
    assertThat(experimentService.getExperimentInt("test.property", 0)).isEqualTo(10);
  }

  @Test
  public void testIntPropertyDefaultValue() {
    ExperimentService experimentService = new ExperimentServiceImpl(new MapExperimentLoader());
    assertThat(experimentService.getExperimentInt("test.property", 100)).isEqualTo(100);
  }

  @Test
  public void testIntPropertyThatDoesntParseReturnsDefaultValue() {
    ExperimentService experimentService =
        new ExperimentServiceImpl(new MapExperimentLoader("test.property", "hello"));
    assertThat(experimentService.getExperimentInt("test.property", 111)).isEqualTo(111);
  }

  @Test
  public void testDataIsReloadedWhenNotInAScope() throws Exception {
    MapExperimentLoader experimentLoader = new MapExperimentLoader();
    ExperimentService experimentService = new ExperimentServiceImpl(experimentLoader);
    assertThat(experimentService.getExperimentString("test.property", "default"))
        .isEqualTo("default");
    experimentLoader.map.put("test.property", "hello");
    assertThat(experimentService.getExperimentString("test.property", "default"))
        .isEqualTo("hello");
  }

  @Test
  public void testDataIsFrozenWheninAScope() throws Exception {
    MapExperimentLoader experimentLoader = new MapExperimentLoader();
    ExperimentService experimentService = new ExperimentServiceImpl(experimentLoader);
    experimentService.startExperimentScope();
    assertThat(experimentService.getExperimentString("test.property", "default"))
        .isEqualTo("default");
    experimentLoader.map.put("test.property", "hello");
    assertThat(experimentService.getExperimentString("test.property", "default"))
        .isEqualTo("default");
  }

  @Test
  public void testDataIsReloadedAgainWhenLeavingAScope() throws Exception {
    MapExperimentLoader experimentLoader = new MapExperimentLoader();
    ExperimentService experimentService = new ExperimentServiceImpl(experimentLoader);
    experimentService.startExperimentScope();
    assertThat(experimentService.getExperimentString("test.property", "default"))
        .isEqualTo("default");
    experimentLoader.map.put("test.property", "hello");
    experimentService.endExperimentScope();
    assertThat(experimentService.getExperimentString("test.property", "default"))
        .isEqualTo("hello");
  }

  @Test
  public void testEnterTwoScopesButOnlyLeaveOne() throws Exception {
    MapExperimentLoader experimentLoader = new MapExperimentLoader();
    ExperimentService experimentService = new ExperimentServiceImpl(experimentLoader);
    experimentService.startExperimentScope();
    assertThat(experimentService.getExperimentString("test.property", "default"))
        .isEqualTo("default");
    experimentService.startExperimentScope();
    experimentService.endExperimentScope();
    experimentLoader.map.put("test.property", "hello");
    assertThat(experimentService.getExperimentString("test.property", "default"))
        .isEqualTo("default");
  }

  @Test
  public void testEnterAndLeaveTwoScopes() throws Exception {
    MapExperimentLoader experimentLoader = new MapExperimentLoader();
    ExperimentService experimentService = new ExperimentServiceImpl(experimentLoader);
    experimentService.startExperimentScope();
    assertThat(experimentService.getExperimentString("test.property", "default"))
        .isEqualTo("default");
    experimentService.startExperimentScope();
    experimentService.endExperimentScope();
    experimentService.endExperimentScope();
    experimentLoader.map.put("test.property", "hello");
    assertThat(experimentService.getExperimentString("test.property", "default"))
        .isEqualTo("hello");
  }

  @Test
  public void testLeaveAndEnterRefreshes() throws Exception {
    MapExperimentLoader experimentLoader = new MapExperimentLoader();
    experimentLoader.map.put("test.property", "one");
    ExperimentService experimentService = new ExperimentServiceImpl(experimentLoader);
    experimentService.startExperimentScope();
    assertThat(experimentService.getExperimentString("test.property", "default")).isEqualTo("one");
    experimentLoader.map.put("test.property", "two");
    experimentService.endExperimentScope();
    experimentService.startExperimentScope();
    assertThat(experimentService.getExperimentString("test.property", "default")).isEqualTo("two");
  }

  private static class MapExperimentLoader extends HashingExperimentLoader {

    private final Map<String, String> map;

    private MapExperimentLoader(String... keysAndValues) {
      checkState(keysAndValues.length % 2 == 0);
      map = new HashMap<>();
      for (int i = 0; i < keysAndValues.length; i += 2) {
        map.put(keysAndValues[i], keysAndValues[i + 1]);
      }
    }

    @Override
    public Map<String, String> getUnhashedExperiments() {
      return map;
    }

    @Override
    public void initialize() {}
  }
}

redpajama_set_name: RedPajamaGithub


text:
package mars.venus;
import mars.*;
import mars.util.*;
import mars.simulator.*;
import mars.mips.hardware.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.table.*;
import javax.swing.event.*;

/**
  *  Sets up a window to display registers in the UI.
 *   @author Sanderson, Bumgarner
 **/

public class RegistersWindow extends JPanel implements Observer {
    private static JTable table;
    private static Register [] registers;
    private Object[][] tableData;
    private boolean highlighting;
    private int highlightRow;
    private ExecutePane executePane;
    private static final int NAME_COLUMN = 0;
    private static final int NUMBER_COLUMN = 1;
    private static final int VALUE_COLUMN = 2;
    private static Settings settings;
    /**
      *  Constructor which sets up a fresh window with a table that contains the register values.
      **/

    public RegistersWindow() {
        Simulator.getInstance().addObserver(this);
        settings = Globals.getSettings();
        this.highlighting = false;
        table = new MyTippedJTable(new RegTableModel(setupWindow()));
        table.getColumnModel().getColumn(NAME_COLUMN).setPreferredWidth(25);
        table.getColumnModel().getColumn(NUMBER_COLUMN).setPreferredWidth(25);
        table.getColumnModel().getColumn(VALUE_COLUMN).setPreferredWidth(60);
        // Display register values (String-ified) right-justified in mono font
        table.getColumnModel().getColumn(NAME_COLUMN).setCellRenderer(new RegisterCellRenderer(MonoRightCellRenderer.MONOSPACED_PLAIN_12POINT, SwingConstants.LEFT));
        table.getColumnModel().getColumn(NUMBER_COLUMN).setCellRenderer(new RegisterCellRenderer(MonoRightCellRenderer.MONOSPACED_PLAIN_12POINT, SwingConstants.RIGHT));
        table.getColumnModel().getColumn(VALUE_COLUMN).setCellRenderer(new RegisterCellRenderer(MonoRightCellRenderer.MONOSPACED_PLAIN_12POINT, SwingConstants.RIGHT));
        table.setPreferredScrollableViewportSize(new Dimension(200,700));
        this.setLayout(new BorderLayout()); // table display will occupy entire width if widened
        this.add(new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
    }

    /**
      *  Sets up the data for the window.
    *   @return The array object with the data for the window.
    **/

    public Object[][] setupWindow() {
        int valueBase = NumberDisplayBaseChooser.getBase(settings.getDisplayValuesInHex());
        tableData = new Object[35][3];
        registers = RegisterFile.getRegisters();
        for(int i=0; i< registers.length; i++) {
            tableData[i][0]= registers[i].getName();
            tableData[i][1]= new Integer(registers[i].getNumber());
            tableData[i][2]= NumberDisplayBaseChooser.formatNumber(registers[i].getValue(),valueBase);
        }
        tableData[32][0]= "pc";
        tableData[32][1]= "";//new Integer(32);
        tableData[32][2]= NumberDisplayBaseChooser.formatUnsignedInteger(RegisterFile.getProgramCounter(),valueBase);

        tableData[33][0]= "hi";
        tableData[33][1]= "";//new Integer(33);
        tableData[33][2]= NumberDisplayBaseChooser.formatNumber(RegisterFile.getValue(33),valueBase);

        tableData[34][0]= "lo";
        tableData[34][1]= "";//new Integer(34);
        tableData[34][2]= NumberDisplayBaseChooser.formatNumber(RegisterFile.getValue(34),valueBase);

        return tableData;
    }
    /**
    *  clear and redisplay registers
    */
    public void clearWindow() {
        this.clearHighlighting();
        RegisterFile.resetRegisters();
        this.updateRegisters(Globals.getGui().getMainPane().getExecutePane().getValueDisplayBase());
    }

    /**
     * Clear highlight background color from any cell currently highlighted.
     */
    public void clearHighlighting() {
        highlighting=false;
        if (table != null) {
            table.tableChanged(new TableModelEvent(table.getModel()));
        }
        highlightRow = -1; // assure highlight will not occur upon re-assemble.
    }

    /**
     * Refresh the table, triggering re-rendering.
     */
    public void refresh() {
        if (table != null) {
            table.tableChanged(new TableModelEvent(table.getModel()));
        }
    }

    /**
     * update register display using current number base (10 or 16)
     */
    public void updateRegisters() {
        updateRegisters(Globals.getGui().getMainPane().getExecutePane().getValueDisplayBase());
    }

    /**
     * update register display using specified number base (10 or 16)
     *
     * @param base desired number base
     */
    public void updateRegisters(int base) {
        registers = RegisterFile.getRegisters();
        for(int i=0; i< registers.length; i++) {
            updateRegisterValue(registers[i].getNumber(), registers[i].getValue(), base);
        }
        updateRegisterUnsignedValue(32, RegisterFile.getProgramCounter(), base);
        updateRegisterValue(33, RegisterFile.getValue(33), base);
        updateRegisterValue(34, RegisterFile.getValue(34), base);
    }

    /**
      *  This method handles the updating of the GUI.
    *   @param number The number of the register to update.
    *   @param val New value.
    **/

    public void updateRegisterValue(int number,int val, int base) {
        ((RegTableModel)table.getModel()).setDisplayAndModelValueAt(NumberDisplayBaseChooser.formatNumber(val,base), number, 2);
    }

    private void updateRegisterUnsignedValue(int number,int val, int base) {
        ((RegTableModel)table.getModel()).setDisplayAndModelValueAt(NumberDisplayBaseChooser.formatUnsignedInteger(val,base), number, 2);
    }

    /** Required by Observer interface.  Called when notified by an Observable that we are registered with.
    * Observables include:
    *   The Simulator object, which lets us know when it starts and stops running
    *   A register object, which lets us know of register operations
    * The Simulator keeps us informed of when simulated MIPS execution is active.
    * This is the only time we care about register operations.
    * @param observable The Observable object who is notifying us
    * @param obj Auxiliary object with additional information.
    */
    public void update(Observable observable, Object obj) {
        if (observable == mars.simulator.Simulator.getInstance()) {
            SimulatorNotice notice = (SimulatorNotice) obj;
            if (notice.getAction()==SimulatorNotice.SIMULATOR_START) {
                // Simulated MIPS execution starts.  Respond to memory changes if running in timed
                // or stepped mode.
                if (notice.getRunSpeed() != RunSpeedPanel.UNLIMITED_SPEED || notice.getMaxSteps()==1) {
                    RegisterFile.addRegistersObserver(this);
                    this.highlighting = true;
                }
            } else {
                // Simulated MIPS execution stops.  Stop responding.
                RegisterFile.deleteRegistersObserver(this);
            }
        } else if (obj instanceof RegisterAccessNotice) {
            // NOTE: each register is a separate Observable
            RegisterAccessNotice access = (RegisterAccessNotice) obj;
            if (access.getAccessType()==AccessNotice.WRITE) {
                // Uses the same highlighting technique as for Text Segment -- see
                // AddressCellRenderer class in DataSegmentWindow.java.
                this.highlighting = true;
                this.highlightCellForRegister((Register)observable);
                Globals.getGui().getRegistersPane().setSelectedComponent(this);
            }
        }
    }

    /**
     *  Highlight the row corresponding to the given register.
    *  @param register Register object corresponding to row to be selected.
    */
    void highlightCellForRegister(Register register) {
        this.highlightRow = register.getNumber();
        // Tell the system that table contents have changed.  This will trigger re-rendering
        // during which cell renderers are obtained.  The row of interest (identified by
        // instance variabls this.registerRow) will get a renderer
        // with highlight background color and all others get renderer with default background.
        table.tableChanged(new TableModelEvent(table.getModel()));
    }

    /*
    * Cell renderer for displaying register entries.  This does highlighting, so if you
    * don't want highlighting for a given column, don't use this.  Currently we highlight
    * all columns.
    */
    private class RegisterCellRenderer extends DefaultTableCellRenderer {
        private Font font;
        private int alignment;

        public RegisterCellRenderer(Font font, int alignment) {
            super();
            this.font = font;
            this.alignment = alignment;
        }

        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            JLabel cell = (JLabel) super.getTableCellRendererComponent(table, value,
                          isSelected, hasFocus, row, column);
            cell.setFont(font);
            cell.setHorizontalAlignment(alignment);
            if (settings.getRegistersHighlighting() && highlighting && row==highlightRow) {
                cell.setBackground( settings.getColorSettingByPosition(Settings.REGISTER_HIGHLIGHT_BACKGROUND) );
                cell.setForeground( settings.getColorSettingByPosition(Settings.REGISTER_HIGHLIGHT_FOREGROUND) );
                cell.setFont( settings.getFontByPosition(Settings.REGISTER_HIGHLIGHT_FONT) );
            } else if (row%2==0) {
                cell.setBackground( settings.getColorSettingByPosition(Settings.EVEN_ROW_BACKGROUND) );
                cell.setForeground( settings.getColorSettingByPosition(Settings.EVEN_ROW_FOREGROUND) );
                cell.setFont( settings.getFontByPosition(Settings.EVEN_ROW_FONT) );
            } else {
                cell.setBackground( settings.getColorSettingByPosition(Settings.ODD_ROW_BACKGROUND) );
                cell.setForeground( settings.getColorSettingByPosition(Settings.ODD_ROW_FOREGROUND) );
                cell.setFont( settings.getFontByPosition(Settings.ODD_ROW_FONT) );
            }
            return cell;
        }
    }

    ////////////////////////////////////////////////////////////////////////////

    class RegTableModel extends AbstractTableModel {
        final String[] columnNames =  {"Name", "Number", "Value"};
        Object[][] data;

        public RegTableModel(Object[][] d) {
            data=d;
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.
        */
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        /*
        * Don't need to implement this method unless your table's
        * editable.
        */
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            // these registers are not editable: $zero (0), $pc (32), $ra (31)
            if (col == VALUE_COLUMN && row != 0 && row != 32 && row != 31) {
                return true;
            } else {
                return false;
            }
        }

        /*
         * Update cell contents in table model.  This method should be called
        * only when user edits cell, so input validation has to be done.  If
        * value is valid, MIPS register is updated.
         */
        public void setValueAt(Object value, int row, int col) {
            int val=0;
            try {
                val = Binary.stringToInt((String) value);
            } catch (NumberFormatException nfe) {
                data[row][col] = "INVALID";
                fireTableCellUpdated(row, col);
                return;
            }
            //  Assures that if changed during MIPS program execution, the update will
            //  occur only between MIPS instructions.
            synchronized (Globals.memoryAndRegistersLock) {
                RegisterFile.updateRegister(row, val);
            }
            int valueBase = Globals.getGui().getMainPane().getExecutePane().getValueDisplayBase();
            data[row][col] = NumberDisplayBaseChooser.formatNumber(val, valueBase);
            fireTableCellUpdated(row, col);
            return;
        }

        /**
         * Update cell contents in table model.  Does not affect MIPS register.
         */
        private void setDisplayAndModelValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
        }

        // handy for debugging....
        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();

            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + data[i][j]);
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }
    }

    ///////////////////////////////////////////////////////////////////
    //
    // JTable subclass to provide custom tool tips for each of the
    // register table column headers and for each register name in
    // the first column. From Sun's JTable tutorial.
    // http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    //
    private class MyTippedJTable extends JTable {
        MyTippedJTable(RegTableModel m) {
            super(m);
            this.setRowSelectionAllowed(true); // highlights background color of entire row
            this.setSelectionBackground(Color.GREEN);
        }

        private String[] regToolTips = {
            /* $zero */  "constant 0",
            /* $at   */  "reserved for assembler",
            /* $v0   */  "expression evaluation and results of a function",
            /* $v1   */  "expression evaluation and results of a function",
            /* $a0   */  "argument 1",
            /* $a1   */  "argument 2",
            /* $a2   */  "argument 3",
            /* $a3   */  "argument 4",
            /* $t0   */  "temporary (not preserved across call)",
            /* $t1   */  "temporary (not preserved across call)",
            /* $t2   */  "temporary (not preserved across call)",
            /* $t3   */  "temporary (not preserved across call)",
            /* $t4   */  "temporary (not preserved across call)",
            /* $t5   */  "temporary (not preserved across call)",
            /* $t6   */  "temporary (not preserved across call)",
            /* $t7   */  "temporary (not preserved across call)",
            /* $s0   */  "saved temporary (preserved across call)",
            /* $s1   */  "saved temporary (preserved across call)",
            /* $s2   */  "saved temporary (preserved across call)",
            /* $s3   */  "saved temporary (preserved across call)",
            /* $s4   */  "saved temporary (preserved across call)",
            /* $s5   */  "saved temporary (preserved across call)",
            /* $s6   */  "saved temporary (preserved across call)",
            /* $s7   */  "saved temporary (preserved across call)",
            /* $t8   */  "temporary (not preserved across call)",
            /* $t9   */  "temporary (not preserved across call)",
            /* $k0   */  "reserved for OS kernel",
            /* $k1   */  "reserved for OS kernel",
            /* $gp   */  "pointer to global area",
            /* $sp   */  "stack pointer",
            /* $fp   */  "frame pointer",
            /* $ra   */  "return address (used by function call)",
            /* pc    */  "program counter",
            /* hi    */  "high-order word of multiply product, or divide remainder",
            /* lo    */  "low-order word of multiply product, or divide quotient"
        };

        //Implement table cell tool tips.
        public String getToolTipText(MouseEvent e) {
            String tip = null;
            java.awt.Point p = e.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColumnIndex = convertColumnIndexToModel(colIndex);
            if (realColumnIndex == NAME_COLUMN) { //Register name column
                tip = regToolTips[rowIndex];
                /* You can customize each tip to encorporiate cell contents if you like:
                   TableModel model = getModel();
                   String regName = (String)model.getValueAt(rowIndex,0);
                	....... etc .......
                */
            } else {
                //You can omit this part if you know you don't have any
                //renderers that supply their own tool tips.
                tip = super.getToolTipText(e);
            }
            return tip;
        }

        private String[] columnToolTips = {
            /* name */   "Each register has a tool tip describing its usage convention",
            /* number */ "Corresponding register number",
            /* value */  "Current 32 bit value"
        };

        //Implement table header tool tips.
        protected JTableHeader createDefaultTableHeader() {
            return
            new JTableHeader(columnModel) {
                public String getToolTipText(MouseEvent e) {
                    String tip = null;
                    java.awt.Point p = e.getPoint();
                    int index = columnModel.getColumnIndexAtX(p.x);
                    int realIndex = columnModel.getColumn(index).getModelIndex();
                    return columnToolTips[realIndex];
                }
            };
        }
    }

}