CS计算机代考程序代写 SQL scheme mips data structure database compiler cache simulator Java file system gui flex F# c# cache assembly assembler algorithm interpreter META-INF/MANIFEST.MF

META-INF/MANIFEST.MF

PseudoOps.txt

Config.properties

Syscall.properties

Settings.properties

MARSlicense.txt

mainclass.txt

CreateMarsJar.bat

Mars.java

Mars.class

docs/constant-values.html

docs/overview-tree.html

docs/index.html

docs/.DS_Store

docs/Mars.html

docs/overview-frame.html

docs/allclasses-noframe.html

docs/serialized-form.html

docs/index-all.html

docs/resources/inherit.gif

docs/deprecated-list.html

docs/package-frame.html

docs/stylesheet.css

docs/overview-summary.html

docs/help-doc.html

docs/package-summary.html

docs/allclasses-frame.html

docs/package-list

docs/package-tree.html

docs/mars/tools/IntroToTools.html

docs/mars/tools/DigitalLabSim.html

docs/mars/tools/FloatRepresentation.html

docs/mars/tools/BHTSimulator.html

docs/mars/tools/KeyboardAndDisplaySimulator.html

docs/mars/tools/InstructionStatistics.html

docs/mars/tools/DigitalLabSim.SevenSegmentPanel.html

docs/mars/tools/InstructionCounter.html

docs/mars/tools/MarsBot.html

docs/mars/tools/CacheSimulator.html

docs/mars/tools/DigitalLabSim.HexaKeyboard.EcouteurClick.html

docs/mars/tools/ScreenMagnifier.html

docs/mars/tools/AbstractMarsToolAndApplication.ConnectButton.html

docs/mars/tools/DigitalLabSim.SevenSegmentDisplay.html

docs/mars/tools/MemoryReferenceVisualization.html

docs/mars/tools/MarsTool.html

docs/mars/tools/package-frame.html

docs/mars/tools/BHTSimGUI.html

docs/mars/tools/BHTableModel.html

docs/mars/tools/package-summary.html

docs/mars/tools/AbstractMarsToolAndApplication.html

docs/mars/tools/package-tree.html

docs/mars/tools/ScavengerHunt.html

docs/mars/tools/DigitalLabSim.OneSecondCounter.html

docs/mars/tools/BHTEntry.html

docs/mars/tools/AbstractMarsToolAndApplication.EnterKeyListener.html

docs/mars/tools/BitmapDisplay.html

docs/mars/tools/DigitalLabSim.HexaKeyboard.html

docs/mars/assembler/MacroPool.html

docs/mars/assembler/Directives.html

docs/mars/assembler/SourceLine.html

docs/mars/assembler/SymbolTable.html

docs/mars/assembler/TokenTypes.html

docs/mars/assembler/OperandFormat.html

docs/mars/assembler/TokenList.html

docs/mars/assembler/TranslationCode.html

docs/mars/assembler/package-frame.html

docs/mars/assembler/Assembler.html

docs/mars/assembler/Tokenizer.html

docs/mars/assembler/Symbol.html

docs/mars/assembler/package-summary.html

docs/mars/assembler/Macro.html

docs/mars/assembler/DataTypes.html

docs/mars/assembler/package-tree.html

docs/mars/assembler/Token.html

docs/mars/util/PropertiesFile.html

docs/mars/util/Binary.html

docs/mars/util/FilenameFinder.html

docs/mars/util/package-frame.html

docs/mars/util/EditorFont.html

docs/mars/util/package-summary.html

docs/mars/util/package-tree.html

docs/mars/util/SystemIO.html

docs/mars/util/MemoryDump.html

docs/mars/MarsSplashScreen.html

docs/mars/venus/FileStatus.html

docs/mars/venus/SettingsAssembleAllAction.html

docs/mars/venus/FilePrintAction.html

docs/mars/venus/FileExitAction.html

docs/mars/venus/EditSelectAllAction.html

docs/mars/venus/RunToggleBreakpointsAction.html

docs/mars/venus/HelpAboutAction.html

docs/mars/venus/TextSegmentWindow.html

docs/mars/venus/RunGoAction.html

docs/mars/venus/ToolAction.html

docs/mars/venus/Coprocessor1Window.html

docs/mars/venus/DataSegmentWindow.html

docs/mars/venus/FileNewAction.html

docs/mars/venus/RunAssembleAction.html

docs/mars/venus/EditRedoAction.html

docs/mars/venus/SettingsStartAtMainAction.html

docs/mars/venus/EditTabbedPane.html

docs/mars/venus/HardcopyWriter.html

docs/mars/venus/SettingsEditorAction.html

docs/mars/venus/SettingsMemoryConfigurationAction.html

docs/mars/venus/SettingsAddressDisplayBaseAction.html

docs/mars/venus/RunResetAction.html

docs/mars/venus/EditPasteAction.html

docs/mars/venus/FileOpenAction.html

docs/mars/venus/RunPauseAction.html

docs/mars/venus/editors/package-frame.html

docs/mars/venus/editors/jeditsyntax/TextAreaPainter.html

docs/mars/venus/editors/jeditsyntax/InputHandler.next_line.html

docs/mars/venus/editors/jeditsyntax/InputHandler.overwrite.html

docs/mars/venus/editors/jeditsyntax/SyntaxDocument.html

docs/mars/venus/editors/jeditsyntax/InputHandler.backspace_word.html

docs/mars/venus/editors/jeditsyntax/KeywordMap.html

docs/mars/venus/editors/jeditsyntax/InputHandler.prev_page.html

docs/mars/venus/editors/jeditsyntax/InputHandler.insert_tab.html

docs/mars/venus/editors/jeditsyntax/JEditTextArea.html

docs/mars/venus/editors/jeditsyntax/InputHandler.repeat.html

docs/mars/venus/editors/jeditsyntax/InputHandler.end.html

docs/mars/venus/editors/jeditsyntax/InputHandler.prev_word.html

docs/mars/venus/editors/jeditsyntax/TextAreaPainter.Highlight.html

docs/mars/venus/editors/jeditsyntax/InputHandler.backspace.html

docs/mars/venus/editors/jeditsyntax/JEditBasedTextArea.html

docs/mars/venus/editors/jeditsyntax/PopupHelpItem.html

docs/mars/venus/editors/jeditsyntax/DefaultInputHandler.html

docs/mars/venus/editors/jeditsyntax/tokenmarker/TokenMarker.html

docs/mars/venus/editors/jeditsyntax/tokenmarker/MIPSTokenMarker.html

docs/mars/venus/editors/jeditsyntax/tokenmarker/package-frame.html

docs/mars/venus/editors/jeditsyntax/tokenmarker/package-summary.html

docs/mars/venus/editors/jeditsyntax/tokenmarker/TokenMarker.LineInfo.html

docs/mars/venus/editors/jeditsyntax/tokenmarker/package-tree.html

docs/mars/venus/editors/jeditsyntax/tokenmarker/Token.html

docs/mars/venus/editors/jeditsyntax/InputHandler.NonRepeatable.html

docs/mars/venus/editors/jeditsyntax/InputHandler.next_char.html

docs/mars/venus/editors/jeditsyntax/InputHandler.prev_char.html

docs/mars/venus/editors/jeditsyntax/InputHandler.clip_paste.html

docs/mars/venus/editors/jeditsyntax/InputHandler.html

docs/mars/venus/editors/jeditsyntax/InputHandler.clip_copy.html

docs/mars/venus/editors/jeditsyntax/TextAreaDefaults.html

docs/mars/venus/editors/jeditsyntax/package-frame.html

docs/mars/venus/editors/jeditsyntax/SyntaxStyle.html

docs/mars/venus/editors/jeditsyntax/InputHandler.insert_break.html

docs/mars/venus/editors/jeditsyntax/package-summary.html

docs/mars/venus/editors/jeditsyntax/InputHandler.select_all.html

docs/mars/venus/editors/jeditsyntax/InputHandler.delete_word.html

docs/mars/venus/editors/jeditsyntax/TextUtilities.html

docs/mars/venus/editors/jeditsyntax/InputHandler.next_word.html

docs/mars/venus/editors/jeditsyntax/package-tree.html

docs/mars/venus/editors/jeditsyntax/SyntaxUtilities.html

docs/mars/venus/editors/jeditsyntax/InputHandler.Wrapper.html

docs/mars/venus/editors/jeditsyntax/InputHandler.next_page.html

docs/mars/venus/editors/jeditsyntax/InputHandler.prev_line.html

docs/mars/venus/editors/jeditsyntax/InputHandler.MacroRecorder.html

docs/mars/venus/editors/jeditsyntax/InputHandler.document_home.html

docs/mars/venus/editors/jeditsyntax/InputHandler.delete.html

docs/mars/venus/editors/jeditsyntax/InputHandler.home.html

docs/mars/venus/editors/jeditsyntax/InputHandler.insert_char.html

docs/mars/venus/editors/jeditsyntax/InputHandler.clip_cut.html

docs/mars/venus/editors/jeditsyntax/InputHandler.NonRecordable.html

docs/mars/venus/editors/jeditsyntax/InputHandler.toggle_rect.html

docs/mars/venus/editors/jeditsyntax/InputHandler.document_end.html

docs/mars/venus/editors/package-summary.html

docs/mars/venus/editors/generic/package-frame.html

docs/mars/venus/editors/generic/package-summary.html

docs/mars/venus/editors/generic/package-tree.html

docs/mars/venus/editors/generic/GenericTextArea.html

docs/mars/venus/editors/package-tree.html

docs/mars/venus/editors/MARSTextEditingArea.html

docs/mars/venus/RegistersWindow.html

docs/mars/venus/EditUndoAction.html

docs/mars/venus/FileSaveAction.html

docs/mars/venus/PopupListener.html

docs/mars/venus/SettingsExtendedAction.html

docs/mars/venus/EditFindReplaceAction.html

docs/mars/venus/Editor.html

docs/mars/venus/FileCloseAllAction.html

docs/mars/venus/SettingsLabelAction.html

docs/mars/venus/SettingsDelayedBranchingAction.html

docs/mars/venus/HardcopyWriter.PrintCanceledException.html

docs/mars/venus/ExecutePane.html

docs/mars/venus/RunClearBreakpointsAction.html

docs/mars/venus/Coprocessor0Window.html

docs/mars/venus/RegistersPane.html

docs/mars/venus/package-frame.html

docs/mars/venus/HelpHelpAction.html

docs/mars/venus/EditCutAction.html

docs/mars/venus/FileDumpMemoryAction.html

docs/mars/venus/package-summary.html

docs/mars/venus/RepeatButton.html

docs/mars/venus/EditCopyAction.html

docs/mars/venus/FileSaveAllAction.html

docs/mars/venus/MessagesPane.html

docs/mars/venus/SettingsWarningsAreErrorsAction.html

docs/mars/venus/NumberDisplayBaseChooser.html

docs/mars/venus/RunStepAction.html

docs/mars/venus/SettingsHighlightingAction.html

docs/mars/venus/EditPane.html

docs/mars/venus/ToolLoader.html

docs/mars/venus/SettingsProgramArgumentsAction.html

docs/mars/venus/package-tree.html

docs/mars/venus/RunSpeedPanel.html

docs/mars/venus/GuiAction.html

docs/mars/venus/FileSaveAsAction.html

docs/mars/venus/VenusUI.html

docs/mars/venus/MainPane.html

docs/mars/venus/RunBackstepAction.html

docs/mars/venus/FileCloseAction.html

docs/mars/venus/SettingsPopupInputAction.html

docs/mars/venus/RunStopAction.html

docs/mars/venus/SettingsAssembleOnOpenAction.html

docs/mars/venus/SettingsExceptionHandlerAction.html

docs/mars/venus/SettingsValueDisplayBaseAction.html

docs/mars/venus/AbstractFontSettingDialog.html

docs/mars/venus/LabelsWindow.html

docs/mars/ProcessingException.html

docs/mars/ErrorList.html

docs/mars/mips/instructions/SimulationCode.html

docs/mars/mips/instructions/ExtendedInstruction.html

docs/mars/mips/instructions/package-frame.html

docs/mars/mips/instructions/BasicInstructionFormat.html

docs/mars/mips/instructions/package-summary.html

docs/mars/mips/instructions/package-tree.html

docs/mars/mips/instructions/Instruction.html

docs/mars/mips/instructions/InstructionSet.html

docs/mars/mips/instructions/syscalls/SyscallPrintString.html

docs/mars/mips/instructions/syscalls/SyscallPrintIntBinary.html

docs/mars/mips/instructions/syscalls/SyscallMidiOut.html

docs/mars/mips/instructions/syscalls/SyscallMessageDialogInt.html

docs/mars/mips/instructions/syscalls/SyscallExit.html

docs/mars/mips/instructions/syscalls/SyscallInputDialogInt.html

docs/mars/mips/instructions/syscalls/SyscallReadFloat.html

docs/mars/mips/instructions/syscalls/SyscallOpen.html

docs/mars/mips/instructions/syscalls/SyscallReadChar.html

docs/mars/mips/instructions/syscalls/SyscallMessageDialog.html

docs/mars/mips/instructions/syscalls/SyscallPrintFloat.html

docs/mars/mips/instructions/syscalls/SyscallSbrk.html

docs/mars/mips/instructions/syscalls/SyscallRandDouble.html

docs/mars/mips/instructions/syscalls/SyscallPrintIntUnsigned.html

docs/mars/mips/instructions/syscalls/SyscallMessageDialogString.html

docs/mars/mips/instructions/syscalls/AbstractSyscall.html

docs/mars/mips/instructions/syscalls/SyscallInputDialogFloat.html

docs/mars/mips/instructions/syscalls/RandomStreams.html

docs/mars/mips/instructions/syscalls/SyscallInputDialogString.html

docs/mars/mips/instructions/syscalls/SyscallReadString.html

docs/mars/mips/instructions/syscalls/SyscallPrintChar.html

docs/mars/mips/instructions/syscalls/SyscallRandIntRange.html

docs/mars/mips/instructions/syscalls/Syscall.html

docs/mars/mips/instructions/syscalls/SyscallTime.html

docs/mars/mips/instructions/syscalls/SyscallRandSeed.html

docs/mars/mips/instructions/syscalls/SyscallPrintIntHex.html

docs/mars/mips/instructions/syscalls/package-frame.html

docs/mars/mips/instructions/syscalls/SyscallPrintInt.html

docs/mars/mips/instructions/syscalls/SyscallMessageDialogDouble.html

docs/mars/mips/instructions/syscalls/SyscallConfirmDialog.html

docs/mars/mips/instructions/syscalls/package-summary.html

docs/mars/mips/instructions/syscalls/SyscallReadInt.html

docs/mars/mips/instructions/syscalls/SyscallExit2.html

docs/mars/mips/instructions/syscalls/SyscallReadDouble.html

docs/mars/mips/instructions/syscalls/SyscallInputDialogDouble.html

docs/mars/mips/instructions/syscalls/SyscallMessageDialogFloat.html

docs/mars/mips/instructions/syscalls/SyscallWrite.html

docs/mars/mips/instructions/syscalls/package-tree.html

docs/mars/mips/instructions/syscalls/SyscallSleep.html

docs/mars/mips/instructions/syscalls/SyscallClose.html

docs/mars/mips/instructions/syscalls/SyscallRandInt.html

docs/mars/mips/instructions/syscalls/SyscallPrintDouble.html

docs/mars/mips/instructions/syscalls/SyscallRead.html

docs/mars/mips/instructions/syscalls/SyscallRandFloat.html

docs/mars/mips/instructions/syscalls/SyscallNumberOverride.html

docs/mars/mips/instructions/syscalls/SyscallMidiOutSync.html

docs/mars/mips/instructions/BasicInstruction.html

docs/mars/mips/hardware/Coprocessor0.html

docs/mars/mips/hardware/Coprocessor1.html

docs/mars/mips/hardware/AccessNotice.html

docs/mars/mips/hardware/MemoryConfiguration.html

docs/mars/mips/hardware/Register.html

docs/mars/mips/hardware/MemoryAccessNotice.html

docs/mars/mips/hardware/MemoryConfigurations.html

docs/mars/mips/hardware/AddressErrorException.html

docs/mars/mips/hardware/package-frame.html

docs/mars/mips/hardware/InvalidRegisterAccessException.html

docs/mars/mips/hardware/package-summary.html

docs/mars/mips/hardware/Memory.html

docs/mars/mips/hardware/RegisterAccessNotice.html

docs/mars/mips/hardware/package-tree.html

docs/mars/mips/hardware/RegisterFile.html

docs/mars/mips/dump/AsciiTextDumpFormat.html

docs/mars/mips/dump/BinaryTextDumpFormat.html

docs/mars/mips/dump/MIFDumpFormat.html

docs/mars/mips/dump/DumpFormat.html

docs/mars/mips/dump/package-frame.html

docs/mars/mips/dump/SegmentWindowDumpFormat.html

docs/mars/mips/dump/DumpFormatLoader.html

docs/mars/mips/dump/package-summary.html

docs/mars/mips/dump/package-tree.html

docs/mars/mips/dump/AbstractDumpFormat.html

docs/mars/mips/dump/BinaryDumpFormat.html

docs/mars/mips/dump/HexTextDumpFormat.html

docs/mars/mips/dump/IntelHexDumpFormat.html

docs/mars/package-frame.html

docs/mars/ErrorMessage.html

docs/mars/simulator/BackStepper.html

docs/mars/simulator/Exceptions.html

docs/mars/simulator/package-frame.html

docs/mars/simulator/Simulator.StopListener.html

docs/mars/simulator/Simulator.html

docs/mars/simulator/SimulatorNotice.html

docs/mars/simulator/package-summary.html

docs/mars/simulator/SwingWorker.html

docs/mars/simulator/ProgramArgumentList.html

docs/mars/simulator/package-tree.html

docs/mars/simulator/DelayedBranch.html

docs/mars/package-summary.html

docs/mars/ProgramStatement.html

docs/mars/MarsLaunch.html

docs/mars/package-tree.html

docs/mars/MIPSprogram.html

docs/mars/Settings.html

docs/mars/Globals.html

help/SyscallMessageDialogQuestion.gif

help/MacrosHelp.html

help/SyscallMessageDialogInformation.gif

help/MarsHelpLimits.html

help/MarsHelpSettings.html

help/ExceptionsHelp.html

help/SyscallMessageDialogError.gif

help/MarsHelpIDE.html

help/MarsHelpIntro.html

help/MarsHelpDebugging.html

help/BugReportingHelp.html

help/MarsHelpCommand.html

help/MarsHelpTools.html

help/MarsHelpHistory.html

help/MIPSInstructionSetSong.html

help/SyscallMessageDialogWarning.gif

help/mipsref.pdf

help/SyscallHelp.html

help/Acknowledgements.html

images/Copy22.png

images/game_gold.png

images/StepBack16.png

images/Cut22.gif

images/mars32.ico

images/Find22.png

images/Undo22.png

images/Redo22.png

images/Paste16.png

images/.DS_Store

images/Play16.png

images/Cut24.gif

images/Stop22.png

images/MyBlank16.gif

images/StepForward16.png

images/game_dynamite.png

images/Pause16.png

images/Reset16.png

images/Open22.png

images/Save22.png

images/Print24.gif

images/SaveAs22.png

images/RedMars16.gif

images/Assemble16.png

images/Help16.png

images/Dump16.png

images/New22.png

images/Print22.gif

images/Pause22.png

images/Previous22.png

images/game_rock.png

images/Save16.png

images/RedMars32.GIF

images/Reset22.png

images/Open16.png

images/game_gem.png

images/Help22.png

images/mars.ico

images/Assemble22.png

images/Edit_tab.jpg

images/SaveAs16.png

images/Print16.gif

images/New16.png

images/Dump22.png

images/game_hook.png

images/MarsSurfacePathfinder.jpg

images/Undo16.png

images/Find16.png

images/game_bg.png

images/MyBlank24.gif

images/Cut16.gif

images/StepBack22.png

images/Copy16.png

images/Redo16.png

images/RedMars50.gif

images/MarsThumbnail.gif

images/StepForward22.png

images/Stop16.png

images/Play22.png

images/Paste22.png

images/Next22.png

images/Execute_tab.jpg

mars/tools/DigitalLabSim.java

mars/tools/AbstractMarsToolAndApplication$MessageField.class

mars/tools/IntroToTools.java

mars/tools/MemoryReferenceVisualization$8.class

mars/tools/CacheSimulator$5.class

mars/tools/MemoryReferenceVisualization$ColorChooserControls$1.class

mars/tools/AbstractMarsToolAndApplication$CreateAssembleRunMIPSprogram.class

mars/tools/BitmapDisplay$4.class

mars/tools/FloatRepresentation$InstructionsPane.class

mars/tools/AbstractMarsToolAndApplication$1.class

mars/tools/FloatRepresentation.java

mars/tools/AbstractMarsToolAndApplication$3.class

mars/tools/BitmapDisplay$6.class

mars/tools/FloatRepresentation$1.class

mars/tools/ScavengerHunt$ScavengerHuntDisplay.class

mars/tools/AbstractMarsToolAndApplication$MessageField$MessageWriter.class

mars/tools/KeyboardAndDisplaySimulator.class

mars/tools/AbstractMarsToolAndApplication.class

mars/tools/MarsBot$BotRunnable.class

mars/tools/BHTSimulator.java

mars/tools/AbstractMarsToolAndApplication$EnterKeyListener.class

mars/tools/KeyboardAndDisplaySimulator.java

mars/tools/CacheSimulator$3.class

mars/tools/KeyboardAndDisplaySimulator$2.class

mars/tools/ScribblerSettings.class

mars/tools/CacheSimulator.class

mars/tools/InstructionStatistics.java

mars/tools/BitmapDisplay$2.class

mars/tools/AbstractMarsToolAndApplication$7.class

mars/tools/CacheSimulator$CacheAccessResult.class

mars/tools/ScavengerHunt$PlayerData.class

mars/tools/AbstractMarsToolAndApplication$5.class

mars/tools/CacheSimulator$AbstractCache.class

mars/tools/CacheSimulator$Animation.class

mars/tools/CacheSimulator$1.class

mars/tools/CacheSimulator$AnyCache.class

mars/tools/FloatRepresentation$HexToBinaryGraphicPanel.class

mars/tools/MagnifierImage$Scribbler.class

mars/tools/KeyboardAndDisplaySimulator$FontChanger.class

mars/tools/AbstractMarsToolAndApplication$2.class

mars/tools/BitmapDisplay.class

mars/tools/AbstractMarsToolAndApplication$10.class

mars/tools/AbstractMarsToolAndApplication$GUIUpdater.class

mars/tools/CacheSimulator$CacheBlock.class

mars/tools/CacheSimulator$4.class

mars/tools/InstructionCounter.java

mars/tools/IntroToTools.class

mars/tools/FloatRepresentation$BinaryFractionDisplayTextField.class

mars/tools/KeyboardAndDisplaySimulator$TransmitterDelayTechnique.class

mars/tools/BitmapDisplay$5.class

mars/tools/CacheSimulator.java

mars/tools/MarsBot.java

mars/tools/MarsTool.class

mars/tools/AbstractMarsToolAndApplication$4.class

mars/tools/BitmapDisplay$1.class

mars/tools/CaptureDisplayAlignmentStrategy.class

mars/tools/InstructionStatistics.class

mars/tools/FloatRepresentation$DecimalDisplayKeystokeListenter.class

mars/tools/DigitalLabSim$SevenSegmentPanel.class

mars/tools/KeyboardAndDisplaySimulator$1.class

mars/tools/FloatRepresentation$BinaryDisplayKeystrokeListener.class

mars/tools/KeyboardAndDisplaySimulator$NormallyDistributedDelay.class

mars/tools/KeyboardAndDisplaySimulator$DelayLengthPanel$DelayLengthListener.class

mars/tools/SettingsDialog.class

mars/tools/ScreenMagnifier.java

mars/tools/ScreenMagnifier$1.class

mars/tools/CacheSimulator$2.class

mars/tools/KeyboardAndDisplaySimulator$3.class

mars/tools/KeyboardAndDisplaySimulator$FontSettingDialog.class

mars/tools/MemoryReferenceVisualization.java

mars/tools/ScavengerHunt.class

mars/tools/KeyboardAndDisplaySimulator$UniformlyDistributedDelay.class

mars/tools/ScavengerHunt$ScavengerHuntRunnable.class

mars/tools/BitmapDisplay$3.class

mars/tools/AbstractMarsToolAndApplication$6.class

mars/tools/MemoryReferenceVisualization$GraphicsPanel.class

mars/tools/MarsBot.class

mars/tools/ScreenMagnifier.class

mars/tools/MemoryReferenceVisualization$3.class

mars/tools/MarsTool.java

mars/tools/Magnifier.class

mars/tools/BitmapDisplay$Grid.class

mars/tools/KeyboardAndDisplaySimulator$FontSettingDialog$3.class

mars/tools/ScavengerHunt$ScavengerHuntRunnable$1.class

mars/tools/Magnifier$4.class

mars/tools/CaptureMagnifierRectangle.class

mars/tools/BHTSimGUI$1.class

mars/tools/KeyboardAndDisplaySimulator$FontSettingDialog$1.class

mars/tools/MemoryReferenceVisualization$1.class

mars/tools/BHTSimGUI.java

mars/tools/BHTableModel.java

mars/tools/SettingsDialog$2.class

mars/tools/BHTSimGUI.class

mars/tools/CaptureDisplayCentered.class

mars/tools/AbstractMarsToolAndApplication$8.class

mars/tools/InstructionCounter.class

mars/tools/MarsBot$MarsBotDisplay.class

mars/tools/KeyboardAndDisplaySimulator$KeyboardKeyListener.class

mars/tools/DigitalLabSim.class

mars/tools/MemoryReferenceVisualization$ColorChooserControls$ColorChooserListener.class

mars/tools/Magnifier$2.class

mars/tools/CaptureModel.class

mars/tools/BHTSimulator.class

mars/tools/AbstractMarsToolAndApplication.java

mars/tools/MemoryReferenceVisualization$5.class

mars/tools/BHTEntry.class

mars/tools/MemoryReferenceVisualization$7.class

mars/tools/BitmapDisplay$GraphicsPanel.class

mars/tools/MarsBot$BotRunnable$2.class

mars/tools/DigitalLabSim$SevenSegmentDisplay.class

mars/tools/AbstractMarsToolAndApplication$ConnectButton.class

mars/tools/MagnifierImage$1.class

mars/tools/DigitalLabSim$1.class

mars/tools/MemoryReferenceVisualization$Grid.class

mars/tools/DigitalLabSim$HexaKeyboard.class

mars/tools/SettingsDialog$3.class

mars/tools/DigitalLabSim$HexaKeyboard$EcouteurClick.class

mars/tools/ScavengerHunt$ScavengerHuntRunnable$2.class

mars/tools/DigitalLabSim$OneSecondCounter.class

mars/tools/AbstractMarsToolAndApplication$9.class

mars/tools/ScavengerHunt.java

mars/tools/BHTEntry.java

mars/tools/FloatRepresentation$BinaryToDecimalFormulaGraphic.class

mars/tools/BHTableModel.class

mars/tools/Magnifier$5.class

mars/tools/CaptureRectangleStrategy.class

mars/tools/SettingsDialog$1.class

mars/tools/MemoryReferenceVisualization$2.class

mars/tools/KeyboardAndDisplaySimulator$FontSettingDialog$2.class

mars/tools/KeyboardAndDisplaySimulator$DelayLengthPanel.class

mars/tools/FloatRepresentation$FlavorsOfFloat.class

mars/tools/BitmapDisplay.java

mars/tools/MagnifierImage.class

mars/tools/Magnifier$1.class

mars/tools/MemoryReferenceVisualization$ColorChooserControls.class

mars/tools/MemoryReferenceVisualization$6.class

mars/tools/CaptureScaledRectangle.class

mars/tools/CaptureDisplayUpperleft.class

mars/tools/MemoryReferenceVisualization$CounterColorScale.class

mars/tools/KeyboardAndDisplaySimulator$FixedLengthDelay.class

mars/tools/MemoryReferenceVisualization.class

mars/tools/MagnifierImage$2.class

mars/tools/MemoryReferenceVisualization$CounterColor.class

mars/tools/MemoryReferenceVisualization$4.class

mars/tools/FloatRepresentation$HexDisplayKeystrokeListener.class

mars/tools/MarsBot$BotRunnable$1.class

mars/tools/ScavengerHunt$Location.class

mars/tools/FloatRepresentation.class

mars/tools/Magnifier$3.class

mars/.DS_Store

mars/assembler/TokenList.class

mars/assembler/MacroPool.java

mars/assembler/Directives.java

mars/assembler/SymbolTable.java

mars/assembler/SourceLine.java

mars/assembler/Directives.class

mars/assembler/TokenTypes.java

mars/assembler/TokenTypes.class

mars/assembler/TranslationCode.class

mars/assembler/Tokenizer.class

mars/assembler/MacroPool.class

mars/assembler/TokenList.java

mars/assembler/OperandFormat.java

mars/assembler/Macro.class

mars/assembler/TranslationCode.java

mars/assembler/Assembler$DataSegmentForwardReferences.class

mars/assembler/Assembler.java

mars/assembler/SourceLine.class

mars/assembler/Tokenizer.java

mars/assembler/Symbol.java

mars/assembler/DataTypes.java

mars/assembler/Assembler$ProgramStatementComparator.class

mars/assembler/SymbolTable.class

mars/assembler/Macro.java

mars/assembler/DataTypes.class

mars/assembler/Token.class

mars/assembler/Assembler$UserKernelAddressSpace.class

mars/assembler/Token.java

mars/assembler/Assembler.class

mars/assembler/OperandFormat.class

mars/assembler/Symbol.class

mars/assembler/Assembler$DataSegmentForwardReferences$DataSegmentForwardReference.class

mars/MarsSplashScreen.java

mars/util/Binary.java

mars/util/PropertiesFile.java

mars/util/FilenameFinder.java

mars/util/PropertiesFile.class

mars/util/EditorFont.class

mars/util/MemoryDump.class

mars/util/EditorFont.java

mars/util/Binary.class

mars/util/SystemIO.class

mars/util/SystemIO$FileIOData.class

mars/util/FilenameFinder.class

mars/util/SystemIO.java

mars/util/FilenameFinder$MarsFileFilter.class

mars/util/MemoryDump.java

mars/MarsSplashScreen.class

mars/venus/SettingsMemoryConfigurationAction$MemoryConfigurationDialog.class

mars/venus/FileStatus.java

mars/venus/HelpHelpAction$1.class

mars/venus/EditFindReplaceAction$FindReplaceDialog$2.class

mars/venus/FilePrintAction.java

mars/venus/SettingsHighlightingAction$BackgroundChanger.class

mars/venus/SettingsAssembleAllAction.java

mars/venus/RunToggleBreakpointsAction.java

mars/venus/MessagesPane$Asker$1$1.class

mars/venus/SettingsHighlightingAction$2.class

mars/venus/EditPane$2.class

mars/venus/SettingsEditorAction$EditorFontDialog$8.class

mars/venus/SettingsWarningsAreErrorsAction.class

mars/venus/MessagesPane$Asker.class

mars/venus/MonoRightCellRenderer.class

mars/venus/GuiAction.class

mars/venus/FileExitAction.class

mars/venus/FileExitAction.java

mars/venus/EditSelectAllAction.java

mars/venus/SettingsAssembleAllAction.class

mars/venus/Coprocessor1Window$MyTippedJTable$1.class

mars/venus/FileDumpMemoryAction$DumpFormatComboBoxRenderer.class

mars/venus/HelpAboutAction.java

mars/venus/FileStatus.class

mars/venus/SettingsHighlightingAction$ForegroundChanger.class

mars/venus/Coprocessor1Window.java

mars/venus/ToolAction.java

mars/venus/RunGoAction.java

mars/venus/NumberDisplayBaseChooser.class

mars/venus/EditFindReplaceAction.class

mars/venus/TextSegmentWindow.java

mars/venus/DataSegmentWindow$NextButton.class

mars/venus/SettingsAssembleOnOpenAction.class

mars/venus/SettingsHighlightingAction$6.class

mars/venus/DataSegmentWindow.java

mars/venus/SettingsHighlightingAction$DefaultChanger.class

mars/venus/RunAssembleAction.java

mars/venus/Coprocessor1Window$MyTippedJTable.class

mars/venus/FileNewAction.java

mars/venus/EditFindReplaceAction$FindReplaceDialog$4.class

mars/venus/FileCloseAction.class

mars/venus/AbstractFontSettingDialog$ComboBoxRenderer.class

mars/venus/SettingsStartAtMainAction.java

mars/venus/SettingsEditorAction$EditorFontDialog$ForegroundChanger.class

mars/venus/RunStepAction.class

mars/venus/SettingsEditorAction$EditorFontDialog$BoldItalicChanger.class

mars/venus/EditRedoAction.java

mars/venus/VenusUI$2.class

mars/venus/SettingsHighlightingAction$4.class

mars/venus/PopupListener.class

mars/venus/DataSegmentWindow$8.class

mars/venus/EditTabbedPane.java

mars/venus/EditPasteAction.class

mars/venus/FilePrintAction.class

mars/venus/SettingsEditorAction.class

mars/venus/EditFindReplaceAction$FindReplaceDialog$1.class

mars/venus/LabelsWindow$LabelsForSymbolTable.class

mars/venus/TextSegmentWindow$MyTableColumnMovingListener.class

mars/venus/SettingsEditorAction.java

mars/venus/ToolLoader.class

mars/venus/SettingsEditorAction$EditorFontDialog$9.class

mars/venus/SettingsHighlightingAction$3.class

mars/venus/HardcopyWriter.java

mars/venus/LabelsWindow$LabelDisplayMouseListener.class

mars/venus/DataSegmentWindow$MyTippedJTable$1.class

mars/venus/FileOpenAction.java

mars/venus/RunStopAction.class

mars/venus/MonoRightCellRenderer.java

mars/venus/SettingsAddressDisplayBaseAction.java

mars/venus/HelpHelpAction$2.class

mars/venus/RunResetAction.java

mars/venus/Coprocessor0Window$RegisterCellRenderer.class

mars/venus/SettingsMemoryConfigurationAction.java

mars/venus/RunAssembleAction.class

mars/venus/EditCopyAction.class

mars/venus/Coprocessor0Window$MyTippedJTable.class

mars/venus/EditPasteAction.java

mars/venus/RunToggleBreakpointsAction.class

mars/venus/LabelsWindow$LabelItemListener.class

mars/venus/SettingsProgramArgumentsAction.class

mars/venus/ColorSelectButton.class

mars/venus/RunPauseAction.java

mars/venus/FileNewAction.class

mars/venus/EditCutAction.class

mars/venus/editors/jeditsyntax/InputHandler$insert_tab.class

mars/venus/editors/jeditsyntax/TextAreaPainter.java

mars/venus/editors/jeditsyntax/KeywordMap.class

mars/venus/editors/jeditsyntax/InputHandler$backspace_word.class

mars/venus/editors/jeditsyntax/InputHandler$MacroRecorder.class

mars/venus/editors/jeditsyntax/InputHandler.class

mars/venus/editors/jeditsyntax/InputHandler$repeat.class

mars/venus/editors/jeditsyntax/InputHandler$delete_word.class

mars/venus/editors/jeditsyntax/InputHandler$insert_break.class

mars/venus/editors/jeditsyntax/InputHandler$prev_word.class

mars/venus/editors/jeditsyntax/InputHandler$backspace.class

mars/venus/editors/jeditsyntax/InputHandler$insert_char.class

mars/venus/editors/jeditsyntax/SyntaxDocument.java

mars/venus/editors/jeditsyntax/PopupHelpItem.class

mars/venus/editors/jeditsyntax/JEditTextArea$AdjustHandler.class

mars/venus/editors/jeditsyntax/JEditTextArea$ScrollLayout.class

mars/venus/editors/jeditsyntax/SyntaxUtilities.class

mars/venus/editors/jeditsyntax/InputHandler$clip_copy.class

mars/venus/editors/jeditsyntax/InputHandler$NonRepeatable.class

mars/venus/editors/jeditsyntax/InputHandler$end.class

mars/venus/editors/jeditsyntax/InputHandler$prev_page.class

mars/venus/editors/jeditsyntax/JEditTextArea.class

mars/venus/editors/jeditsyntax/JEditTextArea.java

mars/venus/editors/jeditsyntax/SyntaxDocument.class

mars/venus/editors/jeditsyntax/InputHandler$home.class

mars/venus/editors/jeditsyntax/KeywordMap.java

mars/venus/editors/jeditsyntax/KeywordMap$Keyword.class

mars/venus/editors/jeditsyntax/JEditTextArea$FocusHandler.class

mars/venus/editors/jeditsyntax/InputHandler$next_char.class

mars/venus/editors/jeditsyntax/PopupHelpItem.java

mars/venus/editors/jeditsyntax/InputHandler$clip_cut.class

mars/venus/editors/jeditsyntax/DefaultInputHandler.java

mars/venus/editors/jeditsyntax/JEditBasedTextArea.java

mars/venus/editors/jeditsyntax/InputHandler$Wrapper.class

mars/venus/editors/jeditsyntax/tokenmarker/TokenMarker.java

mars/venus/editors/jeditsyntax/tokenmarker/MIPSTokenMarker.java

mars/venus/editors/jeditsyntax/tokenmarker/MIPSTokenMarker.class

mars/venus/editors/jeditsyntax/tokenmarker/TokenMarker.class

mars/venus/editors/jeditsyntax/tokenmarker/Token.class

mars/venus/editors/jeditsyntax/tokenmarker/Token.java

mars/venus/editors/jeditsyntax/tokenmarker/TokenMarker$LineInfo.class

mars/venus/editors/jeditsyntax/InputHandler$prev_line.class

mars/venus/editors/jeditsyntax/SyntaxStyle.class

mars/venus/editors/jeditsyntax/InputHandler$overwrite.class

mars/venus/editors/jeditsyntax/InputHandler$select_all.class

mars/venus/editors/jeditsyntax/InputHandler.java

mars/venus/editors/jeditsyntax/TextAreaDefaults.java

mars/venus/editors/jeditsyntax/JEditTextArea$2.class

mars/venus/editors/jeditsyntax/InputHandler$document_end.class

mars/venus/editors/jeditsyntax/TextAreaDefaults.class

mars/venus/editors/jeditsyntax/JEditTextArea$PopupHelpActionListener.class

mars/venus/editors/jeditsyntax/SyntaxStyle.java

mars/venus/editors/jeditsyntax/TextAreaPainter.class

mars/venus/editors/jeditsyntax/InputHandler$next_word.class

mars/venus/editors/jeditsyntax/JEditBasedTextArea$1.class

mars/venus/editors/jeditsyntax/JEditBasedTextArea.class

mars/venus/editors/jeditsyntax/JEditTextArea$MouseHandler.class

mars/venus/editors/jeditsyntax/InputHandler$next_page.class

mars/venus/editors/jeditsyntax/JEditTextArea$CaretBlinker.class

mars/venus/editors/jeditsyntax/JEditTextArea$ComponentHandler.class

mars/venus/editors/jeditsyntax/JEditTextArea$MutableCaretEvent.class

mars/venus/editors/jeditsyntax/InputHandler$document_home.class

mars/venus/editors/jeditsyntax/TextUtilities.java

mars/venus/editors/jeditsyntax/SyntaxUtilities.java

mars/venus/editors/jeditsyntax/JEditTextArea$CaretUndo.class

mars/venus/editors/jeditsyntax/JEditTextArea$1.class

mars/venus/editors/jeditsyntax/TextAreaPainter$Highlight.class

mars/venus/editors/jeditsyntax/InputHandler$prev_char.class

mars/venus/editors/jeditsyntax/JEditTextArea$AdjustHandler$1.class

mars/venus/editors/jeditsyntax/TextUtilities.class

mars/venus/editors/jeditsyntax/InputHandler$clip_paste.class

mars/venus/editors/jeditsyntax/DefaultInputHandler.class

mars/venus/editors/jeditsyntax/JEditTextArea$DragHandler.class

mars/venus/editors/jeditsyntax/InputHandler$NonRecordable.class

mars/venus/editors/jeditsyntax/InputHandler$next_line.class

mars/venus/editors/jeditsyntax/InputHandler$toggle_rect.class

mars/venus/editors/jeditsyntax/JEditTextArea$MouseWheelHandler.class

mars/venus/editors/jeditsyntax/InstructionMouseEvent.class

mars/venus/editors/jeditsyntax/JEditTextArea$DocumentHandler.class

mars/venus/editors/jeditsyntax/InputHandler$delete.class

mars/venus/editors/generic/GenericTextArea$1.class

mars/venus/editors/generic/GenericTextArea.class

mars/venus/editors/generic/GenericTextArea$2.class

mars/venus/editors/generic/GenericTextArea.java

mars/venus/editors/MARSTextEditingArea.java

mars/venus/editors/MARSTextEditingArea.class

mars/venus/EditPane$1.class

mars/venus/SettingsHighlightingAction$1.class

mars/venus/SettingsValueDisplayBaseAction.class

mars/venus/MessagesPane$Asker$1$2.class

mars/venus/LabelsWindow$MyTippedJTable.class

mars/venus/SettingsPopupInputAction.class

mars/venus/FileSaveAction.java

mars/venus/EditSelectAllAction.class

mars/venus/PopupListener.java

mars/venus/EditUndoAction.java

mars/venus/EditFindReplaceAction$FindReplaceDialog$3.class

mars/venus/DataSegmentWindow$PrevButton.class

mars/venus/RegistersWindow.java

mars/venus/VenusUI.class

mars/venus/Coprocessor1Window$RegTableModel.class

mars/venus/DataSegmentWindow$9.class

mars/venus/SettingsStartAtMainAction.class

mars/venus/FileDumpMemoryAction.class

mars/venus/EditFindReplaceAction.java

mars/venus/SettingsHighlightingAction$5.class

mars/venus/Coprocessor0Window.class

mars/venus/RepeatButton.class

mars/venus/SettingsExtendedAction.java

mars/venus/SettingsLabelAction.class

mars/venus/SettingsLabelAction.java

mars/venus/LabelsWindow$MyTippedJTable$SymbolTableHeader$SymbolTableHeaderMouseListener.class

mars/venus/SettingsDelayedBranchingAction.java

mars/venus/Editor.java

mars/venus/FileCloseAllAction.java

mars/venus/RegistersPane.class

mars/venus/SettingsHighlightingAction.class

mars/venus/TextSegmentWindow$CheckBoxTableCellRenderer.class

mars/venus/EditTabbedPane.class

mars/venus/HelpHelpAction$MyCellRenderer.class

mars/venus/EditFindReplaceAction$FindReplaceDialog$5.class

mars/venus/HelpHelpAction.class

mars/venus/EditUndoAction.class

mars/venus/ExecutePane.java

mars/venus/SettingsExceptionHandlerAction$ExceptionHandlerSettingAction.class

mars/venus/FileSaveAllAction.class

mars/venus/SettingsHighlightingAction$7.class

mars/venus/ExecutePane.class

mars/venus/VenusUI$1.class

mars/venus/DataSegmentWindow$7.class

mars/venus/TextSegmentWindow$MachineCodeCellRenderer.class

mars/venus/RunClearBreakpointsAction.java

mars/venus/AbstractFontSettingDialog.class

mars/venus/SettingsEditorAction$EditorFontDialog$1.class

mars/venus/RegistersWindow$RegTableModel.class

mars/venus/MessagesPane$Asker$3.class

mars/venus/DataSegmentWindow$DataTableModel.class

mars/venus/Coprocessor0Window.java

mars/venus/RegistersPane.java

mars/venus/LabelsWindow.class

mars/venus/LabelsWindow$MyTippedJTable$SymbolTableHeader.class

mars/venus/TextSegmentWindow$CodeCellRenderer.class

mars/venus/MainPane$1.class

mars/venus/SettingsHighlightingAction$FontSettingDialog$2.class

mars/venus/TextSegmentWindow$MyTippedJTable.class

mars/venus/EditFindReplaceAction$FindReplaceDialog.class

mars/venus/HardcopyWriter.class

mars/venus/NumberDisplayBaseChooser$1.class

mars/venus/MessagesPane$4.class

mars/venus/SettingsExceptionHandlerAction.class

mars/venus/SettingsAddressDisplayBaseAction.class

mars/venus/DataSegmentWindow$AddressCellRenderer.class

mars/venus/HelpHelpAction.java

mars/venus/DataSegmentWindow$MyTippedJTable.class

mars/venus/SettingsMemoryConfigurationAction$MemoryConfigurationDialog$4.class

mars/venus/AbstractFontSettingDialog$2.class

mars/venus/SettingsExceptionHandlerAction$2.class

mars/venus/SettingsEditorAction$EditorFontDialog$3.class

mars/venus/Coprocessor0Window$RegTableModel.class

mars/venus/EditCutAction.java

mars/venus/MessagesPane$Asker$1.class

mars/venus/RunClearBreakpointsAction.class

mars/venus/DataSegmentWindow$5.class

mars/venus/RepeatButton.java

mars/venus/HelpHelpAction$HelpHyperlinkListener$2.class

mars/venus/SettingsEditorAction$EditorFontDialog$7.class

mars/venus/FileOpenAction.class

mars/venus/FileDumpMemoryAction.java

mars/venus/RegistersWindow$RegisterCellRenderer.class

mars/venus/SettingsHighlightingAction$FontSettingDialog.class

mars/venus/DataSegmentWindow$1.class

mars/venus/FileDumpMemoryAction$1.class

mars/venus/SettingsMemoryConfigurationAction.class

mars/venus/SettingsDelayedBranchingAction.class

mars/venus/MessagesPane.class

mars/venus/SettingsEditorAction$EditorFontDialog$DefaultChanger.class

mars/venus/FileSaveAllAction.java

mars/venus/RunBackstepAction.class

mars/venus/EditTabbedPane$FileOpener.class

mars/venus/RunSpeedPanel$RunSpeedListener.class

mars/venus/EditCopyAction.java

mars/venus/TextSegmentWindow.class

mars/venus/NumberDisplayBaseChooser.java

mars/venus/SettingsMemoryConfigurationAction$MemoryConfigurationDialog$2.class

mars/venus/SettingsHighlightingAction.java

mars/venus/RunStepAction.java

mars/venus/AbstractFontSettingDialog$4.class

mars/venus/MessagesPane.java

mars/venus/LabelsWindow$LabelAddressAscendingComparator.class

mars/venus/FileDumpMemoryAction$3.class

mars/venus/MessagesPane$2.class

mars/venus/RegistersWindow$MyTippedJTable.class

mars/venus/SettingsWarningsAreErrorsAction.java

mars/venus/SettingsEditorAction$EditorFontDialog.class

mars/venus/LabelsWindow$LabelNameAscendingComparator.class

mars/venus/RunSpeedPanel.class

mars/venus/DataSegmentWindow$3.class

mars/venus/EditPane.java

mars/venus/RunGoAction.class

mars/venus/EditTabbedPane$1.class

mars/venus/SettingsProgramArgumentsAction.java

mars/venus/SettingsEditorAction$EditorFontDialog$5.class

mars/venus/TextSegmentWindow$MyTippedJTable$TextTableHeader.class

mars/venus/SettingsExtendedAction.class

mars/venus/ToolLoader.java

mars/venus/HelpAboutAction.class

mars/venus/SettingsMemoryConfigurationAction$MemoryConfigurationDialog$5.class

mars/venus/AbstractFontSettingDialog$3.class

mars/venus/SettingsExceptionHandlerAction$3.class

mars/venus/TextSegmentWindow$TextTableModel.class

mars/venus/LabelsWindow$LabelTableModel.class

mars/venus/FileDumpMemoryAction$4.class

mars/venus/RunSpeedPanel.java

mars/venus/RegistersWindow$MyTippedJTable$1.class

mars/venus/SettingsHighlightingAction$FontSettingDialog$1.class

mars/venus/FileSaveAsAction.java

mars/venus/SettingsHighlightingAction$8.class

mars/venus/RunBackstepAction.java

mars/venus/VenusUI.java

mars/venus/MainPane.class

mars/venus/MainPane.java

mars/venus/DataSegmentWindow$4.class

mars/venus/RegistersWindow.class

mars/venus/GuiAction.java

mars/venus/SettingsEditorAction$EditorFontDialog$2.class

mars/venus/HelpHelpAction$HelpHyperlinkListener.class

mars/venus/DataSegmentWindow.class

mars/venus/MessagesPane$Asker$2.class

mars/venus/FileCloseAction.java

mars/venus/SettingsPopupInputAction.java

mars/venus/AbstractFontSettingDialog$BlockComboListener.class

mars/venus/Editor.class

mars/venus/DataSegmentWindow$6.class

mars/venus/LabelsWindow$DescendingComparator.class

mars/venus/FileSaveAction.class

mars/venus/SettingsAssembleOnOpenAction.java

mars/venus/SettingsHighlightingAction$FontSettingDialog$3.class

mars/venus/SettingsExceptionHandlerAction.java

mars/venus/RunStopAction.java

mars/venus/ToolAction.class

mars/venus/TextSegmentWindow$MyTippedJTable$TextTableHeader$TextTableHeaderMouseListener.class

mars/venus/AbstractFontSettingDialog$1.class

mars/venus/SettingsExceptionHandlerAction$1.class

mars/venus/Coprocessor1Window.class

mars/venus/SettingsHighlightingAction$FontChanger.class

mars/venus/MessagesPane$3.class

mars/venus/SettingsExceptionHandlerAction$ExceptionHandlerSelectionAction.class

mars/venus/EditTabbedPane$FileOpener$ChoosableFileFilterChangeListener.class

mars/venus/DataSegmentWindow$CustomComboBoxModel.class

mars/venus/FileDumpMemoryAction$2.class

mars/venus/SettingsMemoryConfigurationAction$MemoryConfigurationDialog$3.class

mars/venus/FileSaveAsAction.class

mars/venus/FileCloseAllAction.class

mars/venus/SettingsValueDisplayBaseAction.java

mars/venus/SettingsEditorAction$EditorFontDialog$4.class

mars/venus/HelpHelpAction$HelpHyperlinkListener$1.class

mars/venus/SettingsMemoryConfigurationAction$ConfigurationButton.class

mars/venus/DataSegmentWindow$2.class

mars/venus/RunPauseAction.class

mars/venus/Coprocessor0Window$MyTippedJTable$1.class

mars/venus/EditPane.class

mars/venus/SettingsEditorAction$EditorFontDialog$6.class

mars/venus/MessagesPane$Asker$4.class

mars/venus/AbstractFontSettingDialog.java

mars/venus/SettingsMemoryConfigurationAction$MemoryConfigurationDialog$1.class

mars/venus/RunResetAction.class

mars/venus/EditRedoAction.class

mars/venus/HardcopyWriter$PrintCanceledException.class

mars/venus/ToolLoader$MarsToolClassAndInstance.class

mars/venus/LabelsWindow.java

mars/venus/MessagesPane$1.class

mars/venus/Coprocessor1Window$RegisterCellRenderer.class

mars/ext/game/GameScreen.java

mars/ext/game/GameImage.java

mars/ext/game/GameConfigFile.java

mars/ext/game/MMIOInput.java

mars/ext/game/GameObjectDynamite.class

mars/ext/game/GameObjectText.java

mars/ext/game/SoundPlayer.class

mars/ext/game/GameObjectHook.class

mars/ext/game/MMIOThread.class

mars/ext/game/ActiveElementInterface.class

mars/ext/game/GameScreen$1.class

mars/ext/game/GameScreen$ScreenPanel.class

mars/ext/game/GameObjectText.class

mars/ext/game/GameException.java

mars/ext/game/GameObject.class

mars/ext/game/MMIOInput.class

mars/ext/game/GameObjectMineral.class

mars/ext/game/GameObject.java

mars/ext/game/GameObjectMineral.java

mars/ext/game/GameImage.class

mars/ext/game/MMIOThread.java

mars/ext/game/ActiveElementInterface.java

mars/ext/game/GameObjectHook.java

mars/ext/game/GameObjectDynamite.java

mars/ext/game/GameScreen.class

mars/ext/game/GameException.class

mars/ext/game/GameConfigFile.class

mars/ext/game/SoundPlayer.java

mars/ProcessingException.java

mars/ProgramStatement$BasicStatementList$ListElement.class

mars/ErrorList.class

mars/ErrorList.java

mars/mips/instructions/InstructionSet$62.class

mars/mips/instructions/InstructionSet$27.class

mars/mips/instructions/InstructionSet$143.class

mars/mips/instructions/InstructionSet$106.class

mars/mips/instructions/InstructionSet$46.class

mars/mips/instructions/InstructionSet$122.class

mars/mips/instructions/InstructionSet$86.class

mars/mips/instructions/InstructionSet$84.class

mars/mips/instructions/InstructionSet$79.class

mars/mips/instructions/InstructionSet$44.class

mars/mips/instructions/InstructionSet$120.class

mars/mips/instructions/InstructionSet$60.class

mars/mips/instructions/InstructionSet$25.class

mars/mips/instructions/InstructionSet$141.class

mars/mips/instructions/InstructionSet$104.class

mars/mips/instructions/InstructionSet$139.class

mars/mips/instructions/InstructionSet$18.class

mars/mips/instructions/InstructionSet$145.class

mars/mips/instructions/InstructionSet$100.class

mars/mips/instructions/InstructionSet$64.class

mars/mips/instructions/InstructionSet$21.class

mars/mips/instructions/InstructionSet$99.class

mars/mips/instructions/InstructionSet$59.class

mars/mips/instructions/InstructionSet$38.class

mars/mips/instructions/InstructionSet$80.class

mars/mips/instructions/InstructionSet$119.class

mars/mips/instructions/InstructionSet$124.class

mars/mips/instructions/InstructionSet$40.class

mars/mips/instructions/SyscallLoader.class

mars/mips/instructions/ExtendedInstruction.class

mars/mips/instructions/InstructionSet$126.class

mars/mips/instructions/InstructionSet$42.class

mars/mips/instructions/InstructionSet$82.class

mars/mips/instructions/InstructionSet$147.class

mars/mips/instructions/InstructionSet$102.class

mars/mips/instructions/BasicInstructionFormat.class

mars/mips/instructions/InstructionSet$9.class

mars/mips/instructions/InstructionSet$66.class

mars/mips/instructions/InstructionSet$23.class

mars/mips/instructions/InstructionSet$121.class

mars/mips/instructions/InstructionSet$45.class

mars/mips/instructions/InstructionSet$85.class

mars/mips/instructions/InstructionSet$78.class

mars/mips/instructions/InstructionSet$19.class

mars/mips/instructions/InstructionSet$138.class

mars/mips/instructions/InstructionSet$105.class

mars/mips/instructions/InstructionSet$140.class

mars/mips/instructions/InstructionSet$24.class

mars/mips/instructions/InstructionSet$61.class

mars/mips/instructions/InstructionSet$107.class

mars/mips/instructions/InstructionSet$142.class

mars/mips/instructions/InstructionSet$26.class

mars/mips/instructions/InstructionSet$63.class

mars/mips/instructions/InstructionSet$87.class

mars/mips/instructions/SimulationCode.class

mars/mips/instructions/SimulationCode.java

mars/mips/instructions/InstructionSet$123.class

mars/mips/instructions/InstructionSet$47.class

mars/mips/instructions/InstructionSet$83.class

mars/mips/instructions/InstructionSet$43.class

mars/mips/instructions/InstructionSet$127.class

mars/mips/instructions/InstructionSet$22.class

mars/mips/instructions/InstructionSet$67.class

mars/mips/instructions/InstructionSet$103.class

mars/mips/instructions/InstructionSet$146.class

mars/mips/instructions/InstructionSet$8.class

mars/mips/instructions/BasicInstruction.class

mars/mips/instructions/InstructionSet$58.class

mars/mips/instructions/Instruction.class

mars/mips/instructions/InstructionSet$20.class

mars/mips/instructions/InstructionSet$65.class

mars/mips/instructions/InstructionSet$98.class

mars/mips/instructions/InstructionSet$101.class

mars/mips/instructions/InstructionSet$144.class

mars/mips/instructions/InstructionSet$41.class

mars/mips/instructions/InstructionSet$125.class

mars/mips/instructions/InstructionSet$118.class

mars/mips/instructions/InstructionSet$39.class

mars/mips/instructions/ExtendedInstruction.java

mars/mips/instructions/InstructionSet$81.class

mars/mips/instructions/InstructionSet$151.class

mars/mips/instructions/InstructionSet$114.class

mars/mips/instructions/InstructionSet$70.class

mars/mips/instructions/InstructionSet$35.class

mars/mips/instructions/InstructionSet$129.class

mars/mips/instructions/InstructionSet$69.class

mars/mips/instructions/InstructionSet$94.class

mars/mips/instructions/InstructionSet$6.class

mars/mips/instructions/InstructionSet$148.class

mars/mips/instructions/InstructionSet$130.class

mars/mips/instructions/InstructionSet$54.class

mars/mips/instructions/InstructionSet$11.class

mars/mips/instructions/InstructionSet$132.class

mars/mips/instructions/InstructionSet$56.class

mars/mips/instructions/InstructionSet$13.class

mars/mips/instructions/InstructionSet$96.class

mars/mips/instructions/InstructionSet$4.class

mars/mips/instructions/InstructionSet$153.class

mars/mips/instructions/InstructionSet$116.class

mars/mips/instructions/BasicInstructionFormat.java

mars/mips/instructions/InstructionSet$72.class

mars/mips/instructions/InstructionSet$37.class

mars/mips/instructions/InstructionSet$76.class

mars/mips/instructions/InstructionSet$33.class

mars/mips/instructions/InstructionSet$112.class

mars/mips/instructions/InstructionSet$52.class

mars/mips/instructions/InstructionSet$17.class

mars/mips/instructions/InstructionSet$136.class

mars/mips/instructions/InstructionSet$92.class

mars/mips/instructions/InstructionSet$109.class

mars/mips/instructions/InstructionSet$2.class

mars/mips/instructions/InstructionSet$90.class

mars/mips/instructions/InstructionSet$28.class

mars/mips/instructions/InstructionSet$50.class

mars/mips/instructions/InstructionSet$15.class

mars/mips/instructions/InstructionSet$134.class

mars/mips/instructions/InstructionSet.class

mars/mips/instructions/InstructionSet$89.class

mars/mips/instructions/InstructionSet$74.class

mars/mips/instructions/InstructionSet$31.class

mars/mips/instructions/InstructionSet$155.class

mars/mips/instructions/InstructionSet$110.class

mars/mips/instructions/InstructionSet$49.class

mars/mips/instructions/InstructionSet$5.class

mars/mips/instructions/InstructionSet$97.class

mars/mips/instructions/InstructionSet$12.class

mars/mips/instructions/InstructionSet$57.class

mars/mips/instructions/InstructionSet$133.class

mars/mips/instructions/InstructionSet$36.class

mars/mips/instructions/InstructionSet$73.class

mars/mips/instructions/InstructionSet$117.class

mars/mips/instructions/InstructionSet$152.class

mars/mips/instructions/InstructionSet$128.class

mars/mips/instructions/Instruction.java

mars/mips/instructions/SyscallLoader.java

mars/mips/instructions/InstructionSet$34.class

mars/mips/instructions/InstructionSet$71.class

mars/mips/instructions/InstructionSet$115.class

mars/mips/instructions/InstructionSet$150.class

mars/mips/instructions/InstructionSet$10.class

mars/mips/instructions/InstructionSet$55.class

mars/mips/instructions/InstructionSet$131.class

mars/mips/instructions/InstructionSet$7.class

mars/mips/instructions/InstructionSet$149.class

mars/mips/instructions/InstructionSet$68.class

mars/mips/instructions/InstructionSet$95.class

mars/mips/instructions/InstructionSet$135.class

mars/mips/instructions/InstructionSet$14.class

mars/mips/instructions/InstructionSet$51.class

mars/mips/instructions/InstructionSet$91.class

mars/mips/instructions/InstructionSet$29.class

mars/mips/instructions/InstructionSet$108.class

mars/mips/instructions/InstructionSet$3.class

mars/mips/instructions/InstructionSet$48.class

mars/mips/instructions/InstructionSet.java

mars/mips/instructions/InstructionSet$111.class

mars/mips/instructions/InstructionSet$154.class

mars/mips/instructions/InstructionSet$88.class

mars/mips/instructions/InstructionSet$30.class

mars/mips/instructions/InstructionSet$75.class

mars/mips/instructions/InstructionSet$113.class

mars/mips/instructions/InstructionSet$32.class

mars/mips/instructions/InstructionSet$77.class

mars/mips/instructions/syscalls/SyscallInputDialogDouble.class

mars/mips/instructions/syscalls/SyscallClose.class

mars/mips/instructions/syscalls/SyscallGameIsShoot.java

mars/mips/instructions/syscalls/SyscallGameCreateObject.class

mars/mips/instructions/syscalls/SyscallGameUpdateObjLocation.java

mars/mips/instructions/syscalls/SyscallGameUpdateObjDirection.java

mars/mips/instructions/syscalls/SyscallPrintString.java

mars/mips/instructions/syscalls/SyscallPrintIntBinary.java

mars/mips/instructions/syscalls/SyscallMidiOut.java

mars/mips/instructions/syscalls/SyscallRandInt.class

mars/mips/instructions/syscalls/SyscallGameGetObjDirection.java

mars/mips/instructions/syscalls/SyscallMidiOutSync.class

mars/mips/instructions/syscalls/SyscallGameSetObjSpeed.class

mars/mips/instructions/syscalls/SyscallReadInt.class

mars/mips/instructions/syscalls/SyscallSbrk.class

mars/mips/instructions/syscalls/SyscallPrintString.class

mars/mips/instructions/syscalls/SyscallGameCreateObject.java

mars/mips/instructions/syscalls/Syscall.class

mars/mips/instructions/syscalls/SyscallGameSetObjSpeed.java

mars/mips/instructions/syscalls/SyscallCreateGame.java

mars/mips/instructions/syscalls/SyscallMessageDialogString.class

mars/mips/instructions/syscalls/SyscallExit.java

mars/mips/instructions/syscalls/SyscallWrite.class

mars/mips/instructions/syscalls/SyscallInputDialogInt.java

mars/mips/instructions/syscalls/SyscallGameUpdateObjDirection.class

mars/mips/instructions/syscalls/SyscallMessageDialogInt.java

mars/mips/instructions/syscalls/SyscallConfirmDialog.class

mars/mips/instructions/syscalls/SyscallOpen.java

mars/mips/instructions/syscalls/SyscallReadChar.java

mars/mips/instructions/syscalls/SyscallGameSetLevelInfo.class

mars/mips/instructions/syscalls/SyscallReadFloat.java

mars/mips/instructions/syscalls/SyscallGameGetObjPrice.java

mars/mips/instructions/syscalls/SyscallMidiOut.class

mars/mips/instructions/syscalls/SyscallGameCreateObjectText.class

mars/mips/instructions/syscalls/SyscallMessageDialog.java

mars/mips/instructions/syscalls/SyscallTime.class

mars/mips/instructions/syscalls/SyscallReadString.class

mars/mips/instructions/syscalls/SyscallGameSetObjDirection.java

mars/mips/instructions/syscalls/SyscallRandDouble.java

mars/mips/instructions/syscalls/SyscallGameToggleIsHooked.class

mars/mips/instructions/syscalls/SyscallPrintIntUnsigned.java

mars/mips/instructions/syscalls/SyscallPrintFloat.java

mars/mips/instructions/syscalls/SyscallGameToggleIsShoot.java

mars/mips/instructions/syscalls/SyscallSbrk.java

mars/mips/instructions/syscalls/AbstractSyscall.class

mars/mips/instructions/syscalls/SyscallMessageDialogString.java

mars/mips/instructions/syscalls/SyscallInputDialogFloat.java

mars/mips/instructions/syscalls/SyscallGameGetObjDirection.class

mars/mips/instructions/syscalls/AbstractSyscall.java

mars/mips/instructions/syscalls/SyscallGameToggleIsClockwise.java

mars/mips/instructions/syscalls/RandomStreams.java

mars/mips/instructions/syscalls/SyscallRandFloat.class

mars/mips/instructions/syscalls/SyscallReadChar.class

mars/mips/instructions/syscalls/SyscallReadString.java

mars/mips/instructions/syscalls/SyscallInputDialogString.java

mars/mips/instructions/syscalls/SyscallGameHelper.java

mars/mips/instructions/syscalls/EndOfTrackListener.class

mars/mips/instructions/syscalls/Tone.class

mars/mips/instructions/syscalls/SyscallPrintChar.class

mars/mips/instructions/syscalls/SyscallReadDouble.class

mars/mips/instructions/syscalls/SyscallGameCreateObjectText.java

mars/mips/instructions/syscalls/SyscallPrintChar.java

mars/mips/instructions/syscalls/SyscallGameToggleIsShoot.class

mars/mips/instructions/syscalls/SyscallGameSetLevelInfo.java

mars/mips/instructions/syscalls/SyscallMessageDialog.class

mars/mips/instructions/syscalls/SyscallGameSetObjLocation.java

mars/mips/instructions/syscalls/SyscallInputDialogString.class

mars/mips/instructions/syscalls/SyscallRandIntRange.java

mars/mips/instructions/syscalls/SyscallGameGetObjSpeed.class

mars/mips/instructions/syscalls/SyscallGameSetObjDirection.class

mars/mips/instructions/syscalls/SyscallRandIntRange.class

mars/mips/instructions/syscalls/SyscallSleep.class

mars/mips/instructions/syscalls/SyscallGameIsClockwise.class

mars/mips/instructions/syscalls/SyscallGameToggleIsHooked.java

mars/mips/instructions/syscalls/Syscall.java

mars/mips/instructions/syscalls/SyscallPrintIntUnsigned.class

mars/mips/instructions/syscalls/SyscallPrintDouble.class

mars/mips/instructions/syscalls/SyscallGameRefreshScreen.java

mars/mips/instructions/syscalls/SyscallPrintInt.class

mars/mips/instructions/syscalls/SyscallRandSeed.class

mars/mips/instructions/syscalls/SyscallGameHelper.class

mars/mips/instructions/syscalls/SyscallMessageDialogDouble.class

mars/mips/instructions/syscalls/ToneGenerator.java

mars/mips/instructions/syscalls/SyscallTime.java

mars/mips/instructions/syscalls/SyscallPrintIntHex.java

mars/mips/instructions/syscalls/SyscallRandSeed.java

mars/mips/instructions/syscalls/SyscallPrintFloat.class

mars/mips/instructions/syscalls/SyscallGameSetObjPrice.class

mars/mips/instructions/syscalls/SyscallPrintInt.java

mars/mips/instructions/syscalls/ToneGenerator.class

mars/mips/instructions/syscalls/SyscallGameDestroyObject.class

mars/mips/instructions/syscalls/RandomStreams.class

mars/mips/instructions/syscalls/SyscallMessageDialogDouble.java

mars/mips/instructions/syscalls/SyscallGameSoundControl.class

mars/mips/instructions/syscalls/SyscallConfirmDialog.java

mars/mips/instructions/syscalls/SyscallExit.class

mars/mips/instructions/syscalls/SyscallMessageDialogFloat.java

mars/mips/instructions/syscalls/SyscallExit2.class

mars/mips/instructions/syscalls/SyscallReadInt.java

mars/mips/instructions/syscalls/SyscallGameIsHooked.class

mars/mips/instructions/syscalls/SyscallInputDialogDouble.java

mars/mips/instructions/syscalls/SyscallGameGetLevelObjLocation.class

mars/mips/instructions/syscalls/SyscallExit2.java

mars/mips/instructions/syscalls/SyscallReadDouble.java

mars/mips/instructions/syscalls/SyscallPrintIntHex.class

mars/mips/instructions/syscalls/SyscallWrite.java

mars/mips/instructions/syscalls/SyscallMessageDialogInt.class

mars/mips/instructions/syscalls/SyscallGameToggleIsClockwise.class

mars/mips/instructions/syscalls/SyscallGameSoundControl.java

mars/mips/instructions/syscalls/SyscallRandDouble.class

mars/mips/instructions/syscalls/SyscallClose.java

mars/mips/instructions/syscalls/SyscallGameRefreshScreen.class

mars/mips/instructions/syscalls/SyscallSleep.java

mars/mips/instructions/syscalls/SyscallGameSetObjLocation.class

mars/mips/instructions/syscalls/SyscallOpen.class

mars/mips/instructions/syscalls/SyscallRandInt.java

mars/mips/instructions/syscalls/SyscallGameGetLevelObjLocation.java

mars/mips/instructions/syscalls/SyscallMessageDialogFloat.class

mars/mips/instructions/syscalls/SyscallPrintIntBinary.class

mars/mips/instructions/syscalls/SyscallGameIsShoot.class

mars/mips/instructions/syscalls/SyscallGameSetObjPrice.java

mars/mips/instructions/syscalls/SyscallReadFloat.class

mars/mips/instructions/syscalls/SyscallInputDialogInt.class

mars/mips/instructions/syscalls/SyscallInputDialogFloat.class

mars/mips/instructions/syscalls/SyscallGameGetObjSpeed.java

mars/mips/instructions/syscalls/SyscallPrintDouble.java

mars/mips/instructions/syscalls/SyscallRead.java

mars/mips/instructions/syscalls/SyscallGameIsClockwise.java

mars/mips/instructions/syscalls/SyscallNumberOverride.java

mars/mips/instructions/syscalls/SyscallRead.class

mars/mips/instructions/syscalls/SyscallCreateGame.class

mars/mips/instructions/syscalls/SyscallGameDestroyObject.java

mars/mips/instructions/syscalls/SyscallNumberOverride.class

mars/mips/instructions/syscalls/SyscallGameGetObjLocation.class

mars/mips/instructions/syscalls/SyscallRandFloat.java

mars/mips/instructions/syscalls/SyscallMidiOutSync.java

mars/mips/instructions/syscalls/SyscallGameGetObjLocation.java

mars/mips/instructions/syscalls/SyscallGameGetObjPrice.class

mars/mips/instructions/syscalls/SyscallGameUpdateObjLocation.class

mars/mips/instructions/syscalls/SyscallGameIsHooked.java

mars/mips/instructions/BasicInstruction.java

mars/mips/instructions/InstructionSet$93.class

mars/mips/instructions/InstructionSet$1.class

mars/mips/instructions/InstructionSet$137.class

mars/mips/instructions/InstructionSet$16.class

mars/mips/instructions/InstructionSet$53.class

mars/mips/hardware/Coprocessor0.java

mars/mips/hardware/AccessNotice.class

mars/mips/hardware/Coprocessor1.java

mars/mips/hardware/MemoryAccessNotice.class

mars/mips/hardware/Coprocessor0.class

mars/mips/hardware/AccessNotice.java

mars/mips/hardware/RegisterFile.class

mars/mips/hardware/Register.class

mars/mips/hardware/MemoryConfigurations.class

mars/mips/hardware/MemoryConfiguration.java

mars/mips/hardware/Register.java

mars/mips/hardware/Coprocessor1.class

mars/mips/hardware/MemoryAccessNotice.java

mars/mips/hardware/MemoryConfigurations.java

mars/mips/hardware/InvalidRegisterAccessException.class

mars/mips/hardware/AddressErrorException.java

mars/mips/hardware/MemoryConfiguration.class

mars/mips/hardware/InvalidRegisterAccessException.java

mars/mips/hardware/Memory.class

mars/mips/hardware/Memory.java

mars/mips/hardware/Memory$MemoryObservable.class

mars/mips/hardware/RegisterAccessNotice.java

mars/mips/hardware/AddressErrorException.class

mars/mips/hardware/RegisterAccessNotice.class

mars/mips/hardware/RegisterFile.java

mars/mips/dump/BinaryDumpFormat.class

mars/mips/dump/AsciiTextDumpFormat.java

mars/mips/dump/AbstractDumpFormat.class

mars/mips/dump/BinaryTextDumpFormat.java

mars/mips/dump/SegmentWindowDumpFormat.class

mars/mips/dump/AsciiTextDumpFormat.class

mars/mips/dump/MIFDumpFormat.java

mars/mips/dump/HexTextDumpFormat.class

mars/mips/dump/DumpFormat.java

mars/mips/dump/DumpFormat.class

mars/mips/dump/BinaryTextDumpFormat.class

mars/mips/dump/SegmentWindowDumpFormat.java

mars/mips/dump/DumpFormatLoader.java

mars/mips/dump/AbstractDumpFormat.java

mars/mips/dump/DumpFormatLoader.class

mars/mips/dump/MIFDumpFormat.class

mars/mips/dump/IntelHexDumpFormat.class

mars/mips/dump/BinaryDumpFormat.java

mars/mips/dump/HexTextDumpFormat.java

mars/mips/dump/IntelHexDumpFormat.java

mars/Globals.class

mars/MarsSplashScreen$ImageBackgroundPanel.class

mars/MIPSprogram.class

mars/ErrorMessage.java

mars/simulator/BackStepper.class

mars/simulator/Simulator.class

mars/simulator/BackStepper.java

mars/simulator/Simulator$SimThread.class

mars/simulator/Simulator$StopListener.class

mars/simulator/SwingWorker$2.class

mars/simulator/Exceptions.java

mars/simulator/Exceptions.class

mars/simulator/DelayedBranch.class

mars/simulator/BackStepper$BackstepStack.class

mars/simulator/SwingWorker$ThreadVar.class

mars/simulator/Simulator.java

mars/simulator/SimulatorNotice.java

mars/simulator/SwingWorker.java

mars/simulator/ProgramArgumentList.java

mars/simulator/DelayedBranch.java

mars/simulator/SwingWorker$1.class

mars/simulator/BackStepper$BackStep.class

mars/simulator/ProgramArgumentList.class

mars/simulator/SwingWorker.class

mars/simulator/Simulator$UpdateGUI.class

mars/simulator/SimulatorNotice.class

mars/ErrorMessage.class

mars/ProgramStatement.java

mars/ProcessingException.class

mars/Settings.class

mars/MarsLaunch$2.class

mars/MarsLaunch.java

mars/ProgramStatement.class

mars/MIPSprogram.java

mars/Settings.java

mars/ProgramStatement$BasicStatementList.class

mars/Globals.java

mars/MarsLaunch.class

mars/MarsLaunch$1.class

sounds/emit.wav

sounds/win.wav

sounds/lose.wav

sounds/.DS_Store

sounds/hit.au

sounds/background.mid

sounds/hit.wav

Manifest-Version: 1.0
Main-Class: Mars
Class-Path: .
Created-By: 11.0.12 (Eclipse Foundation)

# Copyright (c) 2003-2010, Pete Sanderson and Kenneth Vollmar
#
# Developed by Pete Sanderson ( )
# and Kenneth Vollmar ( )
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# “Software”), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject
# to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
# ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# (MIT license, http://www.opensource.org/licenses/mit-license.html)

# File containing definitions of MIPS pseudo-ops

# File format:
# Each line contains specification for one pseudo-op, including optional description.
# First item is source statement syntax, specified in same “example” parser format used for regular instructions.
# Source statement specification ends with a tab. It is followed by a tab-separated list of basic instruction
# templates to complete and substitute for the pseudo-op.
# Format for specifying syntax of templates is different from specifying syntax of source statement:
# (n=0,1,2,3,…) is token position in source statement (operator is token 0, parentheses are tokens but commas aren’t)
# RGn means substitute register found in n’th token of source statement
# NRn means substitute next higher register than the one in n’th token of source code
# OPn means substitute n’th token of source code as is
# LLn means substitute low order 16-bits from label address in source token n.
# LLnU means substitute low order 16-bits (unsigned) from label address in source token n.
# LLnPm (m=1,2,3,4) means substitute low order 16-bits from label address in source token n, after adding m.
# LHn means substitute high order 16-bits from label address in source token n. Must add 1 if address bit 15 is 1.
# LHnPm (m=1,2,3,4) means substitute high order 16-bits from label address in source token n, after adding m. Must then add 1 if bit 15 is 1.
# VLn means substitute low order 16-bits from 32-bit value in source token n.
# VLnU means substitute low order 16-bits (unsigned) from 32-bit value in source token n.
# VLnPm (m=1,2,3,4) means substitute low order 16-bits from 32-bit value in source token n, after adding m to value.
# VLnPmU (m=1,2,3,4) means substitute low order 16-bits(unsigned) from 32-bit value in source token n, after adding m to value.
# VHLn means substitute high order 16-bits from 32-bit value in source token n. Use this if later combined with low order 16-bits using “ori $1,$1,VLnU”. See logical and branch operations.
# VHn means substitute high order 16-bits from 32-bit value in source token n, then add 1 if value’s bit 15 is 1. Use this only if later instruction uses VLn($1) to calculate 32-bit address. See loads and stores.
# VHLnPm (m=1,2,3,4) means substitute high order 16-bits from 32-bit value in source token n, after adding m. See VHLn.
# VHnPm (m=1,2,3,4) means substitute high order 16-bits from 32-bit value in source token n, after adding m. Must then add 1 if bit 15 is 1. See VHn.
# LLP is similar to LLn, but is needed for “label+100000” address offset. Immediate is added before taking low order 16.
# LLPU is similar to LLn, but is needed for “label+100000” address offset. Immediate is added before taking low order 16 (unsigned).
# LLPPm (m=1,2,3,4) is similar to LLP except m is added along with immediate before taking low order 16.
# LHPA is similar to LHn, but is needed for “label+100000” address offset. Immediate is added before taking high order 16.
# LHPN is similar to LHPA, used only by “la” instruction. Address resolved by “ori” so do not add 1 if bit 15 is 1.
# LHPAPm (m=1,2,3,4) is similar to LHPA except value m is added along with immediate before taking high order 16.
# LHL means substitute high order 16-bits from label address in token 2 of “la” (load address) source statement.
# LAB means substitute textual label from last token of source statement. Used for various branches.
# S32 means substitute the result of subtracting the constant value in last token from 32. Used by “ror”, “rol”.
# DBNOP means Delayed Branching NOP – generate a “nop” instruction but only if delayed branching is enabled. Added in 3.4.1 release.
# BROFFnm means substitute n if delayed branching is NOT enabled otherwise substitute m. n and m are single digit numbers indicating constant branch offset (in words). Added in 3.4.1 release.
# COMPACT is a marker to separate the default template from a second template optimized for 16-bit addresses. See loads and stores having (data) label operands.
# Everything else is copied as is into the generated statement (you must use register numbers not mnemonics)
# The list of basic instruction templates is optionally followed a description of the instruction for help purposes.
# To add optional description, append a tab then the ‘#’ character followed immediately (no spaces) by the description.
#
# See documentation for ExtendedInstruction.makeTemplateSubstitutions() for more details.
#
# Matching for a given instruction mnemonic is first-fit not best-fit. If an instruction has both 16 and 32-bit
# immediate operand options, they should be listed in that order (16-bit version first). Otherwise the 16-bit
# version will never be matched since the 32-bit version fits small immediate values first.
#
# The pseudo-op specification must start in the first column. If first column is blank, the line will be skipped!
#
# When specifying the example instruction (first item on line), the conventions I follow are:
# – for a register operand, specify a numbered register (e.g. $t1 or $f1) to represent any register in the set.
# The numerical value is not significant. This is NOT the case when writing the templates that follow!
# In the templates, numbered registers are parsed as is (use only $0 and $1, which are $zero and $at).
# – for an immediate operand, specify a positive value indicative of the expected range. I use 10 to represent
# a 5 bit value, 100 to represent a 16-bit value, and 100000 to represent a 32-bit value.
# – for a label operand, I use the string “label” (without the quotes).
# The idea is to give the parser an example that will be parsed into the desired token sequence. Syntax checking
# is done by comparing the source token sequence to list of token sequences generated from the examples.
# IMPORTANT NOTE: The use of $t1,$t2, etc in the instruction sample means that any CPU register reference
# can be used in that position. It is simply a placeholder. By contrast, when
# $1 is used in the template specification, $1 ($at) is literally placed into the generated
# instruction! If you want the generated code to echo the source register, use RG1,RG2, etc.

####################### arithmetic and branch pseudo-ops #####################

not $t1,$t2 nor RG1, RG2, $0 #Bitwise NOT (bit inversion)

# Here are some “convenience” arithmetic pseduo-ops. But do they encourage sloppy programming?
add $t1,$t2,-100 addi RG1, RG2, VL3 #ADDition : set $t1 to ($t2 plus 16-bit immediate)
add $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U add RG1, RG2, $1 #ADDition : set $t1 to ($t2 plus 32-bit immediate)
addu $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U addu RG1, RG2, $1 #ADDition Unsigned : set $t1 to ($t2 plus 32-bit immediate), no overflow
addi $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U add RG1, RG2, $1 #ADDition Immediate : set $t1 to ($t2 plus 32-bit immediate)
addiu $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U addu RG1, RG2, $1 #ADDition Immediate Unsigned: set $t1 to ($t2 plus 32-bit immediate), no overflow
sub $t1,$t2,-100 addi $1, $0, VL3 sub RG1, RG2, $1 #SUBtraction : set $t1 to ($t2 minus 16-bit immediate)
sub $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U sub RG1, RG2, $1 #SUBtraction : set $t1 to ($t2 minus 32-bit immediate)
subu $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U subu RG1, RG2, $1 #SUBtraction Unsigned : set $t1 to ($t2 minus 32-bit immediate), no overflow
subi $t1,$t2,-100 addi $1, $0, VL3 sub RG1, RG2, $1 #SUBtraction Immediate : set $t1 to ($t2 minus 16-bit immediate)
subi $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U sub RG1, RG2, $1 #SUBtraction Immediate : set $t1 to ($t2 minus 32-bit immediate)
subiu $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U subu RG1, RG2, $1 #SUBtraction Immediate Unsigned : set $t1 to ($t2 minus 32-bit immediate), no overflow
# feel free to add more convenience arithmetic pseduo-ops.

# convenience logical operations can be added too,
andi $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U and RG1, RG2, $1 #AND Immediate : set $t1 to ($t2 bitwise-AND 32-bit immediate)
ori $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U or RG1, RG2, $1 #OR Immediate : set $t1 to ($t2 bitwise-OR 32-bit immediate)
xori $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U xor RG1, RG2, $1 #XOR Immediate : set $t1 to ($t2 bitwise-exclusive-OR 32-bit immediate)
and $t1,$t2,100 andi RG1, RG2, VL3U #AND : set $t1 to ($t2 bitwise-AND 16-bit unsigned immediate)
or $t1,$t2,100 ori RG1, RG2, VL3U #OR : set $t1 to ($t2 bitwise-OR 16-bit unsigned immediate)
xor $t1,$t2,100 xori RG1, RG2, VL3U #XOR : set $t1 to ($t2 bitwise-exclusive-OR 16-bit unsigned immediate)
and $t1,100 andi RG1, RG1, VL2U #AND : set $t1 to ($t1 bitwise-AND 16-bit unsigned immediate)
or $t1,100 ori RG1, RG1, VL2U #OR : set $t1 to ($t1 bitwise-OR 16-bit unsigned immediate)
xor $t1,100 xori RG1, RG1, VL2U #XOR : set $t1 to ($t1 bitwise-exclusive-OR 16-bit unsigned immediate)
andi $t1,100 andi RG1, RG1, VL2U #AND Immediate : set $t1 to ($t1 bitwise-AND 16-bit unsigned immediate)
ori $t1,100 ori RG1, RG1, VL2U #OR Immediate : set $t1 to ($t1 bitwise-OR 16-bit unsigned immediate)
xori $t1,100 xori RG1, RG1, VL2U #XOR Immediate : set $t1 to ($t1 bitwise-exclusive-OR 16-bit unsigned immediate)
andi $t1,100000 lui $1, VHL2 ori $1, $1, VL2U and RG1, RG1, $1 #AND Immediate : set $t1 to ($t1 bitwise-AND 32-bit immediate)
ori $t1,100000 lui $1, VHL2 ori $1, $1, VL2U or RG1, RG1, $1 #OR Immediate : set $t1 to ($t1 bitwise-OR 32-bit immediate)
xori $t1,100000 lui $1, VHL2 ori $1, $1, VL2U xor RG1, RG1, $1 #XOR Immediate : set $t1 to ($t1 bitwise-exclusive-OR 32-bit immediate)

# Note: most of the expansions in this group were rewritten for Release 3.4.1 to remove internal branching.
seq $t1,$t2,$t3 subu RG1, RG2, RG3 ori $1, $0, 1 sltu RG1, RG1, $1 #Set EQual : if $t2 equal to $t3 then set $t1 to 1 else 0
seq $t1,$t2,-100 addi $1, $0, VL3 subu RG1, RG2, $1 ori $1, $0, 1 sltu RG1, RG1, $1 #Set EQual : if $t2 equal to 16-bit immediate then set $t1 to 1 else 0
seq $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U subu RG1, RG2, $1 ori $1, $0, 1 sltu RG1, RG1, $1 #Set EQual : if $t2 equal to 32-bit immediate then set $t1 to 1 else 0

sne $t1,$t2,$t3 subu RG1, RG2, RG3 sltu RG1, $0, RG1 #Set Not Equal : if $t2 not equal to $t3 then set $t1 to 1 else 0
sne $t1,$t2,-100 addi $1, $0, VL3 subu RG1, RG2, $1 sltu RG1, $0, RG1 #Set Not Equal : if $t2 not equal to 16-bit immediate then set $t1 to 1 else 0
sne $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U subu RG1, RG2, $1 sltu RG1, $0, RG1 #Set Not Equal : if $t2 not equal to 32-bit immediate then set $t1 to 1 else 0

sge $t1,$t2,$t3 slt RG1, RG2, RG3 ori $1, $0, 1 subu RG1, $1, RG1 #Set Greater or Equal : if $t2 greater or equal to $t3 then set $t1 to 1 else 0
sge $t1,$t2,-100 addi $1, $0, VL3 slt RG1, RG2, $1 ori $1, $0, 1 subu RG1, $1, RG1 #Set Greater or Equal : if $t2 greater or equal to 16-bit immediate then set $t1 to 1 else 0
sge $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U slt RG1, RG2, $1 ori $1, $0, 1 subu RG1, $1, RG1 #Set Greater or Equal : if $t2 greater or equal to 32-bit immediate then set $t1 to 1 else 0

sgeu $t1,$t2,$t3 sltu RG1, RG2, RG3 ori $1, $0, 1 subu RG1, $1, RG1 #Set Greater or Equal Unsigned : if $t2 greater or equal to $t3 (unsigned compare) then set $t1 to 1 else 0
sgeu $t1,$t2,-100 addi $1, $0, VL3 sltu RG1, RG2, $1 ori $1, $0, 1 subu RG1, $1, RG1 #Set Greater or Equal Unsigned : if $t2 greater or equal to 16-bit immediate (unsigned compare) then set $t1 to 1 else 0
sgeu $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U sltu RG1, RG2, $1 ori $1, $0, 1 subu RG1, $1, RG1 #Set Greater or Equal Unsigned : if $t2 greater or equal to 32-bit immediate (unsigned compare) then set $t1 to 1 else 0

sgt $t1,$t2,$t3 slt RG1, RG3, RG2 #Set Greater Than : if $t2 greater than $t3 then set $t1 to 1 else 0
sgt $t1,$t2,-100 addi $1, $0, VL3 slt RG1, $1, RG2 #Set Greater Than : if $t2 greater than 16-bit immediate then set $t1 to 1 else 0
sgt $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U slt RG1, $1, RG2 #Set Greater Than : if $t2 greater than 32-bit immediate then set $t1 to 1 else 0

sgtu $t1,$t2,$t3 sltu RG1, RG3, RG2 #Set Greater Than Unsigned : if $t2 greater than $t3 (unsigned compare) then set $t1 to 1 else 0
sgtu $t1,$t2,-100 addi $1, $0, VL3 sltu RG1, $1, RG2 #Set Greater Than Unsigned : if $t2 greater than 16-bit immediate (unsigned compare) then set $t1 to 1 else 0
sgtu $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U sltu RG1, $1, RG2 #Set Greater Than Unsigned : if $t2 greater than 32-bit immediate (unsigned compare) then set $t1 to 1 else 0

sle $t1,$t2,$t3 slt RG1, RG3, RG2 ori $1, $0, 1 subu RG1, $1, RG1 #Set Less or Equal : if $t2 less or equal to $t3 then set $t1 to 1 else 0
sle $t1,$t2,-100 addi $1, $0, VL3 slt RG1, $1, RG2 ori $1, $0, 1 subu RG1, $1, RG1 #Set Less or Equal : if $t2 less or equal to 16-bit immediate then set $t1 to 1 else 0
sle $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U slt RG1, $1, RG2 ori $1, $0, 1 subu RG1, $1, RG1 #Set Less or Equal : if $t2 less or equal to 32-bit immediate then set $t1 to 1 else 0

sleu $t1,$t2,$t3 sltu RG1, RG3, RG2 ori $1, $0, 1 subu RG1, $1, RG1 #Set Less or Equal Unsigned: if $t2 less or equal to $t3 (unsigned compare) then set $t1 to 1 else 0
sleu $t1,$t2,-100 addi $1, $0, VL3 sltu RG1, $1, RG2 ori $1, $0, 1 subu RG1, $1, RG1 #Set Less or Equal Unsigned: if $t2 less or equal to 16-bit immediate (unsigned compare) then set $t1 to 1 else 0
sleu $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U sltu RG1, $1, RG2 ori $1, $0, 1 subu RG1, $1, RG1 #Set Less or Equal Unsigned: if $t2 less or equal to 32-bit immediate (unsigned compare) then set $t1 to 1 else 0

move $t1,$t2 addu RG1, $0, RG2 #MOVE : Set $t1 to contents of $t2
abs $t1,$t2 sra $1, RG2, 31 xor RG1, $1, RG2 subu RG1, RG1, $1 #ABSolute value : Set $t1 to absolute value of $t2 (algorithm from Hacker’s Delight)
neg $t1,$t2 sub RG1, $0, RG2 #NEGate : Set $t1 to negation of $t2
negu $t1,$t2 subu RG1, $0, RG2 #NEGate Unsigned : Set $t1 to negation of $t2, no overflow

b label bgez $0, LAB #Branch : Branch to statement at label unconditionally
beqz $t1,label beq RG1, $0, LAB #Branch if EQual Zero : Branch to statement at label if $t1 is equal to zero
bnez $t1,label bne RG1, $0, LAB #Branch if Not Equal Zero : Branch to statement at label if $t1 is not equal to zero

beq $t1,-100,label addi $1, $0, VL2 beq $1, RG1, LAB #Branch if EQual : Branch to statement at label if $t1 is equal to 16-bit immediate
beq $t1,100000,label lui $1, VHL2 ori $1, $1, VL2U beq $1, RG1, LAB #Branch if EQual : Branch to statement at label if $t1 is equal to 32-bit immediate
bne $t1,-100,label addi $1, $0, VL2 bne $1, RG1, LAB #Branch if Not Equal : Branch to statement at label if $t1 is not equal to 16-bit immediate
bne $t1,100000,label lui $1, VHL2 ori $1, $1, VL2U bne $1, RG1, LAB #Branch if Not Equal : Branch to statement at label if $t1 is not equal to 32-bit immediate

bge $t1,$t2,label slt $1, RG1, RG2 beq $1, $0, LAB #Branch if Greater or Equal : Branch to statement at label if $t1 is greater or equal to $t2
bge $t1,-100,label slti $1, RG1, VL2 beq $1, $0, LAB #Branch if Greater or Equal : Branch to statement at label if $t1 is greater or equal to 16-bit immediate
bge $t1,100000,label lui $1, VHL2 ori $1, $1, VL2U slt $1, RG1, $1 beq $1, $0, LAB #Branch if Greater or Equal : Branch to statement at label if $t1 is greater or equal to 32-bit immediate

bgeu $t1,$t2,label sltu $1, RG1, RG2 beq $1, $0, LAB #Branch if Greater or Equal Unsigned : Branch to statement at label if $t1 is greater or equal to $t2 (unsigned compare)
bgeu $t1,-100,label sltiu $1, RG1, VL2 beq $1, $0, LAB #Branch if Greater or Equal Unsigned : Branch to statement at label if $t1 is greater or equal to 16-bit immediate (unsigned compare)
bgeu $t1,100000,label lui $1, VHL2 ori $1, $1, VL2U sltu $1, RG1, $1 beq $1, $0, LAB #Branch if Greater or Equal Unsigned : Branch to statement at label if $t1 is greater or equal to 32-bit immediate (unsigned compare)

bgt $t1,$t2,label slt $1, RG2, RG1 bne $1, $0, LAB #Branch if Greater Than : Branch to statement at label if $t1 is greater than $t2
bgt $t1,-100,label addi $1, $0, VL2 slt $1, $1, RG1 bne $1, $0, LAB #Branch if Greater Than : Branch to statement at label if $t1 is greater than 16-bit immediate
bgt $t1,100000,label lui $1, VHL2P1 ori $1, $1, VL2P1U slt $1, RG1, $1 beq $1, $0, LAB #Branch if Greater Than : Branch to statement at label if $t1 is greater than 32-bit immediate

bgtu $t1,$t2,label sltu $1, RG2, RG1 bne $1, $0, LAB #Branch if Greater Than Unsigned: Branch to statement at label if $t1 is greater than $t2 (unsigned compare)
bgtu $t1,-100,label addi $1, $0, VL2 sltu $1, $1, RG1 bne $1, $0, LAB #Branch if Greater Than Unsigned: Branch to statement at label if $t1 is greater than 16-bit immediate (unsigned compare)
bgtu $t1,100000,label lui $1, VHL2 ori $1, $1, VL2U sltu $1, $1, RG1 bne $1, $0, LAB #Branch if Greater Than Unsigned: Branch to statement at label if $t1 is greater than 16-bit immediate (unsigned compare)

ble $t1,$t2,label slt $1, RG2, RG1 beq $1, $0, LAB #Branch if Less or Equal : Branch to statement at label if $t1 is less than or equal to $t2
ble $t1,-100,label addi $1, RG1, -1 slti $1, $1, VL2 bne $1, $0, LAB #Branch if Less or Equal : Branch to statement at label if $t1 is less than or equal to 16-bit immediate
ble $t1,100000,label lui $1, VHL2P1 ori $1, $1, VL2P1U slt $1, RG1, $1 bne $1, $0, LAB #Branch if Less or Equal : Branch to statement at label if $t1 is less than or equal to 32-bit immediate

bleu $t1,$t2,label sltu $1, RG2, RG1 beq $1, $0, LAB #Branch if Less or Equal Unsigned : Branch to statement at label if $t1 is less than or equal to $t2 (unsigned compare)
bleu $t1,-100,label addi $1, $0, VL2 sltu $1, $1, RG1 beq $1, $0, LAB #Branch if Less or Equal Unsigned : Branch to statement at label if $t1 is less than or equal to 16-bit immediate (unsigned compare)
bleu $t1,100000,label lui $1, VHL2 ori $1, $1, VL2U sltu $1, $1, RG1 beq $1, $0, LAB #Branch if Less or Equal Unsigned : Branch to statement at label if $t1 is less than or equal to 32-bit immediate (unsigned compare)

blt $t1,$t2,label slt $1, RG1, RG2 bne $1, $0, LAB #Branch if Less Than : Branch to statement at label if $t1 is less than $t2
blt $t1,-100,label slti $1, RG1, VL2 bne $1, $0, LAB #Branch if Less Than : Branch to statement at label if $t1 is less than 16-bit immediate
blt $t1,100000,label lui $1, VHL2 ori $1, $1, VL2U slt $1, RG1, $1 bne $1, $0, LAB #Branch if Less Than : Branch to statement at label if $t1 is less than 32-bit immediate

bltu $t1,$t2,label sltu $1, RG1, RG2 bne $1, $0, LAB #Branch if Less Than Unsigned : Branch to statement at label if $t1 is less than $t2
bltu $t1,-100,label sltiu $1, RG1, VL2 bne $1, $0, LAB #Branch if Less Than Unsigned : Branch to statement at label if $t1 is less than 16-bit immediate
bltu $t1,100000,label lui $1, VHL2 ori $1, $1, VL2U sltu $1, RG1, $1 bne $1, $0, LAB #Branch if Less Than Unsigned : Branch to statement at label if $t1 is less than 32-bit immediate

rol $t1,$t2,$t3 subu $1, $0, RG3 srlv $1, RG2, $1 sllv RG1, RG2, RG3 or RG1, RG1, $1 #ROtate Left : Set $t1 to ($t2 rotated left by number of bit positions specified in $t3)
rol $t1,$t2,10 srl $1, RG2, S32 sll RG1, RG2, OP3 or RG1, RG1, $1 #ROtate Left : Set $t1 to ($t2 rotated left by number of bit positions specified in 5-bit immediate)
ror $t1,$t2,$t3 subu $1, $0, RG3 sllv $1, RG2, $1 srlv RG1, RG2, RG3 or RG1, RG1, $1 #ROtate Right : Set $t1 to ($t2 rotated right by number of bit positions specified in $t3)
ror $t1,$t2,10 sll $1, RG2, S32 srl RG1, RG2, OP3 or RG1, RG1, $1 #ROtate Right : Set $t1 to ($t2 rotated right by number of bit positions specified in 5-bit immediate)

mfc1.d $t1,$f2 mfc1 RG1, RG2 mfc1 NR1, NR2 #Move From Coprocessor 1 Double : Set $t1 to contents of $f2, set next higher register from $t1 to contents of next higher register from $f2
mtc1.d $t1,$f2 mtc1 RG1, RG2 mtc1 NR1, NR2 #Move To Coprocessor 1 Double : Set $f2 to contents of $t1, set next higher register from $f2 to contents of next higher register from $t1

mul $t1,$t2,-100 addi $1, $0, VL3 mul RG1, RG2, $1 #MULtiplication : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of the product of $t2 and 16-bit signed immediate (use mfhi to access HI, mflo to access LO)
mul $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U mul RG1, RG2, $1 #MULtiplication : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of the product of $t2 and 32-bit immediate (use mfhi to access HI, mflo to access LO)
mulu $t1,$t2,$t3 multu RG2, RG3 mflo RG1 #MULtiplication Unsigned : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of ($t2 multiplied by $t3, unsigned multiplication)
mulu $t1,$t2,-100 addi $1, $0, VL3 multu RG2, $1 mflo RG1 #MULtiplication Unsigned : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of ($t2 multiplied by 16-bit immediate, unsigned multiplication)
mulu $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U multu RG2, $1 mflo RG1 #MULtiplication Unsigned : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of ($t2 multiplied by 32-bit immediate, unsigned multiplication)
mulo $t1,$t2,$t3 mult RG2, RG3 mfhi $1 mflo RG1 sra RG1, RG1, 31 beq $1, RG1, BROFF12 DBNOP break mflo RG1 #MULtiplication with Overflow : Set $t1 to low-order 32 bits of the product of $t2 and $t3
mulo $t1,$t2,-100 addi $1, $0, VL3 mult RG2, $1 mfhi $1 mflo RG1 sra RG1, RG1, 31 beq $1, RG1, BROFF12 DBNOP break mflo RG1 #MULtiplication with Overflow : Set $t1 to low-order 32 bits of the product of $t2 and signed 16-bit immediate
mulo $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U mult RG2, $1 mfhi $1 mflo RG1 sra RG1, RG1, 31 beq $1, RG1, BROFF12 DBNOP break mflo RG1 #MULtiplication with Overflow : Set $t1 to low-order 32 bits of the product of $t2 and 32-bit immediate
mulou $t1,$t2,$t3 multu RG2, RG3 mfhi $1 beq $1,$0, BROFF12 DBNOP break mflo RG1 #MULtiplication with Overflow Unsigned : Set $t1 to low-order 32 bits of the product of $t2 and $t3
mulou $t1,$t2,-100 addi $1, $0, VL3 multu RG2, $1 mfhi $1 beq $1,$0, BROFF12 DBNOP break mflo RG1 #MULtiplication with Overflow Unsigned : Set $t1 to low-order 32 bits of the product of $t2 and signed 16-bit immediate
mulou $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U multu RG2, $1 mfhi $1 beq $1,$0, BROFF12 DBNOP break mflo RG1 #MULtiplication with Overflow Unsigned : Set $t1 to low-order 32 bits of the product of $t2 and 32-bit immediate
div $t1,$t2,$t3 bne RG3, $0, BROFF12 DBNOP break div RG2, RG3 mflo RG1 #DIVision : Set $t1 to ($t2 divided by $t3, integer division)
div $t1,$t2,-100 addi $1, $0, VL3 div RG2, $1 mflo RG1 #DIVision : Set $t1 to ($t2 divided by 16-bit immediate, integer division)
div $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U div RG2, $1 mflo RG1 #DIVision : Set $t1 to ($t2 divided by 32-bit immediate, integer division)
divu $t1,$t2,$t3 bne RG3, $0, BROFF12 DBNOP break divu RG2, RG3 mflo RG1 #DIVision Unsigned : Set $t1 to ($t2 divided by $t3, unsigned integer division)
divu $t1,$t2,-100 addi $1, $0, VL3 divu RG2, $1 mflo RG1 #DIVision Unsigned : Set $t1 to ($t2 divided by 16-bit immediate, unsigned integer division)
divu $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U divu RG2, $1 mflo RG1 #DIVision Unsigned : Set $t1 to ($t2 divided by 32-bit immediate, unsigned integer division)
rem $t1,$t2,$t3 bne RG3, $0, BROFF12 DBNOP break div RG2, RG3 mfhi RG1 #REMainder : Set $t1 to (remainder of $t2 divided by $t3)
rem $t1,$t2,-100 addi $1, $0, VL3 div RG2, $1 mfhi RG1 #REMainder : Set $t1 to (remainder of $t2 divided by 16-bit immediate)
rem $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U div RG2, $1 mfhi RG1 #REMainder : Set $t1 to (remainder of $t2 divided by 32-bit immediate)
remu $t1,$t2,$t3 bne RG3, $0, BROFF12 DBNOP break divu RG2, RG3 mfhi RG1 #REMainder : Set $t1 to (remainder of $t2 divided by $t3, unsigned division)
remu $t1,$t2,-100 addi $1, $0, VL3 divu RG2, $1 mfhi RG1 #REMainder : Set $t1 to (remainder of $t2 divided by 16-bit immediate, unsigned division)
remu $t1,$t2,100000 lui $1, VHL3 ori $1, $1, VL3U divu RG2, $1 mfhi RG1 #REMainder : Set $t1 to (remainder of $t2 divided by 32-bit immediate, unsigned division)

######################### load/store pseudo-ops start here ##########################
#
# Most of these simply provide a variety of convenient memory addressing modes for
# specifying load/store address.
#

li $t1,-100 addiu RG1, $0, VL2 #Load Immediate : Set $t1 to 16-bit immediate (sign-extended)
li $t1,100 ori RG1, $0, VL2U #Load Immediate : Set $t1 to unsigned 16-bit immediate (zero-extended)
li $t1,100000 lui $1, VHL2 ori RG1, $1, VL2U #Load Immediate : Set $t1 to 32-bit immediate

la $t1,($t2) addi RG1, RG3, 0 #Load Address : Set $t1 to contents of $t2
la $t1,-100 addiu RG1, $0, VL2 #Load Address : Set $t1 to 16-bit immediate (sign-extended)
la $t1,100 ori RG1, $0, VL2U #Load Address : Set $t1 to 16-bit immediate (zero-extended)
la $t1,100000 lui $1, VHL2 ori RG1, $1, VL2U #Load Address : Set $t1 to 32-bit immediate
la $t1,100($t2) ori $1, $0, VL2U add RG1, RG4, $1 #Load Address : Set $t1 to sum (of $t2 and 16-bit immediate)
la $t1,100000($t2) lui $1, VHL2 ori $1, $1, VL2U add RG1, RG4, $1 #Load Address : Set $t1 to sum (of $t2 and 32-bit immediate)
la $t1,label lui $1, LHL ori RG1, $1, LL2U COMPACT addi RG1, $0, LL2 #Load Address : Set $t1 to label’s address
la $t1,label($t2) lui $1, LHL ori $1, $1, LL2U add RG1, RG4, $1 COMPACT addi RG1, RG4, LL2 #Load Address : Set $t1 to sum (of $t2 and label’s address)
la $t1,label+100000 lui $1, LHPN ori RG1, $1, LLPU #Load Address : Set $t1 to sum (of label’s address and 32-bit immediate)
la $t1,label+100000($t2) lui $1, LHPN ori $1, $1, LLPU add RG1, RG6, $1 #Load Address : Set $t1 to sum (of label’s address, 32-bit immediate, and $t2)

lw $t1,($t2) lw RG1,0(RG3) #Load Word : Set $t1 to contents of effective memory word address
lw $t1,-100 lw RG1, VL2($0) #Load Word : Set $t1 to contents of effective memory word address
lw $t1,100 ori $1, $0, VL2U lw RG1, 0($1) #Load Word : Set $t1 to contents of effective memory word address
lw $t1,100000 lui $1, VH2 lw RG1,VL2($1) #Load Word : Set $t1 to contents of effective memory word address
lw $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 lw RG1, 0($1) #Load Word : Set $t1 to contents of effective memory word address
lw $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 lw RG1, VL2($1) #Load Word : Set $t1 to contents of effective memory word address
lw $t1,label lui $1, LH2 lw RG1, LL2($1) COMPACT lw RG1, LL2($0) #Load Word : Set $t1 to contents of memory word at label’s address
lw $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 lw RG1, LL2($1) COMPACT lw RG1, LL2(RG4) #Load Word : Set $t1 to contents of effective memory word address
lw $t1,label+100000 lui $1, LHPA lw RG1, LLP($1) #Load Word : Set $t1 to contents of effective memory word address
lw $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 lw RG1, LLP($1) #Load Word : Set $t1 to contents of effective memory word address

sw $t1,($t2) sw RG1,0(RG3) #Store Word : Store $t1 contents into effective memory word address
sw $t1,-100 sw RG1, VL2($0) #Store Word : Store $t1 contents into effective memory word address
sw $t1,100 ori $1, $0, VL2U sw RG1, 0($1) #Store Word : Store $t1 contents into effective memory word address
sw $t1,100000 lui $1, VH2 sw RG1,VL2($1) #Store Word : Store $t1 contents into effective memory word address
sw $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 sw RG1, 0($1) #Store Word : Store $t1 contents into effective memory word address
sw $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 sw RG1, VL2($1) #Store Word : Store $t1 contents into effective memory word address
sw $t1,label lui $1, LH2 sw RG1, LL2($1) COMPACT sw RG1, LL2($0) #Store Word : Store $t1 contents into memory word at label’s address
sw $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 sw RG1, LL2($1) COMPACT sw RG1, LL2(RG4) #Store Word : Store $t1 contents into effective memory word address
sw $t1,label+100000 lui $1, LHPA sw RG1, LLP($1) #Store Word : Store $t1 contents into effective memory word address
sw $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 sw RG1, LLP($1) #Store Word : Store $t1 contents into effective memory word address

lh $t1,($t2) lh RG1,0(RG3) #Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address
lh $t1,-100 lh RG1, VL2($0) #Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address
lh $t1,100 ori $1, $0, VL2U lh RG1, 0($1) #Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address
lh $t1,100000 lui $1, VH2 lh RG1,VL2($1) #Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address
lh $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 lh RG1, 0($1) #Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address
lh $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 lh RG1, VL2($1) #Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address
lh $t1,label lui $1, LH2 lh RG1, LL2($1) COMPACT lh RG1, LL2($0) #Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address
lh $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 lh RG1, LL2($1) COMPACT lh RG1, LL2(RG4) #Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address
lh $t1,label+100000 lui $1, LHPA lh RG1, LLP($1) #Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address
lh $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 lh RG1, LLP($1) #Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address

sh $t1,($t2) sh RG1,0(RG3) #Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address
sh $t1,-100 sh RG1, VL2($0) #Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address
sh $t1,100 ori $1, $0, VL2U sh RG1, 0($1) #Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address
sh $t1,100000 lui $1, VH2 sh RG1,VL2($1) #Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address
sh $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 sh RG1, 0($1) #Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address
sh $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 sh RG1, VL2($1) #Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address
sh $t1,label lui $1, LH2 sh RG1, LL2($1) COMPACT sh RG1, LL2($0) #Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address
sh $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 sh RG1, LL2($1) COMPACT sh RG1, LL2(RG4) #Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address
sh $t1,label+100000 lui $1, LHPA sh RG1, LLP($1) #Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address
sh $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 sh RG1, LLP($1) #Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address

lb $t1,($t2) lb RG1,0(RG3) #Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address
lb $t1,-100 lb RG1, VL2($0) #Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address
lb $t1,100 ori $1, $0, VL2U lb RG1, 0($1) #Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address
lb $t1,100000 lui $1, VH2 lb RG1,VL2($1) #Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address
lb $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 lb RG1, 0($1) #Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address
lb $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 lb RG1, VL2($1) #Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address
lb $t1,label lui $1, LH2 lb RG1, LL2($1) COMPACT lb RG1, LL2($0) #Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address
lb $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 lb RG1, LL2($1) COMPACT lb RG1, LL2(RG4) #Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address
lb $t1,label+100000 lui $1, LHPA lb RG1, LLP($1) #Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address
lb $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 lb RG1, LLP($1) #Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address

sb $t1,($t2) sb RG1,0(RG3) #Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address
sb $t1,-100 sb RG1, VL2($0) #Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address
sb $t1,100 ori $1, $0, VL2U sb RG1, 0($1) #Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address
sb $t1,100000 lui $1, VH2 sb RG1,VL2($1) #Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address
sb $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 sb RG1, 0($1) #Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address
sb $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 sb RG1, VL2($1) #Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address
sb $t1,label lui $1, LH2 sb RG1, LL2($1) COMPACT sb RG1, LL2($0) #Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address
sb $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 sb RG1, LL2($1) COMPACT sb RG1, LL2(RG4) #Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address
sb $t1,label+100000 lui $1, LHPA sb RG1, LLP($1) #Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address
sb $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 sb RG1, LLP($1) #Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address

lhu $t1,($t2) lhu RG1,0(RG3) #Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address
lhu $t1,-100 lhu RG1,VL2($0) #Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address
lhu $t1,100 ori $1, $0, VL2U lhu RG1, 0($1) #Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address
lhu $t1,100000 lui $1, VH2 lhu RG1,VL2($1) #Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address
lhu $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 lhu RG1, 0($1) #Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address
lhu $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 lhu RG1, VL2($1) #Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address
lhu $t1,label lui $1, LH2 lhu RG1, LL2($1) COMPACT lhu RG1, LL2($0) #Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address
lhu $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 lhu RG1, LL2($1) COMPACT lhu RG1, LL2(RG4) #Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address
lhu $t1,label+100000 lui $1, LHPA lhu RG1, LLP($1) #Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address
lhu $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 lhu RG1, LLP($1) #Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address

lbu $t1,($t2) lbu RG1,0(RG3) #Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address
lbu $t1,-100 lbu RG1,VL2($0) #Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address
lbu $t1,100 ori $1, $0, VL2U lbu RG1, 0($1) #Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address
lbu $t1,100000 lui $1, VH2 lbu RG1,VL2($1) #Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address
lbu $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 lbu RG1, 0($1) #Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address
lbu $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 lbu RG1, VL2($1) #Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address
lbu $t1,label lui $1, LH2 lbu RG1, LL2($1) COMPACT lbu RG1, LL2($0) #Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address
lbu $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 lbu RG1, LL2($1) COMPACT lbu RG1, LL2(RG4) #Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address
lbu $t1,label+100000 lui $1, LHPA lbu RG1, LLP($1) #Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address
lbu $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 lbu RG1, LLP($1) #Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address

lwl $t1,($t2) lwl RG1,0(RG3) #Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word
lwl $t1,-100 lwl RG1,VL2($0) #Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word
lwl $t1,100 ori $1, $0, VL2U lwl RG1, 0($1) #Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word
lwl $t1,100000 lui $1, VH2 lwl RG1,VL2($1) #Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word
lwl $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 lwl RG1, 0($1) #Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word
lwl $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 lwl RG1, VL2($1) #Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word
lwl $t1,label lui $1, LH2 lwl RG1, LL2($1) COMPACT lwl RG1, LL2($0) #Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word
lwl $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 lwl RG1, LL2($1) COMPACT lwl RG1, LL2(RG4) #Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word
lwl $t1,label+100000 lui $1, LHPA lwl RG1, LLP($1) #Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word
lwl $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 lwl RG1, LLP($1) #Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word

swl $t1,($t2) swl RG1,0(RG3) #Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word
swl $t1,-100 swl RG1,VL2($0) #Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word
swl $t1,100 ori $1, $0, VL2U swl RG1, 0($1) #Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word
swl $t1,100000 lui $1, VH2 swl RG1,VL2($1) #Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word
swl $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 swl RG1, 0($1) #Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word
swl $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 swl RG1, VL2($1) #Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word
swl $t1,label lui $1, LH2 swl RG1, LL2($1) COMPACT swl RG1, LL2($0) #Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word
swl $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 swl RG1, LL2($1) COMPACT swl RG1, LL2(RG4) #Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word
swl $t1,label+100000 lui $1, LHPA swl RG1, LLP($1) #Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word
swl $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 swl RG1, LLP($1) #Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word

lwr $t1,($t2) lwr RG1,0(RG3) #Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word
lwr $t1,-100 lwr RG1,VL2($0) #Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word
lwr $t1,100 ori $1, $0, VL2U lwr RG1, 0($1) #Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word
lwr $t1,100000 lui $1, VH2 lwr RG1,VL2($1) #Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word
lwr $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 lwr RG1, 0($1) #Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word
lwr $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 lwr RG1, VL2($1) #Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word
lwr $t1,label lui $1, LH2 lwr RG1, LL2($1) COMPACT lwr RG1, LL2($0) #Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word
lwr $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 lwr RG1, LL2($1) COMPACT lwr RG1, LL2(RG4) #Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word
lwr $t1,label+100000 lui $1, LHPA lwr RG1, LLP($1) #Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word
lwr $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 lwr RG1, LLP($1) #Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word

swr $t1,($t2) swr RG1,0(RG3) #Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address
swr $t1,-100 swr RG1,VL2($0) #Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address
swr $t1,100 ori $1, $0, VL2U swr RG1, 0 #Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address
swr $t1,100000 lui $1, VH2 swr RG1,VL2($1) #Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address
swr $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 swr RG1, 0($1) #Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address
swr $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 swr RG1, VL2($1) #Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address
swr $t1,label lui $1, LH2 swr RG1, LL2($1) COMPACT swr RG1, LL2($0) #Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address
swr $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 swr RG1, LL2($1) COMPACT swr RG1, LL2(RG4) #Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address
swr $t1,label+100000 lui $1, LHPA swr RG1, LLP($1) #Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address
swr $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 swr RG1, LLP($1) #Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address

ll $t1,($t2) ll RG1,0(RG3) #Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.
ll $t1,-100 ll RG1,VL2($0) #Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.
ll $t1,100 ori $1, $0, VL2U ll RG1, 0($1) #Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.
ll $t1,100000 lui $1, VH2 ll RG1,VL2($1) #Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.
ll $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 ll RG1, 0($1) #Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.
ll $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 ll RG1, VL2($1) #Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.
ll $t1,label lui $1, LH2 ll RG1, LL2($1) COMPACT ll RG1, LL2($0) #Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.
ll $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 ll RG1, LL2($1) COMPACT ll RG1, LL2(RG4) #Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.
ll $t1,label+100000 lui $1, LHPA ll RG1, LLP($1) #Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.
ll $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 ll RG1, LLP($1) #Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.

sc $t1,($t2) sc RG1,0(RG3) #Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors.
sc $t1,-100 sc RG1,VL2($0) #Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors.
sc $t1,100 ori $1, $0, VL2U sc RG1, 0($1) #Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors.
sc $t1,100000 lui $1, VH2 sc RG1,VL2($1) #Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors.
sc $t1,100($t2) ori $1, $0, VL2U addu $1, $1, RG4 sc RG1, 0($1) #Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors.
sc $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 sc RG1, VL2($1) #Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors.
sc $t1,label lui $1, LH2 sc RG1, LL2($1) COMPACT sc RG1, LL2($0) #Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors.
sc $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 sc RG1, LL2($1) COMPACT sc RG1, LL2(RG4) #Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors.
sc $t1,label+100000 lui $1, LHPA sc RG1, LLP($1) #Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors.
sc $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 sc RG1, LLP($1) #Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors.

# Unaligned and double loads and stores. All the them require assembler to add a constant
# byte offset (from 1 to 4 bytes) to the given or calculated address.
# NOTE: I have abandoned the “accepted” expansion of immed16($reg) addressing form for the
# unaligned and double load/store pseudo-instructions because they produce what I consider
# incorrect results for immediate values at the upper edge of the signed 16-bit range
# (32765 through 32767). The expansion of these pseudo’s requires adding an additional
# byte offset (from 1 to 4 bytes) to the immediate value, which overflows the signed 16
# bit range and results in a large negative offset with no counterbalancing increment
# to the high order 16-bits. Thus if the two pieces of unaligned data end up in different
# words, they are stored 64K bytes apart! For example, the normal expansion of
# “usw $8,32767($9)” would be “swl $8,-32766($9)”, “swr $8, 32767($9)” Both SPIM and
# Britten’s text do this but I consider it incorrect. My compromise is the following:
# since each of the expansion calls for two calculated offsets, one of which can possibly
# overflow due to the addition but the other will not (because there is no addition),
# I’ll code the expansion to treat the at-risk calculated offset as 32-bits (it will generate
# the lui and addu, which is unnecessary in almost every case but is always correct)
# and the second as 16-bits. I’ll group all instructions for this addressing mode together.
# ulw $t1,-100($t2) lwl RG1, VL2P3(RG4) lwr RG1, VL2(RG4) — used by SPIM but not me.
# usw $t1,-100($t2) swl RG1, VL2P3(RG4) swr RG1, VL2(RG4) — used by SPIM but not me.

ulw $t1,-100($t2) lui $1, VH2P3 addu $1, $1, RG4 lwl RG1, VL2P3($1) lwr RG1, VL2(RG4) #Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address
ulh $t1,-100($t2) lui $1, VH2P1 addu $1, $1, RG4 lb RG1, VL2P1($1) lbu $1, VL2(RG4) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address
ulhu $t1,-100($t2) lui $1, VH2P1 addu $1, $1, RG4 lbu RG1, VL2P1($1) lbu $1, VL2(RG4) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address
ld $t1,-100($t2) lw RG1, VL2(RG4) lui $1, VH2P4 addu $1, $1, RG4 lw NR1, VL2P4($1) #Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory byte address
usw $t1,-100($t2) lui $1, VH2P3 addu $1, $1, RG4 swl RG1, VL2P3($1) swr RG1, VL2(RG4) #Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address
ush $t1,-100($t2) sb RG1, VL2(RG4) sll $1, RG1, 24 srl RG1, RG1, 8 or RG1, RG1, $1 lui $1, VH2P1 addu $1, $1, RG4 sb RG1, VL2P1($1) srl $1, RG1, 24 sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address
sd $t1,-100($t2) sw RG1, VL2(RG4) lui $1, VH2P4 addu $1, $1, RG4 sw NR1, VL2P4($1) #Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory byte address

# here are the remaining addressing modes, grouped by instruction.

ulw $t1,100000 lui $1, VH2P3 lwl RG1, VL2P3($1) lui $1, VH2 lwr RG1, VL2($1) #Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address
ulw $t1,label lui $1, LH2P3 lwl RG1, LL2P3($1) lui $1, LH2 lwr RG1, LL2($1) #Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address
ulw $t1,label+100000 lui $1, LHPAP3 lwl RG1, LLPP3($1) lui $1, LHPA lwr RG1, LLP($1) #Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address
ulw $t1,($t2) lwl RG1, 3(RG3) lwr RG1, 0(RG3) #Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address
ulw $t1,100000($t2) lui $1, VH2P3 addu $1, $1, RG4 lwl RG1, VL2P3($1) lui $1, VH2 addu $1, $1, RG4 lwr RG1, VL2($1) #Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address
ulw $t1,label($t2) lui $1, LH2P3 addu $1, $1, RG4 lwl RG1, LL2P3($1) lui $1, LH2 addu $1, $1, RG4 lwr RG1, LL2($1) #Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address
ulw $t1,label+100000($t2) lui $1, LHPAP3 addu $1, $1, RG6 lwl RG1, LLPP3($1) lui $1, LHPA addu $1, $1, RG6 lwr RG1, LLP($1) #Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address

ulh $t1,100000 lui $1, VH2P1 lb RG1, VL2P1($1) lui $1, VH2 lbu $1, VL2($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address
ulh $t1,label lui $1, LH2P1 lb RG1, LL2P1($1) lui $1, LH2 lbu $1, LL2($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address
ulh $t1,label+100000 lui $1, LHPAP1 lb RG1, LLPP1($1) lui $1, LHPA lbu $1, LLP($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address
ulh $t1,($t2) lb RG1, 1(RG3) lbu $1, 0(RG3) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address
ulh $t1,100000($t2) lui $1, VH2P1 addu $1, $1, RG4 lb RG1, VL2P1($1) lui $1, VH2 addu $1, $1, RG4 lbu $1, VL2($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address
ulh $t1,label($t2) lui $1, LH2P1 addu $1, $1, RG4 lb RG1, LL2P1($1) lui $1, LH2 addu $1, $1, RG4 lbu $1, LL2($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address
ulh $t1,label+100000($t2) lui $1, LHPAP1 addu $1, $1, RG6 lb RG1, LLPP1($1) lui $1, LHPA addu $1, $1, RG6 lbu $1, LLP($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address

ulhu $t1,100000 lui $1, VH2P1 lbu RG1, VL2P1($1) lui $1, VH2 lbu $1, VL2($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address
ulhu $t1,label lui $1, LH2P1 lbu RG1, LL2P1($1) lui $1, LH2 lbu $1, LL2($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address
ulhu $t1,label+100000 lui $1, LHPAP1 lbu RG1, LLPP1($1) lui $1, LHPA lbu $1, LLP($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address
ulhu $t1,($t2) lbu RG1, 1(RG3) lbu $1, 0(RG3) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address
ulhu $t1,100000($t2) lui $1, VH2P1 addu $1, $1, RG4 lbu RG1, VL2P1($1) lui $1, VH2 addu $1, $1, RG4 lbu $1, VL2($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address
ulhu $t1,label($t2) lui $1, LH2P1 addu $1, $1, RG4 lbu RG1, LL2P1($1) lui $1, LH2 addu $1, $1, RG4 lbu $1, LL2($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address
ulhu $t1,label+100000($t2) lui $1, LHPAP1 addu $1, $1, RG6 lbu RG1, LLPP1($1) lui $1, LHPA addu $1, $1, RG6 lbu $1, LLP($1) sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address

ld $t1,100000 lui $1, VH2 lw RG1, VL2($1) lui $1, VH2P4 lw NR1, VL2P4($1) #Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address
ld $t1,label lui $1, LH2 lw RG1, LL2($1) lui $1, LH2P4 lw NR1, LL2P4($1) #Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address
ld $t1,label+100000 lui $1, LHPA lw RG1, LLP($1) lui $1, LHPAP4 lw NR1, LLPP4($1) #Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address
ld $t1,($t2) lw RG1, 0(RG3) lw NR1, 4(RG3) #Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address
ld $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 lw RG1, VL2($1) lui $1, VH2P4 addu $1, $1, RG4 lw NR1, VL2P4($1) #Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address
ld $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 lw RG1, LL2($1) lui $1, LH2P4 addu $1, $1, RG4 lw NR1, LL2P4($1) #Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address
ld $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 lw RG1, LLP($1) lui $1, LHPAP4 addu $1, $1, RG6 lw NR1, LLPP4($1) #Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address

usw $t1,100000 lui $1, VH2P3 swl RG1, VL2P3($1) lui $1, VH2 swr RG1, VL2($1) #Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address
usw $t1,label lui $1, LH2P3 swl RG1, LL2P3($1) lui $1, LH2 swr RG1, LL2($1) #Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address
usw $t1,label+100000 lui $1, LHPAP3 swl RG1, LLPP3($1) lui $1, LHPA swr RG1, LLP($1) #Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address
usw $t1,($t2) swl RG1, 3(RG3) swr RG1, 0(RG3) #Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address
usw $t1,100000($t2) lui $1, VH2P3 addu $1, $1, RG4 swl RG1, VL2P3($1) lui $1, VH2 addu $1, $1, RG4 swr RG1, VL2($1) #Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address
usw $t1,label($t2) lui $1, LH2P3 addu $1, $1, RG4 swl RG1, LL2P3($1) lui $1, LH2 addu $1, $1, RG4 swr RG1, LL2($1) #Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address
usw $t1,label+100000($t2) lui $1, LHPAP3 addu $1, $1, RG6 swl RG1, LLPP3($1) lui $1, LHPA addu $1, $1, RG6 swr RG1, LLP($1) #Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address

ush $t1,100000 lui $1, VH2 sb RG1, VL2($1) sll $1, RG1, 24 srl RG1, RG1, 8 or RG1, RG1, $1 lui $1, VH2P1 sb RG1, VL2P1($1) srl $1, RG1, 24 sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address
ush $t1,label lui $1, LH2 sb RG1, LL2($1) sll $1, RG1, 24 srl RG1, RG1, 8 or RG1, RG1, $1 lui $1, LH2P1 sb RG1, LL2P1($1) srl $1, RG1, 24 sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address
ush $t1,label+100000 lui $1, LHPA sb RG1, LLP($1) sll $1, RG1, 24 srl RG1, RG1, 8 or RG1, RG1, $1 lui $1, LHPAP1 sb RG1, LLPP1($1) srl $1, RG1, 24 sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address
ush $t1,($t2) sb RG1, 0(RG3) sll $1, RG1, 24 srl RG1, RG1, 8 or RG1, RG1, $1 sb RG1, 1(RG3) srl $1, RG1, 24 sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address
ush $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 sb RG1, VL2($1) sll $1, RG1, 24 srl RG1, RG1, 8 or RG1, RG1, $1 lui $1, VH2P1 addu $1, $1, RG4 sb RG1, VL2P1($1) srl $1, RG1, 24 sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address
ush $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 sb RG1, LL2($1) sll $1, RG1, 24 srl RG1, RG1, 8 or RG1, RG1, $1 lui $1, LH2P1 addu $1, $1, RG4 sb RG1, LL2P1($1) srl $1, RG1, 24 sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address
ush $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 sb RG1, LLP($1) sll $1, RG1, 24 srl RG1, RG1, 8 or RG1, RG1, $1 lui $1, LHPAP1 addu $1, $1, RG6 sb RG1, LLPP1($1) srl $1, RG1, 24 sll RG1, RG1, 8 or RG1, RG1, $1 #Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address

sd $t1,100000 lui $1, VH2 sw RG1, VL2($1) lui $1, VH2P4 sw NR1, VL2P4($1) #Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address
sd $t1,label lui $1, LH2 sw RG1, LL2($1) lui $1, LH2P4 sw NR1, LL2P4($1) #Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address
sd $t1,label+100000 lui $1, LHPA sw RG1, LLP($1) lui $1, LHPAP4 sw NR1, LLPP4($1) #Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address
sd $t1,($t2) sw RG1, 0(RG3) sw NR1, 4(RG3) #Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address
sd $t1,100000($t2) lui $1, VH2 addu $1, $1, RG4 sw RG1, VL2($1) lui $1, VH2P4 addu $1, $1, RG4 sw NR1, VL2P4($1) #Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address
sd $t1,label($t2) lui $1, LH2 addu $1, $1, RG4 sw RG1, LL2($1) lui $1, LH2P4 addu $1, $1, RG4 sw NR1, LL2P4($1) #Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address
sd $t1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 sw RG1, LLP($1) lui $1, LHPAP4 addu $1, $1, RG6 sw NR1, LLPP4($1) #Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address

# load and store pseudo-instructions for floating point (coprocessor 1) registers

lwc1 $f1,($t2) lwc1 RG1,0(RG3) #Load Word Coprocessor 1 : Set $f1 to 32-bit value from effective memory word address
lwc1 $f1,-100 lwc1 RG1,VL2($0) #Load Word Coprocessor 1 : Set $f1 to 32-bit value from effective memory word address
lwc1 $f1,100000 lui $1, VH2 lwc1 RG1,VL2($1) #Load Word Coprocessor 1 : Set $f1 to 32-bit value from effective memory word address
lwc1 $f1,100000($t2) lui $1, VH2 addu $1, $1, RG4 lwc1 RG1, VL2($1) #Load Word Coprocessor 1 : Set $f1 to 32-bit value from effective memory word address
lwc1 $f1,label lui $1, LH2 lwc1 RG1, LL2($1) COMPACT lwc1 RG1, LL2($0) #Load Word Coprocessor 1 : Set $f1 to 32-bit value from effective memory word address
lwc1 $f1,label($t2) lui $1, LH2 addu $1, $1, RG4 lwc1 RG1, LL2($1) COMPACT lwc1 RG1, LL2(RG4) #Load Word Coprocessor 1 : Set $f1 to 32-bit value from effective memory word address
lwc1 $f1,label+100000 lui $1, LHPA lwc1 RG1, LLP($1) #Load Word Coprocessor 1 : Set $f1 to 32-bit value from effective memory word address
lwc1 $f1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 lwc1 RG1, LLP($1) #Load Word Coprocessor 1 : Set $f1 to 32-bit value from effective memory word address

ldc1 $f2,($t2) ldc1 RG1,0(RG3) #Load Doubleword Coprocessor 1 : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
ldc1 $f2,-100 ldc1 RG1,VL2($0) #Load Doubleword Coprocessor 1 : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
ldc1 $f2,100000 lui $1, VH2 ldc1 RG1,VL2($1) #Load Doubleword Coprocessor 1 : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
ldc1 $f2,100000($t2) lui $1, VH2 addu $1, $1, RG4 ldc1 RG1, VL2($1) #Load Doubleword Coprocessor 1 : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
ldc1 $f2,label lui $1, LH2 ldc1 RG1, LL2($1) COMPACT ldc1 RG1, LL2($0) #Load Doubleword Coprocessor 1 : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
ldc1 $f2,label($t2) lui $1, LH2 addu $1, $1, RG4 ldc1 RG1, LL2($1) COMPACT ldc1 RG1, LL2(RG4) #Load Doubleword Coprocessor 1 : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
ldc1 $f2,label+100000 lui $1, LHPA ldc1 RG1, LLP($1) #Load Doubleword Coprocessor 1 : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
ldc1 $f2,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 ldc1 RG1, LLP($1) #Load Doubleword Coprocessor 1 : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address

swc1 $f1,($t2) swc1 RG1,0(RG3) #Store Word Coprocessor 1 : Store 32-bit value from $f1 to effective memory word address
swc1 $f1,-100 swc1 RG1,VL2($0) #Store Word Coprocessor 1 : Store 32-bit value from $f1 to effective memory word address
swc1 $f1,100000 lui $1, VH2 swc1 RG1,VL2($1) #Store Word Coprocessor 1 : Store 32-bit value from $f1 to effective memory word address
swc1 $f1,100000($t2) lui $1, VH2 addu $1, $1, RG4 swc1 RG1, VL2($1) #Store Word Coprocessor 1 : Store 32-bit value from $f1 to effective memory word address
swc1 $f1,label lui $1, LH2 swc1 RG1, LL2($1) COMPACT swc1 RG1, LL2($0) #Store Word Coprocessor 1 : Store 32-bit value from $f1 to effective memory word address
swc1 $f1,label($t2) lui $1, LH2 addu $1, $1, RG4 swc1 RG1, LL2($1) COMPACT swc1 RG1, LL2(RG4) #Store Word Coprocessor 1 : Store 32-bit value from $f1 to effective memory word address
swc1 $f1,label+100000 lui $1, LHPA swc1 RG1, LLP($1) #Store Word Coprocessor 1 : Store 32-bit value from $f1 to effective memory word address
swc1 $f1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 swc1 RG1, LLP($1) #Store Word Coprocessor 1 : Store 32-bit value from $f1 to effective memory word address

sdc1 $f2,($t2) sdc1 RG1,0(RG3) #Store Doubleword Coprocessor 1 : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
sdc1 $f2,-100 sdc1 RG1,VL2($0) #Store Doubleword Coprocessor 1 : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
sdc1 $f2,100000 lui $1, VH2 sdc1 RG1,VL2($1) #Store Doubleword Coprocessor 1 : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
sdc1 $f2,100000($t2) lui $1, VH2 addu $1, $1, RG4 sdc1 RG1, VL2($1) #Store Doubleword Coprocessor 1 : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
sdc1 $f2,label lui $1, LH2 sdc1 RG1, LL2($1) COMPACT sdc1 RG1, LL2($0) #Store Doubleword Coprocessor 1 : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
sdc1 $f2,label($t2) lui $1, LH2 addu $1, $1, RG4 sdc1 RG1, LL2($1) COMPACT sdc1 RG1, LL2(RG4) #Store Doubleword Coprocessor 1 : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
sdc1 $f2,label+100000 lui $1, LHPA sdc1 RG1, LLP($1) #Store Doubleword Coprocessor 1 : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
sdc1 $f2,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 sdc1 RG1, LLP($1) #Store Doubleword Coprocessor 1 : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address

l.s $f1,($t2) lwc1 RG1,0(RG3) #Load floating point Single precision : Set $f1 to 32-bit value at effective memory word address
l.s $f1,-100 lwc1 RG1,VL2($0) #Load floating point Single precision : Set $f1 to 32-bit value at effective memory word address
l.s $f1,100000 lui $1, VH2 lwc1 RG1,VL2($1) #Load floating point Single precision : Set $f1 to 32-bit value at effective memory word address
l.s $f1,100000($t2) lui $1, VH2 addu $1, $1, RG4 lwc1 RG1, VL2($1) #Load floating point Single precision : Set $f1 to 32-bit value at effective memory word address
l.s $f1,label lui $1, LH2 lwc1 RG1, LL2($1) COMPACT lwc1 RG1, LL2($0) #Load floating point Single precision : Set $f1 to 32-bit value at effective memory word address
l.s $f1,label($t2) lui $1, LH2 addu $1, $1, RG4 lwc1 RG1, LL2($1) COMPACT lwc1 RG1, LL2(RG4) #Load floating point Single precision : Set $f1 to 32-bit value at effective memory word address
l.s $f1,label+100000 lui $1, LHPA lwc1 RG1, LLP($1) #Load floating point Single precision : Set $f1 to 32-bit value at effective memory word address
l.s $f1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 lwc1 RG1, LLP($1) #Load floating point Single precision : Set $f1 to 32-bit value at effective memory word address

s.s $f1,($t2) swc1 RG1,0(RG3) #Store floating point Single precision : Store 32-bit value from $f1 to effective memory word address
s.s $f1,-100 swc1 RG1,VL2($0) #Store floating point Single precision : Store 32-bit value from $f1 to effective memory word address
s.s $f1,100000 lui $1, VH2 swc1 RG1,VL2($1) #Store floating point Single precision : Store 32-bit value from $f1 to effective memory word address
s.s $f1,100000($t2) lui $1, VH2 addu $1, $1, RG4 swc1 RG1, VL2($1) #Store floating point Single precision : Store 32-bit value from $f1 to effective memory word address
s.s $f1,label lui $1, LH2 swc1 RG1, LL2($1) COMPACT swc1 RG1, LL2($0) #Store floating point Single precision : Store 32-bit value from $f1 to effective memory word address
s.s $f1,label($t2) lui $1, LH2 addu $1, $1, RG4 swc1 RG1, LL2($1) COMPACT swc1 RG1, LL2(RG4) #Store floating point Single precision : Store 32-bit value from $f1 to effective memory word address
s.s $f1,label+100000 lui $1, LHPA swc1 RG1, LLP($1) #Store floating point Single precision : Store 32-bit value from $f1 to effective memory word address
s.s $f1,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 swc1 RG1, LLP($1) #Store floating point Single precision : Store 32-bit value from $f1 to effective memory word address

l.d $f2,($t2) ldc1 RG1,0(RG3) #Load floating point Double precision : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
l.d $f2,-100 ldc1 RG1,VL2($0) #Load floating point Double precision : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
l.d $f2,100000 lui $1, VH2 ldc1 RG1,VL2($1) #Load floating point Double precision : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
l.d $f2,100000($t2) lui $1, VH2 addu $1, $1, RG4 ldc1 RG1, VL2($1) #Load floating point Double precision : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
l.d $f2,label lui $1, LH2 ldc1 RG1, LL2($1) COMPACT ldc1 RG1, LL2($0) #Load floating point Double precision : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
l.d $f2,label($t2) lui $1, LH2 addu $1, $1, RG4 ldc1 RG1, LL2($1) COMPACT ldc1 RG1, LL2(RG4) #Load floating point Double precision : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
l.d $f2,label+100000 lui $1, LHPA ldc1 RG1, LLP($1) #Load floating point Double precision : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address
l.d $f2,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 ldc1 RG1, LLP($1) #Load floating point Double precision : Set $f2 and $f3 register pair to 64-bit value at effective memory doubleword address

s.d $f2,($t2) sdc1 RG1,0(RG3) #Store floating point Double precision : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
s.d $f2,-100 sdc1 RG1,VL2($0) #Store floating point Double precision : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
s.d $f2,100000 lui $1, VH2 sdc1 RG1,VL2($1) #Store floating point Double precision : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
s.d $f2,100000($t2) lui $1, VH2 addu $1, $1, RG4 sdc1 RG1, VL2($1) #Store floating point Double precision : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
s.d $f2,label lui $1, LH2 sdc1 RG1, LL2($1) COMPACT sdc1 RG1, LL2($0) #Store floating point Double precision : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
s.d $f2,label($t2) lui $1, LH2 addu $1, $1, RG4 sdc1 RG1, LL2($1) COMPACT sdc1 RG1, LL2(RG4) #Store floating point Double precision : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
s.d $f2,label+100000 lui $1, LHPA sdc1 RG1, LLP($1) #Store floating point Double precision : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address
s.d $f2,label+100000($t2) lui $1, LHPA addu $1, $1, RG6 sdc1 RG1, LLP($1) #Store floating point Double precision : Store 64 bits from $f2 and $f3 register pair to effective memory doubleword address

# maximum length of scrolled text in Mars Message and Run I/O tabs, in bytes.
MessageLimit = 1000000
# Maximum number of errors that can be recorded in one assemble operation.
ErrorLimit = 200
# Maximum number of “backstep” operations that can be taken. An instruction
# may produce more than one (e.g. trap instruction may set several registers)
BackstepLimit = 2000
# Acceptable file extensions for MIPS assembly files. Separate with spaces.
Extensions = asm s
# The set of ASCII strings to use for ASCII display or print
# of data segment contents. This covers 8-bit ASCII codes 0-255.
# The space character (decimal 32, hex 20) is encoded here as
# “space” without the quotes. It will be converted upon reading.
# All non-printable codes are encoded here as “null” without
# the quotes. They will be converted upon reading, to the value
# of variable AsciiNonPrint. If you wish to have non-printing
# codes be displayed as their octal value (see unix od) then
# replace all these null with the codes.
# 0 1 2 3 4 5 6 7 8 9
AsciiTable = \
\\0 null null null null null null null \\b \\t \
\\n \\v \\f \\r null null null null null null \
null null null null null null null null null null \
null null space ! ” # $ % & ‘ \
( ) * + , – . / 0 1 \
2 3 4 5 6 7 8 9 : ; \
< = > ? @ A B C D E \
F G H I J K L M N O \
P Q R S T U V W X Y \
Z [ \\ ] ^ _ ` a b c \
d e f g h i j k l m \
n o p q r s t u v w \
x y z { | } ~ null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null null null null null \
null null null null null null
# Use AsciiNonPrint as placeholder for non-printing ASCII codes.
# To use space character, specify AsciiNonPrint = space.
# The value of this variable will be substituted for the
# string “null” for any element in the Ascii list (above)
# having “null” as its value.
AsciiNonPrint = .

# Example of re-assign syscall number. Remove leading “#” to activate.
# I re-assign to same number since I don’t really want to change them.
# None are necessary here since number is assigned as constructor arg.
# Re-assignment here will override constructor arg though.
# The syscall names must match constructor arg exactly, case-sensitive.
# Re-assignment useful if numbering conflict should someday occur.
PrintInt = 1
PrintFloat = 2
PrintDouble = 3
PrintString = 4
ReadInt = 5
ReadFloat = 6
ReadDouble = 7
ReadString = 8
Sbrk = 9
Exit = 10
PrintChar = 11
ReadChar = 12
Open = 13
Read = 14
Write = 15
Close = 16
Exit2 = 17
Time = 30
MidiOut = 31
Sleep = 32
MidiOutSync = 33
PrintIntHex = 34
PrintIntBinary = 35
PrintIntUnsigned = 36
RandSeed = 40
RandInt = 41
RandIntRange = 42
RandFloat = 43
RandDouble = 44
ConfirmDialog = 50
InputDialogInt = 51
InputDialogFloat = 52
InputDialogDouble = 53
InputDialogString = 54
MessageDialog = 55
MessageDialogInt = 56
MessageDialogFloat = 57
MessageDialogDouble = 58
MessageDialogString = 59

# NOTE: These are defaults only. The values of these keys are maintained by Java Preferences
# objects, which store key-value pairs in a system-dependent way (Windows uses Registry).
AssembleAll = false
AssembleOnOpen = false
BareMachine = false
DataSegmentHighlighting = true
DelayedBranching = false
DisplayAddressesInHex = true
DisplayValuesInHex = true
EditorCurrentLineHighlighting = true
EditorLineNumbersDisplayed = true
ExtendedAssembler = true
LabelWindowVisibility = false
LoadExceptionHandler = false
ProgramArguments = false
RegistersHighlighting = true
StartAtMain = false
WarningsAreErrors = false
PopupInstructionGuidance = true
EditorPopupPrefixLength = 2
EvenRowBackground = 0x00e0e0e0
EvenRowForeground = 0
OddRowBackground = 0x00ffffff
OddRowForeground = 0
TextSegmentHighlightBackground = 0x00ffff99
TextSegmentHighlightForeground = 0
TextSegmentDelaySlotHighlightBackground = 0x33ff00
TextSegmentDelaySlotHighlightForeground = 0
DataSegmentHighlightBackground = 0x0099ccff
DataSegmentHighlightForeground = 0
RegisterHighlightBackground = 0x0099cc55
RegisterHighlightForeground = 0

Copyright (c) 2003-2013, Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
“Software”), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject
to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)

Main-Class: Mars
Class-Path: .

jar cfm Mars.jar mainclass.txt PseudoOps.txt Config.properties Syscall.properties Settings.properties MARSlicense.txt mainclass.txt CreateMarsJar.bat Mars.java Mars.class docs help images mars sounds

Mars.java
Mars.java/*
 Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

 Developed by Pete Sanderson ( )
 and Kenneth Vollmar ( )

 Permission is hereby granted, free of charge, to any person obtaining 
 a copy of this software and associated documentation files (the 
 “Software”), to deal in the Software without restriction, including 
 without limitation the rights to use, copy, modify, merge, publish, 
 distribute, sublicense, and/or sell copies of the Software, and to 
 permit persons to whom the Software is furnished to do so, subject 
 to the following conditions:

 The above copyright notice and this permission notice shall be 
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
 ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 (MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Portal to Mars
 * 
 * @author Pete Sanderson
 * @version March 2006
 **/

public class Mars
{
    public static void main(String[] args)
    {
        new mars.MarsLaunch(args);
    }
}

Mars

public synchronized class Mars {
public void Mars();
public static void main(String[]);
}

Constant Field Values

Overview  Package  Class  Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Constant Field Values

Contents mars.*

mars.*

mars.ErrorList

public static final java.lang.String ERROR_MESSAGE_PREFIX “Error”

public static final java.lang.String FILENAME_PREFIX ” in ”

public static final java.lang.String LINE_PREFIX ” line ”

public static final java.lang.String MESSAGE_SEPARATOR “: ”

public static final java.lang.String POSITION_PREFIX ” column ”

public static final java.lang.String WARNING_MESSAGE_PREFIX “Warning”

mars.ErrorMessage

public static final boolean ERROR false

public static final boolean WARNING true

mars.Globals

public static final java.lang.String helpPath “/help/”

public static final java.lang.String imagesPath “/images/”

public static final java.lang.String version “4.3”

mars.Settings

public static final int ASSEMBLE_ALL_ENABLED 3

public static final int ASSEMBLE_ON_OPEN_ENABLED 2

public static final int AUTO_INDENT 19

public static final int BARE_MACHINE_ENABLED 1

public static final int CARET_BLINK_RATE 4

public static final int DATA_SEGMENT_HIGHLIGHTING 12

public static final int DATASEGMENT_HIGHLIGHT_BACKGROUND 8

public static final int DATASEGMENT_HIGHLIGHT_FONT 5

public static final int DATASEGMENT_HIGHLIGHT_FOREGROUND 9

public static final int DELAYED_BRANCHING_ENABLED 8

public static final int DISPLAY_ADDRESSES_IN_HEX 5

public static final int DISPLAY_VALUES_IN_HEX 6

public static final int EDITOR_CURRENT_LINE_HIGHLIGHTING 15

public static final int EDITOR_FONT 0

public static final int EDITOR_LINE_NUMBERS_DISPLAYED 9

public static final int EDITOR_POPUP_PREFIX_LENGTH 6

public static final int EDITOR_TAB_SIZE 5

public static final int EVEN_ROW_BACKGROUND 0

public static final int EVEN_ROW_FONT 1

public static final int EVEN_ROW_FOREGROUND 1

public static final int EXCEPTION_HANDLER 0

public static final int EXCEPTION_HANDLER_ENABLED 7

public static final int EXTENDED_ASSEMBLER_ENABLED 0

public static final int GENERIC_TEXT_EDITOR 18

public static final int LABEL_SORT_STATE 2

public static final int LABEL_WINDOW_VISIBILITY 4

public static final int MEMORY_CONFIGURATION 3

public static final int ODD_ROW_BACKGROUND 2

public static final int ODD_ROW_FONT 2

public static final int ODD_ROW_FOREGROUND 3

public static final int POPUP_INSTRUCTION_GUIDANCE 16

public static final int POPUP_SYSCALL_INPUT 17

public static final int PROGRAM_ARGUMENTS 11

public static final int REGISTER_HIGHLIGHT_BACKGROUND 10

public static final int REGISTER_HIGHLIGHT_FONT 6

public static final int REGISTER_HIGHLIGHT_FOREGROUND 11

public static final int REGISTERS_HIGHLIGHTING 13

public static final int START_AT_MAIN 14

public static final int TEXT_COLUMN_ORDER 1

public static final int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_BACKGROUND 6

public static final int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FONT 4

public static final int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FOREGROUND 7

public static final int TEXTSEGMENT_HIGHLIGHT_BACKGROUND 4

public static final int TEXTSEGMENT_HIGHLIGHT_FONT 3

public static final int TEXTSEGMENT_HIGHLIGHT_FOREGROUND 5

public static final int WARNINGS_ARE_ERRORS 10

mars.assembler.*

mars.assembler.DataTypes

public static final int BYTE_SIZE 1

public static final int CHAR_SIZE 1

public static final int DOUBLE_SIZE 8

public static final int FLOAT_SIZE 4

public static final int HALF_SIZE 2

public static final double LOW_DOUBLE_VALUE -1.7976931348623157E308

public static final double LOW_FLOAT_VALUE -3.4028234663852886E38

public static final int MAX_BYTE_VALUE 127

public static final double MAX_DOUBLE_VALUE 1.7976931348623157E308

public static final double MAX_FLOAT_VALUE 3.4028234663852886E38

public static final int MAX_HALF_VALUE 32767

public static final int MAX_UHALF_VALUE 65535

public static final int MAX_WORD_VALUE 2147483647

public static final int MIN_BYTE_VALUE -128

public static final int MIN_HALF_VALUE -32768

public static final int MIN_UHALF_VALUE 0

public static final int MIN_WORD_VALUE -2147483648

public static final int WORD_SIZE 4

mars.assembler.Symbol

public static final boolean DATA_SYMBOL true

public static final boolean TEXT_SYMBOL false

mars.assembler.SymbolTable

public static final int NOT_FOUND -1

mars.assembler.TokenTypes

public static final java.lang.String TOKEN_DELIMITERS “\t ,()”

mars.mips.*

mars.mips.hardware.AccessNotice

public static final int READ 0

public static final int WRITE 1

mars.mips.hardware.Coprocessor0

public static final int CAUSE 13

public static final int DEFAULT_STATUS_VALUE 65297

public static final int EPC 14

public static final int EXCEPTION_LEVEL 1

public static final int STATUS 12

public static final int VADDR 8

mars.mips.hardware.Memory

public static final boolean BIG_ENDIAN false

public static final boolean LITTLE_ENDIAN true

public static final int WORD_LENGTH_BYTES 4

mars.mips.hardware.RegisterFile

public static final int GLOBAL_POINTER_REGISTER 28

public static final int STACK_POINTER_REGISTER 29

mars.mips.instructions.Instruction

public static final int INSTRUCTION_LENGTH 4

public static final int INSTRUCTION_LENGTH_BITS 32

mars.simulator.*

mars.simulator.Exceptions

public static final int ADDRESS_EXCEPTION_LOAD 4

public static final int ADDRESS_EXCEPTION_STORE 5

public static final int ARITHMETIC_OVERFLOW_EXCEPTION 12

public static final int BREAKPOINT_EXCEPTION 9

public static final int DIVIDE_BY_ZERO_EXCEPTION 15

public static final int EXTERNAL_INTERRUPT_DISPLAY 128

public static final int EXTERNAL_INTERRUPT_KEYBOARD 64

public static final int FLOATING_POINT_OVERFLOW 16

public static final int FLOATING_POINT_UNDERFLOW 17

public static final int RESERVED_INSTRUCTION_EXCEPTION 10

public static final int SYSCALL_EXCEPTION 8

public static final int TRAP_EXCEPTION 13

mars.simulator.Simulator

public static final int BREAKPOINT 1

public static final int CLIFF_TERMINATION 5

public static final int EXCEPTION 2

public static final int MAX_STEPS 3

public static final int NO_DEVICE 0

public static final int NORMAL_TERMINATION 4

public static final int PAUSE_OR_STOP 6

mars.simulator.SimulatorNotice

public static final int SIMULATOR_START 0

public static final int SIMULATOR_STOP 1

mars.tools.*

mars.tools.BHTSimGUI

public static final java.lang.String BHT_DO_NOT_TAKE_BRANCH “NOT TAKE”

public static final java.lang.String BHT_TAKE_BRANCH “TAKE”

mars.tools.BHTSimulator

public static final int BHT_DEFAULT_HISTORY 1

public static final boolean BHT_DEFAULT_INITVAL false

public static final int BHT_DEFAULT_SIZE 16

public static final java.lang.String BHT_HEADING “Branch History Table Simulator”

public static final java.lang.String BHT_NAME “BHT Simulator”

public static final java.lang.String BHT_VERSION “Version 1.0 (Ingo Kofler)”

mars.tools.DigitalLabSim

public static final int EXTERNAL_INTERRUPT_HEXA_KEYBOARD 512

public static final int EXTERNAL_INTERRUPT_TIMER 256

mars.util.*

mars.util.EditorFont

public static final int DEFAULT_SIZE 12

public static final int MAX_SIZE 72

public static final int MIN_SIZE 6

mars.util.SystemIO

public static final int SYSCALL_BUFSIZE 128

public static final int SYSCALL_MAXFILES 32

mars.venus.*

mars.venus.Editor

public static final int MAX_BLINK_RATE 1000

public static final int MAX_TAB_SIZE 32

public static final int MIN_BLINK_RATE 0

public static final int MIN_TAB_SIZE 1

mars.venus.FileStatus

public static final int EDITED 4

public static final int NEW_EDITED 2

public static final int NEW_NOT_EDITED 1

public static final int NO_FILE 0

public static final int NOT_EDITED 3

public static final int OPENING 8

public static final int RUNNABLE 5

public static final int RUNNING 6

public static final int TERMINATED 7

mars.venus.HelpHelpAction

public static final java.lang.String descriptionDetailSeparator “:”

mars.venus.NumberDisplayBaseChooser

public static final int ASCII 0

public static final int DECIMAL 10

public static final int HEXADECIMAL 16

mars.venus.RunSpeedPanel

public static final double UNLIMITED_SPEED 40.0

mars.venus.SettingsHighlightingAction

public static final java.lang.String APPLY_TOOL_TIP_TEXT “Apply current settings now and leave dialog open”

public static final java.lang.String CANCEL_TOOL_TIP_TEXT “Close dialog without applying current settings”

public static final java.lang.String CLOSE_TOOL_TIP_TEXT “Apply current settings and close dialog”

public static final java.lang.String RESET_TOOL_TIP_TEXT “Reset to initial settings without applying”

mars.venus.editors.MARSTextEditingArea

public static final int TEXT_FOUND 1

public static final int TEXT_NOT_FOUND 0

public static final int TEXT_REPLACED_FOUND_NEXT 2

public static final int TEXT_REPLACED_NOT_FOUND_NEXT 3

mars.venus.editors.jeditsyntax.InputHandler

public static final java.lang.String SMART_HOME_END_PROPERTY “InputHandler.homeEnd”

mars.venus.editors.jeditsyntax.tokenmarker.Token

public static final byte COMMENT1 1

public static final byte COMMENT2 2

public static final byte END 127

public static final byte ID_COUNT 12

public static final byte INTERNAL_FIRST 100

public static final byte INTERNAL_LAST 126

public static final byte INVALID 10

public static final byte KEYWORD1 6

public static final byte KEYWORD2 7

public static final byte KEYWORD3 8

public static final byte LABEL 5

public static final byte LITERAL1 3

public static final byte LITERAL2 4

public static final byte MACRO_ARG 11

public static final byte NULL 0

public static final byte OPERATOR 9

Overview  Package  Class  Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For All Packages

Package Hierarchies:
mars, mars.assembler, mars.mips.dump, mars.mips.hardware, mars.mips.instructions, mars.mips.instructions.syscalls, mars.simulator, mars.tools, mars.util, mars.venus, mars.venus.editors, mars.venus.editors.generic, mars.venus.editors.jeditsyntax, mars.venus.editors.jeditsyntax.tokenmarker

Class Hierarchy

java.lang.Object javax.swing.AbstractAction (implements javax.swing.Action, java.lang.Cloneable, java.io.Serializable)
mars.venus.GuiAction mars.venus.EditCopyAction
mars.venus.EditCutAction
mars.venus.EditFindReplaceAction
mars.venus.EditPasteAction
mars.venus.EditRedoAction
mars.venus.EditSelectAllAction
mars.venus.EditUndoAction
mars.venus.FileCloseAction
mars.venus.FileCloseAllAction
mars.venus.FileDumpMemoryAction
mars.venus.FileExitAction
mars.venus.FileNewAction
mars.venus.FileOpenAction
mars.venus.FilePrintAction
mars.venus.FileSaveAction
mars.venus.FileSaveAllAction
mars.venus.FileSaveAsAction
mars.venus.HelpAboutAction
mars.venus.HelpHelpAction
mars.venus.RunAssembleAction
mars.venus.RunBackstepAction
mars.venus.RunClearBreakpointsAction (implements javax.swing.event.TableModelListener)

mars.venus.RunGoAction
mars.venus.RunPauseAction
mars.venus.RunResetAction
mars.venus.RunStepAction
mars.venus.RunStopAction
mars.venus.RunToggleBreakpointsAction
mars.venus.SettingsAddressDisplayBaseAction
mars.venus.SettingsAssembleAllAction
mars.venus.SettingsAssembleOnOpenAction
mars.venus.SettingsDelayedBranchingAction
mars.venus.SettingsEditorAction
mars.venus.SettingsExceptionHandlerAction
mars.venus.SettingsExtendedAction
mars.venus.SettingsHighlightingAction
mars.venus.SettingsLabelAction
mars.venus.SettingsMemoryConfigurationAction
mars.venus.SettingsPopupInputAction
mars.venus.SettingsProgramArgumentsAction
mars.venus.SettingsStartAtMainAction
mars.venus.SettingsValueDisplayBaseAction
mars.venus.SettingsWarningsAreErrorsAction

mars.venus.ToolAction

javax.swing.text.AbstractDocument (implements javax.swing.text.Document, java.io.Serializable)
javax.swing.text.PlainDocument mars.venus.editors.jeditsyntax.SyntaxDocument

mars.mips.dump.AbstractDumpFormat (implements mars.mips.dump.DumpFormat)
mars.mips.dump.AsciiTextDumpFormat
mars.mips.dump.BinaryDumpFormat
mars.mips.dump.BinaryTextDumpFormat
mars.mips.dump.HexTextDumpFormat
mars.mips.dump.IntelHexDumpFormat
mars.mips.dump.SegmentWindowDumpFormat

mars.mips.instructions.syscalls.AbstractSyscall (implements mars.mips.instructions.syscalls.Syscall)
mars.mips.instructions.syscalls.SyscallClose
mars.mips.instructions.syscalls.SyscallConfirmDialog
mars.mips.instructions.syscalls.SyscallExit
mars.mips.instructions.syscalls.SyscallExit2
mars.mips.instructions.syscalls.SyscallInputDialogDouble
mars.mips.instructions.syscalls.SyscallInputDialogFloat
mars.mips.instructions.syscalls.SyscallInputDialogInt
mars.mips.instructions.syscalls.SyscallInputDialogString
mars.mips.instructions.syscalls.SyscallMessageDialog
mars.mips.instructions.syscalls.SyscallMessageDialogDouble
mars.mips.instructions.syscalls.SyscallMessageDialogFloat
mars.mips.instructions.syscalls.SyscallMessageDialogInt
mars.mips.instructions.syscalls.SyscallMessageDialogString
mars.mips.instructions.syscalls.SyscallMidiOut
mars.mips.instructions.syscalls.SyscallMidiOutSync
mars.mips.instructions.syscalls.SyscallOpen
mars.mips.instructions.syscalls.SyscallPrintChar
mars.mips.instructions.syscalls.SyscallPrintDouble
mars.mips.instructions.syscalls.SyscallPrintFloat
mars.mips.instructions.syscalls.SyscallPrintInt
mars.mips.instructions.syscalls.SyscallPrintIntBinary
mars.mips.instructions.syscalls.SyscallPrintIntHex
mars.mips.instructions.syscalls.SyscallPrintIntUnsigned
mars.mips.instructions.syscalls.SyscallPrintString
mars.mips.instructions.syscalls.SyscallRandDouble
mars.mips.instructions.syscalls.SyscallRandFloat
mars.mips.instructions.syscalls.SyscallRandInt
mars.mips.instructions.syscalls.SyscallRandIntRange
mars.mips.instructions.syscalls.SyscallRandSeed
mars.mips.instructions.syscalls.SyscallRead
mars.mips.instructions.syscalls.SyscallReadChar
mars.mips.instructions.syscalls.SyscallReadDouble
mars.mips.instructions.syscalls.SyscallReadFloat
mars.mips.instructions.syscalls.SyscallReadInt
mars.mips.instructions.syscalls.SyscallReadString
mars.mips.instructions.syscalls.SyscallSbrk
mars.mips.instructions.syscalls.SyscallSleep
mars.mips.instructions.syscalls.SyscallTime
mars.mips.instructions.syscalls.SyscallWrite

javax.swing.table.AbstractTableModel (implements java.io.Serializable, javax.swing.table.TableModel)
mars.tools.BHTableModel

mars.mips.hardware.AccessNotice mars.mips.hardware.MemoryAccessNotice
mars.mips.hardware.RegisterAccessNotice

mars.assembler.Assembler
mars.simulator.BackStepper
mars.mips.instructions.BasicInstructionFormat
mars.tools.BHTEntry
mars.util.Binary
java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
java.awt.Container javax.swing.JComponent (implements java.io.Serializable)
javax.swing.AbstractButton (implements java.awt.ItemSelectable, javax.swing.SwingConstants)
javax.swing.JButton (implements javax.accessibility.Accessible)
mars.tools.AbstractMarsToolAndApplication.ConnectButton
mars.venus.RepeatButton (implements java.awt.event.ActionListener, java.awt.event.MouseListener)

javax.swing.JToggleButton (implements javax.accessibility.Accessible)
javax.swing.JCheckBox (implements javax.accessibility.Accessible)
mars.venus.NumberDisplayBaseChooser

mars.tools.DigitalLabSim.SevenSegmentDisplay
mars.venus.editors.jeditsyntax.JEditTextArea mars.venus.editors.jeditsyntax.JEditBasedTextArea (implements javax.swing.event.CaretListener, mars.venus.editors.MARSTextEditingArea)

javax.swing.JInternalFrame (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants)
mars.venus.DataSegmentWindow (implements java.util.Observer)

mars.venus.LabelsWindow
mars.venus.TextSegmentWindow

javax.swing.JLayeredPane (implements javax.accessibility.Accessible)
javax.swing.JDesktopPane (implements javax.accessibility.Accessible)
mars.venus.ExecutePane

javax.swing.JPanel (implements javax.accessibility.Accessible)
mars.tools.BHTSimGUI
mars.venus.Coprocessor0Window (implements java.util.Observer)

mars.venus.Coprocessor1Window (implements java.awt.event.ActionListener, java.util.Observer)

mars.tools.DigitalLabSim.HexaKeyboard
mars.tools.DigitalLabSim.SevenSegmentPanel
mars.venus.EditPane (implements java.util.Observer)

mars.venus.RegistersWindow (implements java.util.Observer)

mars.venus.RunSpeedPanel

javax.swing.JTabbedPane (implements javax.accessibility.Accessible, java.io.Serializable, javax.swing.SwingConstants)
mars.venus.EditTabbedPane
mars.venus.MainPane
mars.venus.MessagesPane
mars.venus.RegistersPane

javax.swing.text.JTextComponent (implements javax.accessibility.Accessible, javax.swing.Scrollable)
javax.swing.JTextArea mars.venus.editors.generic.GenericTextArea (implements mars.venus.editors.MARSTextEditingArea)

mars.venus.editors.jeditsyntax.TextAreaPainter (implements javax.swing.text.TabExpander)

java.awt.Window (implements javax.accessibility.Accessible)
java.awt.Dialog javax.swing.JDialog (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants)
mars.venus.AbstractFontSettingDialog

java.awt.Frame (implements java.awt.MenuContainer)
javax.swing.JFrame (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants)
mars.tools.AbstractMarsToolAndApplication (implements mars.tools.MarsTool, java.util.Observer)
mars.tools.BHTSimulator (implements java.awt.event.ActionListener)

mars.tools.BitmapDisplay
mars.tools.CacheSimulator
mars.tools.DigitalLabSim
mars.tools.FloatRepresentation
mars.tools.InstructionCounter
mars.tools.InstructionStatistics
mars.tools.IntroToTools
mars.tools.KeyboardAndDisplaySimulator
mars.tools.MemoryReferenceVisualization

mars.venus.VenusUI

javax.swing.JWindow (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer)
mars.MarsSplashScreen

mars.mips.hardware.Coprocessor0
mars.mips.hardware.Coprocessor1
mars.assembler.DataTypes
mars.simulator.DelayedBranch
mars.tools.DigitalLabSim.HexaKeyboard.EcouteurClick (implements java.awt.event.MouseListener)

mars.tools.DigitalLabSim.OneSecondCounter
mars.assembler.Directives
mars.mips.dump.DumpFormatLoader
mars.venus.Editor
mars.util.EditorFont
mars.ErrorList
mars.ErrorMessage
mars.simulator.Exceptions
mars.util.FilenameFinder
mars.venus.FileStatus
mars.Globals
mars.venus.editors.jeditsyntax.InputHandler.backspace (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.backspace_word (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.clip_copy (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.clip_cut (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.clip_paste (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.delete (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.delete_word (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.document_end (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.document_home (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.end (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.home (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.insert_break (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.insert_char (implements java.awt.event.ActionListener, mars.venus.editors.jeditsyntax.InputHandler.NonRepeatable)

mars.venus.editors.jeditsyntax.InputHandler.insert_tab (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.next_char (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.next_line (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.next_page (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.next_word (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.overwrite (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.prev_char (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.prev_line (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.prev_page (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.prev_word (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.repeat (implements java.awt.event.ActionListener, mars.venus.editors.jeditsyntax.InputHandler.NonRecordable)

mars.venus.editors.jeditsyntax.InputHandler.select_all (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.toggle_rect (implements java.awt.event.ActionListener)

mars.mips.instructions.Instruction mars.mips.instructions.BasicInstruction
mars.mips.instructions.ExtendedInstruction

mars.mips.instructions.InstructionSet
java.awt.event.KeyAdapter (implements java.awt.event.KeyListener)
mars.tools.AbstractMarsToolAndApplication.EnterKeyListener
mars.venus.editors.jeditsyntax.InputHandler mars.venus.editors.jeditsyntax.DefaultInputHandler

mars.venus.editors.jeditsyntax.KeywordMap
mars.assembler.Macro
mars.assembler.MacroPool
Mars
mars.tools.MarsBot (implements mars.tools.MarsTool, java.util.Observer)

mars.MarsLaunch
mars.mips.hardware.MemoryConfiguration
mars.mips.hardware.MemoryConfigurations
mars.util.MemoryDump
mars.mips.dump.MIFDumpFormat
mars.MIPSprogram
java.awt.event.MouseAdapter (implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.MouseWheelListener)
mars.venus.PopupListener

java.util.Observable mars.mips.hardware.Memory
mars.mips.hardware.Register
mars.Settings
mars.simulator.Simulator

mars.assembler.OperandFormat
mars.venus.editors.jeditsyntax.PopupHelpItem
mars.simulator.ProgramArgumentList
mars.ProgramStatement
mars.util.PropertiesFile
mars.mips.instructions.syscalls.RandomStreams
mars.mips.hardware.RegisterFile
mars.tools.ScavengerHunt (implements mars.tools.MarsTool, java.util.Observer)

mars.tools.ScreenMagnifier (implements mars.tools.MarsTool)

mars.simulator.SimulatorNotice
mars.assembler.SourceLine
mars.simulator.SwingWorker
mars.assembler.Symbol
mars.assembler.SymbolTable
mars.venus.editors.jeditsyntax.SyntaxStyle
mars.venus.editors.jeditsyntax.SyntaxUtilities
mars.mips.instructions.syscalls.SyscallNumberOverride
mars.util.SystemIO
mars.venus.editors.jeditsyntax.TextAreaDefaults
mars.venus.editors.jeditsyntax.TextUtilities
java.lang.Throwable (implements java.io.Serializable)
java.lang.Exception mars.mips.hardware.AddressErrorException
mars.venus.HardcopyWriter.PrintCanceledException
mars.mips.hardware.InvalidRegisterAccessException
mars.ProcessingException

mars.venus.editors.jeditsyntax.tokenmarker.Token
mars.assembler.Token
mars.assembler.Tokenizer
mars.assembler.TokenList (implements java.lang.Cloneable)

mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker.LineInfo
mars.assembler.TokenTypes
mars.venus.ToolLoader
java.io.Writer (implements java.lang.Appendable, java.io.Closeable, java.io.Flushable)
mars.venus.HardcopyWriter

Interface Hierarchy

mars.mips.dump.DumpFormat
mars.venus.editors.jeditsyntax.InputHandler.MacroRecorder
mars.venus.editors.jeditsyntax.InputHandler.NonRecordable
mars.venus.editors.jeditsyntax.InputHandler.NonRepeatable
mars.venus.editors.jeditsyntax.InputHandler.Wrapper
mars.venus.editors.MARSTextEditingArea
mars.tools.MarsTool
mars.mips.instructions.SimulationCode
mars.simulator.Simulator.StopListener
mars.mips.instructions.syscalls.Syscall
mars.venus.editors.jeditsyntax.TextAreaPainter.Highlight
mars.assembler.TranslationCode

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Generated Documentation (Untitled)

Frame Alert

This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.

Link toNon-frame version.

Mars

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Class Mars

java.lang.Object
Mars

public class Mars
extends java.lang.Object

Portal to Mars

Author:
Pete Sanderson

Constructor Summary
Mars()

           

 

Method Summary

static void main(java.lang.String[] args)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

Mars

public Mars()

Method Detail

main

public static void main(java.lang.String[] args)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Overview List

All Classes

Packages

mars

mars.assembler

mars.mips.dump

mars.mips.hardware

mars.mips.instructions

mars.mips.instructions.syscalls

mars.simulator

mars.tools

mars.util

mars.venus

mars.venus.editors

mars.venus.editors.generic

mars.venus.editors.jeditsyntax

mars.venus.editors.jeditsyntax.tokenmarker

 

All Classes

All Classes

AbstractDumpFormat

AbstractFontSettingDialog

AbstractMarsToolAndApplication

AbstractSyscall

AccessNotice

AddressErrorException

AsciiTextDumpFormat

Assembler

BackStepper

BasicInstruction

BasicInstructionFormat

BHTableModel

BHTEntry

BHTSimGUI

BHTSimulator

Binary

BinaryDumpFormat

BinaryTextDumpFormat

BitmapDisplay

CacheSimulator

Coprocessor0

Coprocessor0Window

Coprocessor1

Coprocessor1Window

DataSegmentWindow

DataTypes

DefaultInputHandler

DelayedBranch

DigitalLabSim

Directives

DumpFormat

DumpFormatLoader

EditCopyAction

EditCutAction

EditFindReplaceAction

Editor

EditorFont

EditPane

EditPasteAction

EditRedoAction

EditSelectAllAction

EditTabbedPane

EditUndoAction

ErrorList

ErrorMessage

Exceptions

ExecutePane

ExtendedInstruction

FileCloseAction

FileCloseAllAction

FileDumpMemoryAction

FileExitAction

FilenameFinder

FileNewAction

FileOpenAction

FilePrintAction

FileSaveAction

FileSaveAllAction

FileSaveAsAction

FileStatus

FloatRepresentation

GenericTextArea

Globals

GuiAction

HardcopyWriter

HardcopyWriter.PrintCanceledException

HelpAboutAction

HelpHelpAction

HexTextDumpFormat

InputHandler

InputHandler.backspace

InputHandler.backspace_word

InputHandler.clip_copy

InputHandler.clip_cut

InputHandler.clip_paste

InputHandler.delete

InputHandler.delete_word

InputHandler.document_end

InputHandler.document_home

InputHandler.end

InputHandler.home

InputHandler.insert_break

InputHandler.insert_char

InputHandler.insert_tab

InputHandler.MacroRecorder

InputHandler.next_char

InputHandler.next_line

InputHandler.next_page

InputHandler.next_word

InputHandler.NonRecordable

InputHandler.NonRepeatable

InputHandler.overwrite

InputHandler.prev_char

InputHandler.prev_line

InputHandler.prev_page

InputHandler.prev_word

InputHandler.repeat

InputHandler.select_all

InputHandler.toggle_rect

InputHandler.Wrapper

Instruction

InstructionCounter

InstructionSet

InstructionStatistics

IntelHexDumpFormat

IntroToTools

InvalidRegisterAccessException

JEditBasedTextArea

JEditTextArea

KeyboardAndDisplaySimulator

KeywordMap

LabelsWindow

Macro

MacroPool

MainPane

Mars

MarsBot

MarsLaunch

MarsSplashScreen

MARSTextEditingArea

MarsTool

Memory

MemoryAccessNotice

MemoryConfiguration

MemoryConfigurations

MemoryDump

MemoryReferenceVisualization

MessagesPane

MIFDumpFormat

MIPSprogram

MIPSTokenMarker

NumberDisplayBaseChooser

OperandFormat

PopupHelpItem

PopupListener

ProcessingException

ProgramArgumentList

ProgramStatement

PropertiesFile

RandomStreams

Register

RegisterAccessNotice

RegisterFile

RegistersPane

RegistersWindow

RepeatButton

RunAssembleAction

RunBackstepAction

RunClearBreakpointsAction

RunGoAction

RunPauseAction

RunResetAction

RunSpeedPanel

RunStepAction

RunStopAction

RunToggleBreakpointsAction

ScavengerHunt

ScreenMagnifier

SegmentWindowDumpFormat

Settings

SettingsAddressDisplayBaseAction

SettingsAssembleAllAction

SettingsAssembleOnOpenAction

SettingsDelayedBranchingAction

SettingsEditorAction

SettingsExceptionHandlerAction

SettingsExtendedAction

SettingsHighlightingAction

SettingsLabelAction

SettingsMemoryConfigurationAction

SettingsPopupInputAction

SettingsProgramArgumentsAction

SettingsStartAtMainAction

SettingsValueDisplayBaseAction

SettingsWarningsAreErrorsAction

SimulationCode

Simulator

Simulator.StopListener

SimulatorNotice

SourceLine

SwingWorker

Symbol

SymbolTable

SyntaxDocument

SyntaxStyle

SyntaxUtilities

Syscall

SyscallClose

SyscallConfirmDialog

SyscallExit

SyscallExit2

SyscallInputDialogDouble

SyscallInputDialogFloat

SyscallInputDialogInt

SyscallInputDialogString

SyscallMessageDialog

SyscallMessageDialogDouble

SyscallMessageDialogFloat

SyscallMessageDialogInt

SyscallMessageDialogString

SyscallMidiOut

SyscallMidiOutSync

SyscallNumberOverride

SyscallOpen

SyscallPrintChar

SyscallPrintDouble

SyscallPrintFloat

SyscallPrintInt

SyscallPrintIntBinary

SyscallPrintIntHex

SyscallPrintIntUnsigned

SyscallPrintString

SyscallRandDouble

SyscallRandFloat

SyscallRandInt

SyscallRandIntRange

SyscallRandSeed

SyscallRead

SyscallReadChar

SyscallReadDouble

SyscallReadFloat

SyscallReadInt

SyscallReadString

SyscallSbrk

SyscallSleep

SyscallTime

SyscallWrite

SystemIO

TextAreaDefaults

TextAreaPainter

TextAreaPainter.Highlight

TextSegmentWindow

TextUtilities

Token

Token

Tokenizer

TokenList

TokenMarker

TokenTypes

ToolAction

ToolLoader

TranslationCode

VenusUI

Serialized Form

Overview  Package  Class  Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Serialized Form

Package mars

Class mars.MarsSplashScreen extends javax.swing.JWindow implements Serializable

Serialized Fields

duration

int duration

Class mars.ProcessingException extends java.lang.Exception implements Serializable

Serialized Fields

errs

ErrorList errs

Package mars.mips.hardware

Class mars.mips.hardware.AddressErrorException extends java.lang.Exception implements Serializable

Serialized Fields

address

int address

type

int type

Class mars.mips.hardware.InvalidRegisterAccessException extends java.lang.Exception implements Serializable

Serialized Fields

errs

ErrorList errs

Package mars.tools

Class mars.tools.AbstractMarsToolAndApplication extends javax.swing.JFrame implements Serializable

Serialized Fields

isBeingUsedAsAMarsTool

boolean isBeingUsedAsAMarsTool

thisMarsApp

AbstractMarsToolAndApplication thisMarsApp

dialog

javax.swing.JDialog dialog

theWindow

java.awt.Window theWindow

headingLabel

javax.swing.JLabel headingLabel

title

java.lang.String title

heading

java.lang.String heading

emptyBorder

javax.swing.border.EmptyBorder emptyBorder

backgroundColor

java.awt.Color backgroundColor

lowMemoryAddress

int lowMemoryAddress

highMemoryAddress

int highMemoryAddress

observing

boolean observing

mostRecentlyOpenedFile

java.io.File mostRecentlyOpenedFile

interactiveGUIUpdater

java.lang.Runnable interactiveGUIUpdater

operationStatusMessages

mars.tools.AbstractMarsToolAndApplication.MessageField operationStatusMessages

openFileButton

javax.swing.JButton openFileButton

assembleRunButton

javax.swing.JButton assembleRunButton

stopButton

javax.swing.JButton stopButton

multiFileAssemble

boolean multiFileAssemble

connectButton

AbstractMarsToolAndApplication.ConnectButton connectButton

Class mars.tools.AbstractMarsToolAndApplication.ConnectButton extends javax.swing.JButton implements Serializable

Class mars.tools.BHTableModel extends javax.swing.table.AbstractTableModel implements Serializable

Serialized Fields

m_entries

java.util.Vector m_entries

vector holding the entries of the BHT

m_entryCnt

int m_entryCnt

number of entries in the BHT

m_historySize

int m_historySize

number of past branch events to remember

m_columnNames

java.lang.String[] m_columnNames

name of the table columns

m_columnClasses

java.lang.Class[] m_columnClasses

type of the table columns

Class mars.tools.BHTSimGUI extends javax.swing.JPanel implements Serializable

Serialized Fields

m_tfInstruction

javax.swing.JTextField m_tfInstruction

text field presenting the most recent branch instruction

m_tfAddress

javax.swing.JTextField m_tfAddress

text field representing the address of the most recent branch instruction

m_tfIndex

javax.swing.JTextField m_tfIndex

text field representing the resulting BHT index of the branch instruction

m_cbBHTentries

javax.swing.JComboBox m_cbBHTentries

combo box for selecting the number of BHT entries

m_cbBHThistory

javax.swing.JComboBox m_cbBHThistory

combo box for selecting the history size

m_cbBHTinitVal

javax.swing.JComboBox m_cbBHTinitVal

combo box for selecting the initial value

m_tabBHT

javax.swing.JTable m_tabBHT

the table representing the BHT

m_taLog

javax.swing.JTextArea m_taLog

text field for log output

Class mars.tools.BHTSimulator extends AbstractMarsToolAndApplication implements Serializable

Serialized Fields

m_gui

BHTSimGUI m_gui

the GUI of the BHT simulator

m_bhtModel

BHTableModel m_bhtModel

the model of the BHT

m_pendingBranchInstAddress

int m_pendingBranchInstAddress

state variable that indicates that the last instruction was a branch instruction (if address != 0) or not (address == 0)

m_lastBranchTaken

boolean m_lastBranchTaken

state variable that signals if the last branch was taken

Class mars.tools.BitmapDisplay extends AbstractMarsToolAndApplication implements Serializable

Serialized Fields

visualizationUnitPixelWidthSelector

javax.swing.JComboBox visualizationUnitPixelWidthSelector

visualizationUnitPixelHeightSelector

javax.swing.JComboBox visualizationUnitPixelHeightSelector

visualizationPixelWidthSelector

javax.swing.JComboBox visualizationPixelWidthSelector

visualizationPixelHeightSelector

javax.swing.JComboBox visualizationPixelHeightSelector

displayBaseAddressSelector

javax.swing.JComboBox displayBaseAddressSelector

drawingArea

java.awt.Graphics drawingArea

canvas

javax.swing.JPanel canvas

results

javax.swing.JPanel results

emptyBorder

javax.swing.border.EmptyBorder emptyBorder

countFonts

java.awt.Font countFonts

backgroundColor

java.awt.Color backgroundColor

visualizationUnitPixelWidthChoices

java.lang.String[] visualizationUnitPixelWidthChoices

defaultVisualizationUnitPixelWidthIndex

int defaultVisualizationUnitPixelWidthIndex

visualizationUnitPixelHeightChoices

java.lang.String[] visualizationUnitPixelHeightChoices

defaultVisualizationUnitPixelHeightIndex

int defaultVisualizationUnitPixelHeightIndex

displayAreaPixelWidthChoices

java.lang.String[] displayAreaPixelWidthChoices

defaultDisplayWidthIndex

int defaultDisplayWidthIndex

displayAreaPixelHeightChoices

java.lang.String[] displayAreaPixelHeightChoices

defaultDisplayHeightIndex

int defaultDisplayHeightIndex

unitPixelWidth

int unitPixelWidth

unitPixelHeight

int unitPixelHeight

displayAreaWidthInPixels

int displayAreaWidthInPixels

displayAreaHeightInPixels

int displayAreaHeightInPixels

displayBaseAddressChoices

java.lang.String[] displayBaseAddressChoices

displayBaseAddresses

int[] displayBaseAddresses

defaultBaseAddressIndex

int defaultBaseAddressIndex

baseAddress

int baseAddress

theGrid

mars.tools.BitmapDisplay.Grid theGrid

Class mars.tools.CacheSimulator extends AbstractMarsToolAndApplication implements Serializable

Serialized Fields

cacheBlockSizeSelector

javax.swing.JComboBox cacheBlockSizeSelector

cacheBlockCountSelector

javax.swing.JComboBox cacheBlockCountSelector

cachePlacementSelector

javax.swing.JComboBox cachePlacementSelector

cacheReplacementSelector

javax.swing.JComboBox cacheReplacementSelector

cacheSetSizeSelector

javax.swing.JComboBox cacheSetSizeSelector

memoryAccessCountDisplay

javax.swing.JTextField memoryAccessCountDisplay

cacheHitCountDisplay

javax.swing.JTextField cacheHitCountDisplay

cacheMissCountDisplay

javax.swing.JTextField cacheMissCountDisplay

replacementPolicyDisplay

javax.swing.JTextField replacementPolicyDisplay

cachableAddressesDisplay

javax.swing.JTextField cachableAddressesDisplay

cacheSizeDisplay

javax.swing.JTextField cacheSizeDisplay

cacheHitRateDisplay

javax.swing.JProgressBar cacheHitRateDisplay

animations

mars.tools.CacheSimulator.Animation animations

logPanel

javax.swing.JPanel logPanel

logScroll

javax.swing.JScrollPane logScroll

logText

javax.swing.JTextArea logText

logShow

javax.swing.JCheckBox logShow

emptyBorder

javax.swing.border.EmptyBorder emptyBorder

countFonts

java.awt.Font countFonts

backgroundColor

java.awt.Color backgroundColor

cacheBlockSizeChoicesInt

int[] cacheBlockSizeChoicesInt

cacheBlockCountChoicesInt

int[] cacheBlockCountChoicesInt

cacheBlockSizeChoices

java.lang.String[] cacheBlockSizeChoices

cacheBlockCountChoices

java.lang.String[] cacheBlockCountChoices

placementPolicyChoices

java.lang.String[] placementPolicyChoices

DIRECT

int DIRECT

FULL

int FULL

SET

int SET

replacementPolicyChoices

java.lang.String[] replacementPolicyChoices

LRU

int LRU

RANDOM

int RANDOM

cacheSetSizeChoices

java.lang.String[] cacheSetSizeChoices

defaultCacheBlockSizeIndex

int defaultCacheBlockSizeIndex

defaultCacheBlockCountIndex

int defaultCacheBlockCountIndex

defaultPlacementPolicyIndex

int defaultPlacementPolicyIndex

defaultReplacementPolicyIndex

int defaultReplacementPolicyIndex

defaultCacheSetSizeIndex

int defaultCacheSetSizeIndex

theCache

mars.tools.CacheSimulator.AbstractCache theCache

memoryAccessCount

int memoryAccessCount

cacheHitCount

int cacheHitCount

cacheMissCount

int cacheMissCount

cacheHitRate

double cacheHitRate

randu

java.util.Random randu

Class mars.tools.DigitalLabSim extends AbstractMarsToolAndApplication implements Serializable

Serialized Fields

sevenSegPanel

DigitalLabSim.SevenSegmentPanel sevenSegPanel

hexaKeyPanel

DigitalLabSim.HexaKeyboard hexaKeyPanel

Class mars.tools.DigitalLabSim.HexaKeyboard extends javax.swing.JPanel implements Serializable

Serialized Fields

button

javax.swing.JButton[] button

Class mars.tools.DigitalLabSim.SevenSegmentDisplay extends javax.swing.JComponent implements Serializable

Serialized Fields

aff

char aff

Class mars.tools.DigitalLabSim.SevenSegmentPanel extends javax.swing.JPanel implements Serializable

Serialized Fields

display

DigitalLabSim.SevenSegmentDisplay[] display

Class mars.tools.FloatRepresentation extends AbstractMarsToolAndApplication implements Serializable

Serialized Fields

attachedRegister

Register attachedRegister

fpRegisters

Register[] fpRegisters

thisFloatTool

FloatRepresentation thisFloatTool

binarySignDecoratedDisplay

javax.swing.JPanel binarySignDecoratedDisplay

binaryExponentDecoratedDisplay

javax.swing.JPanel binaryExponentDecoratedDisplay

binaryFractionDecoratedDisplay

javax.swing.JPanel binaryFractionDecoratedDisplay

hexDisplay

javax.swing.JTextField hexDisplay

decimalDisplay

javax.swing.JTextField decimalDisplay

binarySignDisplay

javax.swing.JTextField binarySignDisplay

binaryExponentDisplay

javax.swing.JTextField binaryExponentDisplay

binaryFractionDisplay

javax.swing.JTextField binaryFractionDisplay

expansionDisplay

javax.swing.JLabel expansionDisplay

significandLabel

javax.swing.JLabel significandLabel

binaryToDecimalFormulaGraphic

mars.tools.FloatRepresentation.BinaryToDecimalFormulaGraphic binaryToDecimalFormulaGraphic

instructions

mars.tools.FloatRepresentation.InstructionsPane instructions

defaultInstructions

java.lang.String defaultInstructions

Class mars.tools.InstructionCounter extends AbstractMarsToolAndApplication implements Serializable

Serialized Fields

counter

int counter

Number of instructions executed until now.

counterField

javax.swing.JTextField counterField

counterR

int counterR

Number of instructions of type R.

counterRField

javax.swing.JTextField counterRField

progressbarR

javax.swing.JProgressBar progressbarR

counterI

int counterI

Number of instructions of type I.

counterIField

javax.swing.JTextField counterIField

progressbarI

javax.swing.JProgressBar progressbarI

counterJ

int counterJ

Number of instructions of type J.

counterJField

javax.swing.JTextField counterJField

progressbarJ

javax.swing.JProgressBar progressbarJ

lastAddress

int lastAddress

The last address we saw. We ignore it because the only way for a
program to execute twice the same instruction is to enter an infinite
loop, which is not insteresting in the POV of counting instructions.

Class mars.tools.InstructionStatistics extends AbstractMarsToolAndApplication implements Serializable

Serialized Fields

m_tfTotalCounter

javax.swing.JTextField m_tfTotalCounter

text field for visualizing the total number of instructions processed

m_tfCounters

javax.swing.JTextField[] m_tfCounters

array of text field – one for each instruction category

m_pbCounters

javax.swing.JProgressBar[] m_pbCounters

array of progress pars – one for each instruction category

m_totalCounter

int m_totalCounter

counter for the total number of instructions processed

m_counters

int[] m_counters

array of counter variables – one for each instruction category

m_categoryLabels

java.lang.String[] m_categoryLabels

names of the instruction categories as array

lastAddress

int lastAddress

The last address we saw. We ignore it because the only way for a
program to execute twice the same instruction is to enter an infinite
loop, which is not insteresting in the POV of counting instructions.

Class mars.tools.IntroToTools extends AbstractMarsToolAndApplication implements Serializable

Class mars.tools.KeyboardAndDisplaySimulator extends AbstractMarsToolAndApplication implements Serializable

Serialized Fields

delayTechniques

mars.tools.KeyboardAndDisplaySimulator.TransmitterDelayTechnique[] delayTechniques

countingInstructions

boolean countingInstructions

instructionCount

int instructionCount

transmitDelayInstructionCountLimit

int transmitDelayInstructionCountLimit

currentDelayInstructionLimit

int currentDelayInstructionLimit

characterToDisplay

char characterToDisplay

displayAfterDelay

boolean displayAfterDelay

keyboardAndDisplay

javax.swing.JPanel keyboardAndDisplay

displayScrollPane

javax.swing.JScrollPane displayScrollPane

display

javax.swing.JTextArea display

displayPanel

javax.swing.JPanel displayPanel

displayOptions

javax.swing.JPanel displayOptions

delayTechniqueChooser

javax.swing.JComboBox delayTechniqueChooser

delayLengthPanel

mars.tools.KeyboardAndDisplaySimulator.DelayLengthPanel delayLengthPanel

delayLengthSlider

javax.swing.JSlider delayLengthSlider

displayAfterDelayCheckBox

javax.swing.JCheckBox displayAfterDelayCheckBox

keyboardPanel

javax.swing.JPanel keyboardPanel

keyAccepterScrollPane

javax.swing.JScrollPane keyAccepterScrollPane

keyEventAccepter

javax.swing.JTextArea keyEventAccepter

fontButton

javax.swing.JButton fontButton

defaultFont

java.awt.Font defaultFont

Class mars.tools.MemoryReferenceVisualization extends AbstractMarsToolAndApplication implements Serializable

Serialized Fields

wordsPerUnitSelector

javax.swing.JComboBox wordsPerUnitSelector

visualizationUnitPixelWidthSelector

javax.swing.JComboBox visualizationUnitPixelWidthSelector

visualizationUnitPixelHeightSelector

javax.swing.JComboBox visualizationUnitPixelHeightSelector

visualizationPixelWidthSelector

javax.swing.JComboBox visualizationPixelWidthSelector

visualizationPixelHeightSelector

javax.swing.JComboBox visualizationPixelHeightSelector

displayBaseAddressSelector

javax.swing.JComboBox displayBaseAddressSelector

drawHashMarksSelector

javax.swing.JCheckBox drawHashMarksSelector

drawingArea

java.awt.Graphics drawingArea

canvas

javax.swing.JPanel canvas

results

javax.swing.JPanel results

emptyBorder

javax.swing.border.EmptyBorder emptyBorder

countFonts

java.awt.Font countFonts

backgroundColor

java.awt.Color backgroundColor

wordsPerUnitChoices

java.lang.String[] wordsPerUnitChoices

defaultWordsPerUnitIndex

int defaultWordsPerUnitIndex

visualizationUnitPixelWidthChoices

java.lang.String[] visualizationUnitPixelWidthChoices

defaultVisualizationUnitPixelWidthIndex

int defaultVisualizationUnitPixelWidthIndex

visualizationUnitPixelHeightChoices

java.lang.String[] visualizationUnitPixelHeightChoices

defaultVisualizationUnitPixelHeightIndex

int defaultVisualizationUnitPixelHeightIndex

displayAreaPixelWidthChoices

java.lang.String[] displayAreaPixelWidthChoices

defaultDisplayWidthIndex

int defaultDisplayWidthIndex

displayAreaPixelHeightChoices

java.lang.String[] displayAreaPixelHeightChoices

defaultDisplayHeightIndex

int defaultDisplayHeightIndex

defaultDrawHashMarks

boolean defaultDrawHashMarks

unitPixelWidth

int unitPixelWidth

unitPixelHeight

int unitPixelHeight

wordsPerUnit

int wordsPerUnit

visualizationAreaWidthInPixels

int visualizationAreaWidthInPixels

visualizationAreaHeightInPixels

int visualizationAreaHeightInPixels

defaultCounterColors

mars.tools.MemoryReferenceVisualization.CounterColor[] defaultCounterColors

countTable

int[] countTable

COUNT_INDEX_INIT

int COUNT_INDEX_INIT

displayBaseAddressChoices

java.lang.String[] displayBaseAddressChoices

displayBaseAddresses

int[] displayBaseAddresses

defaultBaseAddressIndex

int defaultBaseAddressIndex

baseAddress

int baseAddress

theGrid

mars.tools.MemoryReferenceVisualization.Grid theGrid

counterColorScale

mars.tools.MemoryReferenceVisualization.CounterColorScale counterColorScale

Package mars.venus

Class mars.venus.AbstractFontSettingDialog extends javax.swing.JDialog implements Serializable

Serialized Fields

editorDialog

javax.swing.JDialog editorDialog

fontFamilySelector

javax.swing.JComboBox fontFamilySelector

fontStyleSelector

javax.swing.JComboBox fontStyleSelector

fontSizeSelector

javax.swing.JSlider fontSizeSelector

fontSizeSpinSelector

javax.swing.JSpinner fontSizeSpinSelector

fontSample

javax.swing.JLabel fontSample

currentFont

java.awt.Font currentFont

initialFontFamily

java.lang.String initialFontFamily

initialFontStyle

java.lang.String initialFontStyle

initialFontSize

java.lang.String initialFontSize

Class mars.venus.Coprocessor0Window extends javax.swing.JPanel implements Serializable

Serialized Fields

tableData

java.lang.Object[][] tableData

highlighting

boolean highlighting

highlightRow

int highlightRow

executePane

ExecutePane executePane

rowGivenRegNumber

int[] rowGivenRegNumber

Class mars.venus.Coprocessor1Window extends javax.swing.JPanel implements Serializable

Serialized Fields

tableData

java.lang.Object[][] tableData

highlighting

boolean highlighting

highlightRow

int highlightRow

executePane

ExecutePane executePane

conditionFlagCheckBox

javax.swing.JCheckBox[] conditionFlagCheckBox

Class mars.venus.DataSegmentWindow extends javax.swing.JInternalFrame implements Serializable

Serialized Fields

dataTableScroller

javax.swing.JScrollPane dataTableScroller

contentPane

java.awt.Container contentPane

tablePanel

javax.swing.JPanel tablePanel

dataButton

javax.swing.JButton dataButton

nextButton

javax.swing.JButton nextButton

prevButton

javax.swing.JButton prevButton

stakButton

javax.swing.JButton stakButton

globButton

javax.swing.JButton globButton

heapButton

javax.swing.JButton heapButton

kernButton

javax.swing.JButton kernButton

extnButton

javax.swing.JButton extnButton

mmioButton

javax.swing.JButton mmioButton

asciiDisplayCheckBox

javax.swing.JCheckBox asciiDisplayCheckBox

addressHighlighting

boolean addressHighlighting

asciiDisplay

boolean asciiDisplay

addressRow

int addressRow

addressColumn

int addressColumn

addressRowFirstAddress

int addressRowFirstAddress

settings

Settings settings

firstAddress

int firstAddress

homeAddress

int homeAddress

userOrKernelMode

boolean userOrKernelMode

baseAddressSelector

javax.swing.JComboBox baseAddressSelector

displayBaseAddressChoices

java.lang.String[] displayBaseAddressChoices

displayBaseAddresses

int[] displayBaseAddresses

defaultBaseAddressIndex

int defaultBaseAddressIndex

baseAddressButtons

javax.swing.JButton[] baseAddressButtons

displayBaseAddressArray

int[] displayBaseAddressArray

descriptions

java.lang.String[] descriptions

Class mars.venus.EditCopyAction extends GuiAction implements Serializable

Class mars.venus.EditCutAction extends GuiAction implements Serializable

Class mars.venus.EditFindReplaceAction extends GuiAction implements Serializable

Serialized Fields

findReplaceDialog

javax.swing.JDialog findReplaceDialog

Class mars.venus.EditPane extends javax.swing.JPanel implements Serializable

Serialized Fields

sourceCode

MARSTextEditingArea sourceCode

mainUI

VenusUI mainUI

currentDirectoryPath

java.lang.String currentDirectoryPath

caretPositionLabel

javax.swing.JLabel caretPositionLabel

showLineNumbers

javax.swing.JCheckBox showLineNumbers

lineNumbers

javax.swing.JLabel lineNumbers

isCompoundEdit

boolean isCompoundEdit

compoundEdit

javax.swing.undo.CompoundEdit compoundEdit

fileStatus

FileStatus fileStatus

Class mars.venus.EditPasteAction extends GuiAction implements Serializable

Class mars.venus.EditRedoAction extends GuiAction implements Serializable

Class mars.venus.EditSelectAllAction extends GuiAction implements Serializable

Class mars.venus.EditTabbedPane extends javax.swing.JTabbedPane implements Serializable

Serialized Fields

editTab

EditPane editTab

mainPane

MainPane mainPane

mainUI

VenusUI mainUI

editor

Editor editor

fileOpener

mars.venus.EditTabbedPane.FileOpener fileOpener

Class mars.venus.EditUndoAction extends GuiAction implements Serializable

Class mars.venus.ExecutePane extends javax.swing.JDesktopPane implements Serializable

Serialized Fields

registerValues

RegistersWindow registerValues

coprocessor1Values

Coprocessor1Window coprocessor1Values

coprocessor0Values

Coprocessor0Window coprocessor0Values

dataSegment

DataSegmentWindow dataSegment

textSegment

TextSegmentWindow textSegment

labelValues

LabelsWindow labelValues

mainUI

VenusUI mainUI

valueDisplayBase

NumberDisplayBaseChooser valueDisplayBase

addressDisplayBase

NumberDisplayBaseChooser addressDisplayBase

labelWindowVisible

boolean labelWindowVisible

Class mars.venus.FileCloseAction extends GuiAction implements Serializable

Class mars.venus.FileCloseAllAction extends GuiAction implements Serializable

Class mars.venus.FileDumpMemoryAction extends GuiAction implements Serializable

Serialized Fields

dumpDialog

javax.swing.JDialog dumpDialog

segmentArray

java.lang.String[] segmentArray

baseAddressArray

int[] baseAddressArray

limitAddressArray

int[] limitAddressArray

highAddressArray

int[] highAddressArray

segmentListArray

java.lang.String[] segmentListArray

segmentListBaseArray

int[] segmentListBaseArray

segmentListHighArray

int[] segmentListHighArray

segmentListSelector

javax.swing.JComboBox segmentListSelector

formatListSelector

javax.swing.JComboBox formatListSelector

Class mars.venus.FileExitAction extends GuiAction implements Serializable

Class mars.venus.FileNewAction extends GuiAction implements Serializable

Class mars.venus.FileOpenAction extends GuiAction implements Serializable

Serialized Fields

mostRecentlyOpenedFile

java.io.File mostRecentlyOpenedFile

fileChooser

javax.swing.JFileChooser fileChooser

fileFilterCount

int fileFilterCount

fileFilterList

java.util.ArrayList fileFilterList

listenForUserAddedFileFilter

java.beans.PropertyChangeListener listenForUserAddedFileFilter

Class mars.venus.FilePrintAction extends GuiAction implements Serializable

Class mars.venus.FileSaveAction extends GuiAction implements Serializable

Class mars.venus.FileSaveAllAction extends GuiAction implements Serializable

Class mars.venus.FileSaveAsAction extends GuiAction implements Serializable

Class mars.venus.GuiAction extends javax.swing.AbstractAction implements Serializable

Serialized Fields

mainUI

VenusUI mainUI

Class mars.venus.HardcopyWriter.PrintCanceledException extends java.lang.Exception implements Serializable

Class mars.venus.HelpAboutAction extends GuiAction implements Serializable

Class mars.venus.HelpHelpAction extends GuiAction implements Serializable

Class mars.venus.LabelsWindow extends javax.swing.JInternalFrame implements Serializable

Serialized Fields

contentPane

java.awt.Container contentPane

labelPanel

javax.swing.JPanel labelPanel

dataLabels

javax.swing.JCheckBox dataLabels

textLabels

javax.swing.JCheckBox textLabels

listOfLabelsForSymbolTable

java.util.ArrayList listOfLabelsForSymbolTable

labelsWindow

LabelsWindow labelsWindow

tableSortComparator

java.util.Comparator tableSortComparator

tableSortingComparators

java.util.Comparator[] tableSortingComparators

sortState

int sortState

Class mars.venus.MainPane extends javax.swing.JTabbedPane implements Serializable

Serialized Fields

editTab

EditPane editTab

executeTab

ExecutePane executeTab

editTabbedPane

EditTabbedPane editTabbedPane

mainUI

VenusUI mainUI

Class mars.venus.MessagesPane extends javax.swing.JTabbedPane implements Serializable

Serialized Fields

assemble

javax.swing.JTextArea assemble

run

javax.swing.JTextArea run

assembleTab

javax.swing.JPanel assembleTab

runTab

javax.swing.JPanel runTab

Class mars.venus.NumberDisplayBaseChooser extends javax.swing.JCheckBox implements Serializable

Serialized Fields

base

int base

settingMenuItem

javax.swing.JCheckBoxMenuItem settingMenuItem

Class mars.venus.RegistersPane extends javax.swing.JTabbedPane implements Serializable

Serialized Fields

regsTab

RegistersWindow regsTab

cop1Tab

Coprocessor1Window cop1Tab

cop0Tab

Coprocessor0Window cop0Tab

mainUI

VenusUI mainUI

Class mars.venus.RegistersWindow extends javax.swing.JPanel implements Serializable

Serialized Fields

tableData

java.lang.Object[][] tableData

highlighting

boolean highlighting

highlightRow

int highlightRow

executePane

ExecutePane executePane

Class mars.venus.RepeatButton extends javax.swing.JButton implements Serializable

Serialized Fields

pressed

boolean pressed

The pressed state for this button.

repeatEnabled

boolean repeatEnabled

Flag to indicate that the button should fire events when held.
If false, the button is effectively a plain old JButton, but
there may be times when this feature might wish to be disabled.

timer

javax.swing.Timer timer

The hold-down timer for this button.

initialDelay

int initialDelay

The initial delay for this button. Hold-down time before first
timer firing. In milliseconds.

delay

int delay

The delay between timer firings for this button once the delay
period is past. In milliseconds.

modifiers

int modifiers

Holder of the modifiers used when the mouse pressed the button.
This is used for subsequently fired action events. This may change
after mouse pressed if the user moves the mouse out, releases a key
and then moves the mouse back in.

Class mars.venus.RunAssembleAction extends GuiAction implements Serializable

Class mars.venus.RunBackstepAction extends GuiAction implements Serializable

Serialized Fields

name

java.lang.String name

executePane

ExecutePane executePane

Class mars.venus.RunClearBreakpointsAction extends GuiAction implements Serializable

Class mars.venus.RunGoAction extends GuiAction implements Serializable

Serialized Fields

name

java.lang.String name

executePane

ExecutePane executePane

Class mars.venus.RunPauseAction extends GuiAction implements Serializable

Class mars.venus.RunResetAction extends GuiAction implements Serializable

Class mars.venus.RunSpeedPanel extends javax.swing.JPanel implements Serializable

Serialized Fields

speedTable

double[] speedTable

sliderLabel

javax.swing.JLabel sliderLabel

runSpeedSlider

javax.swing.JSlider runSpeedSlider

runSpeedIndex

int runSpeedIndex

Class mars.venus.RunStepAction extends GuiAction implements Serializable

Serialized Fields

name

java.lang.String name

executePane

ExecutePane executePane

Class mars.venus.RunStopAction extends GuiAction implements Serializable

Class mars.venus.RunToggleBreakpointsAction extends GuiAction implements Serializable

Class mars.venus.SettingsAddressDisplayBaseAction extends GuiAction implements Serializable

Class mars.venus.SettingsAssembleAllAction extends GuiAction implements Serializable

Class mars.venus.SettingsAssembleOnOpenAction extends GuiAction implements Serializable

Class mars.venus.SettingsDelayedBranchingAction extends GuiAction implements Serializable

Class mars.venus.SettingsEditorAction extends GuiAction implements Serializable

Serialized Fields

editorDialog

javax.swing.JDialog editorDialog

fontFamilySelector

javax.swing.JComboBox fontFamilySelector

fontStyleSelector

javax.swing.JComboBox fontStyleSelector

tabSizeSelector

javax.swing.JSlider tabSizeSelector

fontSizeDisplay

javax.swing.JTextField fontSizeDisplay

initialFontFamily

java.lang.String initialFontFamily

initialFontStyle

java.lang.String initialFontStyle

initialFontSize

java.lang.String initialFontSize

Class mars.venus.SettingsExceptionHandlerAction extends GuiAction implements Serializable

Serialized Fields

exceptionHandlerDialog

javax.swing.JDialog exceptionHandlerDialog

exceptionHandlerSetting

javax.swing.JCheckBox exceptionHandlerSetting

exceptionHandlerSelectionButton

javax.swing.JButton exceptionHandlerSelectionButton

exceptionHandlerDisplay

javax.swing.JTextField exceptionHandlerDisplay

initialSelected

boolean initialSelected

initialPathname

java.lang.String initialPathname

Class mars.venus.SettingsExtendedAction extends GuiAction implements Serializable

Class mars.venus.SettingsHighlightingAction extends GuiAction implements Serializable

Serialized Fields

highlightDialog

javax.swing.JDialog highlightDialog

backgroundButtons

javax.swing.JButton[] backgroundButtons

foregroundButtons

javax.swing.JButton[] foregroundButtons

fontButtons

javax.swing.JButton[] fontButtons

defaultCheckBoxes

javax.swing.JCheckBox[] defaultCheckBoxes

samples

javax.swing.JLabel[] samples

currentNondefaultBackground

java.awt.Color[] currentNondefaultBackground

currentNondefaultForeground

java.awt.Color[] currentNondefaultForeground

initialSettingsBackground

java.awt.Color[] initialSettingsBackground

initialSettingsForeground

java.awt.Color[] initialSettingsForeground

initialFont

java.awt.Font[] initialFont

currentFont

java.awt.Font[] currentFont

currentNondefaultFont

java.awt.Font[] currentNondefaultFont

dataHighlightButton

javax.swing.JButton dataHighlightButton

registerHighlightButton

javax.swing.JButton registerHighlightButton

currentDataHighlightSetting

boolean currentDataHighlightSetting

initialDataHighlightSetting

boolean initialDataHighlightSetting

currentRegisterHighlightSetting

boolean currentRegisterHighlightSetting

initialRegisterHighlightSetting

boolean initialRegisterHighlightSetting

Class mars.venus.SettingsLabelAction extends GuiAction implements Serializable

Class mars.venus.SettingsMemoryConfigurationAction extends GuiAction implements Serializable

Serialized Fields

configDialog

javax.swing.JDialog configDialog

fontFamilySelector

javax.swing.JComboBox fontFamilySelector

fontStyleSelector

javax.swing.JComboBox fontStyleSelector

fontSizeSelector

javax.swing.JSlider fontSizeSelector

fontSizeDisplay

javax.swing.JTextField fontSizeDisplay

thisAction

SettingsMemoryConfigurationAction thisAction

initialFontFamily

java.lang.String initialFontFamily

initialFontStyle

java.lang.String initialFontStyle

initialFontSize

java.lang.String initialFontSize

Class mars.venus.SettingsPopupInputAction extends GuiAction implements Serializable

Class mars.venus.SettingsProgramArgumentsAction extends GuiAction implements Serializable

Class mars.venus.SettingsStartAtMainAction extends GuiAction implements Serializable

Class mars.venus.SettingsValueDisplayBaseAction extends GuiAction implements Serializable

Class mars.venus.SettingsWarningsAreErrorsAction extends GuiAction implements Serializable

Class mars.venus.TextSegmentWindow extends javax.swing.JInternalFrame implements Serializable

Serialized Fields

programArgumentsPanel

javax.swing.JPanel programArgumentsPanel

programArgumentsTextField

javax.swing.JTextField programArgumentsTextField

table

javax.swing.JTable table

tableScroller

javax.swing.JScrollPane tableScroller

data

java.lang.Object[][] data

intAddresses

int[] intAddresses

addressRows

java.util.Hashtable addressRows

contentPane

java.awt.Container contentPane

tableModel

mars.venus.TextSegmentWindow.TextTableModel tableModel

tableCellFont

java.awt.Font tableCellFont

codeHighlighting

boolean codeHighlighting

breakpointsEnabled

boolean breakpointsEnabled

highlightAddress

int highlightAddress

tableModelListener

javax.swing.event.TableModelListener tableModelListener

inDelaySlot

boolean inDelaySlot

Class mars.venus.ToolAction extends javax.swing.AbstractAction implements Serializable

Serialized Fields

toolClass

java.lang.Class toolClass

Class mars.venus.VenusUI extends javax.swing.JFrame implements Serializable

Serialized Fields

mainUI

VenusUI mainUI

menu

javax.swing.JMenuBar menu

toolbar

javax.swing.JToolBar toolbar

mainPane

MainPane mainPane

registersPane

RegistersPane registersPane

registersTab

RegistersWindow registersTab

coprocessor1Tab

Coprocessor1Window coprocessor1Tab

coprocessor0Tab

Coprocessor0Window coprocessor0Tab

messagesPane

MessagesPane messagesPane

splitter

javax.swing.JSplitPane splitter

horizonSplitter

javax.swing.JSplitPane horizonSplitter

north

javax.swing.JPanel north

frameState

int frameState

editor

Editor editor

file

javax.swing.JMenu file

run

javax.swing.JMenu run

window

javax.swing.JMenu window

help

javax.swing.JMenu help

edit

javax.swing.JMenu edit

settings

javax.swing.JMenu settings

fileNew

javax.swing.JMenuItem fileNew

fileOpen

javax.swing.JMenuItem fileOpen

fileClose

javax.swing.JMenuItem fileClose

fileCloseAll

javax.swing.JMenuItem fileCloseAll

fileSave

javax.swing.JMenuItem fileSave

fileSaveAs

javax.swing.JMenuItem fileSaveAs

fileSaveAll

javax.swing.JMenuItem fileSaveAll

fileDumpMemory

javax.swing.JMenuItem fileDumpMemory

filePrint

javax.swing.JMenuItem filePrint

fileExit

javax.swing.JMenuItem fileExit

editUndo

javax.swing.JMenuItem editUndo

editRedo

javax.swing.JMenuItem editRedo

editCut

javax.swing.JMenuItem editCut

editCopy

javax.swing.JMenuItem editCopy

editPaste

javax.swing.JMenuItem editPaste

editFindReplace

javax.swing.JMenuItem editFindReplace

editSelectAll

javax.swing.JMenuItem editSelectAll

runGo

javax.swing.JMenuItem runGo

runStep

javax.swing.JMenuItem runStep

runBackstep

javax.swing.JMenuItem runBackstep

runReset

javax.swing.JMenuItem runReset

runAssemble

javax.swing.JMenuItem runAssemble

runStop

javax.swing.JMenuItem runStop

runPause

javax.swing.JMenuItem runPause

runClearBreakpoints

javax.swing.JMenuItem runClearBreakpoints

runToggleBreakpoints

javax.swing.JMenuItem runToggleBreakpoints

settingsLabel

javax.swing.JCheckBoxMenuItem settingsLabel

settingsPopupInput

javax.swing.JCheckBoxMenuItem settingsPopupInput

settingsValueDisplayBase

javax.swing.JCheckBoxMenuItem settingsValueDisplayBase

settingsAddressDisplayBase

javax.swing.JCheckBoxMenuItem settingsAddressDisplayBase

settingsExtended

javax.swing.JCheckBoxMenuItem settingsExtended

settingsAssembleOnOpen

javax.swing.JCheckBoxMenuItem settingsAssembleOnOpen

settingsAssembleAll

javax.swing.JCheckBoxMenuItem settingsAssembleAll

settingsWarningsAreErrors

javax.swing.JCheckBoxMenuItem settingsWarningsAreErrors

settingsStartAtMain

javax.swing.JCheckBoxMenuItem settingsStartAtMain

settingsDelayedBranching

javax.swing.JCheckBoxMenuItem settingsDelayedBranching

settingsProgramArguments

javax.swing.JCheckBoxMenuItem settingsProgramArguments

settingsExceptionHandler

javax.swing.JMenuItem settingsExceptionHandler

settingsEditor

javax.swing.JMenuItem settingsEditor

settingsHighlighting

javax.swing.JMenuItem settingsHighlighting

settingsMemoryConfiguration

javax.swing.JMenuItem settingsMemoryConfiguration

helpHelp

javax.swing.JMenuItem helpHelp

helpAbout

javax.swing.JMenuItem helpAbout

Undo

javax.swing.JButton Undo

Redo

javax.swing.JButton Redo

Cut

javax.swing.JButton Cut

Copy

javax.swing.JButton Copy

Paste

javax.swing.JButton Paste

FindReplace

javax.swing.JButton FindReplace

SelectAll

javax.swing.JButton SelectAll

New

javax.swing.JButton New

Open

javax.swing.JButton Open

Save

javax.swing.JButton Save

SaveAs

javax.swing.JButton SaveAs

SaveAll

javax.swing.JButton SaveAll

DumpMemory

javax.swing.JButton DumpMemory

Print

javax.swing.JButton Print

Run

javax.swing.JButton Run

Assemble

javax.swing.JButton Assemble

Reset

javax.swing.JButton Reset

Step

javax.swing.JButton Step

Backstep

javax.swing.JButton Backstep

Stop

javax.swing.JButton Stop

Pause

javax.swing.JButton Pause

Help

javax.swing.JButton Help

fileNewAction

javax.swing.Action fileNewAction

fileOpenAction

javax.swing.Action fileOpenAction

fileCloseAction

javax.swing.Action fileCloseAction

fileCloseAllAction

javax.swing.Action fileCloseAllAction

fileSaveAction

javax.swing.Action fileSaveAction

fileSaveAsAction

javax.swing.Action fileSaveAsAction

fileSaveAllAction

javax.swing.Action fileSaveAllAction

fileDumpMemoryAction

javax.swing.Action fileDumpMemoryAction

filePrintAction

javax.swing.Action filePrintAction

fileExitAction

javax.swing.Action fileExitAction

editUndoAction

EditUndoAction editUndoAction

editRedoAction

EditRedoAction editRedoAction

editCutAction

javax.swing.Action editCutAction

editCopyAction

javax.swing.Action editCopyAction

editPasteAction

javax.swing.Action editPasteAction

editFindReplaceAction

javax.swing.Action editFindReplaceAction

editSelectAllAction

javax.swing.Action editSelectAllAction

runAssembleAction

javax.swing.Action runAssembleAction

runGoAction

javax.swing.Action runGoAction

runStepAction

javax.swing.Action runStepAction

runBackstepAction

javax.swing.Action runBackstepAction

runResetAction

javax.swing.Action runResetAction

runStopAction

javax.swing.Action runStopAction

runPauseAction

javax.swing.Action runPauseAction

runClearBreakpointsAction

javax.swing.Action runClearBreakpointsAction

runToggleBreakpointsAction

javax.swing.Action runToggleBreakpointsAction

settingsLabelAction

javax.swing.Action settingsLabelAction

settingsPopupInputAction

javax.swing.Action settingsPopupInputAction

settingsValueDisplayBaseAction

javax.swing.Action settingsValueDisplayBaseAction

settingsAddressDisplayBaseAction

javax.swing.Action settingsAddressDisplayBaseAction

settingsExtendedAction

javax.swing.Action settingsExtendedAction

settingsAssembleOnOpenAction

javax.swing.Action settingsAssembleOnOpenAction

settingsAssembleAllAction

javax.swing.Action settingsAssembleAllAction

settingsWarningsAreErrorsAction

javax.swing.Action settingsWarningsAreErrorsAction

settingsStartAtMainAction

javax.swing.Action settingsStartAtMainAction

settingsProgramArgumentsAction

javax.swing.Action settingsProgramArgumentsAction

settingsDelayedBranchingAction

javax.swing.Action settingsDelayedBranchingAction

settingsExceptionHandlerAction

javax.swing.Action settingsExceptionHandlerAction

settingsEditorAction

javax.swing.Action settingsEditorAction

settingsHighlightingAction

javax.swing.Action settingsHighlightingAction

settingsMemoryConfigurationAction

javax.swing.Action settingsMemoryConfigurationAction

helpHelpAction

javax.swing.Action helpHelpAction

helpAboutAction

javax.swing.Action helpAboutAction

Package mars.venus.editors.generic

Class mars.venus.editors.generic.GenericTextArea extends javax.swing.JTextArea implements Serializable

Serialized Fields

editPane

EditPane editPane

undoManager

javax.swing.undo.UndoManager undoManager

undoableEditListener

javax.swing.event.UndoableEditListener undoableEditListener

sourceCode

javax.swing.JTextArea sourceCode

editAreaScrollPane

javax.swing.JScrollPane editAreaScrollPane

isCompoundEdit

boolean isCompoundEdit

compoundEdit

javax.swing.undo.CompoundEdit compoundEdit

Package mars.venus.editors.jeditsyntax

Class mars.venus.editors.jeditsyntax.JEditBasedTextArea extends JEditTextArea implements Serializable

Serialized Fields

editPane

EditPane editPane

undoManager

javax.swing.undo.UndoManager undoManager

undoableEditListener

javax.swing.event.UndoableEditListener undoableEditListener

isCompoundEdit

boolean isCompoundEdit

compoundEdit

javax.swing.undo.CompoundEdit compoundEdit

sourceCode

JEditBasedTextArea sourceCode

Class mars.venus.editors.jeditsyntax.JEditTextArea extends javax.swing.JComponent implements Serializable

Serialized Fields

lineNumbersVertical

javax.swing.JScrollBar lineNumbersVertical

Creates a new JEditTextArea with the specified settings.

popupMenu

javax.swing.JPopupMenu popupMenu

painter

TextAreaPainter painter

popup

javax.swing.JPopupMenu popup

listenerList

javax.swing.event.EventListenerList listenerList

caretEvent

mars.venus.editors.jeditsyntax.JEditTextArea.MutableCaretEvent caretEvent

caretBlinks

boolean caretBlinks

caretVisible

boolean caretVisible

blink

boolean blink

editable

boolean editable

caretBlinkRate

int caretBlinkRate

firstLine

int firstLine

visibleLines

int visibleLines

electricScroll

int electricScroll

horizontalOffset

int horizontalOffset

vertical

javax.swing.JScrollBar vertical

horizontal

javax.swing.JScrollBar horizontal

scrollBarsInitialized

boolean scrollBarsInitialized

inputHandler

InputHandler inputHandler

document

SyntaxDocument document

documentHandler

mars.venus.editors.jeditsyntax.JEditTextArea.DocumentHandler documentHandler

lineSegment

javax.swing.text.Segment lineSegment

selectionStart

int selectionStart

selectionStartLine

int selectionStartLine

selectionEnd

int selectionEnd

selectionEndLine

int selectionEndLine

biasLeft

boolean biasLeft

bracketPosition

int bracketPosition

bracketLine

int bracketLine

magicCaret

int magicCaret

overwrite

boolean overwrite

rectSelect

boolean rectSelect

unredoing

boolean unredoing

Class mars.venus.editors.jeditsyntax.SyntaxDocument extends javax.swing.text.PlainDocument implements Serializable

Serialized Fields

tokenMarker

TokenMarker tokenMarker

Class mars.venus.editors.jeditsyntax.TextAreaPainter extends javax.swing.JComponent implements Serializable

Serialized Fields

currentLineIndex

int currentLineIndex

currentLineTokens

Token currentLineTokens

currentLine

javax.swing.text.Segment currentLine

textArea

JEditTextArea textArea

styles

SyntaxStyle[] styles

caretColor

java.awt.Color caretColor

selectionColor

java.awt.Color selectionColor

lineHighlightColor

java.awt.Color lineHighlightColor

bracketHighlightColor

java.awt.Color bracketHighlightColor

eolMarkerColor

java.awt.Color eolMarkerColor

blockCaret

boolean blockCaret

lineHighlight

boolean lineHighlight

bracketHighlight

boolean bracketHighlight

paintInvalid

boolean paintInvalid

eolMarkers

boolean eolMarkers

cols

int cols

rows

int rows

tabSize

int tabSize

tabSizeChars

int tabSizeChars

fm

java.awt.FontMetrics fm

highlights

TextAreaPainter.Highlight highlights

Overview  Package  Class  Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Index

Overview  Package  Class  Tree  Deprecated   Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

A B C D E F G H I J K L M N O P Q R S T U V W X Y _

A

AbstractDumpFormat – Class in mars.mips.dump
Abstract class for memory dump file formats.
AbstractDumpFormat(String, String, String, String) –
Constructor for class mars.mips.dump.AbstractDumpFormat

Typical constructor.

AbstractFontSettingDialog – Class in mars.venus
Abstract class for a font selection dialog.
AbstractFontSettingDialog(Frame, String, boolean, Font) –
Constructor for class mars.venus.AbstractFontSettingDialog

Create a new font chooser.

AbstractMarsToolAndApplication – Class in mars.tools
An abstract class that provides generic components to facilitate implementation of
a MarsTool and/or stand-alone Mars-based application.
AbstractMarsToolAndApplication(String, String) –
Constructor for class mars.tools.AbstractMarsToolAndApplication

Simple constructor

AbstractMarsToolAndApplication.ConnectButton – Class in mars.tools
 
AbstractMarsToolAndApplication.ConnectButton() –
Constructor for class mars.tools.AbstractMarsToolAndApplication.ConnectButton

 

AbstractMarsToolAndApplication.EnterKeyListener – Class in mars.tools
 
AbstractMarsToolAndApplication.EnterKeyListener(AbstractButton) –
Constructor for class mars.tools.AbstractMarsToolAndApplication.EnterKeyListener

 

AbstractSyscall – Class in mars.mips.instructions.syscalls
Abstract class that a MIPS syscall system service may extend.
AbstractSyscall(int, String) –
Constructor for class mars.mips.instructions.syscalls.AbstractSyscall

Constructor is provided so subclass may initialize instance variables.

accessIsFromGUI() –
Method in class mars.mips.hardware.AccessNotice

Query whether the access originated from MARS GUI (AWT event queue)

accessIsFromMIPS() –
Method in class mars.mips.hardware.AccessNotice

Query whether the access originated from executing MIPS program

AccessNotice – Class in mars.mips.hardware
Object provided to Observers of runtime access to MIPS memory or registers.
AccessNotice(int) –
Constructor for class mars.mips.hardware.AccessNotice

 

action() –
Method in class mars.tools.AbstractMarsToolAndApplication

Required MarsTool method to carry out Tool functions.

action() –
Method in class mars.tools.MarsBot

 

action() –
Method in interface mars.tools.MarsTool

Performs tool functions.

action() –
Method in class mars.tools.ScavengerHunt

 

action() –
Method in class mars.tools.ScreenMagnifier

 

actionPerformed(ActionEvent) –
Method in class mars.tools.BHTSimulator

Handles the actions when selecting another value in one of the two combo boxes.

actionPerformed(ActionEvent) –
Method in class mars.venus.Coprocessor1Window

Called when user clicks on a condition flag checkbox.

actionPerformed(ActionEvent) –
Method in class mars.venus.EditCopyAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.EditCutAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.EditFindReplaceAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.backspace

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.backspace_word

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.clip_copy

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.clip_cut

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.clip_paste

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.delete

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.delete_word

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.document_end

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.document_home

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.end

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.home

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.insert_break

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.insert_char

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.insert_tab

 

actionPerformed(ActionListener, String) –
Method in interface mars.venus.editors.jeditsyntax.InputHandler.MacroRecorder

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.next_char

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.next_line

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.next_page

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.next_word

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.overwrite

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.prev_char

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.prev_line

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.prev_page

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.prev_word

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.repeat

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.select_all

 

actionPerformed(ActionEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler.toggle_rect

 

actionPerformed(ActionEvent) –
Method in class mars.venus.EditPasteAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.EditRedoAction

Adapted from TextComponentDemo.java in the
Java Tutorial “Text Component Features”

actionPerformed(ActionEvent) –
Method in class mars.venus.EditSelectAllAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.EditUndoAction

Adapted from TextComponentDemo.java in the
Java Tutorial “Text Component Features”

actionPerformed(ActionEvent) –
Method in class mars.venus.FileCloseAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.FileCloseAllAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.FileDumpMemoryAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.FileExitAction

Exit MARS, unless one or more files have unsaved edits and user cancels.

actionPerformed(ActionEvent) –
Method in class mars.venus.FileNewAction

Code to create a new document.

actionPerformed(ActionEvent) –
Method in class mars.venus.FileOpenAction

Launch a file chooser for name of file to open

actionPerformed(ActionEvent) –
Method in class mars.venus.FilePrintAction

Uses the HardcopyWriter class developed by David Flanagan for the book
“Java Examples in a Nutshell”.

actionPerformed(ActionEvent) –
Method in class mars.venus.FileSaveAction

saves the file, if not alredy saved it will do a saveAs

actionPerformed(ActionEvent) –
Method in class mars.venus.FileSaveAllAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.FileSaveAsAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.GuiAction

does nothing by default.

actionPerformed(ActionEvent) –
Method in class mars.venus.HelpAboutAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.HelpHelpAction

Displays tabs with categories of information

actionPerformed(ActionEvent) –
Method in class mars.venus.RepeatButton

Handle action events.

actionPerformed(ActionEvent) –
Method in class mars.venus.RunAssembleAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.RunBackstepAction

perform next simulated instruction step.

actionPerformed(ActionEvent) –
Method in class mars.venus.RunClearBreakpointsAction

When this option is selected, tell text segment window to clear breakpoints in its table model.

actionPerformed(ActionEvent) –
Method in class mars.venus.RunGoAction

Action to take when GO is selected — run the MIPS program!

actionPerformed(ActionEvent) –
Method in class mars.venus.RunPauseAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.RunResetAction

reset GUI components and MIPS resources

actionPerformed(ActionEvent) –
Method in class mars.venus.RunStepAction

perform next simulated instruction step.

actionPerformed(ActionEvent) –
Method in class mars.venus.RunStopAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.RunToggleBreakpointsAction

When this option is selected, tell text segment window to clear breakpoints in its table model.

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsAddressDisplayBaseAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsAssembleAllAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsAssembleOnOpenAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsDelayedBranchingAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsEditorAction

When this action is triggered, launch a dialog to view and modify
editor settings.

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsExceptionHandlerAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsExtendedAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsHighlightingAction

When this action is triggered, launch a dialog to view and modify
editor settings.

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsLabelAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsMemoryConfigurationAction

When this action is triggered, launch a dialog to view and modify
editor settings.

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsPopupInputAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsProgramArgumentsAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsStartAtMainAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsValueDisplayBaseAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.SettingsWarningsAreErrorsAction

 

actionPerformed(ActionEvent) –
Method in class mars.venus.ToolAction

Response when tool’s item selected from menu.

add(Token) –
Method in class mars.assembler.TokenList

Adds a Token object to the end of the list.

add(ErrorMessage) –
Method in class mars.ErrorList

Add new error message to end of list.

add(ErrorMessage, int) –
Method in class mars.ErrorList

Add new error message at specified index position.

add(String, byte) –
Method in class mars.venus.editors.jeditsyntax.KeywordMap

Adds a key-value mapping.

addArg(String) –
Method in class mars.assembler.Macro

 

addAsObserver() –
Method in class mars.tools.AbstractMarsToolAndApplication

Add this app/tool as an Observer of desired MIPS Observables (memory and registers).

addAsObserver(int, int) –
Method in class mars.tools.AbstractMarsToolAndApplication

Add this app/tool as an Observer of the specified subrange of MIPS memory.

addAsObserver(Register) –
Method in class mars.tools.AbstractMarsToolAndApplication

Add this app/tool as an Observer of the specified MIPS register.

addAsObserver() –
Method in class mars.tools.BHTSimulator

Adds BHTSimulator as observer of the text segment.

addAsObserver() –
Method in class mars.tools.BitmapDisplay

Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only.

addAsObserver() –
Method in class mars.tools.DigitalLabSim

 

addAsObserver() –
Method in class mars.tools.FloatRepresentation

Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only.

addAsObserver() –
Method in class mars.tools.InstructionCounter

 

addAsObserver() –
Method in class mars.tools.InstructionStatistics

registers the tool as observer for the text segment of the MIPS program

addAsObserver() –
Method in class mars.tools.KeyboardAndDisplaySimulator

Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only.

addAsObserver() –
Method in class mars.tools.MemoryReferenceVisualization

Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only.

addCaretListener(CaretListener) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Adds a caret change listener to this text area.

addConditionFlagClear(int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addConditionFlagSet(int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addCoprocessor0Restore(int, int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addCoprocessor1Restore(int, int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addCustomHighlight(TextAreaPainter.Highlight) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Adds a custom highlight painter.

addDefaultKeyBindings() –
Method in class mars.venus.editors.jeditsyntax.DefaultInputHandler

Sets up the default key bindings.

addDefaultKeyBindings() –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Adds the default key bindings to this input handler.

addDoNothing(int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addKeyBinding(String, ActionListener) –
Method in class mars.venus.editors.jeditsyntax.DefaultInputHandler

Adds a key binding to this input handler.

addKeyBinding(String, ActionListener) –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Adds a key binding to this input handler.

addLabel(String) –
Method in class mars.assembler.Macro

 

addMemoryRestoreByte(int, int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addMemoryRestoreHalf(int, int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addMemoryRestoreRawWord(int, int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addMemoryRestoreWord(int, int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addObserver(Observer) –
Method in class mars.mips.hardware.Memory

Method to accept registration from observer for any memory address.

addObserver(Observer, int) –
Method in class mars.mips.hardware.Memory

Method to accept registration from observer for specific address.

addObserver(Observer, int, int) –
Method in class mars.mips.hardware.Memory

Method to accept registration from observer for specific address range.

addPCRestore(int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addProgramArgumentsPanel() –
Method in class mars.venus.TextSegmentWindow

 

addRegisterFileRestore(int, int) –
Method in class mars.simulator.BackStepper

Add a new “back step” (the undo action) to the stack.

addRegistersObserver(Observer) –
Static method in class mars.mips.hardware.Coprocessor0

Each individual register is a separate object and Observable.

addRegistersObserver(Observer) –
Static method in class mars.mips.hardware.Coprocessor1

Each individual register is a separate object and Observable.

addRegistersObserver(Observer) –
Static method in class mars.mips.hardware.RegisterFile

Each individual register is a separate object and Observable.

ADDRESS_EXCEPTION_LOAD –
Static variable in class mars.simulator.Exceptions

 

ADDRESS_EXCEPTION_STORE –
Static variable in class mars.simulator.Exceptions

 

AddressErrorException – Exception in mars.mips.hardware
Represents MIPS AddressErrorException.
AddressErrorException(String, int, int) –
Constructor for exception mars.mips.hardware.AddressErrorException

Constructor for the AddressErrorException class

addStopListener(Simulator.StopListener) –
Method in class mars.simulator.Simulator

 

addSymbol(Token, int, boolean, ErrorList) –
Method in class mars.assembler.SymbolTable

Adds a Symbol object into the array of Symbols.

addToken(int, byte) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Adds a token to the token list.

addUndoableEdit(UndoableEdit) –
Method in class mars.venus.editors.jeditsyntax.SyntaxDocument

Adds an undoable edit to this document’s undo list.

aff –
Variable in class mars.tools.DigitalLabSim.SevenSegmentDisplay

 

ALIGN –
Static variable in class mars.assembler.Directives

 

alignToWordBoundary(int) –
Static method in class mars.mips.hardware.Memory

Utility method to align given address to next full word boundary, if not already
aligned.

allocateBytesFromHeap(int) –
Method in class mars.mips.hardware.Memory

Returns the next available word-aligned heap address.

apply(Font) –
Method in class mars.venus.AbstractFontSettingDialog

Apply the given font.

APPLY_TOOL_TIP_TEXT –
Static variable in class mars.venus.SettingsHighlightingAction

 

ARITHMETIC_OVERFLOW_EXCEPTION –
Static variable in class mars.simulator.Exceptions

 

ASCII –
Static variable in class mars.assembler.Directives

 

ASCII –
Static variable in class mars.venus.NumberDisplayBaseChooser

 

ASCII_NON_PRINT –
Static variable in class mars.Globals

Placeholder for non-printable ASCII codes

ASCII_TABLE –
Static variable in class mars.Globals

Array of strings to display for ASCII codes in ASCII display of data segment.

AsciiTextDumpFormat – Class in mars.mips.dump
Class that represents the “ASCII text” memory dump format.
AsciiTextDumpFormat() –
Constructor for class mars.mips.dump.AsciiTextDumpFormat

Constructor.

ASCIIZ –
Static variable in class mars.assembler.Directives

 

assemble(MIPSprogram, boolean) –
Method in class mars.assembler.Assembler

Parse and generate machine code for the given MIPS program.

assemble(MIPSprogram, boolean, boolean) –
Method in class mars.assembler.Assembler

Parse and generate machine code for the given MIPS program.

assemble(ArrayList, boolean) –
Method in class mars.assembler.Assembler

Parse and generate machine code for the given MIPS program.

assemble(ArrayList, boolean, boolean) –
Method in class mars.assembler.Assembler

Parse and generate machine code for the given MIPS program.

assemble(ArrayList, boolean) –
Method in class mars.MIPSprogram

Assembles the MIPS source program.

assemble(ArrayList, boolean, boolean) –
Method in class mars.MIPSprogram

Assembles the MIPS source program.

ASSEMBLE_ALL_ENABLED –
Static variable in class mars.Settings

Flag to determine whether only the current editor source file (enabled false) or
all files in its directory (enabled true) will be assembled when assembly is selected.

ASSEMBLE_ON_OPEN_ENABLED –
Static variable in class mars.Settings

Flag to determine whether or not a file is immediately and automatically assembled
upon opening.

Assembler – Class in mars.assembler
An Assembler is capable of assembling a MIPS program.
Assembler() –
Constructor for class mars.assembler.Assembler

 

AUTO_INDENT –
Static variable in class mars.Settings

Flag to control whether or not language-aware editor will use auto-indent feature

B

BACKSPACE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

BACKSPACE_WORD –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

backStep() –
Method in class mars.simulator.BackStepper

Carry out a “back step”, which will undo the latest execution step.

BackStepper – Class in mars.simulator
Used to “step backward” through execution, undoing each instruction.
BackStepper() –
Constructor for class mars.simulator.BackStepper

Create a fresh BackStepper.

backSteppingEnabled() –
Method in class mars.MIPSprogram

Returns status of BackStepper associated with this program.

BARE_MACHINE_ENABLED –
Static variable in class mars.Settings

Flag to determine whether or not program being assembled is limited to
using register numbers instead of names.

BasicInstruction – Class in mars.mips.instructions
Class to represent a basic instruction in the MIPS instruction set.
BasicInstruction(String, String, BasicInstructionFormat, String, SimulationCode) –
Constructor for class mars.mips.instructions.BasicInstruction

BasicInstruction constructor.

BasicInstruction(String, BasicInstructionFormat, String, SimulationCode) –
Constructor for class mars.mips.instructions.BasicInstruction

 

BasicInstructionFormat – Class in mars.mips.instructions
These are the MIPS-defined formats of basic machine instructions.
beginCompoundEdit() –
Method in class mars.venus.editors.jeditsyntax.SyntaxDocument

Starts a compound edit that can be undone in one operation.

beginMacro(Token) –
Method in class mars.assembler.MacroPool

This method will be called by parser when reached .macro
directive.

Instantiates a new Macro object and stores it in MacroPool.current
.

BHT_DEFAULT_HISTORY –
Static variable in class mars.tools.BHTSimulator

constant for the default history size

BHT_DEFAULT_INITVAL –
Static variable in class mars.tools.BHTSimulator

constant for the default inital value

BHT_DEFAULT_SIZE –
Static variable in class mars.tools.BHTSimulator

constant for the default size of the BHT

BHT_DO_NOT_TAKE_BRANCH –
Static variable in class mars.tools.BHTSimGUI

constant for the String representing “do not take the branch”

BHT_HEADING –
Static variable in class mars.tools.BHTSimulator

the heading of the tool

BHT_NAME –
Static variable in class mars.tools.BHTSimulator

the name of the tool

BHT_TAKE_BRANCH –
Static variable in class mars.tools.BHTSimGUI

constant for the String representing “take the branch”

BHT_VERSION –
Static variable in class mars.tools.BHTSimulator

the version of the tool

BHTableModel – Class in mars.tools
Simulates the actual functionality of a Branch History Table (BHT).
BHTableModel(int, int, boolean) –
Constructor for class mars.tools.BHTableModel

Constructs a new BHT with given number of entries and history size.

BHTEntry – Class in mars.tools
Represents a single entry of the Branch History Table.
BHTEntry(int, boolean) –
Constructor for class mars.tools.BHTEntry

Constructs a BHT entry with a given history size.

BHTSimGUI – Class in mars.tools
Represents the GUI of the BHT Simulator Tool.
BHTSimGUI() –
Constructor for class mars.tools.BHTSimGUI

Creates the GUI components of the BHT Simulator
The GUI is a subclass of JPanel which is integrated in the GUI of the MARS tool

BHTSimulator – Class in mars.tools
A MARS tool for simulating branch prediction with a Branch History Table (BHT)
BHTSimulator() –
Constructor for class mars.tools.BHTSimulator

Creates a BHT Simulator with given name and heading.

biasLeft –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

BIG_ENDIAN –
Static variable in class mars.mips.hardware.Memory

Constant representing byte order of each memory word.

Binary – Class in mars.util
Some utility methods for working with binary representations.
Binary() –
Constructor for class mars.util.Binary

 

BinaryDumpFormat – Class in mars.mips.dump
Class that represents the “binary” memory dump format.
BinaryDumpFormat() –
Constructor for class mars.mips.dump.BinaryDumpFormat

Constructor.

binaryStringToHexDigit(String) –
Static method in class mars.util.Binary

Translate String consisting of ‘1’s and ‘0’s into char equivalent of the corresponding
hexadecimal digit.

binaryStringToHexString(String) –
Static method in class mars.util.Binary

Translate String consisting of ‘1’s and ‘0’s into String equivalent of the corresponding
hexadecimal value.

binaryStringToInt(String) –
Static method in class mars.util.Binary

Translate String consisting of ‘1’s and ‘0’s into an int value having that binary representation.

binaryStringToLong(String) –
Static method in class mars.util.Binary

Translate String consisting of ‘1’s and ‘0’s into a long value having that binary representation.

BinaryTextDumpFormat – Class in mars.mips.dump
Class that represents the “binary text” memory dump format.
BinaryTextDumpFormat() –
Constructor for class mars.mips.dump.BinaryTextDumpFormat

Constructor.

BitmapDisplay – Class in mars.tools
Bitmapp display simulator.
BitmapDisplay(String, String) –
Constructor for class mars.tools.BitmapDisplay

Simple constructor, likely used to run a stand-alone bitmap display tool.

BitmapDisplay() –
Constructor for class mars.tools.BitmapDisplay

Simple constructor, likely used by the MARS Tools menu mechanism

bitValue(int, int) –
Static method in class mars.util.Binary

Returns the bit value of the given bit position of the given int value.

bitValue(long, int) –
Static method in class mars.util.Binary

Returns the bit value of the given bit position of the given long value.

blink –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

blinkCaret() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Blinks the caret.

blockCaret –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

blockCaret –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

BOTTOM –
Static variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

bracketHighlight –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

bracketHighlight –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

bracketHighlightColor –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

bracketHighlightColor –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

bracketLine –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

bracketPosition –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

BREAKPOINT –
Static variable in class mars.simulator.Simulator

various reasons for simulate to end…

BREAKPOINT_EXCEPTION –
Static variable in class mars.simulator.Exceptions

 

buildBasicStatementFromBasicInstruction(ErrorList) –
Method in class mars.ProgramStatement

Given specification of BasicInstruction for this operator, build the
corresponding assembly statement in basic assembly format (e.g.

buildButtonAreaMarsTool() –
Method in class mars.tools.AbstractMarsToolAndApplication

The MarsTool default set of controls has one row of 3 buttons.

buildButtonAreaStandAlone() –
Method in class mars.tools.AbstractMarsToolAndApplication

The Mars stand-alone app default set of controls has two rows of controls.

buildConfigurationCollection() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

buildControlPanel() –
Method in class mars.venus.AbstractFontSettingDialog

 

buildDialogPanel() –
Method in class mars.venus.AbstractFontSettingDialog

 

buildDisplayArea() –
Method in class mars.tools.FloatRepresentation

 

buildHeadingArea() –
Method in class mars.tools.AbstractMarsToolAndApplication

Constructs GUI header as label with default positioning and font.

buildMachineStatementFromBasicStatement(ErrorList) –
Method in class mars.ProgramStatement

Given the current statement in Basic Assembly format (see above), build the
32-bit binary machine code statement.

buildMainDisplayArea() –
Method in class mars.tools.AbstractMarsToolAndApplication

Abstract method that must be instantiated by subclass to build the main display area
of the GUI.

buildMainDisplayArea() –
Method in class mars.tools.BHTSimulator

Creates a GUI and initialize the GUI with the default values.

buildMainDisplayArea() –
Method in class mars.tools.BitmapDisplay

Method that constructs the main display area.

buildMainDisplayArea() –
Method in class mars.tools.CacheSimulator

Method that constructs the main cache simulator display area.

buildMainDisplayArea() –
Method in class mars.tools.DigitalLabSim

 

buildMainDisplayArea() –
Method in class mars.tools.FloatRepresentation

Method that constructs the main display area.

buildMainDisplayArea() –
Method in class mars.tools.InstructionCounter

 

buildMainDisplayArea() –
Method in class mars.tools.InstructionStatistics

creates the display area for the tool as required by the API

buildMainDisplayArea() –
Method in class mars.tools.IntroToTools

Implementation of the inherited abstract method to build the main
display area of the GUI.

buildMainDisplayArea() –
Method in class mars.tools.KeyboardAndDisplaySimulator

Method that constructs the main display area.

buildMainDisplayArea() –
Method in class mars.tools.MemoryReferenceVisualization

Method that constructs the main display area.

buildToolsMenu() –
Method in class mars.venus.ToolLoader

Called in VenusUI to build its Tools menu.

button –
Variable in class mars.tools.DigitalLabSim.HexaKeyboard

 

BYTE –
Static variable in class mars.assembler.Directives

 

BYTE_SIZE –
Static variable in class mars.assembler.DataTypes

Number of bytes occupied by MIPS byte is 1.

C

CacheSimulator – Class in mars.tools
A data cache simulator.
CacheSimulator(String, String) –
Constructor for class mars.tools.CacheSimulator

Simple constructor, likely used to run a stand-alone cache simulator.

CacheSimulator() –
Constructor for class mars.tools.CacheSimulator

Simple constructor, likely used by the MARS Tools menu mechanism

CANCEL_TOOL_TIP_TEXT –
Static variable in class mars.venus.SettingsHighlightingAction

 

CARET_BLINK_RATE –
Static variable in class mars.Settings

Caret blink rate in milliseconds, 0 means don’t blink.

caretBlinkRate –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

caretBlinkRate –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

caretBlinks –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

caretBlinks –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

caretColor –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

caretColor –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

caretEvent –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

caretTimer –
Static variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

caretUpdate(CaretEvent) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Display caret position on the edit pane.

caretVisible –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

caretVisible –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

CAUSE –
Static variable in class mars.mips.hardware.Coprocessor0

 

CENTER –
Static variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

changeResetValue(int) –
Method in class mars.mips.hardware.Register

Change the register’s reset value; the value to which it will be
set when resetValue() is called.

CHAR_SIZE –
Static variable in class mars.assembler.DataTypes

Number of bytes occupied by MIPS character is 1.

charnum –
Variable in class mars.venus.HardcopyWriter

 

chars_per_line –
Variable in class mars.venus.HardcopyWriter

 

chars_per_tab –
Variable in class mars.venus.HardcopyWriter

 

charwidth –
Variable in class mars.venus.HardcopyWriter

 

clear() –
Method in class mars.assembler.SymbolTable

Creates a fresh arrayList for a new table.

clear() –
Method in class mars.mips.hardware.Memory

Explicitly clear the contents of memory.

clearAllBreakpoints() –
Method in class mars.venus.TextSegmentWindow

Clears all breakpoints that have been set since last assemble, and
updates the display of the breakpoint column.

clearBit(int, int) –
Static method in class mars.util.Binary

Sets the specified bit of the specified value to 0, and returns the result.

clearConditionFlag(int) –
Static method in class mars.mips.hardware.Coprocessor1

Set condition flag to 0 (false).

clearConditionFlags() –
Static method in class mars.mips.hardware.Coprocessor1

Clear all condition flags (0-7).

clearHighlighting() –
Method in class mars.venus.Coprocessor0Window

Clear highlight background color from any row currently highlighted.

clearHighlighting() –
Method in class mars.venus.Coprocessor1Window

Clear highlight background color from any row currently highlighted.

clearHighlighting() –
Method in class mars.venus.DataSegmentWindow

Clear highlight background color from any cell currently highlighted.

clearHighlighting() –
Method in class mars.venus.RegistersWindow

Clear highlight background color from any cell currently highlighted.

clearPane() –
Method in class mars.venus.ExecutePane

Clears out all components of the Execute tab: text segment
display, data segment display, label display and register display.

clearWindow() –
Method in class mars.venus.Coprocessor0Window

Reset and redisplay registers

clearWindow() –
Method in class mars.venus.Coprocessor1Window

Reset and redisplay registers.

clearWindow() –
Method in class mars.venus.DataSegmentWindow

Removes the table from its frame, typically done when a file is closed.

clearWindow() –
Method in class mars.venus.LabelsWindow

Clear the window

clearWindow() –
Method in class mars.venus.RegistersWindow

clear and redisplay registers

clearWindow() –
Method in class mars.venus.TextSegmentWindow

remove all components

CLIFF_TERMINATION –
Static variable in class mars.simulator.Simulator

 

CLIP_COPY –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

CLIP_CUT –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

CLIP_PASTE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

clone() –
Method in class mars.assembler.TokenList

Makes clone (shallow copy) of this token list object.

close() –
Method in class mars.venus.Editor

Perform “close” operation on current tab’s file.

close() –
Method in class mars.venus.HardcopyWriter

This is the close( ) method that all Writer subclasses must implement.

CLOSE_TOOL_TIP_TEXT –
Static variable in class mars.venus.SettingsHighlightingAction

 

closeAll() –
Method in class mars.venus.Editor

Close all currently open files.

closeAllFiles() –
Method in class mars.venus.EditTabbedPane

Carries out all necessary operations to implement
the Close All operation from the File menu.

closeCurrentFile() –
Method in class mars.venus.EditTabbedPane

Carries out all necessary operations to implement
the Close operation from the File menu.

closeDialog() –
Method in class mars.venus.AbstractFontSettingDialog

 

closeFile(int) –
Static method in class mars.util.SystemIO

Close the file with specified file descriptor

COLON –
Static variable in class mars.assembler.TokenTypes

 

COLOR_PREDICTION_CORRECT –
Static variable in class mars.tools.BHTSimGUI

constant for the color to signal a correct prediction

COLOR_PREDICTION_INCORRECT –
Static variable in class mars.tools.BHTSimGUI

constant for the color to signal a misprediction

COLOR_PREPREDICTION –
Static variable in class mars.tools.BHTSimGUI

constant for the color that highlights the current BHT entry

cols –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

cols –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

COMMENT –
Static variable in class mars.assembler.TokenTypes

 

COMMENT1 –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Comment 1 token id.

COMMENT2 –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Comment 2 token id.

commitMacro(Token) –
Method in class mars.assembler.MacroPool

This method will be called by parser when reached .end_macro
directive.

connect() –
Method in class mars.tools.AbstractMarsToolAndApplication.ConnectButton

 

connectButton –
Variable in class mars.tools.AbstractMarsToolAndApplication

 

construct() –
Method in class mars.simulator.SwingWorker

Compute the value to be returned by the get method.

convertLineColumnToStreamPosition(int, int) –
Method in class mars.venus.EditPane

Given line and column (position in the line) numbers, calculate
its byte stream position in text being edited.

convertStreamPositionToLineColumn(int) –
Method in class mars.venus.EditPane

 

Coprocessor0 – Class in mars.mips.hardware
Represents Coprocessor 0.
Coprocessor0() –
Constructor for class mars.mips.hardware.Coprocessor0

 

Coprocessor0Window – Class in mars.venus
Sets up a window to display registers in the UI.
Coprocessor0Window() –
Constructor for class mars.venus.Coprocessor0Window

Constructor which sets up a fresh window with a table that contains the register values.

Coprocessor1 – Class in mars.mips.hardware
Represents Coprocessor 1, the Floating Point Unit (FPU)
Coprocessor1() –
Constructor for class mars.mips.hardware.Coprocessor1

 

Coprocessor1Window – Class in mars.venus
Sets up a window to display Coprocessor 1 registers in the Registers pane of the UI.
Coprocessor1Window() –
Constructor for class mars.venus.Coprocessor1Window

Constructor which sets up a fresh window with a table that contains the register values.

copy() –
Method in class mars.venus.editors.jeditsyntax.DefaultInputHandler

Returns a copy of this input handler that shares the same
key bindings.

copy() –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Returns a copy of this input handler that shares the same
key bindings.

copy() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Places the selected text into the clipboard.

copy() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

copyrightHolders –
Static variable in class mars.Globals

MARS copyright holders

copyrightYears –
Static variable in class mars.Globals

MARS copyright years

copyText() –
Method in class mars.venus.EditPane

copy currently-selected text into clipboard

counter –
Variable in class mars.tools.InstructionCounter

Number of instructions executed until now.

counterI –
Variable in class mars.tools.InstructionCounter

Number of instructions of type I.

counterJ –
Variable in class mars.tools.InstructionCounter

Number of instructions of type J.

counterR –
Variable in class mars.tools.InstructionCounter

Number of instructions of type R.

countObservers() –
Method in class mars.mips.hardware.Memory

Return number of observers

createExampleTokenList() –
Method in class mars.mips.instructions.Instruction

Used to build a token list from the example instruction
provided as constructor argument.

createFontFromStringValues(String, String, String) –
Static method in class mars.util.EditorFont

Creates a new Font object based on the given String specifications.

createMacroPool() –
Method in class mars.MIPSprogram

Instantiates a new MacroPool and sends reference of this
MIPSprogram to it

createParsedList() –
Method in class mars.MIPSprogram

Produces new empty list to hold parsed source code statements.

currentFont –
Variable in class mars.venus.AbstractFontSettingDialog

 

cut() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Deletes the selected text from the text area and places it
into the clipboard.

cut() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

cutText() –
Method in class mars.venus.EditPane

cut currently-selected text into clipboard

D

DATA –
Static variable in class mars.assembler.Directives

 

DATA_SEGMENT_HIGHLIGHTING –
Static variable in class mars.Settings

Flag to control whether or not highlighting is applied to data segment window

DATA_SYMBOL –
Static variable in class mars.assembler.Symbol

 

dataBaseAddress –
Static variable in class mars.mips.hardware.Memory

base address for storage of non-global static data in data segment: 0x10010000 (from SPIM)

DATASEGMENT_HIGHLIGHT_BACKGROUND –
Static variable in class mars.Settings

RGB color for text segment highlighted background

DATASEGMENT_HIGHLIGHT_FONT –
Static variable in class mars.Settings

Font for text segment highlighted background

DATASEGMENT_HIGHLIGHT_FOREGROUND –
Static variable in class mars.Settings

RGB color for text segment highlighted foreground

dataSegmentBaseAddress –
Static variable in class mars.mips.hardware.Memory

base address for (user) data segment: 0x10000000

dataSegmentLimitAddress –
Static variable in class mars.mips.hardware.Memory

 

DataSegmentWindow – Class in mars.venus
Represents the Data Segment window, which is a type of JInternalFrame.
DataSegmentWindow(NumberDisplayBaseChooser[]) –
Constructor for class mars.venus.DataSegmentWindow

Constructor for the Data Segment window.

DataTypes – Class in mars.assembler
Information about MIPS data types.
DataTypes() –
Constructor for class mars.assembler.DataTypes

 

debug –
Static variable in class mars.Globals

Flag to determine whether or not to produce internal debugging information.

DECIMAL –
Static variable in class mars.venus.NumberDisplayBaseChooser

 

DEFAULT_SIZE –
Static variable in class mars.util.EditorFont

 

DEFAULT_STATUS_VALUE –
Static variable in class mars.mips.hardware.Coprocessor0

 

DEFAULT_STYLE_INT –
Static variable in class mars.util.EditorFont

 

DEFAULT_STYLE_STRING –
Static variable in class mars.util.EditorFont

 

defaultBooleanSettingsValues –
Static variable in class mars.Settings

Last resort default values for boolean settings; will use only if neither
the Preferences nor the properties file work.

DefaultInputHandler – Class in mars.venus.editors.jeditsyntax
The default input handler.
DefaultInputHandler() –
Constructor for class mars.venus.editors.jeditsyntax.DefaultInputHandler

Creates a new input handler with no key bindings defined.

defaultMaxSteps –
Static variable in class mars.venus.RunGoAction

 

DELAYED_BRANCHING_ENABLED –
Static variable in class mars.Settings

Flag to determine whether or not delayed branching is in effect at MIPS execution.

DelayedBranch – Class in mars.simulator
Represents a (potential) delayed branch.
DelayedBranch() –
Constructor for class mars.simulator.DelayedBranch

 

DELETE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

DELETE_WORD –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

deleteAsObserver() –
Method in class mars.tools.AbstractMarsToolAndApplication

Delete this app/tool as an Observer of MIPS Observables (memory and registers).

deleteAsObserver(Register) –
Method in class mars.tools.AbstractMarsToolAndApplication

Delete this app/tool as an Observer of the specified MIPS register

deleteAsObserver() –
Method in class mars.tools.FloatRepresentation

Delete this app/tool as an Observer of the attached register.

deleteLines(int, int) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Informs the token marker that line have been deleted from
the document.

deleteObserver(Observer) –
Method in class mars.mips.hardware.Memory

Remove specified memory observers

deleteObservers() –
Method in class mars.mips.hardware.Memory

Remove all memory observers

deleteRegistersObserver(Observer) –
Static method in class mars.mips.hardware.Coprocessor0

Each individual register is a separate object and Observable.

deleteRegistersObserver(Observer) –
Static method in class mars.mips.hardware.Coprocessor1

Each individual register is a separate object and Observable.

deleteRegistersObserver(Observer) –
Static method in class mars.mips.hardware.RegisterFile

Each individual register is a separate object and Observable.

DELIMITER –
Static variable in class mars.assembler.TokenTypes

 

description –
Variable in class mars.mips.instructions.Instruction

Description of instruction for display to user

descriptionDetailSeparator –
Static variable in class mars.venus.HelpHelpAction

Separates Instruction name descriptor from detailed (operation) description
in help string.

DigitalLabSim – Class in mars.tools
 
DigitalLabSim(String, String) –
Constructor for class mars.tools.DigitalLabSim

 

DigitalLabSim() –
Constructor for class mars.tools.DigitalLabSim

 

DigitalLabSim.HexaKeyboard – Class in mars.tools
 
DigitalLabSim.HexaKeyboard() –
Constructor for class mars.tools.DigitalLabSim.HexaKeyboard

 

DigitalLabSim.HexaKeyboard.EcouteurClick – Class in mars.tools
 
DigitalLabSim.HexaKeyboard.EcouteurClick(int) –
Constructor for class mars.tools.DigitalLabSim.HexaKeyboard.EcouteurClick

 

DigitalLabSim.OneSecondCounter – Class in mars.tools
 
DigitalLabSim.OneSecondCounter() –
Constructor for class mars.tools.DigitalLabSim.OneSecondCounter

 

DigitalLabSim.SevenSegmentDisplay – Class in mars.tools
 
DigitalLabSim.SevenSegmentDisplay(char) –
Constructor for class mars.tools.DigitalLabSim.SevenSegmentDisplay

 

DigitalLabSim.SevenSegmentPanel – Class in mars.tools
 
DigitalLabSim.SevenSegmentPanel() –
Constructor for class mars.tools.DigitalLabSim.SevenSegmentPanel

 

DIRECTIVE –
Static variable in class mars.assembler.TokenTypes

 

Directives – Class in mars.assembler
Class representing MIPS assembler directives.
discardAllUndoableEdits() –
Method in class mars.venus.editors.generic.GenericTextArea

Tell UndoManager to discard all its collected undoable edits.

discardAllUndoableEdits() –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Get rid of any accumulated undoable edits.

discardAllUndoableEdits() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

discardAllUndoableEdits() –
Method in class mars.venus.EditPane

Get rid of any accumulated undoable edits.

disconnect() –
Method in class mars.tools.AbstractMarsToolAndApplication.ConnectButton

 

dispatchEventToMenu(KeyEvent) –
Method in class mars.venus.VenusUI

Send keyboard event to menu for possible processing.

display –
Variable in class mars.tools.DigitalLabSim.SevenSegmentPanel

 

DISPLAY_ADDRESSES_IN_HEX –
Static variable in class mars.Settings

Default setting for displaying addresses and values in hexidecimal in the Execute
pane.

DISPLAY_VALUES_IN_HEX –
Static variable in class mars.Settings

 

displayCaretPosition(int) –
Method in class mars.venus.EditPane

Update the caret position label on the editor’s border to
display the current line and column.

displayCaretPosition(Point) –
Method in class mars.venus.EditPane

Display cursor coordinates

DIVIDE_BY_ZERO_EXCEPTION –
Static variable in class mars.simulator.Exceptions

 

document –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

document –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

DOCUMENT_END –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

DOCUMENT_HOME –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

documentChanged(DocumentEvent) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

 

documentHandler –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

doFindText(String, boolean) –
Method in class mars.venus.editors.generic.GenericTextArea

Finds next occurrence of text in a forward search of a string.

doFindText(String, boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Finds next occurrence of text in a forward search of a string.

doFindText(String, boolean) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

doFindText(String, boolean) –
Method in class mars.venus.EditPane

Finds next occurrence of text in a forward search of a string.

doReplace(String, String, boolean) –
Method in class mars.venus.editors.generic.GenericTextArea

Finds and replaces next occurrence of text in a string in a forward search.

doReplace(String, String, boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Finds and replaces next occurrence of text in a string in a forward search.

doReplace(String, String, boolean) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

doReplace(String, String, boolean) –
Method in class mars.venus.EditPane

Finds and replaces next occurrence of text in a string in a forward search.

doReplaceAll(String, String, boolean) –
Method in class mars.venus.editors.generic.GenericTextArea

Finds and replaces ALL occurrences of text in a string in a forward search.

doReplaceAll(String, String, boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Finds and replaces ALL occurrences of text in a string in a forward search.

doReplaceAll(String, String, boolean) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

doReplaceAll(String, String, boolean) –
Method in class mars.venus.EditPane

Finds and replaces ALL occurrences of text in a string in a forward search.

DOUBLE –
Static variable in class mars.assembler.Directives

 

DOUBLE_SIZE –
Static variable in class mars.assembler.DataTypes

Number of bytes occupied by MIPS double is 8.

doublewordAligned(int) –
Static method in class mars.mips.hardware.Memory

Utility to determine if given address is doubleword-aligned.

DumpFormat – Interface in mars.mips.dump
Interface for memory dump file formats.
DumpFormatLoader – Class in mars.mips.dump
 
DumpFormatLoader() –
Constructor for class mars.mips.dump.DumpFormatLoader

 

dumpMemoryRange(File, int, int) –
Method in class mars.mips.dump.AbstractDumpFormat

Write MIPS memory contents according to the
specification for this format.

dumpMemoryRange(File, int, int) –
Method in class mars.mips.dump.AsciiTextDumpFormat

Interpret MIPS memory contents as ASCII characters.

dumpMemoryRange(File, int, int) –
Method in class mars.mips.dump.BinaryDumpFormat

Write MIPS memory contents in pure binary format.

dumpMemoryRange(File, int, int) –
Method in class mars.mips.dump.BinaryTextDumpFormat

Write MIPS memory contents in binary text format.

dumpMemoryRange(File, int, int) –
Method in interface mars.mips.dump.DumpFormat

Write MIPS memory contents according to the
specification for this format.

dumpMemoryRange(File, int, int) –
Method in class mars.mips.dump.HexTextDumpFormat

Write MIPS memory contents in hexadecimal text format.

dumpMemoryRange(File, int, int) –
Method in class mars.mips.dump.IntelHexDumpFormat

Write MIPS memory contents according to the Memory Initialization File
(MIF) specification.

dumpMemoryRange(File, int, int) –
Method in class mars.mips.dump.MIFDumpFormat

Write MIPS memory contents according to the Memory Initialization File
(MIF) specification.

dumpMemoryRange(File, int, int) –
Method in class mars.mips.dump.SegmentWindowDumpFormat

Write MIPS memory contents in Segment Window format.

dumpTriples –
Static variable in class mars.util.MemoryDump

A list of segmentname/dumpformat/filename triples which should be dumped

E

editable –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

editable –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

EditCopyAction – Class in mars.venus
Action for the Edit -> Copy menu item
EditCopyAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.EditCopyAction

 

EditCutAction – Class in mars.venus
Action for the Edit -> Cut menu item
EditCutAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.EditCutAction

 

EDITED –
Static variable in class mars.venus.FileStatus

open/saved edit window with unsaved edits

EditFindReplaceAction – Class in mars.venus
Action for the Edit -> Find/Replace menu item
EditFindReplaceAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.EditFindReplaceAction

 

Editor – Class in mars.venus
Manage the file being edited.
Editor(VenusUI) –
Constructor for class mars.venus.Editor

Create editor.

EDITOR_CURRENT_LINE_HIGHLIGHTING –
Static variable in class mars.Settings

Flag to control whether or not editor will highlight the line currently being edited

EDITOR_FONT –
Static variable in class mars.Settings

Font for the text editor

EDITOR_LINE_NUMBERS_DISPLAYED –
Static variable in class mars.Settings

Flag to determine whether or not the editor will display line numbers.

EDITOR_POPUP_PREFIX_LENGTH –
Static variable in class mars.Settings

Number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled)

EDITOR_TAB_SIZE –
Static variable in class mars.Settings

Editor tab size in characters.

EditorFont – Class in mars.util
Specialized Font class designed to be used by both the
settings menu methods and the Settings class.
EditorFont() –
Constructor for class mars.util.EditorFont

 

EditPane – Class in mars.venus
Represents one file opened for editing.
EditPane(VenusUI) –
Constructor for class mars.venus.EditPane

Constructor for the EditPane class.

EditPasteAction – Class in mars.venus
Action for the Edit -> Paste menu item
EditPasteAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.EditPasteAction

 

EditRedoAction – Class in mars.venus
Action for the Edit -> Redo menu item
EditRedoAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.EditRedoAction

 

EditSelectAllAction – Class in mars.venus
Action for the Edit -> Copy menu item
EditSelectAllAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.EditSelectAllAction

 

editsSavedOrAbandoned() –
Method in class mars.venus.Editor

Called by several of the Action objects when there is potential
loss of editing changes.

editsSavedOrAbandoned() –
Method in class mars.venus.EditTabbedPane

Check whether file has unsaved edits and, if so, check with user about saving them.

EditTabbedPane – Class in mars.venus
Tabbed pane for the editor.
EditTabbedPane(VenusUI, Editor, MainPane) –
Constructor for class mars.venus.EditTabbedPane

Constructor for the EditTabbedPane class.

EditUndoAction – Class in mars.venus
Action for the Edit -> Undo menu item
EditUndoAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.EditUndoAction

 

electricScroll –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

electricScroll –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

empty() –
Method in class mars.simulator.BackStepper

Test whether there are steps that can be undone.

enabled() –
Method in class mars.simulator.BackStepper

Determine whether execution “undo” steps are currently being recorded.

END –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

END –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

The token type, that along with a length of 0
marks the end of the token list.

END_MACRO –
Static variable in class mars.assembler.Directives

 

endCompoundEdit() –
Method in class mars.venus.editors.jeditsyntax.SyntaxDocument

Ends a compound edit that can be undone in one operation.

ensureCapacity(int) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Ensures that the lineInfo array can contain the
specified index.

eolMarkerColor –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

eolMarkerColor –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

eolMarkers –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

eolMarkers –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

EPC –
Static variable in class mars.mips.hardware.Coprocessor0

 

equals(Object) –
Method in class mars.assembler.Macro

 

EQV –
Static variable in class mars.assembler.Directives

 

ERROR –
Static variable in class mars.assembler.TokenTypes

 

ERROR –
Static variable in class mars.ErrorMessage

Constant to indicate this message is error not warning

ERROR_MESSAGE_PREFIX –
Static variable in class mars.ErrorList

 

errorCount() –
Method in class mars.ErrorList

Count of number of error messages in list.

errorLimitExceeded() –
Method in class mars.ErrorList

Check to see if error limit has been exceeded.

ErrorList – Class in mars
Maintains list of generated error messages, regardless of source (tokenizing, parsing,
assembly, execution).
ErrorList() –
Constructor for class mars.ErrorList

Constructor for ErrorList

ErrorMessage – Class in mars
Represents occurrance of an error detected during tokenizing, assembly or simulation.
ErrorMessage(String, int, int, String) –
Constructor for class mars.ErrorMessage

Deprecated. Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.

ErrorMessage(String, int, int, String, String) –
Constructor for class mars.ErrorMessage

Deprecated. Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.

ErrorMessage(boolean, String, int, int, String, String) –
Constructor for class mars.ErrorMessage

Deprecated. Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.

ErrorMessage(MIPSprogram, int, int, String) –
Constructor for class mars.ErrorMessage

Constructor for ErrorMessage.

ErrorMessage(boolean, MIPSprogram, int, int, String) –
Constructor for class mars.ErrorMessage

Constructor for ErrorMessage.

errors() –
Method in exception mars.ProcessingException

Produce the list of error messages.

errorsOccurred() –
Method in class mars.ErrorList

Determine whether error has occured or not.

EVEN_ROW_BACKGROUND –
Static variable in class mars.Settings

RGB color for table even row background (text, data, register displays)

EVEN_ROW_FONT –
Static variable in class mars.Settings

Font for table even row background (text, data, register displays)

EVEN_ROW_FOREGROUND –
Static variable in class mars.Settings

RGB color for table even row foreground (text, data, register displays)

exampleFormat –
Variable in class mars.mips.instructions.Instruction

Example usage of this instruction.

EXCEPTION –
Static variable in class mars.simulator.Simulator

 

EXCEPTION_HANDLER –
Static variable in class mars.Settings

Current specified exception handler file (a MIPS assembly source file)

EXCEPTION_HANDLER_ENABLED –
Static variable in class mars.Settings

Flag to determine whether the currently selected exception handler source file will
be included in each assembly operation.

EXCEPTION_LEVEL –
Static variable in class mars.mips.hardware.Coprocessor0

 

exceptionHandlerAddress –
Static variable in class mars.mips.hardware.Memory

starting address for exception handlers: 0x80000180

Exceptions – Class in mars.simulator
Represents an error/interrupt that occurs during execution (simulation).
Exceptions() –
Constructor for class mars.simulator.Exceptions

 

executeAction(ActionListener, Object, String) –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Executes the specified action, repeating and recording it as
necessary.

ExecutePane – Class in mars.venus
Container for the execution-related windows.
ExecutePane(VenusUI, RegistersWindow, Coprocessor1Window, Coprocessor0Window) –
Constructor for class mars.venus.ExecutePane

initialize the Execute pane with major components

exitCode –
Static variable in class mars.Globals

MARS exit code — useful with SYSCALL 17 when running from command line (not GUI)

EXTENDED_ASSEMBLER_ENABLED –
Static variable in class mars.Settings

Flag to determine whether or not program being assembled is limited to
basic MIPS instructions and formats.

ExtendedInstruction – Class in mars.mips.instructions
ExtendedInstruction represents a MIPS extended (a.k.a pseudo) instruction.
ExtendedInstruction(String, String, String, String) –
Constructor for class mars.mips.instructions.ExtendedInstruction

Constructor for ExtendedInstruction.

ExtendedInstruction(String, String, String) –
Constructor for class mars.mips.instructions.ExtendedInstruction

Constructor for ExtendedInstruction.

ExtendedInstruction(String, String) –
Constructor for class mars.mips.instructions.ExtendedInstruction

Constructor for ExtendedInstruction, where no instruction description or
compact translation is provided.

EXTERN –
Static variable in class mars.assembler.Directives

 

EXTERNAL_INTERRUPT_DISPLAY –
Static variable in class mars.simulator.Exceptions

 

EXTERNAL_INTERRUPT_HEXA_KEYBOARD –
Static variable in class mars.tools.DigitalLabSim

 

EXTERNAL_INTERRUPT_KEYBOARD –
Static variable in class mars.simulator.Exceptions

The exception number is stored in coprocessor 0 cause register ($13)
Note: the codes for External Interrupts have been modified from MIPS
specs in order to encode two pieces of information.

EXTERNAL_INTERRUPT_TIMER –
Static variable in class mars.tools.DigitalLabSim

 

externalInterruptingDevice –
Static variable in class mars.simulator.Simulator

 

externBaseAddress –
Static variable in class mars.mips.hardware.Memory

base address for .extern directive: 0x10000000

extractBranchAddress(ProgramStatement) –
Static method in class mars.tools.BHTSimulator

Extracts the target address of the branch.

extractOperator(String) –
Method in class mars.mips.instructions.Instruction

Used by subclass constructors to extract operator mnemonic from the
instruction example.

F

FileCloseAction – Class in mars.venus
Action for the File -> Close menu item
FileCloseAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.FileCloseAction

 

FileCloseAllAction – Class in mars.venus
Action for the File -> Close All menu item
FileCloseAllAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.FileCloseAllAction

 

FileDumpMemoryAction – Class in mars.venus
Action for the File -> Save For Dump Memory menu item
FileDumpMemoryAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.FileDumpMemoryAction

 

fileErrorString –
Static variable in class mars.util.SystemIO

String used for description of file error

FileExitAction – Class in mars.venus
Action for the File -> Exit menu item
FileExitAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.FileExitAction

 

fileExtensionMatch(String, String) –
Static method in class mars.util.FilenameFinder

Determine if given filename ends with given extension.

fileExtensions –
Static variable in class mars.Globals

List of accepted file extensions for MIPS assembly source files.

FILENAME_PREFIX –
Static variable in class mars.ErrorList

 

FilenameFinder – Class in mars.util
Utility class to perform necessary file-related search
operations.
FilenameFinder() –
Constructor for class mars.util.FilenameFinder

 

FileNewAction – Class in mars.venus
Action for the File -> New menu item
FileNewAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.FileNewAction

 

FileOpenAction – Class in mars.venus
Action for the File -> Open menu item
FileOpenAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.FileOpenAction

 

FilePrintAction – Class in mars.venus
Action for the File -> Print menu item
FilePrintAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.FilePrintAction

 

FileSaveAction – Class in mars.venus
Action for the File -> Save menu item
FileSaveAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.FileSaveAction

 

FileSaveAllAction – Class in mars.venus
Action for the File -> Close All menu item
FileSaveAllAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.FileSaveAllAction

 

FileSaveAsAction – Class in mars.venus
Action for the File -> Save As menu item
FileSaveAsAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.FileSaveAsAction

 

FileStatus – Class in mars.venus
Used to store and return information on the status of the current ASM file that
is being edited in the program.
FileStatus() –
Constructor for class mars.venus.FileStatus

Create a FileStatus object with FileStatis.NO_FILE for status and null for file getters.

FileStatus(int, String) –
Constructor for class mars.venus.FileStatus

Create a FileStatus object with given status and file pathname.

findDumpFormatGivenCommandDescriptor(ArrayList, String) –
Static method in class mars.mips.dump.DumpFormatLoader

 

findMatchingBracket(Document, int) –
Static method in class mars.venus.editors.jeditsyntax.TextUtilities

Returns the offset of the bracket matching the one at the
specified offset of the document, or -1 if the bracket is
unmatched (or if the character is not a bracket).

findWordEnd(String, int, String) –
Static method in class mars.venus.editors.jeditsyntax.TextUtilities

Locates the end of the word at the specified position.

findWordStart(String, int, String) –
Static method in class mars.venus.editors.jeditsyntax.TextUtilities

Locates the start of the word at the specified position.

finished() –
Method in class mars.simulator.SwingWorker

Called on the event dispatching thread (not on the worker thread)
after the construct method has returned.

fireCaretEvent() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

 

fireInsertUpdate(DocumentEvent) –
Method in class mars.venus.editors.jeditsyntax.SyntaxDocument

We overwrite this method to update the token marker
state immediately so that any event listeners get a
consistent token marker.

fireRemoveUpdate(DocumentEvent) –
Method in class mars.venus.editors.jeditsyntax.SyntaxDocument

We overwrite this method to update the token marker
state immediately so that any event listeners get a
consistent token marker.

firstLine –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

firstToken –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

The first token in the list.

fixSymbolTableAddress(int, int) –
Method in class mars.assembler.SymbolTable

Fix address in symbol table entry.

FLOAT –
Static variable in class mars.assembler.Directives

 

FLOAT_SIZE –
Static variable in class mars.assembler.DataTypes

Number of bytes occupied by MIPS float is 4.

FLOATING_POINT_OVERFLOW –
Static variable in class mars.simulator.Exceptions

 

FLOATING_POINT_UNDERFLOW –
Static variable in class mars.simulator.Exceptions

 

FloatRepresentation – Class in mars.tools
Tool to help students learn about IEEE 754 representation of 32 bit
floating point values.
FloatRepresentation(String, String) –
Constructor for class mars.tools.FloatRepresentation

Simple constructor, likely used to run a stand-alone memory reference visualizer.

FloatRepresentation() –
Constructor for class mars.tools.FloatRepresentation

Simple constructor, likely used by the MARS Tools menu mechanism

flush() –
Method in class mars.venus.HardcopyWriter

This is the flush( ) method that all Writer subclasses must implement.

fm –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

focusedComponent –
Static variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

font –
Variable in class mars.venus.HardcopyWriter

 

fontsize –
Variable in class mars.venus.HardcopyWriter

 

formatDoubleNumber(long, int) –
Static method in class mars.venus.NumberDisplayBaseChooser

Produces a string form of a double given a long containing
the 64 bit pattern and the numerical base to use (10 or 16).

formatFloatNumber(int, int) –
Static method in class mars.venus.NumberDisplayBaseChooser

Produces a string form of a float given an integer containing
the 32 bit pattern and the numerical base to use (10 or 16).

formatNumber(int, int) –
Static method in class mars.venus.NumberDisplayBaseChooser

Produces a string form of an integer given the value and the
numerical base to convert it to.

formatNumber(float, int) –
Static method in class mars.venus.NumberDisplayBaseChooser

Produces a string form of a float given the value and the
numerical base to convert it to.

formatNumber(double, int) –
Static method in class mars.venus.NumberDisplayBaseChooser

Produces a string form of a double given the value and the
numerical base to convert it to.

formatNumber(int) –
Method in class mars.venus.NumberDisplayBaseChooser

Produces a string form of a number given the value.

formatUnsignedInteger(int, int) –
Static method in class mars.venus.NumberDisplayBaseChooser

Produces a string form of an unsigned given the value and the
numerical base to convert it to.

formatUnsignedInteger(int) –
Method in class mars.venus.NumberDisplayBaseChooser

Produces a string form of an unsigned integer given the value.

FP_REGISTER_NAME –
Static variable in class mars.assembler.TokenTypes

 

G

generateErrorAndWarningReport() –
Method in class mars.ErrorList

Produce report containing both warnings and errors, warnings first.

generateErrorReport() –
Method in class mars.ErrorList

Produce error report.

generateWarningReport() –
Method in class mars.ErrorList

Produce warning report.

GENERIC_TEXT_EDITOR –
Static variable in class mars.Settings

Flag to control whether or not to use generic text editor instead of language-aware styled editor

GenericTextArea – Class in mars.venus.editors.generic
 
GenericTextArea(EditPane, JComponent) –
Constructor for class mars.venus.editors.generic.GenericTextArea

 

get(int) –
Method in class mars.assembler.TokenList

Returns requested token given position number (starting at 0).

get(int, int) –
Method in class mars.mips.hardware.Memory

Starting at the given word address, read the given number of bytes (max 4).

get() –
Method in class mars.simulator.SwingWorker

Return the value created by the construct method.

get() –
Static method in class mars.venus.FileStatus

Get file status

getAccessType() –
Method in class mars.mips.hardware.AccessNotice

Get the access type: READ or WRITE.

getAction() –
Method in class mars.simulator.SimulatorNotice

Fetch the memory address that was accessed.

getAction(String) –
Static method in class mars.venus.editors.jeditsyntax.InputHandler

Returns a named text area action.

getActionName(ActionListener) –
Static method in class mars.venus.editors.jeditsyntax.InputHandler

Returns the name of the specified text area action.

getActions() –
Static method in class mars.venus.editors.jeditsyntax.InputHandler

Returns an enumeration of all available actions.

getAddress() –
Method in class mars.assembler.Symbol

Returns the address of the the Symbol.

getAddress(String) –
Method in class mars.assembler.SymbolTable

Method to return the address associated with the given label.

getAddress() –
Method in exception mars.mips.hardware.AddressErrorException

Get the erroneous memory address.

getAddress() –
Method in class mars.mips.hardware.MemoryAccessNotice

Fetch the memory address that was accessed.

getAddress() –
Method in class mars.ProgramStatement

Produces Text Segment address where the binary machine statement is stored.

getAddressDisplayBase() –
Method in class mars.venus.ExecutePane

Retrieve the number system base for displaying memory addresses

getAddressDisplayBaseChooser() –
Method in class mars.venus.ExecutePane

Retrieve component used to set numerical base (10 or 16) of address display.

getAddressDisplayBaseMenuItem() –
Method in class mars.venus.VenusUI

Get reference to settings menu item for display base of memory/register values.

getAddressLocalOrGlobal(String) –
Method in class mars.assembler.SymbolTable

Method to return the address associated with the given label.

getAddressOfFirstNull(int, int) –
Method in class mars.mips.hardware.Memory

Look for first “null” memory value in an address range.

getAddressOfFirstNull(int, int) –
Static method in class mars.util.MemoryDump

Look for first “null” memory value in an address range.

getAllFamilies() –
Static method in class mars.util.EditorFont

Obtain an array of all available font family names.

getAllSymbols() –
Method in class mars.assembler.SymbolTable

For obtaining all the Symbols.

getArgs() –
Method in class mars.assembler.Macro

 

getAsciiNonPrint() –
Static method in class mars.Globals

 

getAsciiStrings() –
Static method in class mars.Globals

 

getAssembleAllEnabled() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ALL_ENABLED)

getAssembleOnOpenEnabled() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ON_OPEN_ENABLED)

getAssembleTextArea() –
Method in class mars.venus.MessagesPane

Returns component used to display assembler messages

getAutoIndent() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Constructs string for auto-indent feature.

getBackStepper() –
Method in class mars.MIPSprogram

Returns BackStepper associated with this program.

getBackSteppingEnabled() –
Method in class mars.Settings

Return whether backstepping is permitted at this time.

getBareMachineEnabled() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.BARE_MACHINE_ENABLED)

getBase() –
Method in class mars.venus.NumberDisplayBaseChooser

Retrieve the current number base.

getBase(boolean) –
Static method in class mars.venus.NumberDisplayBaseChooser

Return the number base corresponding to the specified setting.

getBaseAddresses(String[]) –
Static method in class mars.util.MemoryDump

Get the MIPS memory base address(es) of the specified segment name(s).

getBasicAssemblyStatement() –
Method in class mars.ProgramStatement

Produces Basic Assembly statement for this MIPS source statement.

getBasicIntructionTemplateList() –
Method in class mars.mips.instructions.ExtendedInstruction

Get ArrayList of Strings that represent list of templates for
basic instructions generated by this extended instruction.

getBinaryStatement() –
Method in class mars.ProgramStatement

Produces 32-bit binary machine statement as int.

getBooleanSetting(int) –
Method in class mars.Settings

Fetch value of a boolean setting given its identifier.

getBracketHighlightColor() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns the bracket highlight color.

getBracketLine() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the line of the highlighted bracket (the bracket
matching the one before the caret)

getBracketPosition() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the position of the highlighted bracket (the bracket
matching the one before the caret)

getBreakpointCount() –
Method in class mars.venus.TextSegmentWindow

Returns number of breakpoints currently set.

getByte(int) –
Method in class mars.mips.hardware.Memory

Reads specified Memory byte into low order 8 bits of int.

getByte(int, int) –
Static method in class mars.util.Binary

Gets the specified byte of the specified value.

getByteOrder() –
Method in class mars.mips.hardware.Memory

Retrieve memory byte order.

getCallStack() –
Method in class mars.assembler.MacroPool

 

getCaretBlinkRate() –
Method in class mars.Settings

Retrieve the caret blink rate in milliseconds.

getCaretColor() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns the caret color.

getCaretLine() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the caret line.

getCaretPosition() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the caret position.

getCaretPosition() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

getCbBHTentries() –
Method in class mars.tools.BHTSimGUI

Returns the combo box for selecting the number of BHT entries.

getCbBHThistory() –
Method in class mars.tools.BHTSimGUI

Returns the combo box for selecting the size of the BHT history.

getCbBHTinitVal() –
Method in class mars.tools.BHTSimGUI

Returns the combo box for selecting the initial value of the BHT

getCharactersPerLine() –
Method in class mars.venus.HardcopyWriter

Return the number of columns of characters that fit on the page

getCodeHighlighting() –
Method in class mars.venus.TextSegmentWindow

Get code highlighting status.

getColor() –
Method in class mars.venus.editors.jeditsyntax.SyntaxStyle

Returns the color specified in this style.

getColorAsHexString() –
Method in class mars.venus.editors.jeditsyntax.SyntaxStyle

Returns the color coded as Stringified 32-bit hex with
Red in bits 16-23, Green in bits 8-15, Blue in bits 0-7
e.g.

getColorSettingByKey(String) –
Method in class mars.Settings

Get Color object for specified settings key.

getColorSettingByPosition(int) –
Method in class mars.Settings

Get Color object for specified settings name (a static constant).

getColumnClass(int) –
Method in class mars.tools.BHTableModel

Returns the class/type of the i-th column of the table.

getColumnCount() –
Method in class mars.tools.BHTableModel

Returns the number of columns.

getColumnName(int) –
Method in class mars.tools.BHTableModel

Returns the name of the i-th column of the table.

getCommandDescriptor() –
Method in class mars.mips.dump.AbstractDumpFormat

One-word description of format to be used by MARS command mode parser
and user in conjunction with the “dump” option.

getCommandDescriptor() –
Method in interface mars.mips.dump.DumpFormat

A short one-word descriptor that will be used by the MARS
command line parser (and the MARS command line user) to specify
that this format is to be used.

getCommonFamilies() –
Static method in class mars.util.EditorFont

Obtain an array of common font family names.

getCompactBasicIntructionTemplateList() –
Method in class mars.mips.instructions.ExtendedInstruction

Get ArrayList of Strings that represent list of templates for
basic instructions generated by the “compact” or 16-bit version
of this extended instruction.

getCompactInstructionLength() –
Method in class mars.mips.instructions.ExtendedInstruction

Get length in bytes that this extended instruction requires in its
binary form if it includes an alternative expansion for compact
memory (16 bit addressing) configuration.

getConditionFlag(int) –
Static method in class mars.mips.hardware.Coprocessor1

Get value of specified condition flag (0-7).

getConditionFlagCount() –
Static method in class mars.mips.hardware.Coprocessor1

Get count of condition flags.

getConditionFlags() –
Static method in class mars.mips.hardware.Coprocessor1

Get array of condition flags (0-7).

getConfigurationByName(String) –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getConfigurationIdentifier() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getConfigurationItemNames() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getConfigurationItemValues() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getConfigurationName() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getConfigurationsIterator() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getCoprocessor0Window() –
Method in class mars.venus.ExecutePane

Access the coprocessor0 values window.

getCoprocessor0Window() –
Method in class mars.venus.RegistersPane

Return component containing coprocessor 0 (exceptions) register set.

getCoprocessor1Window() –
Method in class mars.venus.ExecutePane

Access the coprocessor1 values window.

getCoprocessor1Window() –
Method in class mars.venus.RegistersPane

Return component containing coprocessor 1 (floating point) register set.

getCurrent() –
Method in class mars.assembler.MacroPool

 

getCurrentConfiguration() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getCurrentEditTab() –
Method in class mars.venus.EditTabbedPane

The current EditPane representing a file.

getCurrentEditTabForFile(File) –
Method in class mars.venus.EditTabbedPane

If the given file is open in the tabbed pane, make it the
current tab.

getCurrentOpenDirectory() –
Method in class mars.venus.Editor

Get name of current directory for Open operation.

getCurrentSaveDirectory() –
Method in class mars.venus.Editor

Get name of current directory for Save or Save As operation.

getCurrentSyntaxStyles() –
Static method in class mars.venus.editors.jeditsyntax.SyntaxUtilities

Returns the CURRENT style table.

getDataBaseAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getDataSegmentBaseAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getDataSegmentHighlighting() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DATA_SEGMENT_HIGHLIGHTING)

getDataSegmentLimitAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getDataSegmentWindow() –
Method in class mars.venus.ExecutePane

Access the data segment window.

getDataSymbols() –
Method in class mars.assembler.SymbolTable

For obtaining the Data Symbols.

getDefaultColorSettingByKey(String) –
Method in class mars.Settings

Get default Color value for specified settings key.

getDefaultColorSettingByPosition(int) –
Method in class mars.Settings

Get default Color object for specified settings name (a static constant).

getDefaultConfiguration() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultDataBaseAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultDataSegmentBaseAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultDataSegmentLimitAddress() –
Method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultEditorSyntaxStyleByPosition(int) –
Method in class mars.Settings

 

getDefaultEditorTabSize() –
Method in class mars.Settings

Get the text editor default tab size in characters

getDefaultExceptionHandlerAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultExternBaseAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultFontByPosition(int) –
Method in class mars.Settings

Retrieve a default Font setting

getDefaultGlobalPointer() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultHeapBaseAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultKernelBaseAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultKernelDataBaseAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultKernelDataSegmentLimitAddress() –
Method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultKernelHighAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultKernelTextBaseAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultKernelTextLimitAddress() –
Method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultMemoryMapBaseAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaults() –
Static method in class mars.venus.editors.jeditsyntax.TextAreaDefaults

Returns a new TextAreaDefaults object with the default values filled
in.

getDefaultStackBaseAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultStackLimitAddress() –
Method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultStackPointer() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultSyntaxStyles() –
Static method in class mars.venus.editors.jeditsyntax.SyntaxUtilities

Returns the default style table.

getDefaultTextBaseAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultTextLimitAddress() –
Method in class mars.mips.hardware.MemoryConfigurations

 

getDefaultUserHighAddress() –
Static method in class mars.mips.hardware.MemoryConfigurations

 

getDelay() –
Method in class mars.venus.RepeatButton

Gets the delay for the timer of this button.

getDelayedBranchingEnabled() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED)

getDescription() –
Method in class mars.assembler.Directives

Get description of this Directives object

getDescription() –
Method in class mars.mips.dump.AbstractDumpFormat

Get a short description of the format, suitable for displaying along with
the extension, in the file save dialog, or as a tool tip.

getDescription() –
Method in interface mars.mips.dump.DumpFormat

Get a short description of the format, suitable
for displaying along with the extension, if any, in the file
save dialog and also for displaying as a tool tip.

getDescription() –
Method in class mars.mips.instructions.Instruction

Get string describing the instruction.

getDescription() –
Method in class mars.venus.editors.jeditsyntax.PopupHelpItem

 

getDirectiveList() –
Static method in class mars.assembler.Directives

Produces List of Directive objects

getDisplayAddressesInHex() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_ADDRESSES_IN_HEX)

getDisplayValuesInHex() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_VALUES_IN_HEX)

getDocument() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the document this text area is editing.

getDocument() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

getDocumentLength() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the length of the document.

getDoubleFromRegisterPair(int) –
Static method in class mars.mips.hardware.Coprocessor1

Gets the double value stored in the given FPU register.

getDoubleFromRegisterPair(String) –
Static method in class mars.mips.hardware.Coprocessor1

Gets the double value stored in the given FPU register.

getEditor() –
Method in class mars.venus.VenusUI

Get reference to Editor object associated with this GUI.

getEditorFont() –
Method in class mars.Settings

Current editor font.

getEditorLineNumbersDisplayed() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EDITOR_LINE_NUMBERS_DISPLAYED)

getEditorPopupPrefixLength() –
Method in class mars.Settings

Get number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled).

getEditorSyntaxStyleByPosition(int) –
Method in class mars.Settings

 

getEditorTabSize() –
Method in class mars.Settings

Get the tab size in characters.

getEditPane() –
Method in class mars.venus.MainPane

Returns current edit pane.

getEditPaneForFile(String) –
Method in class mars.venus.EditTabbedPane

If there is an EditPane for the given file pathname, return it else return null.

getEditTabbedPane() –
Method in class mars.venus.MainPane

Returns component containing editor display

getElectricScroll() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the number of lines from the top and button of the
text area that are always visible.

getEOLMarkerColor() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns the EOL marker color.

getEOLMarkersPainted() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns true if EOL markers are drawn, false otherwise.

getErrorLimit() –
Method in class mars.ErrorList

Get limit on number of error messages to be generated
by one assemble operation.

getErrorList() –
Method in class mars.assembler.Assembler

Get list of assembler errors and warnings

getErrorMessages() –
Method in class mars.ErrorList

Get ArrayList of error messages.

getErrors() –
Method in class mars.assembler.Tokenizer

Fetch this Tokenizer’s error list.

getExact() –
Method in class mars.venus.editors.jeditsyntax.PopupHelpItem

Determines whether match occurred in an exact-match or prefix-match search.

getExample() –
Method in class mars.venus.editors.jeditsyntax.PopupHelpItem

 

getExampleFormat() –
Method in class mars.mips.instructions.Instruction

Get string descriptor of instruction’s format.

getExampleLength() –
Method in class mars.venus.editors.jeditsyntax.PopupHelpItem

 

getExamplePaddedToLength(int) –
Method in class mars.venus.editors.jeditsyntax.PopupHelpItem

 

getExceptionHandler() –
Method in class mars.Settings

Name of currently selected exception handler file.

getExceptionHandlerAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getExceptionHandlerEnabled() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EXCEPTION_HANDLER_ENABLED)

getExecutePane() –
Method in class mars.venus.MainPane

returns component containing execution-time display

getExecuteTab() –
Method in class mars.venus.MainPane

returns component containing execution-time display.

getExpansionHistory() –
Method in class mars.assembler.MacroPool

 

getExtendedAssemblerEnabled() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EXTENDED_ASSEMBLER_ENABLED)

getExtension(File) –
Static method in class mars.util.FilenameFinder

Get the filename extension of the specified File.

getExternalTools() –
Static method in class mars.Globals

Get list of MarsTools that reside outside the MARS distribution.

getExternBaseAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getFile() –
Static method in class mars.venus.FileStatus

Returns the ASM file.

getFileErrorMessage() –
Static method in class mars.util.SystemIO

Retrieve file operation or error message

getFileExtension() –
Method in class mars.mips.dump.AbstractDumpFormat

Get the file extension associated with this format.

getFileExtension() –
Method in interface mars.mips.dump.DumpFormat

Get the file extension associated with this format.

getFileFilter(ArrayList, String, boolean) –
Static method in class mars.util.FilenameFinder

Get a FileFilter that will filter files based on the given list of filename extensions.

getFileFilter(ArrayList, String) –
Static method in class mars.util.FilenameFinder

Get a FileFilter that will filter files based on the given list of filename extensions.

getFileFilter(String, String, boolean) –
Static method in class mars.util.FilenameFinder

Get a FileFilter that will filter files based on the given filename extension.

getFileFilter(String, String) –
Static method in class mars.util.FilenameFinder

Get a FileFilter that will filter files based on the given filename extension.

getFilename() –
Method in class mars.assembler.SourceLine

Retrieve name of file containing source statement

getFilename() –
Method in class mars.ErrorMessage

Produce name of file containing error.

getFilename() –
Method in class mars.MIPSprogram

Produces name of associated source code file.

getFilename() –
Method in class mars.venus.EditPane

Delegates to corresponding FileStatus method

getFilename() –
Method in class mars.venus.FileStatus

Get file name with no path information.

getFilenameList(ClassLoader, String, String) –
Static method in class mars.util.FilenameFinder

Locate files and return list of file names.

getFilenameList(ClassLoader, String, ArrayList) –
Static method in class mars.util.FilenameFinder

Locate files and return list of file names.

getFilenameList(String, String) –
Static method in class mars.util.FilenameFinder

Locate files and return list of file names.

getFilenameList(String, ArrayList) –
Static method in class mars.util.FilenameFinder

Locate files and return list of file names.

getFilenameList(ArrayList, String) –
Static method in class mars.util.FilenameFinder

Return list of file names.

getFilenameList(ArrayList, ArrayList) –
Static method in class mars.util.FilenameFinder

Return list of file names.

getFileStatus() –
Method in class mars.venus.EditPane

Get the editing status for this EditPane’s associated document.

getFileStatus() –
Method in class mars.venus.FileStatus

Get editing status of this file.

getFirstLine() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the line displayed at the text area’s origin.

getFloatFromRegister(int) –
Static method in class mars.mips.hardware.Coprocessor1

Gets the float value stored in the given FPU register.

getFloatFromRegister(String) –
Static method in class mars.mips.hardware.Coprocessor1

Gets the float value stored in the given FPU register.

getFont() –
Method in class mars.venus.AbstractFontSettingDialog

 

getFont() –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

 

getFont() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

getFontByPosition(int) –
Method in class mars.Settings

Retrieve a Font setting

getFontMetrics(Font) –
Method in class mars.venus.editors.jeditsyntax.SyntaxStyle

Returns the font metrics for the styled font.

getFontMetrics() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns the font metrics used by this component.

getFontMetrics(Font) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

getFontStyleStrings() –
Static method in class mars.util.EditorFont

Get array containing String values for font style names.

getFromLine() –
Method in class mars.assembler.Macro

 

getGlobalPointer() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getGui() –
Static method in class mars.Globals

 

getHalf(int) –
Method in class mars.mips.hardware.Memory

Starting at the given word address, read a 2 byte word into lower 16 bits of int.

getHeapBaseAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getHelpComponent() –
Method in class mars.tools.AbstractMarsToolAndApplication

Override this method to provide a JComponent (probably a JButton) of your choice
to be placed just left of the Close/Exit button.

getHelpComponent() –
Method in class mars.tools.BitmapDisplay

Overrides default method, to provide a Help button for this tool/app.

getHelpComponent() –
Method in class mars.tools.DigitalLabSim

 

getHelpComponent() –
Method in class mars.tools.KeyboardAndDisplaySimulator

Overrides default method, to provide a Help button for this tool/app.

getHelpComponent() –
Method in class mars.tools.MemoryReferenceVisualization

Overrides default method, to provide a Help button for this tool/app.

getHistoryAsStr() –
Method in class mars.tools.BHTEntry

Builds a string representation of the BHT entry’s history.

getHorizontalOffset() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the horizontal offset of drawn lines.

getIdxForAddress(int) –
Method in class mars.tools.BHTableModel

Returns the index into the BHT for a given branch instruction address.

getIgnoreCase() –
Method in class mars.venus.editors.jeditsyntax.KeywordMap

Returns true if the keyword map is set to be case insensitive,
false otherwise.

getInitialDelay() –
Method in class mars.venus.RepeatButton

Gets the initial delay for the timer of this button.

getInitialProgramCounter() –
Static method in class mars.mips.hardware.RegisterFile

For returning the program counter’s initial (reset) value.

getInputHandler() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the input handler.

getInputString(String) –
Method in class mars.venus.MessagesPane

Method used by the SystemIO class to get interactive user input
requested by a running MIPS program (e.g.

getInputString(int) –
Method in class mars.venus.MessagesPane

Method used by the SystemIO class to get interactive user input
requested by a running MIPS program (e.g.

getInstance() –
Static method in class mars.mips.hardware.Memory

Returns the unique Memory instance, which becomes in essence global.

getInstance() –
Static method in class mars.simulator.Simulator

Returns the Simulator object

getInstance() –
Static method in class mars.venus.RunSpeedPanel

Retrieve the run speed panel object

getInstruction() –
Method in class mars.ProgramStatement

Produces Instruction object corresponding to this statement’s operator.

getInstructionCategory(ProgramStatement) –
Method in class mars.tools.InstructionStatistics

decodes the instruction and determines the category of the instruction.

getInstructionFormat() –
Method in class mars.mips.instructions.BasicInstruction

Gets the operand format of the instruction.

getInstructionLength() –
Method in class mars.mips.instructions.ExtendedInstruction

Get length in bytes that this extended instruction requires in its
binary form.

getInstructionLength() –
Method in class mars.mips.instructions.Instruction

Get length in bytes that this instruction requires in its binary form.

getInstructionList() –
Method in class mars.mips.instructions.InstructionSet

Retrieve the current instruction set.

getIntFromRegister(int) –
Static method in class mars.mips.hardware.Coprocessor1

Gets the 32-bit int bit pattern stored in the given FPU register.

getIntFromRegister(String) –
Static method in class mars.mips.hardware.Coprocessor1

Gets the 32-bit int bit pattern stored in the given FPU register.

getInvalidLinesPainted() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns true if invalid lines are painted as red tildes (~),
false otherwise.

getKernelBaseAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getKernelDataBaseAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getKernelDataSegmentLimitAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getKernelHighAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getKernelTextBaseAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getKernelTextLimitAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getKeywords() –
Static method in class mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

Get KeywordMap containing all MIPS key words.

getLabelSortState() –
Method in class mars.Settings

Get the saved state of the Labels Window sorting (can sort by either
label or address and either ascending or descending order).

getLabelsWindow() –
Method in class mars.venus.ExecutePane

Access the label values window.

getLabelWindowVisibility() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.LABEL_WINDOW_VISIBILITY)

getLeadingWhiteSpace() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Makes a copy of leading white space (tab or space) from the current line and
returns it.

getLength() –
Method in class mars.mips.hardware.MemoryAccessNotice

Fetch the length in bytes of the access operation (4,2,1).

getLengthInBytes(Directives) –
Static method in class mars.assembler.DataTypes

Get length in bytes for numeric MIPS directives.

getLimitAddresses(String[]) –
Static method in class mars.util.MemoryDump

Get the MIPS memory limit address(es) of the specified segment name(s).

getLine() –
Method in class mars.ErrorMessage

Produce line number of error.

getLineCount() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the number of lines in the document.

getLineCount() –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Returns the number of lines in this token marker.

getLineEndOffset(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the end offset of the specified line.

getLineHighlightColor() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns the line highlight color.

getLineLength(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the length of the specified line.

getLineNumber() –
Method in class mars.assembler.SourceLine

Retrieve line number of source statement

getLineNumbersList(Document) –
Method in class mars.venus.EditPane

 

getLineOfOffset(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the line containing the specified offset.

getLinesPerPage() –
Method in class mars.venus.HardcopyWriter

Return the number of lines that fit on a page

getLineStartOffset(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the start offset of the specified line.

getLineText(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the text on the specified line.

getLineText(int, Segment) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Copies the text on the specified line into a segment.

getLocalMacroPool() –
Method in class mars.MIPSprogram

Gets local macro pool MacroPool for this program

getLocalSymbolTable() –
Method in class mars.MIPSprogram

Returns SymbolTable associated with this program.

getLongFromRegisterPair(int) –
Static method in class mars.mips.hardware.Coprocessor1

Gets a long representing the double value stored in the given double
precision FPU register.

getLongFromRegisterPair(String) –
Static method in class mars.mips.hardware.Coprocessor1

Gets the double value stored in the given FPU register.

getMachineList() –
Method in class mars.MIPSprogram

Produces list of machine statements that are assembled from the program.

getMachineStatement() –
Method in class mars.ProgramStatement

Produces binary machine statement as 32 character string, all ‘0’ and ‘1’ chars.

getMacroExpansionHistory() –
Method in class mars.ErrorMessage

Returns string describing macro expansion.

getMacroRecorder() –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Returns the macro recorder.

getMagicCaretPosition() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the `magic’ caret position.

getMainPane() –
Method in class mars.venus.VenusUI

Get reference to messages pane associated with this GUI.

getMarkLine() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the mark line.

getMarkPosition() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the mark position.

getMatchingMacro(TokenList, int) –
Method in class mars.assembler.MacroPool

Will be called by parser when reaches a macro expansion call

getMaxSteps() –
Method in class mars.simulator.SimulatorNotice

Fetch the length in bytes of the access operation (4,2,1).

getMemoryConfiguration() –
Method in class mars.Settings

Returns identifier of current built-in memory configuration.

getMemoryMapBaseAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getMemoryMapLimitAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getMemoryMapLimitAddress() –
Method in class mars.mips.hardware.MemoryConfigurations

 

getMenuState() –
Static method in class mars.venus.VenusUI

Get current menu state.

getMessage() –
Method in class mars.ErrorMessage

Produce error message.

getMessagesPane() –
Method in class mars.venus.VenusUI

Get reference to messages pane associated with this GUI.

getMinimumSize() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns the painter’s minimum size.

getMIPSprogram() –
Method in class mars.assembler.SourceLine

Retrieve MIPSprogram object containing source statement

getMIPSTokenExamples() –
Static method in class mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

 

getMIPSTokenLabels() –
Static method in class mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

 

getName() –
Method in class mars.assembler.Directives

Get name of this Directives object

getName() –
Method in class mars.assembler.Macro

 

getName() –
Method in class mars.assembler.Symbol

Returns the label of the the Symbol.

getName() –
Method in class mars.mips.hardware.Register

Returns the name of the Register.

getName() –
Method in class mars.mips.instructions.Instruction

Get operation mnemonic

getName() –
Method in class mars.mips.instructions.syscalls.AbstractSyscall

Return the name you have chosen for this syscall.

getName() –
Method in interface mars.mips.instructions.syscalls.Syscall

Return a name you have chosen for this syscall.

getName() –
Method in class mars.mips.instructions.syscalls.SyscallNumberOverride

Get the service name as a String.

getName() –
Method in class mars.tools.AbstractMarsToolAndApplication

Required MarsTool method to return Tool name.

getName() –
Method in class mars.tools.BHTSimulator

Returns the name of the tool.

getName() –
Method in class mars.tools.BitmapDisplay

Required MarsTool method to return Tool name.

getName() –
Method in class mars.tools.CacheSimulator

Required MarsTool method to return Tool name.

getName() –
Method in class mars.tools.DigitalLabSim

 

getName() –
Method in class mars.tools.FloatRepresentation

Fetch tool name (for display in MARS Tools menu)

getName() –
Method in class mars.tools.InstructionCounter

 

getName() –
Method in class mars.tools.InstructionStatistics

returns the name of the tool

getName() –
Method in class mars.tools.IntroToTools

Required method to return Tool name.

getName() –
Method in class mars.tools.KeyboardAndDisplaySimulator

Required MarsTool method to return Tool name.

getName() –
Method in class mars.tools.MarsBot

 

getName() –
Method in interface mars.tools.MarsTool

Return a name you have chosen for this tool.

getName() –
Method in class mars.tools.MemoryReferenceVisualization

Required MarsTool method to return Tool name.

getName() –
Method in class mars.tools.ScavengerHunt

 

getName() –
Method in class mars.tools.ScreenMagnifier

 

getName() –
Static method in class mars.venus.FileStatus

Returns the name of the file.

getNextCounter() –
Method in class mars.assembler.MacroPool

MacroPool.counter will be set to 0 on construction of this class and will
be incremented by each call.

getNextDefaultFilename() –
Method in class mars.venus.Editor

Generates a default file name

getNumber(String) –
Static method in class mars.mips.hardware.Coprocessor0

For getting the number representation of the register.

getNumber() –
Method in class mars.mips.hardware.Register

Returns the number of the Register.

getNumber(String) –
Static method in class mars.mips.hardware.RegisterFile

For getting the number representation of the register.

getNumber() –
Method in class mars.mips.instructions.syscalls.AbstractSyscall

Return the assigned service number.

getNumber() –
Method in interface mars.mips.instructions.syscalls.Syscall

Return the assigned service number.

getNumber() –
Method in class mars.mips.instructions.syscalls.SyscallNumberOverride

Get the new service number as an int.

getOperand(int) –
Method in class mars.ProgramStatement

Produces operand value from given array position (first operand is position 0).

getOperands() –
Method in class mars.ProgramStatement

Produces int array of operand values for this statement.

getOperationMask() –
Method in class mars.mips.instructions.BasicInstruction

Gets the 32-character operation mask.

getOriginalFromLine() –
Method in class mars.assembler.Macro

 

getOriginalProgram() –
Method in class mars.assembler.Token

Produces original program containing this token.

getOriginalSourceLine() –
Method in class mars.assembler.Token

Produces original line number of this token.

getOriginalTokenList() –
Method in class mars.ProgramStatement

Produces token list generated from original source statement.

getOriginalToLine() –
Method in class mars.assembler.Macro

 

getOuterComponent() –
Method in class mars.venus.editors.generic.GenericTextArea

 

getOuterComponent() –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

 

getOuterComponent() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

getPainter() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the object responsible for painting this text area.

getParent() –
Method in class mars.venus.FileStatus

Get file parent pathname.

getParsedList() –
Method in class mars.MIPSprogram

Produces existing list of parsed source code statements.

getPathname() –
Method in class mars.venus.EditPane

Delegates to corresponding FileStatus method

getPathname() –
Method in class mars.venus.FileStatus

Get full file pathname.

getPosition() –
Method in class mars.ErrorMessage

Produce position within erroneous line.

getPrediction() –
Method in class mars.tools.BHTEntry

Returns the branch prediction based on the history.

getPredictionAsStr() –
Method in class mars.tools.BHTEntry

Returns a string representation of the BHT entry’s current prediction.

getPredictionAtIdx(int) –
Method in class mars.tools.BHTableModel

Retrieve the prediction for the i-th BHT entry.

getPreferredSize() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns the painter’s preferred size.

getPrintableBasicAssemblyStatement() –
Method in class mars.ProgramStatement

Produces printable Basic Assembly statement for this MIPS source
statement.

getProcessedLine() –
Method in class mars.assembler.TokenList

Retrieve the source line String associated with this
token list.

getProgram() –
Method in class mars.assembler.Macro

 

getProgramArguments() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.PROGRAM_ARGUMENTS)

getProgramArguments() –
Method in class mars.venus.TextSegmentWindow

Get program arguments from text field in south border of text segment window.

getProgramCounter() –
Static method in class mars.mips.hardware.RegisterFile

For returning the program counters value.

getProgramCounter() –
Method in class mars.simulator.SimulatorNotice

Fetch the value of the access operation (the value read or written).

getProgramCounterRegister() –
Static method in class mars.mips.hardware.RegisterFile

Returns Register object for program counter.

getPropertyEntry(String, String) –
Static method in class mars.Globals

Read and return property file value (if any) for requested property.

getRawWord(int) –
Method in class mars.mips.hardware.Memory

Starting at the given word address, read a 4 byte word as an int.

getRawWordOrNull(int) –
Method in class mars.mips.hardware.Memory

Starting at the given word address, read a 4 byte word as an int and return Integer.

getRegister(String) –
Static method in class mars.mips.hardware.Coprocessor0

Get register object corresponding to given name.

getRegister(String) –
Static method in class mars.mips.hardware.Coprocessor1

Get register object corresponding to given name.

getRegisterName() –
Method in class mars.mips.hardware.RegisterAccessNotice

Fetch the register number of register accessed.

getRegisterNumber(String) –
Static method in class mars.mips.hardware.Coprocessor1

For getting the number representation of the FPU register.

getRegisterPosition(Register) –
Static method in class mars.mips.hardware.Coprocessor0

Coprocessor0 implements only selected registers, so the register number
(8, 12, 13, 14) does not correspond to its position in the list of registers
(0, 1, 2, 3).

getRegisters() –
Static method in class mars.mips.hardware.Coprocessor0

For returning the set of registers.

getRegisters() –
Static method in class mars.mips.hardware.Coprocessor1

For returning the set of registers.

getRegisters() –
Static method in class mars.mips.hardware.RegisterFile

For returning the set of registers.

getRegistersHighlighting() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.REGISTERS_HIGHLIGHTING)

getRegistersPane() –
Method in class mars.venus.VenusUI

Get reference to registers pane associated with this GUI.

getRegistersWindow() –
Method in class mars.venus.ExecutePane

Access the register values window.

getRegistersWindow() –
Method in class mars.venus.RegistersPane

Return component containing integer register set.

getRepeatCount() –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Returns the number of times the next action will be repeated.

getReset() –
Static method in class mars.venus.VenusUI

To find out whether the register values are reset.

getResetValue() –
Method in class mars.mips.hardware.Register

Returns the reset value of the Register.

getRightClickPopup() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the right click popup menu.

getRowCount() –
Method in class mars.tools.BHTableModel

Returns the number of entries of the BHT.

getRunAssembleAction() –
Method in class mars.venus.VenusUI

Return reference tothe Run->Assemble item’s action.

getRunSpeed() –
Method in class mars.simulator.SimulatorNotice

Fetch the value of the access operation (the value read or written).

getRunSpeed() –
Method in class mars.venus.RunSpeedPanel

returns current run speed setting, in instructions/second.

getRunTextArea() –
Method in class mars.venus.MessagesPane

Returns component used to display runtime messages

getSegmentBounds(String) –
Static method in class mars.util.MemoryDump

Return array with segment address bounds for specified segment.

getSegmentMapKey(Segment, int, int) –
Method in class mars.venus.editors.jeditsyntax.KeywordMap

 

getSegmentNames() –
Static method in class mars.util.MemoryDump

Get the names of segments available for memory dump.

getSelectedText() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the selected text, or null if no selection is active.

getSelectedText() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

getSelectionColor() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns the selection color.

getSelectionEnd() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the selection end offset.

getSelectionEnd(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the offset where the selection ends on the specified
line.

getSelectionEnd() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

getSelectionEndLine() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the selection end line.

getSelectionStart() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the selection start offset.

getSelectionStart(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the offset where the selection starts on the specified
line.

getSelectionStart() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

getSelectionStartLine() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the selection start line.

getSettings() –
Static method in class mars.Globals

 

getSimulationCode() –
Method in class mars.mips.instructions.BasicInstruction

Gets the SimulationCode object.

getSize() –
Method in class mars.assembler.SymbolTable

Get the count of entries currently in the table.

getSortedBreakPointsArray() –
Method in class mars.venus.TextSegmentWindow

Returns array of current breakpoints, each represented by a MIPS program counter address.

getSource() –
Method in class mars.assembler.SourceLine

Retrieve source statement itself

getSource() –
Method in class mars.ProgramStatement

Produces MIPS source statement.

getSource() –
Method in class mars.venus.EditPane

Get source code text

getSourceFile() –
Method in class mars.ProgramStatement

Produces String name of the source file containing this statement.

getSourceLine() –
Method in class mars.assembler.Token

Produces line number of MIPS program of this token.

getSourceLine(int) –
Method in class mars.MIPSprogram

Produces specified line of MIPS source program.

getSourceLine() –
Method in class mars.ProgramStatement

Produces line number of MIPS source statement.

getSourceLineCount() –
Method in class mars.venus.EditPane

Calculate and return number of lines in source code text.

getSourceLineList() –
Method in class mars.MIPSprogram

Retrieve list of source statements that comprise the program.

getSourceList() –
Method in class mars.MIPSprogram

Produces list of source statements that comprise the program.

getSourceMIPSprogram() –
Method in class mars.assembler.Token

Produces MIPSprogram object associated with this token.

getSourceMIPSprogram() –
Method in class mars.ProgramStatement

Produces MIPSprogram object representing the source file containing this statement.

getStackBaseAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getStackLimitAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getStackPointer() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getStartAtMain() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.START_AT_MAIN)

getStarted() –
Static method in class mars.venus.VenusUI

To find out whether MIPS program is currently executing.

getStartLabel() –
Static method in class mars.assembler.SymbolTable

Fetches the text segment label (symbol) which, if declared global, indicates
the starting address for execution.

getStartPos() –
Method in class mars.assembler.Token

Produces position within source line of this token.

getStatement(int) –
Method in class mars.mips.hardware.Memory

Gets ProgramStatement from Text Segment.

getStatementNoNotify(int) –
Method in class mars.mips.hardware.Memory

Gets ProgramStatement from Text Segment without notifying observers.

getStatsPredCorrect() –
Method in class mars.tools.BHTEntry

Get the absolute number of correct predictions.

getStatsPredIncorrect() –
Method in class mars.tools.BHTEntry

Get the absolute number of mispredictions.

getStatsPredPrecision() –
Method in class mars.tools.BHTEntry

Get the percentage of correct predictions.

getStringMapKey(String) –
Method in class mars.venus.editors.jeditsyntax.KeywordMap

 

getStrippedTokenList() –
Method in class mars.ProgramStatement

Produces token list stripped of all but operator and operand tokens.

getStyledFont(Font) –
Method in class mars.venus.editors.jeditsyntax.SyntaxStyle

Returns the specified font, but with the style’s bold and
italic flags applied.

getStyles() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns the syntax styles used to paint colorized text.

getSubstitutedLine(int, TokenList, long, ErrorList) –
Method in class mars.assembler.Macro

Substitutes macro arguments in a line of source code inside macro
definition to be parsed after macro expansion.

getSymbol(String) –
Method in class mars.assembler.SymbolTable

Produce Symbol object from symbol table that corresponds to given String.

getSymbolGivenAddress(String) –
Method in class mars.assembler.SymbolTable

Produce Symbol object from symbol table that has the given address.

getSymbolGivenAddressLocalOrGlobal(String) –
Method in class mars.assembler.SymbolTable

Produce Symbol object from either local or global symbol table that has the
given address.

getSyntaxSensitiveToolTipText(int, int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Return any relevant tool tip text for token at specified position.

getSyscallOverrides() –
Method in class mars.Globals

Read any syscall number assignment overrides from config file.

getTabBHT() –
Method in class mars.tools.BHTSimGUI

Returns the table representing the BHT.

getTabSize() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Fetch the tab size in characters.

getTaLog() –
Method in class mars.tools.BHTSimGUI

Returns the text area for log purposes.

getText() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the entire text of this text area.

getText(int, int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the specified substring of the document.

getText(int, int, Segment) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Copies the specified substring of the document into a segment.

getText() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

getTextArea(EventObject) –
Static method in class mars.venus.editors.jeditsyntax.InputHandler

Returns the text area that fired the specified event.

getTextBaseAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getTextColumnOrder() –
Method in class mars.Settings

Order of text segment display columns (there are 5, numbered 0 to 4).

getTextLimitAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getTextSegmentWindow() –
Method in class mars.venus.ExecutePane

Access the text segment window.

getTextSymbols() –
Method in class mars.assembler.SymbolTable

For obtaining the Text Symbols.

getTfAddress() –
Method in class mars.tools.BHTSimGUI

Returns the text field for displaying the address of the most recent branch instruction

getTfIndex() –
Method in class mars.tools.BHTSimGUI

Returns the text field for displaying the corresponding index into the BHT

getTfInstruction() –
Method in class mars.tools.BHTSimGUI

Returns the text field for displaying the most recent branch instruction

getThread() –
Method in class mars.mips.hardware.AccessNotice

Get reference to thread that created this notice

getTokenExactMatchHelp(Token, String) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

Construct and return any appropriate help information for
the given token.

getTokenExactMatchHelp(Token, String) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Construct and return any appropriate help information for
the given token.

getTokenList() –
Method in class mars.mips.instructions.Instruction

Get TokenList corresponding to correct instruction syntax.

getTokenList() –
Method in class mars.MIPSprogram

Produces list of tokens that comprise the program.

getTokenMarker() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the document’s token marker.

getTokenMarker() –
Method in class mars.venus.editors.jeditsyntax.SyntaxDocument

Returns the token marker that is to be used to split lines
of this document up into tokens.

getTokenPrefixMatchHelp(String, Token, Token, String) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

Construct and return any appropriate help information for
prefix match based on current line’s token list.

getTokenPrefixMatchHelp(String, Token, Token, String) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Construct and return any appropriate help information for
the given token or “token prefix”.

getTokenText() –
Method in class mars.venus.editors.jeditsyntax.PopupHelpItem

The document text that mached this item

getToLine() –
Method in class mars.assembler.Macro

 

getToolTipText(MouseEvent) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns the tool tip to display at the specified location.

getToolTipText(MouseEvent) –
Method in interface mars.venus.editors.jeditsyntax.TextAreaPainter.Highlight

Returns the tool tip to display at the specified
location.

getType() –
Method in class mars.assembler.Symbol

Finds the type of symbol, text or data.

getType() –
Method in class mars.assembler.Token

Produces token type of this token.

getType() –
Method in exception mars.mips.hardware.AddressErrorException

Get the exception type (load or store).

getUndoManager() –
Method in class mars.venus.editors.generic.GenericTextArea

Returns the undo manager for this editing area

getUndoManager() –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Returns the undo manager for this editing area

getUndoManager() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

getUndoManager() –
Method in class mars.venus.EditPane

get the manager in charge of Undo and Redo operations

getUserHighAddress() –
Method in class mars.mips.hardware.MemoryConfiguration

 

getUserRegister(String) –
Static method in class mars.mips.hardware.RegisterFile

Get register object corresponding to given name.

getValue() –
Method in class mars.assembler.Token

Produces source code of this token.

getValue(int) –
Static method in class mars.mips.hardware.Coprocessor0

Returns the value of the register who’s number is num.

getValue(int) –
Static method in class mars.mips.hardware.Coprocessor1

Returns the value of the FPU register who’s number is num.

getValue() –
Method in class mars.mips.hardware.MemoryAccessNotice

Fetch the value of the access operation (the value read or written).

getValue() –
Method in class mars.mips.hardware.Register

Returns the value of the Register.

getValue(int) –
Static method in class mars.mips.hardware.RegisterFile

Returns the value of the register who’s number is num.

getValue() –
Method in class mars.simulator.SwingWorker

Get the value produced by the worker thread, or null if it
hasn’t been constructed yet.

getValueAt(int, int) –
Method in class mars.tools.BHTableModel

Returns the value of the cell at the given row and column
Required by the TableModel interface.

getValueDisplayBase() –
Method in class mars.venus.ExecutePane

Retrieve the number system base for displaying values (mem/register contents)

getValueDisplayBaseChooser() –
Method in class mars.venus.ExecutePane

Retrieve component used to set numerical base (10 or 16) of data value display.

getValueDisplayBaseMenuItem() –
Method in class mars.venus.VenusUI

Get reference to settings menu item for display base of memory/register values.

getValueNoNotify() –
Method in class mars.mips.hardware.Register

Returns the value of the Register.

getVisibleLines() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns the number of lines visible in this text area.

getWarningsAreErrors() –
Method in class mars.Settings

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.WARNINGS_ARE_ERRORS)

getWord(int) –
Method in class mars.mips.hardware.Memory

Starting at the given word address, read a 4 byte word as an int.

getWordNoNotify(int) –
Method in class mars.mips.hardware.Memory

Starting at the given word address, read a 4 byte word as an int.

GLOBAL_POINTER_REGISTER –
Static variable in class mars.mips.hardware.RegisterFile

 

globalPointer –
Static variable in class mars.mips.hardware.Memory

base address for storing globals

Globals – Class in mars
Collection of globally-available data structures.
Globals() –
Constructor for class mars.Globals

 

GLOBL –
Static variable in class mars.assembler.Directives

 

go() –
Method in class mars.tools.AbstractMarsToolAndApplication

Run the simulator as stand-alone application.

grabAction –
Variable in class mars.venus.editors.jeditsyntax.InputHandler

 

grabFocus() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

grabNextKeyStroke(ActionListener) –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Grabs the next key typed event and invokes the specified
action with the key as a the action command.

GuiAction – Class in mars.venus
parent class for Action subclasses to be defined for every menu/toolbar
option.
GuiAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.GuiAction

 

H

HALF –
Static variable in class mars.assembler.Directives

 

HALF_SIZE –
Static variable in class mars.assembler.DataTypes

Number of bytes occupied by MIPS halfword is 2.

handleExecBranchInst(int, boolean) –
Method in class mars.tools.BHTSimulator

Handles the execution of the branch instruction.

handleGrabAction(KeyEvent) –
Method in class mars.venus.editors.jeditsyntax.InputHandler

If a key is being grabbed, this method should be called with
the appropriate key event.

handlePreBranchInst(ProgramStatement) –
Method in class mars.tools.BHTSimulator

Handles the execution branch instruction.

HardcopyWriter – Class in mars.venus
 
HardcopyWriter(Frame, String, int, double, double, double, double) –
Constructor for class mars.venus.HardcopyWriter

The constructor for this class has a bunch of arguments:
The frame argument is required for all printing in Java.

HardcopyWriter.PrintCanceledException – Exception in mars.venus
This is the exception class that the HardcopyWriter constructor
throws when the user clicks “Cancel” in the print dialog box.
HardcopyWriter.PrintCanceledException(String) –
Constructor for exception mars.venus.HardcopyWriter.PrintCanceledException

 

hasCompactTranslation() –
Method in class mars.mips.instructions.ExtendedInstruction

Determine whether or not this pseudo-instruction has a second
translation optimized for 16 bit address space: a compact version.

hasUnsavedEdits() –
Method in class mars.venus.EditPane

Delegates to corresponding FileStatus method

hasUnsavedEdits() –
Method in class mars.venus.FileStatus

Determine if file has been modified since last save or, if not yet saved, since
being created using New or Open.

haveMenuRequestFocus() –
Method in class mars.venus.VenusUI

Have the menu request keyboard focus.

headerfont –
Variable in class mars.venus.HardcopyWriter

 

headermetrics –
Variable in class mars.venus.HardcopyWriter

 

headery –
Variable in class mars.venus.HardcopyWriter

 

heapAddress –
Static variable in class mars.mips.hardware.Memory

 

heapBaseAddress –
Static variable in class mars.mips.hardware.Memory

base address for heap: 0x10040000 (I think from SPIM not MIPS)

height –
Variable in class mars.venus.HardcopyWriter

 

HelpAboutAction – Class in mars.venus
Action for the Help -> About menu item
HelpAboutAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.HelpAboutAction

 

HelpHelpAction – Class in mars.venus
Action for the Help -> Help menu item
HelpHelpAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.HelpHelpAction

 

helpPath –
Static variable in class mars.Globals

Path to folder that contains help text

HEXADECIMAL –
Static variable in class mars.venus.NumberDisplayBaseChooser

 

hexStringToBinaryString(String) –
Static method in class mars.util.Binary

Translate String consisting of hexadecimal digits into String consisting of
corresponding binary digits (‘1’s and ‘0’s).

HexTextDumpFormat – Class in mars.mips.dump
Class that represents the “hexadecimal text” memory dump format.
HexTextDumpFormat() –
Constructor for class mars.mips.dump.HexTextDumpFormat

Constructor.

highlights –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

highlightStepAtAddress(int) –
Method in class mars.venus.TextSegmentWindow

Highlights the source code line whose address matches the given
text segment address.

highlightStepAtAddress(int, boolean) –
Method in class mars.venus.TextSegmentWindow

Highlights the source code line whose address matches the given
text segment address.

highlightStepAtPC() –
Method in class mars.venus.TextSegmentWindow

Highlights the source code line whose address matches the current
program counter value.

highlightStepAtPC(boolean) –
Method in class mars.venus.TextSegmentWindow

Highlights the source code line whose address matches the current
program counter value.

highOrderLongToInt(long) –
Static method in class mars.util.Binary

Returns int representing the bit values of the high order 32 bits of given
64 bit long value.

HOME –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

horizontal –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

horizontalOffset –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

I

I_BRANCH_FORMAT –
Static variable in class mars.mips.instructions.BasicInstructionFormat

 

I_FORMAT –
Static variable in class mars.mips.instructions.BasicInstructionFormat

 

id –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

The id of this token.

ID_COUNT –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

The total number of defined token ids.

IDENTIFIER –
Static variable in class mars.assembler.TokenTypes

 

imagesPath –
Static variable in class mars.Globals

Path to folder that contains images

INCLUDE –
Static variable in class mars.assembler.Directives

 

incrementPC() –
Static method in class mars.mips.hardware.RegisterFile

Method to increment the Program counter in the general case (not a jump or branch).

inDataSegment(int) –
Static method in class mars.mips.hardware.Memory

Handy little utility to find out if given address is in MARS data
segment (starts at Memory.dataSegmentBaseAddress).

inDelaySlot() –
Method in class mars.simulator.BackStepper

Determine whether the next back-step action occurred as the result of
an instruction that executed in the “delay slot” of a delayed branch.

inDelaySlot() –
Static method in class mars.simulator.Simulator

Determine whether or not the next instruction to be executed is in a
“delay slot”.

init(JEditTextArea, TextAreaPainter.Highlight) –
Method in interface mars.venus.editors.jeditsyntax.TextAreaPainter.Highlight

Called after the highlight painter has been added.

initBHT(int, int, boolean) –
Method in class mars.tools.BHTableModel

Initializes the BHT with the given size and history.

initialize(boolean) –
Static method in class mars.Globals

Method called once upon system initialization to create the global data structures.

initializePostGUI() –
Method in class mars.tools.AbstractMarsToolAndApplication

Method that will be called once just after the GUI is constructed in the go() and action()
methods.

initializePostGUI() –
Method in class mars.tools.BitmapDisplay

The only post-GUI initialization is to create the initial Grid object based on the default settings
of the various combo boxes.

initializePostGUI() –
Method in class mars.tools.CacheSimulator

The only post-GUI initialization is to create the initial cache object based on the default settings
of the various combo boxes.

initializePostGUI() –
Method in class mars.tools.KeyboardAndDisplaySimulator

Initialization code to be executed after the GUI is configured.

initializePostGUI() –
Method in class mars.tools.MemoryReferenceVisualization

The only post-GUI initialization is to create the initial Grid object based on the default settings
of the various combo boxes.

initializePreGUI() –
Method in class mars.tools.AbstractMarsToolAndApplication

Method that will be called once just before the GUI is constructed in the go() and action()
methods.

initializePreGUI() –
Method in class mars.tools.BitmapDisplay

Initialize all JComboBox choice structures not already initialized at declaration.

initializePreGUI() –
Method in class mars.tools.CacheSimulator

Initialize all JComboBox choice structures not already initialized at declaration.

initializePreGUI() –
Method in class mars.tools.InstructionCounter

 

initializePreGUI() –
Method in class mars.tools.InstructionStatistics

performs initialization tasks of the counters before the GUI is created.

initializePreGUI() –
Method in class mars.tools.KeyboardAndDisplaySimulator

 

initializePreGUI() –
Method in class mars.tools.MemoryReferenceVisualization

Initialize all JComboBox choice structures not already initialized at declaration.

initializeProgramCounter(int) –
Static method in class mars.mips.hardware.RegisterFile

For initializing the Program Counter.

initializeProgramCounter(boolean) –
Static method in class mars.mips.hardware.RegisterFile

Will initialize the Program Counter to either the default reset value, or the address
associated with source program global label “main”, if it exists as a text segment label
and the global setting is set.

inKernelDataSegment(int) –
Static method in class mars.mips.hardware.Memory

Handy little utility to find out if given address is in MARS kernel data
segment (starts at Memory.kernelDataSegmentBaseAddress).

inKernelTextSegment(int) –
Static method in class mars.mips.hardware.Memory

Handy little utility to find out if given address is in MARS kernel
text segment (starts at Memory.kernelTextBaseAddress).

inMemoryMapSegment(int) –
Static method in class mars.mips.hardware.Memory

Handy little utility to find out if given address is in the Memory Map area
starts at Memory.memoryMapBaseAddress, range 0xffff0000 to 0xffffffff.

InputHandler – Class in mars.venus.editors.jeditsyntax
An input handler converts the user’s key strokes into concrete actions.
InputHandler() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler

 

inputHandler –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

inputHandler –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

InputHandler.backspace – Class in mars.venus.editors.jeditsyntax
 
InputHandler.backspace() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.backspace

 

InputHandler.backspace_word – Class in mars.venus.editors.jeditsyntax
 
InputHandler.backspace_word() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.backspace_word

 

InputHandler.clip_copy – Class in mars.venus.editors.jeditsyntax
 
InputHandler.clip_copy() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.clip_copy

 

InputHandler.clip_cut – Class in mars.venus.editors.jeditsyntax
 
InputHandler.clip_cut() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.clip_cut

 

InputHandler.clip_paste – Class in mars.venus.editors.jeditsyntax
 
InputHandler.clip_paste() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.clip_paste

 

InputHandler.delete – Class in mars.venus.editors.jeditsyntax
 
InputHandler.delete() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.delete

 

InputHandler.delete_word – Class in mars.venus.editors.jeditsyntax
 
InputHandler.delete_word() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.delete_word

 

InputHandler.document_end – Class in mars.venus.editors.jeditsyntax
 
InputHandler.document_end(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.document_end

 

InputHandler.document_home – Class in mars.venus.editors.jeditsyntax
 
InputHandler.document_home(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.document_home

 

InputHandler.end – Class in mars.venus.editors.jeditsyntax
 
InputHandler.end(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.end

 

InputHandler.home – Class in mars.venus.editors.jeditsyntax
 
InputHandler.home(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.home

 

InputHandler.insert_break – Class in mars.venus.editors.jeditsyntax
 
InputHandler.insert_break() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.insert_break

 

InputHandler.insert_char – Class in mars.venus.editors.jeditsyntax
 
InputHandler.insert_char() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.insert_char

 

InputHandler.insert_tab – Class in mars.venus.editors.jeditsyntax
 
InputHandler.insert_tab() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.insert_tab

 

InputHandler.MacroRecorder – Interface in mars.venus.editors.jeditsyntax
Macro recorder.
InputHandler.next_char – Class in mars.venus.editors.jeditsyntax
 
InputHandler.next_char(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.next_char

 

InputHandler.next_line – Class in mars.venus.editors.jeditsyntax
 
InputHandler.next_line(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.next_line

 

InputHandler.next_page – Class in mars.venus.editors.jeditsyntax
 
InputHandler.next_page(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.next_page

 

InputHandler.next_word – Class in mars.venus.editors.jeditsyntax
 
InputHandler.next_word(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.next_word

 

InputHandler.NonRecordable – Interface in mars.venus.editors.jeditsyntax
If an action implements this interface, it should not be recorded
by the macro recorder.
InputHandler.NonRepeatable – Interface in mars.venus.editors.jeditsyntax
If an action implements this interface, it should not be repeated.
InputHandler.overwrite – Class in mars.venus.editors.jeditsyntax
 
InputHandler.overwrite() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.overwrite

 

InputHandler.prev_char – Class in mars.venus.editors.jeditsyntax
 
InputHandler.prev_char(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.prev_char

 

InputHandler.prev_line – Class in mars.venus.editors.jeditsyntax
 
InputHandler.prev_line(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.prev_line

 

InputHandler.prev_page – Class in mars.venus.editors.jeditsyntax
 
InputHandler.prev_page(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.prev_page

 

InputHandler.prev_word – Class in mars.venus.editors.jeditsyntax
 
InputHandler.prev_word(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.prev_word

 

InputHandler.repeat – Class in mars.venus.editors.jeditsyntax
 
InputHandler.repeat() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.repeat

 

InputHandler.select_all – Class in mars.venus.editors.jeditsyntax
 
InputHandler.select_all() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.select_all

 

InputHandler.toggle_rect – Class in mars.venus.editors.jeditsyntax
 
InputHandler.toggle_rect() –
Constructor for class mars.venus.editors.jeditsyntax.InputHandler.toggle_rect

 

InputHandler.Wrapper – Interface in mars.venus.editors.jeditsyntax
For use by EditAction.Wrapper only.
INSERT_BREAK –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

INSERT_CHAR –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

INSERT_TAB –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

insertLines(int, int) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Informs the token marker that lines have been inserted into
the document.

inSteppedExecution() –
Method in class mars.MIPSprogram

Will be true only while in process of simulating a program statement
in step mode (e.g.

Instruction – Class in mars.mips.instructions
Base class to represent member of MIPS instruction set.
Instruction() –
Constructor for class mars.mips.instructions.Instruction

 

INSTRUCTION_LENGTH –
Static variable in class mars.mips.instructions.Instruction

Length in bytes of a machine instruction.

INSTRUCTION_LENGTH_BITS –
Static variable in class mars.mips.instructions.Instruction

 

InstructionCounter – Class in mars.tools
Instruction counter tool.
InstructionCounter(String, String) –
Constructor for class mars.tools.InstructionCounter

Simple constructor, likely used to run a stand-alone memory reference visualizer.

InstructionCounter() –
Constructor for class mars.tools.InstructionCounter

Simple construction, likely used by the MARS Tools menu mechanism.

instructionSet –
Static variable in class mars.Globals

The set of implemented MIPS instructions.

InstructionSet – Class in mars.mips.instructions
The list of Instruction objects, each of which represents a MIPS instruction.
InstructionSet() –
Constructor for class mars.mips.instructions.InstructionSet

Creates a new InstructionSet object.

InstructionStatistics – Class in mars.tools
A MARS tool for obtaining instruction statistics by instruction category.
InstructionStatistics(String, String) –
Constructor for class mars.tools.InstructionStatistics

Simple constructor, likely used to run a stand-alone enhanced instruction counter.

InstructionStatistics() –
Constructor for class mars.tools.InstructionStatistics

Simple construction, likely used by the MARS Tools menu mechanism.

INTEGER_16 –
Static variable in class mars.assembler.TokenTypes

 

INTEGER_16U –
Static variable in class mars.assembler.TokenTypes

 

INTEGER_32 –
Static variable in class mars.assembler.TokenTypes

 

INTEGER_5 –
Static variable in class mars.assembler.TokenTypes

 

IntelHexDumpFormat – Class in mars.mips.dump
Intel’s Hex memory initialization format
IntelHexDumpFormat() –
Constructor for class mars.mips.dump.IntelHexDumpFormat

Constructor.

INTERNAL_FIRST –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

The first id that can be used for internal state
in a token marker.

INTERNAL_LAST –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

The last id that can be used for internal state
in a token marker.

interrupt() –
Method in class mars.simulator.SwingWorker

A new method that interrupts the worker thread.

inTextSegment(int) –
Static method in class mars.mips.hardware.Memory

Handy little utility to find out if given address is in MARS text
segment (starts at Memory.textBaseAddress).

IntroToTools – Class in mars.tools
The “hello world” of MarsTools!
IntroToTools(String, String) –
Constructor for class mars.tools.IntroToTools

Simple constructor, likely used to run a stand-alone memory reference visualizer.

IntroToTools() –
Constructor for class mars.tools.IntroToTools

Simple constructor, likely used by the MARS Tools menu mechanism

intToAscii(int) –
Static method in class mars.util.Binary

Produce ASCII string equivalent of integer value, interpreting it as 4 one-byte
characters.

intToBinaryString(int, int) –
Static method in class mars.util.Binary

Translate int value into a String consisting of ‘1’s and ‘0’s.

intToBinaryString(int) –
Static method in class mars.util.Binary

Translate int value into a String consisting of ‘1’s and ‘0’s.

intToHalfHexString(int) –
Static method in class mars.util.Binary

Returns a 6 character string representing the 16-bit hexadecimal equivalent of the
given integer value.

intToHexString(int) –
Static method in class mars.util.Binary

Prefix a hexadecimal-indicating string “0x” to the string which is
returned by the method “Integer.toHexString”.

INVALID –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Invalid token id.

invalidateLine(int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Marks a line as needing a repaint.

invalidateLineRange(int, int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Marks a range of lines as needing a repaint.

invalidateSelectedLines() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Repaints the lines containing the selection.

InvalidRegisterAccessException – Exception in mars.mips.hardware
Represents attempt to access double precision register using an odd
(e.g.
InvalidRegisterAccessException() –
Constructor for exception mars.mips.hardware.InvalidRegisterAccessException

Constructor for IllegalRegisterException.

isAssembled() –
Static method in class mars.venus.FileStatus

Tells whether the file has been assembled.

isBeingUsedAsAMarsTool –
Variable in class mars.tools.AbstractMarsToolAndApplication

 

isBlockCaretEnabled() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns true if the caret should be drawn as a block, false otherwise.

isBold() –
Method in class mars.venus.editors.jeditsyntax.SyntaxStyle

Returns true if boldface is enabled for this style.

isBracketHighlightEnabled() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns true if bracket highlighting is enabled, false otherwise.

isBranchInstruction(ProgramStatement) –
Static method in class mars.tools.BHTSimulator

Determines if the instruction is a branch instruction or not.

isCaretBlinkEnabled() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns true if the caret is blinking, false otherwise.

isCaretVisible() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns true if the caret is visible, false otherwise.

isConnected() –
Method in class mars.tools.AbstractMarsToolAndApplication.ConnectButton

 

isEditable() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns true if this text area is editable, false otherwise.

isEdited() –
Static method in class mars.venus.FileStatus

Tells whether the file has been edited since it has been saved.

isEmpty() –
Method in class mars.assembler.TokenList

Returns empty/non-empty status of list.

isFloatingDirective(Directives) –
Static method in class mars.assembler.Directives

Lets you know whether given directive is for floating number (FLOAT,DOUBLE).

isFloatingTokenType(TokenTypes) –
Static method in class mars.assembler.TokenTypes

Lets you know if given tokentype is for floating point numbers (REAL_NUMBER).

isHex(String) –
Static method in class mars.util.Binary

Parsing method to see if a string represents a hex number.

isIntegerDirective(Directives) –
Static method in class mars.assembler.Directives

Lets you know whether given directive is for integer (WORD,HALF,BYTE).

isIntegerTokenType(TokenTypes) –
Static method in class mars.assembler.TokenTypes

Lets you know if given tokentype is for integers (INTGER_5, INTEGER_16, INTEGER_32).

isItalic() –
Method in class mars.venus.editors.jeditsyntax.SyntaxStyle

Returns true if italics is enabled for this style.

isLineHighlightEnabled() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns true if line highlight is enabled, false otherwise.

isManagingFocus() –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Returns if this component can be traversed by pressing the
Tab key.

isNew() –
Method in class mars.venus.EditPane

Delegates to corresponding FileStatus method

isNew() –
Method in class mars.venus.FileStatus

Determine if file is “new”, which means created using New but not yet saved.

isNextLineRequested() –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Returns true if the next line should be repainted.

isObserving() –
Method in class mars.tools.AbstractMarsToolAndApplication

Query method to let you know if the tool/app is (or could be) currently
“observing” any MIPS resources.

isOctal(String) –
Static method in class mars.util.Binary

Parsing method to see if a string represents an octal number.

isOverwriteEnabled() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns true if overwrite mode is enabled, false otherwise.

isPlain() –
Method in class mars.venus.editors.jeditsyntax.SyntaxStyle

Returns true if no font styles are enabled.

isRepeatEnabled() –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Returns if repeating is enabled.

isRepeatEnabled() –
Method in class mars.venus.RepeatButton

Checks if the button should fire events when held.

isSaved() –
Static method in class mars.venus.FileStatus

Tells whether the file has been saved.

isSelectionRectangular() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Returns true if the selection is rectangular, false otherwise.

isValidIdentifier(String) –
Static method in class mars.assembler.TokenTypes

 

isWarning() –
Method in class mars.ErrorMessage

Determine whether this message represents error or warning.

J

J_FORMAT –
Static variable in class mars.mips.instructions.BasicInstructionFormat

 

JEditBasedTextArea – Class in mars.venus.editors.jeditsyntax
Adaptor subclass for JEditTextArea

Provides those methods required by the MARSTextEditingArea interface
that are not defined by JEditTextArea.
JEditBasedTextArea(EditPane, JComponent) –
Constructor for class mars.venus.editors.jeditsyntax.JEditBasedTextArea

 

JEditTextArea – Class in mars.venus.editors.jeditsyntax
jEdit’s text area component.
JEditTextArea(JComponent) –
Constructor for class mars.venus.editors.jeditsyntax.JEditTextArea

Creates a new JEditTextArea with the default settings.

JEditTextArea(TextAreaDefaults, JComponent) –
Constructor for class mars.venus.editors.jeditsyntax.JEditTextArea

 

job –
Variable in class mars.venus.HardcopyWriter

 

jobname –
Variable in class mars.venus.HardcopyWriter

 

K

KDATA –
Static variable in class mars.assembler.Directives

 

kernelBaseAddress –
Static variable in class mars.mips.hardware.Memory

kernel boundary.

kernelDataBaseAddress –
Static variable in class mars.mips.hardware.Memory

base address for kernel data segment: 0x90000000

kernelDataSegmentLimitAddress –
Static variable in class mars.mips.hardware.Memory

 

kernelHighAddress –
Static variable in class mars.mips.hardware.Memory

highest address acessible in kernel mode.

kernelTextBaseAddress –
Static variable in class mars.mips.hardware.Memory

base address for kernel text segment: 0x80000000

kernelTextLimitAddress –
Static variable in class mars.mips.hardware.Memory

 

KeyboardAndDisplaySimulator – Class in mars.tools
Keyboard and Display Simulator.
KeyboardAndDisplaySimulator(String, String) –
Constructor for class mars.tools.KeyboardAndDisplaySimulator

Simple constructor, likely used to run a stand-alone keyboard/display simulator.

KeyboardAndDisplaySimulator() –
Constructor for class mars.tools.KeyboardAndDisplaySimulator

Simple constructor, likely used by the MARS Tools menu mechanism

keyPressed(KeyEvent) –
Method in class mars.tools.AbstractMarsToolAndApplication.EnterKeyListener

 

keyPressed(KeyEvent) –
Method in class mars.venus.editors.jeditsyntax.DefaultInputHandler

Handle a key pressed event.

keyTyped(KeyEvent) –
Method in class mars.venus.editors.jeditsyntax.DefaultInputHandler

Handle a key typed event.

KEYWORD1 –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Keyword 1 token id.

KEYWORD2 –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Keyword 2 token id.

KEYWORD3 –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Keyword 3 token id.

KeywordMap – Class in mars.venus.editors.jeditsyntax
A KeywordMap is similar to a hashtable in that it maps keys
to values.
KeywordMap(boolean) –
Constructor for class mars.venus.editors.jeditsyntax.KeywordMap

Creates a new KeywordMap.

KeywordMap(boolean, int) –
Constructor for class mars.venus.editors.jeditsyntax.KeywordMap

Creates a new KeywordMap.

KTEXT –
Static variable in class mars.assembler.Directives

 

L

LABEL –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Label token id.

LABEL_SORT_STATE –
Static variable in class mars.Settings

State for sorting label window display

LABEL_WINDOW_VISIBILITY –
Static variable in class mars.Settings

Default visibilty of label window (symbol table).

LabelsWindow – Class in mars.venus
Represents the Labels window, which is a type of JInternalFrame.
LabelsWindow() –
Constructor for class mars.venus.LabelsWindow

Constructor for the Labels (symbol table) window.

lastAddress –
Variable in class mars.tools.InstructionCounter

The last address we saw.

lastAddress –
Variable in class mars.tools.InstructionStatistics

The last address we saw.

lastLine –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

The last tokenized line.

lastToken –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

The last token in the list.

LEFT_OF_SCROLLBAR –
Static variable in class mars.venus.editors.jeditsyntax.JEditTextArea

Adding components with this name to the text area will place
them left of the horizontal scroll bar.

LEFT_PAREN –
Static variable in class mars.assembler.TokenTypes

 

length –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

The length of this token.

length –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

The number of lines in the model being tokenized.

LINE_PREFIX –
Static variable in class mars.ErrorList

 

lineascent –
Variable in class mars.venus.HardcopyWriter

 

lineheight –
Variable in class mars.venus.HardcopyWriter

 

lineHighlight –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

lineHighlight –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

lineHighlightColor –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

lineHighlightColor –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

lineInfo –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

An array for storing information about lines.

linenum –
Variable in class mars.venus.HardcopyWriter

 

lines_per_page –
Variable in class mars.venus.HardcopyWriter

 

lineSegment –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

lineToY(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Converts a line index to a y co-ordinate.

listenerList –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

LITERAL1 –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Literal 1 token id.

LITERAL2 –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Literal 2 token id.

LITTLE_ENDIAN –
Static variable in class mars.mips.hardware.Memory

Constant representing byte order of each memory word.

loadDumpFormats() –
Method in class mars.mips.dump.DumpFormatLoader

Dynamically loads dump formats into an ArrayList.

loadPropertiesFromFile(String) –
Static method in class mars.util.PropertiesFile

Produce Properties (a Hashtable) object containing key-value pairs
from specified properties file.

longToBinaryString(long, int) –
Static method in class mars.util.Binary

Translate long value into a String consisting of ‘1’s and ‘0’s.

longToBinaryString(long) –
Static method in class mars.util.Binary

Translate long value into a String consisting of ‘1’s and ‘0’s.

longToHexString(long) –
Static method in class mars.util.Binary

Prefix a hexadecimal-indicating string “0x” to the string equivalent to the
hexadecimal value in the long parameter.

lookup(Segment, int, int) –
Method in class mars.venus.editors.jeditsyntax.KeywordMap

Looks up a key.

LOW_DOUBLE_VALUE –
Static variable in class mars.assembler.DataTypes

Largest magnitude negative value that can be stored in a MIPS double(negative of the max)

LOW_FLOAT_VALUE –
Static variable in class mars.assembler.DataTypes

Largest magnitude negative value that can be stored in a MIPS float (negative of the max)

lowOrderLongToInt(long) –
Static method in class mars.util.Binary

Returns int representing the bit values of the low order 32 bits of given
64 bit long value.

M

MACRO –
Static variable in class mars.assembler.Directives

 

Macro – Class in mars.assembler
Stores information of a macro definition.
Macro() –
Constructor for class mars.assembler.Macro

 

MACRO_ARG –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Macro parameter token.

MACRO_PARAMETER –
Static variable in class mars.assembler.TokenTypes

 

MacroPool – Class in mars.assembler
Stores information of macros defined by now.
MacroPool(MIPSprogram) –
Constructor for class mars.assembler.MacroPool

Create an empty MacroPool for given program

magicCaret –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

main(String[]) –
Static method in class Mars

 

main(String[]) –
Static method in class mars.tools.BitmapDisplay

Main provided for pure stand-alone use.

main(String[]) –
Static method in class mars.tools.CacheSimulator

Main provided for pure stand-alone use.

main(String[]) –
Static method in class mars.tools.DigitalLabSim

 

main(String[]) –
Static method in class mars.tools.FloatRepresentation

Main provided for pure stand-alone use.

main(String[]) –
Static method in class mars.tools.IntroToTools

Main provided for pure stand-alone use.

main(String[]) –
Static method in class mars.tools.KeyboardAndDisplaySimulator

Main provided for pure stand-alone use.

main(String[]) –
Static method in class mars.tools.MemoryReferenceVisualization

Main provided for pure stand-alone use.

main(String[]) –
Static method in class mars.tools.ScreenMagnifier

 

main(String[]) –
Static method in class mars.venus.HardcopyWriter

A program that prints the specified file using HardcopyWriter

main(String[]) –
Static method in class mars.venus.RepeatButton

Main method, for testing.

MainPane – Class in mars.venus
Creates the tabbed areas in the UI and also created the internal windows that
exist in them.
MainPane(VenusUI, Editor, RegistersWindow, Coprocessor1Window, Coprocessor0Window) –
Constructor for class mars.venus.MainPane

Constructor for the MainPane class.

mainUI –
Variable in class mars.venus.GuiAction

 

makeTemplateSubstitutions(MIPSprogram, String, TokenList) –
Static method in class mars.mips.instructions.ExtendedInstruction

Given a basic instruction template and the list of tokens from an extended
instruction statement, substitute operands from the token list appropriately into the
template to generate the basic statement.

mapLength –
Variable in class mars.venus.editors.jeditsyntax.KeywordMap

 

markTokens(Segment, int) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

A wrapper for the lower-level markTokensImpl method
that is called to split a line up into tokens.

markTokensImpl(byte, Segment, int) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

 

markTokensImpl(byte, Segment, int) –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

An abstract method that splits a line up into tokens.

mars – package mars
 
Mars – Class in
Portal to Mars
Mars() –
Constructor for class Mars

 

mars.assembler – package mars.assembler
 
mars.mips.dump – package mars.mips.dump
 
mars.mips.hardware – package mars.mips.hardware
 
mars.mips.instructions – package mars.mips.instructions
 
mars.mips.instructions.syscalls – package mars.mips.instructions.syscalls
 
mars.simulator – package mars.simulator
 
mars.tools – package mars.tools
 
mars.util – package mars.util
 
mars.venus – package mars.venus
 
mars.venus.editors – package mars.venus.editors
 
mars.venus.editors.generic – package mars.venus.editors.generic
 
mars.venus.editors.jeditsyntax – package mars.venus.editors.jeditsyntax
 
mars.venus.editors.jeditsyntax.tokenmarker – package mars.venus.editors.jeditsyntax.tokenmarker
 
MarsBot – Class in mars.tools
Simple Demo of Mars tool capability
MarsBot() –
Constructor for class mars.tools.MarsBot

 

MarsLaunch – Class in mars
Launch the Mars application
MarsLaunch(String[]) –
Constructor for class mars.MarsLaunch

 

MarsSplashScreen – Class in mars
Produces MARS splash screen.

Adapted from http://www.java-tips.org/content/view/1267/2/

MarsSplashScreen(int) –
Constructor for class mars.MarsSplashScreen

 

MARSTextEditingArea – Interface in mars.venus.editors
Specifies capabilities that any test editor used in MARS must have.
MarsTool – Interface in mars.tools
Interface for any tool that interacts with an executing MIPS program.
MATCH_ALL_EXTENSIONS –
Static variable in class mars.util.FilenameFinder

 

matchDirective(String) –
Static method in class mars.assembler.Directives

Find Directive object, if any, which matches the given String.

matchesAnyMacroName(String) –
Method in class mars.assembler.MacroPool

 

matchOperator(String) –
Method in class mars.mips.instructions.InstructionSet

Given an operator mnemonic, will return the corresponding Instruction object(s)
from the instruction set.

matchTokenType(String) –
Static method in class mars.assembler.TokenTypes

Classifies the given token into one of the MIPS types.

MAX_BLINK_RATE –
Static variable in class mars.venus.Editor

 

MAX_BYTE_VALUE –
Static variable in class mars.assembler.DataTypes

Maximum value that can be stored in a MIPS byte is 27-1

MAX_DOUBLE_VALUE –
Static variable in class mars.assembler.DataTypes

Maximum positive finite value that can be stored in a MIPS double is same as Java Double

MAX_FLOAT_VALUE –
Static variable in class mars.assembler.DataTypes

Maximum positive finite value that can be stored in a MIPS float is same as Java Float

MAX_HALF_VALUE –
Static variable in class mars.assembler.DataTypes

Maximum value that can be stored in a MIPS halfword is 215-1

MAX_SIZE –
Static variable in class mars.util.EditorFont

 

MAX_STEPS –
Static variable in class mars.simulator.Simulator

 

MAX_TAB_SIZE –
Static variable in class mars.venus.Editor

 

MAX_UHALF_VALUE –
Static variable in class mars.assembler.DataTypes

Maximum value that can be stored in an unsigned MIPS halfword is 216-1

MAX_WORD_VALUE –
Static variable in class mars.assembler.DataTypes

Maximum value that can be stored in a MIPS word is 231-1

maxExampleLength(ArrayList) –
Static method in class mars.venus.editors.jeditsyntax.PopupHelpItem

 

MAXIMUM_SCROLLED_CHARACTERS –
Static variable in class mars.venus.MessagesPane

 

maximumBacksteps –
Static variable in class mars.Globals

Maximum number of back-step operations to buffer

maximumErrorMessages –
Static variable in class mars.Globals

Maximum number of assembler errors produced by one assemble operation

maximumMessageCharacters –
Static variable in class mars.Globals

Maximum length of scrolled message window (MARS Messages and Run I/O)

maxSteps –
Static variable in class mars.venus.RunGoAction

 

memory –
Static variable in class mars.Globals

Simulated MIPS memory component.

Memory – Class in mars.mips.hardware
Represents MIPS memory.
MEMORY_CONFIGURATION –
Static variable in class mars.Settings

Identifier of current memory configuration

MemoryAccessNotice – Class in mars.mips.hardware
Object provided to Observers of runtime access to MIPS memory.
memoryAndRegistersLock –
Static variable in class mars.Globals

Lock variable used at head of synchronized block to guard MIPS memory and registers

MemoryConfiguration – Class in mars.mips.hardware
Models the memory configuration for the simulated MIPS machine.
MemoryConfiguration(String, String, String[], int[]) –
Constructor for class mars.mips.hardware.MemoryConfiguration

 

MemoryConfigurations – Class in mars.mips.hardware
Models the collection of MIPS memory configurations.
MemoryConfigurations() –
Constructor for class mars.mips.hardware.MemoryConfigurations

 

MemoryDump – Class in mars.util
 
MemoryDump() –
Constructor for class mars.util.MemoryDump

 

memoryMapBaseAddress –
Static variable in class mars.mips.hardware.Memory

starting address for memory mapped I/O: 0xffff0000 (-65536)

memoryMapLimitAddress –
Static variable in class mars.mips.hardware.Memory

 

MemoryReferenceVisualization – Class in mars.tools
Memory reference visualization.
MemoryReferenceVisualization(String, String) –
Constructor for class mars.tools.MemoryReferenceVisualization

Simple constructor, likely used to run a stand-alone memory reference visualizer.

MemoryReferenceVisualization() –
Constructor for class mars.tools.MemoryReferenceVisualization

Simple constructor, likely used by the MARS Tools menu mechanism

menu –
Variable in class mars.venus.VenusUI

 

MESSAGE_SEPARATOR –
Static variable in class mars.ErrorList

 

MessagesPane – Class in mars.venus
Creates the message window at the bottom of the UI.
MessagesPane() –
Constructor for class mars.venus.MessagesPane

Constructor for the class, sets up two fresh tabbed text areas for program feedback.

metrics –
Variable in class mars.venus.HardcopyWriter

 

MIFDumpFormat – Class in mars.mips.dump
The Memory Initialization File (.mif) VHDL-supported file format
This is documented for the Altera platform at
www.altera.com/support/software/nativelink/quartus2/glossary/def_mif.html.
MIFDumpFormat() –
Constructor for class mars.mips.dump.MIFDumpFormat

Constructor.

MIN_BLINK_RATE –
Static variable in class mars.venus.Editor

 

MIN_BYTE_VALUE –
Static variable in class mars.assembler.DataTypes

Lowest value that can be stored in a MIPS byte is -27

MIN_HALF_VALUE –
Static variable in class mars.assembler.DataTypes

Lowest value that can be stored in a MIPS halfword is -215

MIN_SIZE –
Static variable in class mars.util.EditorFont

 

MIN_TAB_SIZE –
Static variable in class mars.venus.Editor

 

MIN_UHALF_VALUE –
Static variable in class mars.assembler.DataTypes

Lowest value that can be stored in na unsigned MIPS halfword is 0

MIN_WORD_VALUE –
Static variable in class mars.assembler.DataTypes

Lowest value that can be stored in a MIPS word is -231

MINUS –
Static variable in class mars.assembler.TokenTypes

 

MIPSprogram – Class in mars
Internal representations of MIPS program.
MIPSprogram() –
Constructor for class mars.MIPSprogram

 

MIPSTokenMarker – Class in mars.venus.editors.jeditsyntax.tokenmarker
MIPS token marker.
MIPSTokenMarker() –
Constructor for class mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

 

MIPSTokenMarker(KeywordMap) –
Constructor for class mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

 

mnemonic –
Variable in class mars.mips.instructions.Instruction

The instruction name.

modifyDisplay(char) –
Method in class mars.tools.DigitalLabSim.SevenSegmentDisplay

 

modifyDisplay(int, char) –
Method in class mars.tools.DigitalLabSim.SevenSegmentPanel

 

mouseClicked(MouseEvent) –
Method in class mars.tools.DigitalLabSim.HexaKeyboard.EcouteurClick

 

mouseClicked(MouseEvent) –
Method in class mars.venus.RepeatButton

Handle mouse clicked events.

mouseEntered(MouseEvent) –
Method in class mars.tools.DigitalLabSim.HexaKeyboard.EcouteurClick

 

mouseEntered(MouseEvent) –
Method in class mars.venus.RepeatButton

Handle mouse entered events.

mouseExited(MouseEvent) –
Method in class mars.tools.DigitalLabSim.HexaKeyboard.EcouteurClick

 

mouseExited(MouseEvent) –
Method in class mars.venus.RepeatButton

Handle mouse exited events.

mousePressed(MouseEvent) –
Method in class mars.tools.DigitalLabSim.HexaKeyboard.EcouteurClick

 

mousePressed(MouseEvent) –
Method in class mars.venus.PopupListener

 

mousePressed(MouseEvent) –
Method in class mars.venus.RepeatButton

Handle mouse pressed events.

mouseReleased(MouseEvent) –
Method in class mars.tools.DigitalLabSim.HexaKeyboard.EcouteurClick

 

mouseReleased(MouseEvent) –
Method in class mars.venus.PopupListener

 

mouseReleased(MouseEvent) –
Method in class mars.venus.RepeatButton

Handle mouse released events.

N

NEW_EDITED –
Static variable in class mars.venus.FileStatus

New edit window with unsaved edits

NEW_NOT_EDITED –
Static variable in class mars.venus.FileStatus

New edit window with no edits

newFile() –
Method in class mars.venus.Editor

Perform “new” operation to create an empty tab.

newFile() –
Method in class mars.venus.EditTabbedPane

Carries out all necessary operations to implement
the New operation from the File menu.

newline() –
Method in class mars.venus.HardcopyWriter

This internal method begins a new line

newpage() –
Method in class mars.venus.HardcopyWriter

This internal method begins a new page and prints the header.

next –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

The next token in the linked list.

NEXT_CHAR –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

NEXT_LINE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

NEXT_PAGE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

NEXT_WORD –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

nextIndex(String, String, int, boolean) –
Method in class mars.venus.editors.generic.GenericTextArea

Returns next posn of word in text – forward search.

nextIndex(String, String, int, boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Returns next posn of word in text – forward search.

nextLineRequested –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

True if the next line should be painted.

nextTabStop(float, int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Implementation of TabExpander interface.

NO_DEVICE –
Static variable in class mars.simulator.Simulator

 

NO_FILE –
Static variable in class mars.venus.FileStatus

initial state or after close

NORMAL_TERMINATION –
Static variable in class mars.simulator.Simulator

 

NOT_EDITED –
Static variable in class mars.venus.FileStatus

open/saved edit window with no edits

NOT_FOUND –
Static variable in class mars.assembler.SymbolTable

 

notifyObservers() –
Method in class mars.mips.hardware.Memory

Overridden to be unavailable.

notifyObservers(Object) –
Method in class mars.mips.hardware.Memory

Overridden to be unavailable.

NULL –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Normal text token id.

NUMBER_OF_CHARACTERS_TO_CUT –
Static variable in class mars.venus.MessagesPane

 

numberDisplayBaseChanged(NumberDisplayBaseChooser) –
Method in class mars.venus.ExecutePane

Update display of columns based on state of given chooser.

NumberDisplayBaseChooser – Class in mars.venus
Use to select base for displaying numbers.
NumberDisplayBaseChooser(String, boolean) –
Constructor for class mars.venus.NumberDisplayBaseChooser

constructor.

O

obj –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker.LineInfo

This is for use by the token marker implementations
themselves.

ODD_ROW_BACKGROUND –
Static variable in class mars.Settings

RGB color for table odd row background (text, data, register displays)

ODD_ROW_FONT –
Static variable in class mars.Settings

Font for table odd row background (text, data, register displays)

ODD_ROW_FOREGROUND –
Static variable in class mars.Settings

RGB color for table odd row foreground (text, data, register displays)

offsetToX(int, int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Converts an offset in a line into an x co-ordinate.

open() –
Method in class mars.venus.Editor

Open file in a new tab.

openFile(String, int) –
Static method in class mars.util.SystemIO

Open a file for either reading or writing.

openFile() –
Method in class mars.venus.EditTabbedPane

Carries out all necessary operations to implement
the Open operation from the File menu.

openFile(File) –
Method in class mars.venus.EditTabbedPane

Carries out all necessary operations to open the
specified file in the editor.

OPENING –
Static variable in class mars.venus.FileStatus

file is being opened.

OperandFormat – Class in mars.assembler
Provides utility method related to MIPS operand formats.
operandMask –
Static variable in class mars.mips.instructions.Instruction

Characters used in instruction mask to indicate bit positions
for ‘f’irst, ‘s’econd, and ‘t’hird operands.

OPERATOR –
Static variable in class mars.assembler.TokenTypes

 

OPERATOR –
Static variable in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Operator token id.

outOfRange(Directives, int) –
Static method in class mars.assembler.DataTypes

Determines whether given integer value falls within value range for given directive.

outOfRange(Directives, double) –
Static method in class mars.assembler.DataTypes

Determines whether given floating point value falls within value range for given directive.

OVERWRITE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

overwrite –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

overwriteSetSelectedText(String) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Similar to setSelectedText(), but overstrikes the
appropriate number of characters if overwrite mode is enabled.

P

page –
Variable in class mars.venus.HardcopyWriter

 

pageBreak() –
Method in class mars.venus.HardcopyWriter

End the current page.

pagedpi –
Variable in class mars.venus.HardcopyWriter

 

pagenum –
Variable in class mars.venus.HardcopyWriter

 

pagesize –
Variable in class mars.venus.HardcopyWriter

 

paint(Graphics) –
Method in class mars.tools.DigitalLabSim.SevenSegmentDisplay

 

paint(Graphics) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Repaints the text.

paintBracketHighlight(Graphics, int, int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

paintCaret(Graphics, int, int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

painter –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

paintHighlight(Graphics, int, int) –
Method in interface mars.venus.editors.jeditsyntax.TextAreaPainter.Highlight

This should paint the highlight and delgate to the
next highlight painter.

paintHighlight(Graphics, int, int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

paintInvalid –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

paintInvalid –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

paintLine(Graphics, TokenMarker, int, int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

paintLineHighlight(Graphics, int, int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

paintPlainLine(Graphics, int, Font, Color, int, int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

paintSyntaxLine(Segment, Token, SyntaxStyle[], TabExpander, Graphics, int, int) –
Static method in class mars.venus.editors.jeditsyntax.SyntaxUtilities

 

paintSyntaxLine(Graphics, TokenMarker, int, Font, Color, int, int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

parseKeyStroke(String) –
Static method in class mars.venus.editors.jeditsyntax.DefaultInputHandler

Converts a string to a keystroke.

paste() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Inserts the clipboard contents into the text.

paste() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

pasteText() –
Method in class mars.venus.EditPane

paste clipboard contents at cursor position

PAUSE_OR_STOP –
Static variable in class mars.simulator.Simulator

 

paused(boolean, int, ProcessingException) –
Method in class mars.venus.RunGoAction

Method to be called when Pause is selected through menu/toolbar/shortcut.

performApply() –
Method in class mars.venus.AbstractFontSettingDialog

 

performSpecialClosingDuties() –
Method in class mars.tools.AbstractMarsToolAndApplication

This method is called when tool/app is exited either through the close/exit button or the window’s X box.

PLUS –
Static variable in class mars.assembler.TokenTypes

 

popFromCallStack() –
Method in class mars.assembler.MacroPool

 

populate() –
Method in class mars.mips.instructions.InstructionSet

Adds all instructions to the set.

popup –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

popup –
Static variable in class mars.venus.editors.jeditsyntax.SyntaxUtilities

 

popup –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

POPUP_INSTRUCTION_GUIDANCE –
Static variable in class mars.Settings

Flag to control whether or not editor will provide popup instruction guidance while typing

POPUP_SYSCALL_INPUT –
Static variable in class mars.Settings

Flag to control whether or not simulator will use popup dialog for input syscalls

PopupHelpItem – Class in mars.venus.editors.jeditsyntax
Handly little class to contain help information for a popupMenu or
tool tip item.
PopupHelpItem(String, String, String, boolean) –
Constructor for class mars.venus.editors.jeditsyntax.PopupHelpItem

Create popup help item.

PopupHelpItem(String, String, String) –
Constructor for class mars.venus.editors.jeditsyntax.PopupHelpItem

Create popup help item, where match is result of an exact-match search.

PopupListener – Class in mars.venus
 
PopupListener(JPopupMenu) –
Constructor for class mars.venus.PopupListener

 

popupShowing –
Static variable in class mars.venus.editors.jeditsyntax.SyntaxUtilities

Paints the specified line onto the graphics context.

POSITION_PREFIX –
Static variable in class mars.ErrorList

 

postMarsMessage(String) –
Method in class mars.venus.MessagesPane

Post a message to the assembler display

postRunMessage(String) –
Method in class mars.venus.MessagesPane

Post a message to the runtime display

preferredTextAreaDimension –
Static variable in class mars.tools.KeyboardAndDisplaySimulator

 

prefixMatchDirectives(String) –
Static method in class mars.assembler.Directives

Find Directive object, if any, which contains the given string as a prefix.

prefixMatchOperator(String) –
Method in class mars.mips.instructions.InstructionSet

Given a string, will return the Instruction object(s) from the instruction
set whose operator mnemonic prefix matches it.

prepareFilesForAssembly(ArrayList, String, String) –
Method in class mars.MIPSprogram

Prepares the given list of files for assembly.

PREV_CHAR –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

PREV_LINE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

PREV_PAGE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

PREV_WORD –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

printprops –
Static variable in class mars.venus.HardcopyWriter

 

printString(String) –
Static method in class mars.util.SystemIO

Implements syscall having 4 in $v0, to print a string.

ProcessingException – Exception in mars
Class to represent error that occurs while assembling or running a MIPS program.
ProcessingException(ErrorList) –
Constructor for exception mars.ProcessingException

Constructor for ProcessingException.

ProcessingException(ProgramStatement, String) –
Constructor for exception mars.ProcessingException

Constructor for ProcessingException to handle runtime exceptions

ProcessingException(ProgramStatement, String, int) –
Constructor for exception mars.ProcessingException

Constructor for ProcessingException to handle runtime exceptions

ProcessingException(ProgramStatement, AddressErrorException) –
Constructor for exception mars.ProcessingException

Constructor for ProcessingException to handle address runtime exceptions

ProcessingException() –
Constructor for exception mars.ProcessingException

Constructor for ProcessingException.

processKeyEvent(KeyEvent) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Forwards key events directly to the input handler.

processMIPSUpdate(Observable, AccessNotice) –
Method in class mars.tools.AbstractMarsToolAndApplication

Override this method to process a received notice from MIPS Observable (memory or register)
It will only be called if the notice was generated as the result of MIPS instruction execution.

processMIPSUpdate(Observable, AccessNotice) –
Method in class mars.tools.BHTSimulator

Callback for text segment access by the MIPS simulator.

processMIPSUpdate(Observable, AccessNotice) –
Method in class mars.tools.BitmapDisplay

Update display when connected MIPS program accesses (data) memory.

processMIPSUpdate(Observable, AccessNotice) –
Method in class mars.tools.CacheSimulator

Apply caching policies and update display when connected MIPS program accesses (data) memory.

processMIPSUpdate(Observable, AccessNotice) –
Method in class mars.tools.InstructionCounter

 

processMIPSUpdate(Observable, AccessNotice) –
Method in class mars.tools.InstructionStatistics

method that is called each time the MIPS simulator accesses the text segment.

processMIPSUpdate(Observable, AccessNotice) –
Method in class mars.tools.KeyboardAndDisplaySimulator

Update display when connected MIPS program accesses (data) memory.

processMIPSUpdate(Observable, AccessNotice) –
Method in class mars.tools.MemoryReferenceVisualization

Update display when connected MIPS program accesses (data) memory.

program –
Static variable in class mars.Globals

the program currently being worked with.

PROGRAM_ARGUMENTS –
Static variable in class mars.Settings

Flag to determine whether or not to display and use program arguments

ProgramArgumentList – Class in mars.simulator
Models Program Arguments, one or more strings provided to the MIPS
program at runtime.
ProgramArgumentList(String) –
Constructor for class mars.simulator.ProgramArgumentList

Constructor that parses string to produce list.

ProgramArgumentList(String[]) –
Constructor for class mars.simulator.ProgramArgumentList

Constructor that gets list from String array, one argument per element.

ProgramArgumentList(String[], int) –
Constructor for class mars.simulator.ProgramArgumentList

Constructor that gets list from section of String array, one
argument per element.

ProgramArgumentList(ArrayList) –
Constructor for class mars.simulator.ProgramArgumentList

Constructor that gets list from ArrayList of String, one argument per element.

ProgramArgumentList(ArrayList, int) –
Constructor for class mars.simulator.ProgramArgumentList

Constructor that gets list from section of String ArrayList, one
argument per element.

ProgramStatement – Class in mars
Represents one assembly/machine statement.
ProgramStatement(MIPSprogram, String, TokenList, TokenList, Instruction, int, int) –
Constructor for class mars.ProgramStatement

Constructor for ProgramStatement when there are links back to all source and token
information.

ProgramStatement(int, int) –
Constructor for class mars.ProgramStatement

Constructor for ProgramStatement used only for writing a binary machine
instruction with no source code to refer back to.

PropertiesFile – Class in mars.util
Provides means to work with “.properties” files which are used to store
various MARS settings.
PropertiesFile() –
Constructor for class mars.util.PropertiesFile

 

pushOnCallStack(Token) –
Method in class mars.assembler.MacroPool

 

Q

QUOTED_STRING –
Static variable in class mars.assembler.TokenTypes

 

R

R_FORMAT –
Static variable in class mars.mips.instructions.BasicInstructionFormat

 

RandomStreams – Class in mars.mips.instructions.syscalls
This small class serves only to hold a static HashMap for storing
random number generators for use by all the random number generator
syscalls.
RandomStreams() –
Constructor for class mars.mips.instructions.syscalls.RandomStreams

 

READ –
Static variable in class mars.mips.hardware.AccessNotice

Indicates the purpose of access was to read.

readChar(int) –
Static method in class mars.util.SystemIO

Implements syscall having 12 in $v0, to read a char value.

readDouble(int) –
Static method in class mars.util.SystemIO

Implements syscall to read a double value.

readFloat(int) –
Static method in class mars.util.SystemIO

Implements syscall to read a float value.

readFromFile(int, byte[], int) –
Static method in class mars.util.SystemIO

Read bytes from file.

readInteger(int) –
Static method in class mars.util.SystemIO

Implements syscall to read an integer value.

readSource(String) –
Method in class mars.MIPSprogram

Reads MIPS source code from file into structure.

readString(int, int) –
Static method in class mars.util.SystemIO

Implements syscall to read a string.

readyForCommit() –
Method in class mars.assembler.Macro

Operations to be done on this macro before it is committed in macro pool.

REAL_NUMBER –
Static variable in class mars.assembler.TokenTypes

 

recalculateVisibleLines() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Recalculates the number of visible lines.

RECEIVER_CONTROL –
Static variable in class mars.tools.KeyboardAndDisplaySimulator

 

RECEIVER_DATA –
Static variable in class mars.tools.KeyboardAndDisplaySimulator

 

recorder –
Variable in class mars.venus.editors.jeditsyntax.InputHandler

 

rectSelect –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

redo() –
Method in class mars.venus.editors.generic.GenericTextArea

Redo previous edit

redo() –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Redo previous edit

redo() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

redo() –
Method in class mars.venus.EditPane

Redo previous edit

refresh() –
Method in class mars.venus.Coprocessor0Window

Refresh the table, triggering re-rendering.

refresh() –
Method in class mars.venus.Coprocessor1Window

Refresh the table, triggering re-rendering.

refresh() –
Method in class mars.venus.RegistersWindow

Refresh the table, triggering re-rendering.

regionMatches(boolean, Segment, int, String) –
Static method in class mars.venus.editors.jeditsyntax.SyntaxUtilities

Checks if a subregion of a Segment is equal to a
string.

regionMatches(boolean, Segment, int, char[]) –
Static method in class mars.venus.editors.jeditsyntax.SyntaxUtilities

Checks if a subregion of a Segment is equal to a
character array.

Register – Class in mars.mips.hardware
Abstraction to represent a register of a MIPS Assembler.
Register(String, int, int) –
Constructor for class mars.mips.hardware.Register

Creates a new register with specified name, number, and value.

register(int) –
Static method in class mars.simulator.DelayedBranch

Register the fact that a successful branch is to occur.

REGISTER_HIGHLIGHT_BACKGROUND –
Static variable in class mars.Settings

RGB color for register highlighted background

REGISTER_HIGHLIGHT_FONT –
Static variable in class mars.Settings

Font for register highlighted background

REGISTER_HIGHLIGHT_FOREGROUND –
Static variable in class mars.Settings

RGB color for register highlighted foreground

REGISTER_NAME –
Static variable in class mars.assembler.TokenTypes

note: REGISTER_NAME is token of form $zero whereas REGISTER_NUMBER is token
of form $0.

REGISTER_NUMBER –
Static variable in class mars.assembler.TokenTypes

 

RegisterAccessNotice – Class in mars.mips.hardware
Object provided to Observers of runtime access to MIPS register.
RegisterFile – Class in mars.mips.hardware
Represents the collection of MIPS registers.
RegisterFile() –
Constructor for class mars.mips.hardware.RegisterFile

 

REGISTERS_HIGHLIGHTING –
Static variable in class mars.Settings

Flag to control whether or not highlighting is applied to register windows

RegistersPane – Class in mars.venus
Contains tabbed areas in the UI to display register contents
RegistersPane(VenusUI, RegistersWindow, Coprocessor1Window, Coprocessor0Window) –
Constructor for class mars.venus.RegistersPane

Constructor for the RegistersPane class.

RegistersWindow – Class in mars.venus
Sets up a window to display registers in the UI.
RegistersWindow() –
Constructor for class mars.venus.RegistersWindow

Constructor which sets up a fresh window with a table that contains the register values.

registerTableModelListener(TableModelListener) –
Method in class mars.venus.TextSegmentWindow

Assign listener to Table model.

remove(int) –
Method in class mars.assembler.TokenList

Removes Token object at specified list position.

remove(EditPane) –
Method in class mars.venus.EditTabbedPane

Remove the pane and update menu status

removeAllKeyBindings() –
Method in class mars.venus.editors.jeditsyntax.DefaultInputHandler

Removes all key bindings from this input handler.

removeAllKeyBindings() –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Removes all key bindings from this input handler.

removeCaretListener(CaretListener) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Removes a caret change listener from this text area.

removeKeyBinding(String) –
Method in class mars.venus.editors.jeditsyntax.DefaultInputHandler

Removes a key binding from this input handler.

removeKeyBinding(String) –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Removes a key binding from this input handler.

removeNotify() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Called by the AWT when this component is removed from it’s parent.

removeProgramArgumentsPanel() –
Method in class mars.venus.TextSegmentWindow

 

removeStopListener(Simulator.StopListener) –
Method in class mars.simulator.Simulator

 

removeSymbol(Token) –
Method in class mars.assembler.SymbolTable

Removes a symbol from the Symbol table.

REPEAT –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

repeat –
Variable in class mars.venus.editors.jeditsyntax.InputHandler

 

RepeatButton – Class in mars.venus
RepeatButton is a JButton which contains a timer
for firing events while the button is held down.
RepeatButton() –
Constructor for class mars.venus.RepeatButton

Creates a button with no set text or icon.

RepeatButton(Action) –
Constructor for class mars.venus.RepeatButton

Creates a button where properties are taken from the Action supplied.

RepeatButton(Icon) –
Constructor for class mars.venus.RepeatButton

Creates a button with an icon.

RepeatButton(String) –
Constructor for class mars.venus.RepeatButton

Creates a button with text.

RepeatButton(String, Icon) –
Constructor for class mars.venus.RepeatButton

Creates a button with initial text and an icon.

repeatCount –
Variable in class mars.venus.editors.jeditsyntax.InputHandler

 

replaceSelection(String) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Same as setSelectedText but named for compatibility with
JTextComponent method replaceSelection.

replaceSelection(String) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

requestFocusInWindow() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

RESERVED_INSTRUCTION_EXCEPTION –
Static variable in class mars.simulator.Exceptions

 

reset(boolean) –
Method in class mars.Settings

Reset settings to default values, as described in the constructor comments.

reset() –
Method in class mars.tools.AbstractMarsToolAndApplication

Method that will be called each time the default Reset button is clicked.

reset() –
Method in class mars.tools.BHTSimulator

Performs a reset of the simulator.

reset() –
Method in class mars.tools.BitmapDisplay

Method to reset counters and display when the Reset button selected.

reset() –
Method in class mars.tools.CacheSimulator

Method to reset cache, counters and display when the Reset button selected.

reset() –
Method in class mars.tools.DigitalLabSim

 

reset() –
Method in class mars.tools.FloatRepresentation

Method to reset display values to 0 when the Reset button selected.

reset() –
Method in class mars.tools.InstructionCounter

 

reset() –
Method in class mars.tools.InstructionStatistics

resets the counter values of the tool and updates the display.

reset() –
Method in class mars.tools.KeyboardAndDisplaySimulator

Method to reset counters and display when the Reset button selected.

reset() –
Method in class mars.tools.MemoryReferenceVisualization

Method to reset counters and display when the Reset button selected.

reset() –
Method in class mars.venus.AbstractFontSettingDialog

 

reset() –
Static method in class mars.venus.FileStatus

Resets all the values in FileStatus

RESET_TOOL_TIP_TEXT –
Static variable in class mars.venus.SettingsHighlightingAction

 

resetFiles() –
Static method in class mars.util.SystemIO

Reset all files — clears out the file descriptor table.

resetHexaKeyboard() –
Method in class mars.tools.DigitalLabSim.HexaKeyboard

 

resetMaxSteps() –
Static method in class mars.venus.RunGoAction

Reset max steps limit to default value at termination of a simulated execution.

resetMemoryRange() –
Method in class mars.venus.DataSegmentWindow

Reset range of memory addresses to base address of currently selected segment and update display.

resetOneSecondCounter() –
Method in class mars.tools.DigitalLabSim.OneSecondCounter

 

resetRegisters() –
Static method in class mars.mips.hardware.Coprocessor0

Method to reinitialize the values of the registers.

resetRegisters() –
Static method in class mars.mips.hardware.Coprocessor1

Method to reinitialize the values of the registers.

resetRegisters() –
Static method in class mars.mips.hardware.RegisterFile

Method to reinitialize the values of the registers.

resetSevenSegment() –
Method in class mars.tools.DigitalLabSim.SevenSegmentPanel

 

resetSimulator() –
Method in class mars.tools.BHTSimulator

Resets the simulator by clearing the GUI elements and resetting the BHT.

resetValue() –
Method in class mars.mips.hardware.Register

Resets the value of the register to the value it was constructed with.

resetValues() –
Method in class mars.venus.DataSegmentWindow

Reset all data display values to 0

revalidate() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

RIGHT –
Static variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

RIGHT_PAREN –
Static variable in class mars.assembler.TokenTypes

 

rows –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

rows –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

RunAssembleAction – Class in mars.venus
Action class for the Run -> Assemble menu item (and toolbar icon)
RunAssembleAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.RunAssembleAction

 

RunBackstepAction – Class in mars.venus
Action for the Run -> Backstep menu item
RunBackstepAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.RunBackstepAction

 

RunClearBreakpointsAction – Class in mars.venus
Action class for the Run menu item to clear execution breakpoints that have been set.
RunClearBreakpointsAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.RunClearBreakpointsAction

Create the object and register with text segment window as a listener on its table model.

RunGoAction – Class in mars.venus
Action class for the Run -> Go menu item (and toolbar icon)
RunGoAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.RunGoAction

 

RUNNABLE –
Static variable in class mars.venus.FileStatus

successful assembly

RUNNING –
Static variable in class mars.venus.FileStatus

execution is under way

RunPauseAction – Class in mars.venus
Action class for the Run -> Pause menu item (and toolbar icon)
RunPauseAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.RunPauseAction

 

RunResetAction – Class in mars.venus
Action for the Run -> Reset menu item
RunResetAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.RunResetAction

 

RunSpeedPanel – Class in mars.venus
Class for the Run speed slider control.
runSpeedPanelExists –
Static variable in class mars.Globals

 

RunStepAction – Class in mars.venus
Action for the Run -> Step menu item
RunStepAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.RunStepAction

 

RunStopAction – Class in mars.venus
Action class for the Run -> Stop menu item (and toolbar icon)
RunStopAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.RunStopAction

 

RunToggleBreakpointsAction – Class in mars.venus
Action class for the Run menu item to clear execution breakpoints that have been set.
RunToggleBreakpointsAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.RunToggleBreakpointsAction

Create the object and register with text segment window as a listener on its table model.

S

save() –
Method in class mars.venus.Editor

Perform “save” operation on current tab’s file.

saveAll() –
Method in class mars.venus.Editor

Perform save operation on all open files (tabs).

saveAllFiles() –
Method in class mars.venus.EditTabbedPane

Saves all files currently open in the editor.

saveAs() –
Method in class mars.venus.Editor

Perform “save as” operation on current tab’s file.

saveAsCurrentFile() –
Method in class mars.venus.EditTabbedPane

Pops up a dialog box to do “Save As” operation.

saveCurrentFile() –
Method in class mars.venus.EditTabbedPane

Saves file under existing name.

ScavengerHunt – Class in mars.tools
Demo of Mars tool capability.
ScavengerHunt() –
Constructor for class mars.tools.ScavengerHunt

 

ScreenMagnifier – Class in mars.tools
Handy little tool to magnify a selected section of the screen
by a given scale and display it.
ScreenMagnifier() –
Constructor for class mars.tools.ScreenMagnifier

 

scrollBarsInitialized –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

scrollTo(int, int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Ensures that the specified line and offset is visible by scrolling
the text area if necessary.

scrollToCaret() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Ensures that the caret is visible by scrolling the text area if
necessary.

SegmentWindowDumpFormat – Class in mars.mips.dump
Dump MIPS memory contents in Segment Window format.
SegmentWindowDumpFormat() –
Constructor for class mars.mips.dump.SegmentWindowDumpFormat

Constructor.

select(int, int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Selects from the start offset to the end offset.

select(int, int) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

SELECT_ALL –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_DOC_END –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_DOC_HOME –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_END –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_HOME –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_NEXT_CHAR –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_NEXT_LINE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_NEXT_PAGE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_NEXT_WORD –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_PREV_CHAR –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_PREV_LINE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_PREV_PAGE –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

SELECT_PREV_WORD –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

selectAll() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Selects all text in the document.

selectAll() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

selectAllText() –
Method in class mars.venus.EditPane

select all text

selectEditorTextLine(String, int, int) –
Method in class mars.venus.MessagesPane

Will select the specified line in an editor tab.

selectErrorMessage(String, int, int) –
Method in class mars.venus.MessagesPane

Will select the Mars Messages tab error message that matches the given
specifications, if it is found.

selectionColor –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

selectionColor –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

selectionEnd –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

selectionEndLine –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

selectionStart –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

selectionStartLine –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

selectLine(int) –
Method in class mars.venus.EditPane

Select the specified editor text line.

selectLine(int, int) –
Method in class mars.venus.EditPane

Select the specified editor text line.

selectMarsMessageTab() –
Method in class mars.venus.MessagesPane

Make the assembler message tab current (up front)

selectNone() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Moves the mark to the caret position.

selectRunMessageTab() –
Method in class mars.venus.MessagesPane

Make the runtime message tab current (up front)

SET –
Static variable in class mars.assembler.Directives

 

set(int, Token) –
Method in class mars.assembler.TokenList

Replaces token at position with different one.

set(int, int, int) –
Method in class mars.mips.hardware.Memory

Starting at the given address, write the given value over the given number of bytes.

set(int) –
Static method in class mars.venus.FileStatus

Set file status.

setAddress(int) –
Method in class mars.assembler.Symbol

Sets (replaces) the address of the the Symbol.

setArgs(ArrayList) –
Method in class mars.assembler.Macro

 

setAssembleAllEnabled(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ALL_ENABLED)

setAssembled(boolean) –
Static method in class mars.venus.FileStatus

Changes the value of assenbked to the parameter given.

setAssembleOnOpenEnabled(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ON_OPEN_ENABLED)

setBackground(Color) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setBase(int) –
Method in class mars.venus.NumberDisplayBaseChooser

Set the current number base.

setBasicAssemblyStatement(String) –
Method in class mars.ProgramStatement

Assigns given String to be Basic Assembly statement equivalent to this source line.

setBinaryStatement(int) –
Method in class mars.ProgramStatement

Assigns given int to be binary machine code equivalent to this source line.

setBit(int, int) –
Static method in class mars.util.Binary

Sets the specified bit of the specified value to 1, and returns the result.

setBlockCaretEnabled(boolean) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Sets if the caret should be drawn as a block, false otherwise.

setBooleanSetting(int, boolean) –
Method in class mars.Settings

Set value of a boolean setting given its id and the value.

setBracketHighlightColor(Color) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Sets the bracket highlight color.

setBracketHighlightEnabled(boolean) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Enables or disables bracket highlighting.

setByte(int, int) –
Method in class mars.mips.hardware.Memory

Writes low order 8 bits of given value into specified Memory byte.

setByte(int, int, int) –
Static method in class mars.util.Binary

Sets the specified byte of the specified value to the low order 8 bits of
specified replacement value, and returns the result.

setByteOrder(boolean) –
Method in class mars.mips.hardware.Memory

Set byte order to either LITTLE_ENDIAN or BIG_ENDIAN.

setCaretBlinkEnabled(boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Toggles caret blinking.

setCaretBlinkRate(int) –
Method in class mars.Settings

Set the caret blinking rate in milliseconds.

setCaretBlinkRate(int) –
Method in class mars.venus.editors.generic.GenericTextArea

Set the caret blinking rate in milliseconds.

setCaretBlinkRate(int) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Set the caret blinking rate in milliseconds.

setCaretBlinkRate(int) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setCaretColor(Color) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Sets the caret color.

setCaretPosition(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the caret position.

setCaretPosition(int) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setCaretVisible(boolean) –
Method in class mars.venus.editors.generic.GenericTextArea

Control caret visibility

setCaretVisible(boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets if the caret should be visible.

setCaretVisible(boolean) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setCodeHighlighting(boolean) –
Method in class mars.venus.TextSegmentWindow

Used to enable or disable source code highlighting.

setColorSettingByKey(String, Color) –
Method in class mars.Settings

Set Color object for specified settings key.

setColorSettingByPosition(int, Color) –
Method in class mars.Settings

Set Color object for specified settings name (a static constant).

setConditionFlag(int) –
Static method in class mars.mips.hardware.Coprocessor1

Set condition flag to 1 (true).

setConditionFlags() –
Static method in class mars.mips.hardware.Coprocessor1

Set all condition flags (0-7).

setConfiguration() –
Static method in class mars.mips.hardware.Memory

Sets current memory configuration for simulated MIPS.

setCurrent(Macro) –
Method in class mars.assembler.MacroPool

 

setCurrentConfiguration(MemoryConfiguration) –
Static method in class mars.mips.hardware.MemoryConfigurations

 

setCurrentEditTab(EditPane) –
Method in class mars.venus.EditTabbedPane

Select the specified EditPane to be the current tab.

setDataSegmentHighlighting(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DATA_SEGMENT_HIGHLIGHTING)

setDelay(int) –
Method in class mars.venus.RepeatButton

Set the delay for the timer of this button.

setDelayedBranchingEnabled(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED)

setDelayedBranchingEnabledNonPersistent(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED)

setDescription(String) –
Method in class mars.venus.editors.jeditsyntax.PopupHelpItem

 

setDisplayAddressesInHex(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_ADDRESSES_IN_HEX)

setDisplayValuesInHex(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_VALUES_IN_HEX)

setDocument(SyntaxDocument) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the document this text area is editing.

setDouble(int, double) –
Method in class mars.mips.hardware.Memory

Writes 64 bit double value starting at specified Memory address.

setEditable(boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets if this component is editable.

setEditable(boolean) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setEdited(boolean) –
Static method in class mars.venus.FileStatus

Changes the value of edited to the parameter given.

setEditorFont(Font) –
Method in class mars.Settings

Set editor font to the specified Font object and write it to persistent storage.

setEditorLineNumbersDisplayed(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EDITOR_LINE_NUMBERS_DISPLAYED)

setEditorPopupPrefixLength(int) –
Method in class mars.Settings

Set number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled).

setEditorSyntaxStyleByPosition(int, SyntaxStyle) –
Method in class mars.Settings

 

setEditorTabSize(int) –
Method in class mars.Settings

Set the tab size in characters.

setEditTabbedPane(EditTabbedPane) –
Method in class mars.venus.Editor

Set associated EditTabbedPane.

setElectricScroll(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the number of lines from the top and bottom of the text
area that are always visible

setEnabled(boolean) –
Method in class mars.simulator.BackStepper

Set enable status.

setEnabled(boolean) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setEnabled(boolean) –
Method in class mars.venus.RepeatButton

Sets the enabled state of this button.

setEOLMarkerColor(Color) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Sets the EOL marker color.

setEOLMarkersPainted(boolean) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Sets if EOL markers are to be drawn.

setExample(String) –
Method in class mars.venus.editors.jeditsyntax.PopupHelpItem

 

setExceptionHandler(String) –
Method in class mars.Settings

Set name of exception handler file and write it to persistent storage.

setExceptionHandlerEnabled(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EXCEPTION_HANDLER_ENABLED)

setExtendedAssemblerEnabled(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EXTENDED_ASSEMBLER_ENABLED)

setFile(File) –
Static method in class mars.venus.FileStatus

Sets the file to the ASM file passed.

setFileStatus(int) –
Method in class mars.venus.EditPane

Set the editing status for this EditPane’s associated document.

setFileStatus(int) –
Method in class mars.venus.FileStatus

Set editing status of this file.

setFirstLine(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the line displayed at the text area’s origin and
updates the scroll bars.

setFont(Font) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

 

setFont(Font) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Sets the font for this component.

setFont(Font) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setFontByPosition(int, Font) –
Method in class mars.Settings

Store a Font setting

setFontStyle(int) –
Method in class mars.venus.HardcopyWriter

Set the font style.

setFromLine(int) –
Method in class mars.assembler.Macro

 

setGraphicsFlags(Graphics, Font) –
Method in class mars.venus.editors.jeditsyntax.SyntaxStyle

Sets the foreground color and font of the specified graphics
context to that specified in this style.

setGui(VenusUI) –
Static method in class mars.Globals

 

setHalf(int, int) –
Method in class mars.mips.hardware.Memory

Starting at the given halfword address, write the lower 16 bits of given value
into 2 bytes (a halfword).

setHorizontalOffset(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the horizontal offset of drawn lines.

setIgnoreCase(boolean) –
Method in class mars.venus.editors.jeditsyntax.KeywordMap

Sets if the keyword map should be case insensitive.

setInitialDelay(int) –
Method in class mars.venus.RepeatButton

Sets the initial delay for the timer of this button.

setInputHandler(InputHandler) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the input handler.

setInvalidLinesPainted(boolean) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Sets if invalid lines are to be painted as red tildes.

setLabelSortState(String) –
Method in class mars.Settings

Store the current state of the Labels Window sorter.

setLabelWindowVisibility(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.LABEL_WINDOW_VISIBILITY)

setLabelWindowVisibility(boolean) –
Method in class mars.venus.ExecutePane

Show or hide the label window (symbol table).

setLineHighlightColor(Color) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Sets the line highlight color.

setLineHighlightEnabled(boolean) –
Method in class mars.venus.editors.generic.GenericTextArea

Does nothing, but required by the interface.

setLineHighlightEnabled(boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Use for highlighting the line currently being edited.

setLineHighlightEnabled(boolean) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Enables or disables current line highlighting.

setLineHighlightEnabled(boolean) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setLocalMacroPool(MacroPool) –
Method in class mars.MIPSprogram

Sets local macro pool MacroPool for this program

setMachineStatement(String) –
Method in class mars.ProgramStatement

Assigns given String to be binary machine code (32 characters, all of them 0 or 1)
equivalent to this source line.

setMacroRecorder(InputHandler.MacroRecorder) –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Sets the macro recorder.

setMagicCaretPosition(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the `magic’ caret position.

setMemoryConfiguration(String) –
Method in class mars.Settings

Store the identifier of the memory configuration.

setName(String) –
Method in class mars.assembler.Macro

 

setName(String) –
Static method in class mars.venus.FileStatus

Changes the value of name to the parameter given.

setNumber(int) –
Method in class mars.mips.instructions.syscalls.AbstractSyscall

Set the service number.

setNumber(int) –
Method in interface mars.mips.instructions.syscalls.Syscall

Set the service number.

setOrigin(int, int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

A fast way of changing both the first line and horizontal
offset.

setOriginal(MIPSprogram, int) –
Method in class mars.assembler.Token

Set original program and line number for this token.

setOriginalFromLine(int) –
Method in class mars.assembler.Macro

 

setOriginalToLine(int) –
Method in class mars.assembler.Macro

 

setOverwriteEnabled(boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets if overwrite mode should be enabled.

setPathname(String) –
Method in class mars.venus.EditPane

Delegates to corresponding FileStatus method

setPathname(String) –
Method in class mars.venus.FileStatus

Set full file pathname.

setPathname(String, String) –
Method in class mars.venus.FileStatus

Set full file pathname.

setProcessedLine(String) –
Method in class mars.assembler.TokenList

Use this to record the source line String for this token list
after possible modification (textual substitution) during
assembly preprocessing.

setProgram(MIPSprogram) –
Method in class mars.assembler.Macro

 

setProgramArguments(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.PROGRAM_ARGUMENTS)

setProgramCounter(int) –
Static method in class mars.mips.hardware.RegisterFile

For setting the Program Counter.

setRawWord(int, int) –
Method in class mars.mips.hardware.Memory

Starting at the given word address, write the given value over 4 bytes (a word).

setRegisterPairToDouble(int, double) –
Static method in class mars.mips.hardware.Coprocessor1

Sets the value of the FPU register given to the double value given.

setRegisterPairToDouble(String, double) –
Static method in class mars.mips.hardware.Coprocessor1

Sets the value of the FPU register given to the double value given.

setRegisterPairToLong(int, long) –
Static method in class mars.mips.hardware.Coprocessor1

Sets the value of the FPU register pair given to the long value containing 64 bit pattern
given.

setRegisterPairToLong(String, long) –
Static method in class mars.mips.hardware.Coprocessor1

Sets the value of the FPU register pair given to the long value containing 64 bit pattern
given.

setRegisters(int) –
Static method in class mars.simulator.Exceptions

Given MIPS exception cause code, will place that code into
coprocessor 0 CAUSE register ($13), set the EPC register to
“current” program counter, and set Exception Level bit in STATUS register.

setRegisters(int, int) –
Static method in class mars.simulator.Exceptions

Given MIPS exception cause code and bad address, place the bad address into VADDR
register ($8) then call overloaded setRegisters with the cause code to do the rest.

setRegistersHighlighting(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.REGISTERS_HIGHLIGHTING)

setRegisterToFloat(String, float) –
Static method in class mars.mips.hardware.Coprocessor1

Sets the value of the FPU register given to the value given.

setRegisterToFloat(int, float) –
Static method in class mars.mips.hardware.Coprocessor1

Sets the value of the FPU register given to the value given.

setRegisterToInt(String, int) –
Static method in class mars.mips.hardware.Coprocessor1

Sets the value of the FPU register given to the 32-bit
pattern given by the int parameter.

setRegisterToInt(int, int) –
Static method in class mars.mips.hardware.Coprocessor1

Sets the value of the FPU register given to the 32-bit
pattern given by the int parameter.

setRepeatCount(int) –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Sets the number of times the next action will be repeated.

setRepeatEnabled(boolean) –
Method in class mars.venus.editors.jeditsyntax.InputHandler

Enables repeating.

setRepeatEnabled(boolean) –
Method in class mars.venus.RepeatButton

Sets if the button should fire events when held.

setReset(boolean) –
Static method in class mars.venus.VenusUI

To set whether the register values are reset.

setRightClickPopup(JPopupMenu) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the right click popup menu.

setSaved(boolean) –
Static method in class mars.venus.FileStatus

Changes the value of saved to the parameter given.

setSelectedText(String) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Replaces the selection with the specified text.

setSelectionColor(Color) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Sets the selection color.

setSelectionEnd(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the selection end.

setSelectionEnd(int) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setSelectionRectangular(boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets if the selection should be rectangular.

setSelectionStart(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the selection start.

setSelectionStart(int) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setSelectionVisible(boolean) –
Method in class mars.venus.editors.generic.GenericTextArea

Control selection visibility

setSelectionVisible(boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

 

setSelectionVisible(boolean) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setSettingsMenuItem(JCheckBoxMenuItem) –
Method in class mars.venus.NumberDisplayBaseChooser

Set the menu item from Settings menu that corresponds to this chooser.

setShowLineNumbersEnabled(boolean) –
Method in class mars.venus.EditPane

enable or disable checkbox that controls display of line numbers

setSource(String) –
Method in class mars.ProgramStatement

associates MIPS source statement.

setSourceCode(String, boolean) –
Method in class mars.venus.editors.generic.GenericTextArea

For initalizing the source code when opening an ASM file

setSourceCode(String, boolean) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

 

setSourceCode(String, boolean) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setSourceCode(String, boolean) –
Method in class mars.venus.EditPane

For initalizing the source code when opening an ASM file

setSourceLineList(ArrayList) –
Method in class mars.MIPSprogram

Set list of source statements that comprise the program.

setStartAtMain(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.START_AT_MAIN)

setStarted(boolean) –
Static method in class mars.venus.VenusUI

To set whether MIPS program execution has started.

setStatement(int, ProgramStatement) –
Method in class mars.mips.hardware.Memory

Stores ProgramStatement in Text Segment.

setStyles(SyntaxStyle[]) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Sets the syntax styles used to paint colorized text.

setTabSize(int) –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Set the number of characters a tab will expand to.

setTabSize(int) –
Method in class mars.venus.editors.jeditsyntax.TextAreaPainter

Set the tab size in characters.

setTabSize(int) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setText(String) –
Method in class mars.venus.editors.generic.GenericTextArea

Override inherited setText to temporarily remove UndoableEditListener because this
operation is not undoable.

setText(String) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the entire text of this text area.

setText(String) –
Method in interface mars.venus.editors.MARSTextEditingArea

 

setTextColumnOrder(int[]) –
Method in class mars.Settings

Store the current order of Text Segment window table columns, so the ordering
can be preserved and restored.

Settings – Class in mars
Contains various IDE settings.
Settings() –
Constructor for class mars.Settings

Create Settings object and set to saved values.

Settings(boolean) –
Constructor for class mars.Settings

Create Settings object and set to saved values.

SettingsAddressDisplayBaseAction – Class in mars.venus
Action class for the Settings menu item to control number base (10 or 16) of memory addresses.
SettingsAddressDisplayBaseAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsAddressDisplayBaseAction

 

SettingsAssembleAllAction – Class in mars.venus
Action class for the Settings menu item to determine whether assemble operation applies
only to current file or to all files in its directory.
SettingsAssembleAllAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsAssembleAllAction

 

SettingsAssembleOnOpenAction – Class in mars.venus
Action class for the Settings menu item to control automatic assemble of file upon opening.
SettingsAssembleOnOpenAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsAssembleOnOpenAction

 

SettingsDelayedBranchingAction – Class in mars.venus
Action class for the Settings menu item to control delayed branching.
SettingsDelayedBranchingAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsDelayedBranchingAction

 

SettingsEditorAction – Class in mars.venus
Action class for the Settings menu item for text editor settings.
SettingsEditorAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsEditorAction

Create a new SettingsEditorAction.

SettingsExceptionHandlerAction – Class in mars.venus
Action class for the Settings menu item for optionally loading a MIPS exception handler.
SettingsExceptionHandlerAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsExceptionHandlerAction

 

SettingsExtendedAction – Class in mars.venus
Action class for the Settings menu item to control use of extended (pseudo) instructions or formats.
SettingsExtendedAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsExtendedAction

 

SettingsHighlightingAction – Class in mars.venus
Action class for the Settings menu item for text editor settings.
SettingsHighlightingAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsHighlightingAction

Create a new SettingsEditorAction.

SettingsLabelAction – Class in mars.venus
Action class for the Settings menu item to control display of Labels window (symbol table).
SettingsLabelAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsLabelAction

 

SettingsMemoryConfigurationAction – Class in mars.venus
Action class for the Settings menu item for text editor settings.
SettingsMemoryConfigurationAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsMemoryConfigurationAction

Create a new SettingsEditorAction.

SettingsPopupInputAction – Class in mars.venus
Action class for the Settings menu item to control use of popup dialog for input syscalls.
SettingsPopupInputAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsPopupInputAction

 

SettingsProgramArgumentsAction – Class in mars.venus
Action class for the Settings menu item to control whether or not
program arguments can be entered and used.
SettingsProgramArgumentsAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsProgramArgumentsAction

 

SettingsStartAtMainAction – Class in mars.venus
Action class for the Settings menu item to control whether or not
assembler warnings are considered errors.
SettingsStartAtMainAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsStartAtMainAction

 

SettingsValueDisplayBaseAction – Class in mars.venus
Action class for the Settings menu item to control number base (10 or 16) of memory/register contents.
SettingsValueDisplayBaseAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsValueDisplayBaseAction

 

SettingsWarningsAreErrorsAction – Class in mars.venus
Action class for the Settings menu item to control whether or not
assembler warnings are considered errors.
SettingsWarningsAreErrorsAction(String, Icon, String, Integer, KeyStroke, VenusUI) –
Constructor for class mars.venus.SettingsWarningsAreErrorsAction

 

setTitle(String, String, int) –
Method in class mars.venus.Editor

Places name of file currently being edited into its edit tab and
the application’s title bar.

setTokenMarker(TokenMarker) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Sets the document’s token marker.

setTokenMarker(TokenMarker) –
Method in class mars.venus.editors.jeditsyntax.SyntaxDocument

Sets the token marker that is to be used to split lines of
this document up into tokens.

setToLine(int) –
Method in class mars.assembler.Macro

 

setType(TokenTypes) –
Method in class mars.assembler.Token

Set or modify token type.

setupTable() –
Method in class mars.venus.DataSegmentWindow

Generates and displays fresh table, typically done upon successful assembly.

setupTable() –
Method in class mars.venus.LabelsWindow

Initialize table of labels (symbol table)

setupTable() –
Method in class mars.venus.TextSegmentWindow

Method to be called once the user compiles the program.

setupWindow() –
Method in class mars.venus.Coprocessor0Window

Sets up the data for the window.

setupWindow() –
Method in class mars.venus.Coprocessor1Window

Sets up the data for the window.

setupWindow() –
Method in class mars.venus.RegistersWindow

Sets up the data for the window.

setValue(int) –
Method in class mars.mips.hardware.Register

Sets the value of the register to the val passed to it.

setWarningsAreErrors(boolean) –
Method in class mars.Settings

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.WARNINGS_ARE_ERRORS)

setWindowBounds() –
Method in class mars.venus.ExecutePane

This method will set the bounds of this JDesktopPane’s internal windows
relative to the current size of this JDesktopPane.

setWord(int, int) –
Method in class mars.mips.hardware.Memory

Starting at the given word address, write the given value over 4 bytes (a word).

showingLineNumbers() –
Method in class mars.venus.EditPane

get editor’s line number display status

showRegisters() –
Static method in class mars.mips.hardware.Coprocessor0

Method for displaying the register values for debugging.

showRegisters() –
Static method in class mars.mips.hardware.Coprocessor1

Method for displaying the register values for debugging.

showRegisters() –
Static method in class mars.mips.hardware.RegisterFile

Method for displaying the register values for debugging.

showSplash() –
Method in class mars.MarsSplashScreen

A simple little method to show a title screen in the center
of the screen for the amount of time given in the constructor

simulate(ProgramStatement) –
Method in interface mars.mips.instructions.SimulationCode

Method to simulate the execution of a specific MIPS basic instruction.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.AbstractSyscall

Performs syscall function.

simulate(ProgramStatement) –
Method in interface mars.mips.instructions.syscalls.Syscall

Performs syscall function.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallClose

Performs syscall function to close file descriptor given in $a0.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallConfirmDialog

System call to display a message to user.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallExit

Performs syscall function to exit the MIPS program.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallExit2

Performs syscall function to exit the MIPS program with return value given in $a0.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallInputDialogDouble

System call to input data.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallInputDialogFloat

System call to input data.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallInputDialogInt

System call to input data.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallInputDialogString

System call to input data.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallMessageDialog

System call to display a message to user.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallMessageDialogDouble

System call to display a message to user.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallMessageDialogFloat

System call to display a message to user.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallMessageDialogInt

System call to display a message to user.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallMessageDialogString

System call to display a message to user.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallMidiOut

Performs syscall function to send MIDI output to sound card.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallMidiOutSync

Performs syscall function to send MIDI output to sound card.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallOpen

Performs syscall function to open file name specified by $a0.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallPrintChar

Performs syscall function to print on the console the character stored in $a0.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallPrintDouble

Performs syscall function to print double whose bits are stored in $f12 & $f13.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallPrintFloat

Performs syscall function to display float whose bits are stored in $f12

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallPrintInt

Performs syscall function to print on the console the integer stored in $a0.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallPrintIntBinary

Performs syscall function to print on the console the integer stored in $a0, in hexadecimal format.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallPrintIntHex

Performs syscall function to print on the console the integer stored in $a0, in hexadecimal format.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallPrintIntUnsigned

Performs syscall function to print on the console the integer stored in $a0.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallPrintString

Performs syscall function to print string stored starting at address in $a0.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallRandDouble

System call to the random number generator.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallRandFloat

System call to the random number generator.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallRandInt

System call to the random number generator.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallRandIntRange

System call to the random number generator, with an upper range specified.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallRandSeed

Set the seed of the underlying Java pseudorandom number generator.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallRead

Performs syscall function to read from file descriptor given in $a0.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallReadChar

Performs syscall function to read a character from input console into $a0

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallReadDouble

Performs syscall function to read the bits of input double into $f0 and $f1.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallReadFloat

Performs syscall function to read the bits of input float into $f0

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallReadInt

Performs syscall function to read an integer from input console into $v0

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallReadString

Performs syscall function to read console input string into buffer starting at address in $a0.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallSbrk

Performs syscall function to allocate amount of heap memory specified in $a0, putting address into $v0.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallSleep

System call to cause the MARS Java thread to sleep for (at least) the specified number of milliseconds.

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallTime

Performs syscall function to place current system time into $a0 (low order 32 bits)
and $a1 (high order 32 bits).

simulate(ProgramStatement) –
Method in class mars.mips.instructions.syscalls.SyscallWrite

Performs syscall function to write to file descriptor given in $a0.

simulate(int[]) –
Method in class mars.MIPSprogram

Simulates execution of the MIPS program.

simulate(int) –
Method in class mars.MIPSprogram

Simulates execution of the MIPS program.

simulate(MIPSprogram, int, int, int[], AbstractAction) –
Method in class mars.simulator.Simulator

Simulate execution of given MIPS program.

simulateFromPC(int[], int, AbstractAction) –
Method in class mars.MIPSprogram

Simulates execution of the MIPS program.

simulateStepAtPC(AbstractAction) –
Method in class mars.MIPSprogram

Simulates execution of the MIPS program.

SimulationCode – Interface in mars.mips.instructions
Interface to represent the method for simulating the execution of a specific MIPS basic
instruction.
Simulator – Class in mars.simulator
Used to simulate the execution of an assembled MIPS program.
Simulator.StopListener – Interface in mars.simulator
 
SIMULATOR_START –
Static variable in class mars.simulator.SimulatorNotice

 

SIMULATOR_STOP –
Static variable in class mars.simulator.SimulatorNotice

 

SimulatorNotice – Class in mars.simulator
Object provided to Observers of the Simulator.
SimulatorNotice(int, int, double, int) –
Constructor for class mars.simulator.SimulatorNotice

Constructor will be called only within this package, so assume
address and length are in valid ranges.

size() –
Method in class mars.assembler.TokenList

Returns number of tokens in list.

sizeIntToSizeString(int) –
Static method in class mars.util.EditorFont

Given an int representing font size, returns corresponding string.

sizeStringToSizeInt(String) –
Static method in class mars.util.EditorFont

Given a String representing font size, returns corresponding int.

SMART_HOME_END_PROPERTY –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

If this client property is set to Boolean.TRUE on the text area,
the home/end keys will support ‘smart’ BRIEF-like behaviour
(one press = start/end of line, two presses = start/end of
viewscreen, three presses = start/end of document).

SourceLine – Class in mars.assembler
Handy class to represent, for a given line of source code, the code
itself, the program containing it, and its line number within that program.
SourceLine(String, MIPSprogram, int) –
Constructor for class mars.assembler.SourceLine

SourceLine constructor

SPACE –
Static variable in class mars.assembler.Directives

 

STACK_POINTER_REGISTER –
Static variable in class mars.mips.hardware.RegisterFile

 

stackBaseAddress –
Static variable in class mars.mips.hardware.Memory

base address for stack: 0x7ffffffc (this is mine – start of highest word below kernel space)

stackLimitAddress –
Static variable in class mars.mips.hardware.Memory

 

stackPointer –
Static variable in class mars.mips.hardware.Memory

starting address for stack: 0x7fffeffc (this is from SPIM not MIPS)

start() –
Method in class mars.simulator.SwingWorker

Start the worker thread.

START_AT_MAIN –
Static variable in class mars.Settings

Flag to control whether or not assembler automatically initializes program counter to ‘main’s address

STATUS –
Static variable in class mars.mips.hardware.Coprocessor0

 

stepped(boolean, int, ProcessingException) –
Method in class mars.venus.RunStepAction

 

stopExecution(AbstractAction) –
Method in class mars.simulator.Simulator

Set the volatile stop boolean variable checked by the execution
thread at the end of each MIPS instruction execution.

stopped(Simulator) –
Method in interface mars.simulator.Simulator.StopListener

 

stopped(ProcessingException, int) –
Method in class mars.venus.RunGoAction

Method to be called when Stop is selected through menu/toolbar/shortcut.

storeProgramArguments() –
Method in class mars.simulator.ProgramArgumentList

 

stringToInt(String) –
Static method in class mars.util.Binary

Attempt to validate given string whose characters represent a 32 bit integer.

stringToLong(String) –
Static method in class mars.util.Binary

Attempt to validate given string whose characters represent a 64 bit long.

styleIntToStyleString(int) –
Static method in class mars.util.EditorFont

Given an int that represents a font style from the Font class,
returns the corresponding String.

styles –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

styles –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

styleStringToStyleInt(String) –
Static method in class mars.util.EditorFont

Given a string that represents a font style, returns the
corresponding final int defined in Font: PLAIN, BOLD, ITALIC.

substituteSpacesForTabs(String) –
Static method in class mars.util.EditorFont

 

substituteSpacesForTabs(String, int) –
Static method in class mars.util.EditorFont

Handy utility to produce a string that substitutes spaces for all tab characters
in the given string.

supportsMultilineTokens() –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Returns if the token marker supports tokens that span multiple
lines.

SwingWorker – Class in mars.simulator
This is the 3rd version of SwingWorker (also known as
SwingWorker 3), an abstract class that you subclass to
perform GUI-related work in a dedicated thread.
SwingWorker(boolean) –
Constructor for class mars.simulator.SwingWorker

Start a thread that will call the construct method
and then exit.

SwitchSegment(Graphics, char) –
Method in class mars.tools.DigitalLabSim.SevenSegmentDisplay

 

Symbol – Class in mars.assembler
Represents a MIPS program identifier to be stored in the symbol table.
Symbol(String, int, boolean) –
Constructor for class mars.assembler.Symbol

Basic constructor, creates a symbol object.

SymbolTable – Class in mars.assembler
Creats a table of Symbol objects.
SymbolTable(String) –
Constructor for class mars.assembler.SymbolTable

Create a new empty symbol table for given file

symbolTable –
Static variable in class mars.Globals

Symbol table for file currently being assembled.

SyntaxDocument – Class in mars.venus.editors.jeditsyntax
A document implementation that can be tokenized by the syntax highlighting
system.
SyntaxDocument() –
Constructor for class mars.venus.editors.jeditsyntax.SyntaxDocument

 

SyntaxStyle – Class in mars.venus.editors.jeditsyntax
A simple text style class.
SyntaxStyle(Color, boolean, boolean) –
Constructor for class mars.venus.editors.jeditsyntax.SyntaxStyle

Creates a new SyntaxStyle.

SyntaxUtilities – Class in mars.venus.editors.jeditsyntax
Class with several utility functions used by jEdit’s syntax colorizing
subsystem.
Syscall – Interface in mars.mips.instructions.syscalls
Interface for any MIPS syscall system service.
SYSCALL_BUFSIZE –
Static variable in class mars.util.SystemIO

Buffer size for syscalls for file I/O

SYSCALL_EXCEPTION –
Static variable in class mars.simulator.Exceptions

 

SYSCALL_MAXFILES –
Static variable in class mars.util.SystemIO

Maximum number of files that can be open

SyscallClose – Class in mars.mips.instructions.syscalls
Service to close file descriptor given in $a0.
SyscallClose() –
Constructor for class mars.mips.instructions.syscalls.SyscallClose

Build an instance of the Close syscall.

SyscallConfirmDialog – Class in mars.mips.instructions.syscalls
Service to display a message to user.
SyscallConfirmDialog() –
Constructor for class mars.mips.instructions.syscalls.SyscallConfirmDialog

Build an instance of the syscall with its default service number and name.

SyscallExit – Class in mars.mips.instructions.syscalls
Service to exit the MIPS program.
SyscallExit() –
Constructor for class mars.mips.instructions.syscalls.SyscallExit

Build an instance of the Exit syscall.

SyscallExit2 – Class in mars.mips.instructions.syscalls
Service to exit the MIPS program with return value given in $a0.
SyscallExit2() –
Constructor for class mars.mips.instructions.syscalls.SyscallExit2

Build an instance of the Exit2 syscall.

SyscallInputDialogDouble – Class in mars.mips.instructions.syscalls
Service to input data.
SyscallInputDialogDouble() –
Constructor for class mars.mips.instructions.syscalls.SyscallInputDialogDouble

Build an instance of the syscall with its default service number and name.

SyscallInputDialogFloat – Class in mars.mips.instructions.syscalls
Service to input data.
SyscallInputDialogFloat() –
Constructor for class mars.mips.instructions.syscalls.SyscallInputDialogFloat

Build an instance of the syscall with its default service number and name.

SyscallInputDialogInt – Class in mars.mips.instructions.syscalls
Service to input data.
SyscallInputDialogInt() –
Constructor for class mars.mips.instructions.syscalls.SyscallInputDialogInt

Build an instance of the syscall with its default service number and name.

SyscallInputDialogString – Class in mars.mips.instructions.syscalls
Service to input data.
SyscallInputDialogString() –
Constructor for class mars.mips.instructions.syscalls.SyscallInputDialogString

Build an instance of the syscall with its default service number and name.

SyscallMessageDialog – Class in mars.mips.instructions.syscalls
Service to display a message to user.
SyscallMessageDialog() –
Constructor for class mars.mips.instructions.syscalls.SyscallMessageDialog

Build an instance of the syscall with its default service number and name.

SyscallMessageDialogDouble – Class in mars.mips.instructions.syscalls
Service to display a message to user.
SyscallMessageDialogDouble() –
Constructor for class mars.mips.instructions.syscalls.SyscallMessageDialogDouble

Build an instance of the syscall with its default service number and name.

SyscallMessageDialogFloat – Class in mars.mips.instructions.syscalls
Service to display a message to user.
SyscallMessageDialogFloat() –
Constructor for class mars.mips.instructions.syscalls.SyscallMessageDialogFloat

Build an instance of the syscall with its default service number and name.

SyscallMessageDialogInt – Class in mars.mips.instructions.syscalls
Service to display a message to user.
SyscallMessageDialogInt() –
Constructor for class mars.mips.instructions.syscalls.SyscallMessageDialogInt

Build an instance of the syscall with its default service number and name.

SyscallMessageDialogString – Class in mars.mips.instructions.syscalls
Service to display a message to user.
SyscallMessageDialogString() –
Constructor for class mars.mips.instructions.syscalls.SyscallMessageDialogString

Build an instance of the syscall with its default service number and name.

SyscallMidiOut – Class in mars.mips.instructions.syscalls
Service to output simulated MIDI tone to sound card.
SyscallMidiOut() –
Constructor for class mars.mips.instructions.syscalls.SyscallMidiOut

Build an instance of the MIDI (simulated) out syscall.

SyscallMidiOutSync – Class in mars.mips.instructions.syscalls
Service to output simulated MIDI tone to sound card.
SyscallMidiOutSync() –
Constructor for class mars.mips.instructions.syscalls.SyscallMidiOutSync

Build an instance of the MIDI (simulated) out syscall.

SyscallNumberOverride – Class in mars.mips.instructions.syscalls
Represents User override of default syscall number assignment.
SyscallNumberOverride(String, String) –
Constructor for class mars.mips.instructions.syscalls.SyscallNumberOverride

Constructor is called with two strings: service name and desired
number.

SyscallOpen – Class in mars.mips.instructions.syscalls
Service to open file name specified by $a0.
SyscallOpen() –
Constructor for class mars.mips.instructions.syscalls.SyscallOpen

Build an instance of the Open file syscall.

SyscallPrintChar – Class in mars.mips.instructions.syscalls
Service to display character stored in $a0 on the console.
SyscallPrintChar() –
Constructor for class mars.mips.instructions.syscalls.SyscallPrintChar

Build an instance of the Print Char syscall.

SyscallPrintDouble – Class in mars.mips.instructions.syscalls
Service to display double whose bits are stored in $f12 & $f13 onto the console.
SyscallPrintDouble() –
Constructor for class mars.mips.instructions.syscalls.SyscallPrintDouble

Build an instance of the Print Double syscall.

SyscallPrintFloat – Class in mars.mips.instructions.syscalls
Service to display on the console float whose bits are stored in $f12
SyscallPrintFloat() –
Constructor for class mars.mips.instructions.syscalls.SyscallPrintFloat

Build an instance of the Print Float syscall.

SyscallPrintInt – Class in mars.mips.instructions.syscalls
Service to display integer stored in $a0 on the console.
SyscallPrintInt() –
Constructor for class mars.mips.instructions.syscalls.SyscallPrintInt

Build an instance of the Print Integer syscall.

SyscallPrintIntBinary – Class in mars.mips.instructions.syscalls
Service to display integer stored in $a0 on the console.
SyscallPrintIntBinary() –
Constructor for class mars.mips.instructions.syscalls.SyscallPrintIntBinary

Build an instance of the Print Integer syscall.

SyscallPrintIntHex – Class in mars.mips.instructions.syscalls
Service to display integer stored in $a0 on the console.
SyscallPrintIntHex() –
Constructor for class mars.mips.instructions.syscalls.SyscallPrintIntHex

Build an instance of the Print Integer syscall.

SyscallPrintIntUnsigned – Class in mars.mips.instructions.syscalls
Service to display integer stored in $a0 on the console as unsigned decimal.
SyscallPrintIntUnsigned() –
Constructor for class mars.mips.instructions.syscalls.SyscallPrintIntUnsigned

Build an instance of the Print Integer Unsigned syscall.

SyscallPrintString – Class in mars.mips.instructions.syscalls
Service to display string stored starting at address in $a0 onto the console.
SyscallPrintString() –
Constructor for class mars.mips.instructions.syscalls.SyscallPrintString

Build an instance of the Print String syscall.

SyscallRandDouble – Class in mars.mips.instructions.syscalls
Service to return a random floating point value.
SyscallRandDouble() –
Constructor for class mars.mips.instructions.syscalls.SyscallRandDouble

Build an instance of the syscall with its default service number and name.

SyscallRandFloat – Class in mars.mips.instructions.syscalls
Service to return a random floating point value.
SyscallRandFloat() –
Constructor for class mars.mips.instructions.syscalls.SyscallRandFloat

Build an instance of the syscall with its default service number and name.

SyscallRandInt – Class in mars.mips.instructions.syscalls
Service to return a random integer.
SyscallRandInt() –
Constructor for class mars.mips.instructions.syscalls.SyscallRandInt

Build an instance of the syscall with its default service number and name.

SyscallRandIntRange – Class in mars.mips.instructions.syscalls
Service to return a random integer in a specified range.
SyscallRandIntRange() –
Constructor for class mars.mips.instructions.syscalls.SyscallRandIntRange

Build an instance of the syscall with its default service number and name.

SyscallRandSeed – Class in mars.mips.instructions.syscalls
Service to set seed for the underlying Java pseudorandom number generator.
SyscallRandSeed() –
Constructor for class mars.mips.instructions.syscalls.SyscallRandSeed

Build an instance of the syscall with its default service number and name.

SyscallRead – Class in mars.mips.instructions.syscalls
Service to read from file descriptor given in $a0.
SyscallRead() –
Constructor for class mars.mips.instructions.syscalls.SyscallRead

Build an instance of the Read file syscall.

SyscallReadChar – Class in mars.mips.instructions.syscalls
Service to read a character from input console into $a0.
SyscallReadChar() –
Constructor for class mars.mips.instructions.syscalls.SyscallReadChar

Build an instance of the Read Char syscall.

SyscallReadDouble – Class in mars.mips.instructions.syscalls
Service to read the bits of console input double into $f0 and $f1.
SyscallReadDouble() –
Constructor for class mars.mips.instructions.syscalls.SyscallReadDouble

Build an instance of the Read Double syscall.

SyscallReadFloat – Class in mars.mips.instructions.syscalls
Service to read the bits of input float into $f0
SyscallReadFloat() –
Constructor for class mars.mips.instructions.syscalls.SyscallReadFloat

Build an instance of the Read Float syscall.

SyscallReadInt – Class in mars.mips.instructions.syscalls
Service to read an integer from input console into $v0.
SyscallReadInt() –
Constructor for class mars.mips.instructions.syscalls.SyscallReadInt

Build an instance of the Read Integer syscall.

SyscallReadString – Class in mars.mips.instructions.syscalls
Service to read console input string into buffer starting at address in $a0.
SyscallReadString() –
Constructor for class mars.mips.instructions.syscalls.SyscallReadString

Build an instance of the Read String syscall.

SyscallSbrk – Class in mars.mips.instructions.syscalls
Service to allocate amount of heap memory specified in $a0, putting address into $v0.
SyscallSbrk() –
Constructor for class mars.mips.instructions.syscalls.SyscallSbrk

Build an instance of the Sbrk syscall.

SyscallSleep – Class in mars.mips.instructions.syscalls
Service to cause the MARS Java thread to sleep for (at least) the specified number of milliseconds.
SyscallSleep() –
Constructor for class mars.mips.instructions.syscalls.SyscallSleep

Build an instance of the syscall with its default service number and name.

SyscallTime – Class in mars.mips.instructions.syscalls
Service to read a character from input console into $a0.
SyscallTime() –
Constructor for class mars.mips.instructions.syscalls.SyscallTime

Build an instance of the Read Char syscall.

SyscallWrite – Class in mars.mips.instructions.syscalls
Service to write to file descriptor given in $a0.
SyscallWrite() –
Constructor for class mars.mips.instructions.syscalls.SyscallWrite

Build an instance of the Write file syscall.

SystemIO – Class in mars.util
Provides standard i/o services needed to simulate the MIPS syscall
routines.
SystemIO() –
Constructor for class mars.util.SystemIO

 

T

tableChanged(TableModelEvent) –
Method in class mars.venus.RunClearBreakpointsAction

Required TableModelListener method.

tabSize –
Variable in class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

tabSize –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

tabSizeChars –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

tellEditingComponentToRequestFocusInWindow() –
Method in class mars.venus.EditPane

Delegates to text area’s requestFocusInWindow method.

TERMINATED –
Static variable in class mars.venus.FileStatus

execution terminated

TEXT –
Static variable in class mars.assembler.Directives

 

TEXT_COLUMN_ORDER –
Static variable in class mars.Settings

Order of text segment table columns

TEXT_FOUND –
Static variable in interface mars.venus.editors.MARSTextEditingArea

 

TEXT_NOT_FOUND –
Static variable in interface mars.venus.editors.MARSTextEditingArea

 

TEXT_REPLACED_FOUND_NEXT –
Static variable in interface mars.venus.editors.MARSTextEditingArea

 

TEXT_REPLACED_NOT_FOUND_NEXT –
Static variable in interface mars.venus.editors.MARSTextEditingArea

 

TEXT_SYMBOL –
Static variable in class mars.assembler.Symbol

 

textArea –
Variable in class mars.venus.editors.jeditsyntax.TextAreaPainter

 

TextAreaDefaults – Class in mars.venus.editors.jeditsyntax
Encapsulates default settings for a text area.
TextAreaDefaults() –
Constructor for class mars.venus.editors.jeditsyntax.TextAreaDefaults

 

TextAreaPainter – Class in mars.venus.editors.jeditsyntax
The text area repaint manager.
TextAreaPainter(JEditTextArea, TextAreaDefaults) –
Constructor for class mars.venus.editors.jeditsyntax.TextAreaPainter

Creates a new repaint manager.

TextAreaPainter.Highlight – Interface in mars.venus.editors.jeditsyntax
Highlight interface.
textBaseAddress –
Static variable in class mars.mips.hardware.Memory

base address for (user) text segment: 0x00400000

textLimitAddress –
Static variable in class mars.mips.hardware.Memory

 

TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_BACKGROUND –
Static variable in class mars.Settings

RGB color for text segment delay slot highlighted background

TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FONT –
Static variable in class mars.Settings

Font for text segment delay slot highlighted background

TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FOREGROUND –
Static variable in class mars.Settings

RGB color for text segment delay slot highlighted foreground

TEXTSEGMENT_HIGHLIGHT_BACKGROUND –
Static variable in class mars.Settings

RGB color for text segment highlighted background

TEXTSEGMENT_HIGHLIGHT_FONT –
Static variable in class mars.Settings

Font for table odd row foreground (text, data, register displays)

TEXTSEGMENT_HIGHLIGHT_FOREGROUND –
Static variable in class mars.Settings

RGB color for text segment highlighted foreground

TextSegmentWindow – Class in mars.venus
Creates the Text Segment window in the Execute tab of the UI
TextSegmentWindow() –
Constructor for class mars.venus.TextSegmentWindow

Constructor, sets up a new JInternalFrame.

TextUtilities – Class in mars.venus.editors.jeditsyntax
Class with several utility functions used by the text area component.
TextUtilities() –
Constructor for class mars.venus.editors.jeditsyntax.TextUtilities

 

theWindow –
Variable in class mars.tools.AbstractMarsToolAndApplication

 

thisMarsApp –
Variable in class mars.tools.AbstractMarsToolAndApplication

 

time –
Variable in class mars.venus.HardcopyWriter

 

TOGGLE_RECT –
Static variable in class mars.venus.editors.jeditsyntax.InputHandler

 

toggleBreakpoints() –
Method in class mars.venus.TextSegmentWindow

Enable or disable all items in the Breakpoints column.

Token – Class in mars.assembler
Represents one token in the input MIPS program.
Token(TokenTypes, String, MIPSprogram, int, int) –
Constructor for class mars.assembler.Token

Constructor for Token class.

Token – Class in mars.venus.editors.jeditsyntax.tokenmarker
A linked list of tokens.
Token(int, byte) –
Constructor for class mars.venus.editors.jeditsyntax.tokenmarker.Token

Creates a new token.

token –
Variable in class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker.LineInfo

The id of the last token of the line.

TOKEN_DELIMITERS –
Static variable in class mars.assembler.TokenTypes

 

tokenIsMacroParameter(String, boolean) –
Static method in class mars.assembler.Macro

returns whether tokenValue is macro parameter or not

tokenize(MIPSprogram) –
Method in class mars.assembler.Tokenizer

Will tokenize a complete MIPS program.

tokenize() –
Method in class mars.MIPSprogram

Tokenizes the MIPS source program.

tokenizeExampleInstruction(String) –
Method in class mars.assembler.Tokenizer

Used only to create a token list for the example provided with each instruction
specification.

tokenizeLine(int, String) –
Method in class mars.assembler.Tokenizer

Will tokenize one line of source code.

tokenizeLine(MIPSprogram, int, String) –
Method in class mars.assembler.Tokenizer

 

tokenizeLine(int, String, ErrorList) –
Method in class mars.assembler.Tokenizer

Will tokenize one line of source code.

tokenizeLines() –
Method in class mars.venus.editors.jeditsyntax.SyntaxDocument

Reparses the document, by passing all lines to the token
marker.

tokenizeLines(int, int) –
Method in class mars.venus.editors.jeditsyntax.SyntaxDocument

Reparses the document, by passing the specified lines to the
token marker.

Tokenizer – Class in mars.assembler
A tokenizer is capable of tokenizing a complete MIPS program, or a given line from
a MIPS program.
Tokenizer() –
Constructor for class mars.assembler.Tokenizer

Simple constructor.

Tokenizer(MIPSprogram) –
Constructor for class mars.assembler.Tokenizer

Constructor for use with existing MIPSprogram.

TokenList – Class in mars.assembler
Represents the list of tokens in a single line of MIPS code.
TokenList() –
Constructor for class mars.assembler.TokenList

Constructor for objects of class TokenList

tokenList –
Variable in class mars.mips.instructions.Instruction

List of tokens generated by tokenizing example usage (see exampleFormat).

tokenMarker –
Variable in class mars.venus.editors.jeditsyntax.SyntaxDocument

 

TokenMarker – Class in mars.venus.editors.jeditsyntax.tokenmarker
A token marker that splits lines of text into tokens.
TokenMarker() –
Constructor for class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Creates a new TokenMarker.

TokenMarker.LineInfo – Class in mars.venus.editors.jeditsyntax.tokenmarker
Inner class for storing information about tokenized lines.
TokenMarker.LineInfo() –
Constructor for class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker.LineInfo

Creates a new LineInfo object with token = Token.NULL
and obj = null.

TokenMarker.LineInfo(byte, Object) –
Constructor for class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker.LineInfo

Creates a new LineInfo object with the specified
parameters.

TokenTypes – Class in mars.assembler
Constants to identify the types of tokens found in MIPS programs.
ToolAction – Class in mars.venus
Connects a MarsTool class (class that implements MarsTool interface) to
the Mars menu system by supplying the response to that tool’s menu item
selection.
ToolAction(Class, String) –
Constructor for class mars.venus.ToolAction

Simple constructor.

ToolLoader – Class in mars.venus
This class provides functionality to bring external Mars tools into the Mars
system by adding them to its Tools menu.
ToolLoader() –
Constructor for class mars.venus.ToolLoader

 

toString() –
Method in class mars.assembler.Directives

Produces String-ified version of Directive object

toString() –
Method in class mars.assembler.Token

Get a String representing the token.

toString() –
Method in class mars.assembler.TokenList

Get a String representing the token list.

toString() –
Method in class mars.assembler.TokenTypes

Produces String equivalent of this token type, which is its name.

toString() –
Method in class mars.mips.dump.AbstractDumpFormat

String representing this object.

toString() –
Method in interface mars.mips.dump.DumpFormat

Descriptive name for the format.

toString() –
Method in class mars.mips.hardware.MemoryAccessNotice

String representation indicates access type, address and length in bytes

toString() –
Method in class mars.mips.hardware.RegisterAccessNotice

String representation indicates access type and which register

toString() –
Method in class mars.ProgramStatement

Crude attempt at building String representation of this complex structure.

toString() –
Method in class mars.simulator.SimulatorNotice

String representation indicates access type, address and length in bytes

toString() –
Method in class mars.venus.editors.jeditsyntax.SyntaxStyle

Returns a string representation of this object.

toString() –
Method in class mars.venus.editors.jeditsyntax.tokenmarker.Token

Returns a string representation of this token.

toTypeString() –
Method in class mars.assembler.TokenList

Get a String representing the sequence of token types for this list.

translate() –
Method in interface mars.assembler.TranslationCode

This is a callback method defined in anonymous class specified as
argument to ExtendedInstruction constructor.

TranslationCode – Interface in mars.assembler
This interface is intended for use by ExtendedInstruction objects to define, using
the translate() method, how to translate the extended (pseudo) instruction into
a sequence of one or more basic instructions, which can then be translated into
binary machine code.
TRANSMITTER_CONTROL –
Static variable in class mars.tools.KeyboardAndDisplaySimulator

 

TRANSMITTER_DATA –
Static variable in class mars.tools.KeyboardAndDisplaySimulator

 

TRAP_EXCEPTION –
Static variable in class mars.simulator.Exceptions

 

twoIntsToLong(int, int) –
Static method in class mars.util.Binary

Returns long (64 bit integer) combining the bit values of two given 32 bit
integer values.

U

undo() –
Method in class mars.venus.editors.generic.GenericTextArea

Undo previous edit

undo() –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Undo previous edit

undo() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

undo() –
Method in class mars.venus.EditPane

Undo previous edit

unhighlightAllSteps() –
Method in class mars.venus.TextSegmentWindow

If any steps are highlighted, this erases the highlighting.

UNLIMITED_SPEED –
Static variable in class mars.venus.RunSpeedPanel

Constant that represents unlimited run speed.

unredoing –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

unsignedIntToIntString(int) –
Static method in class mars.util.Binary

Produce String equivalent of integer value interpreting it as an unsigned integer.

update(Observable, Object) –
Method in class mars.tools.AbstractMarsToolAndApplication

Called when receiving notice of access to MIPS memory or registers.

update(Observable, Object) –
Method in class mars.tools.DigitalLabSim

 

update(Observable, Object) –
Method in class mars.tools.FloatRepresentation

Override inherited update() to update display when “attached” register is modified
either by MIPS program or by user editing it on the MARS user interface.

update(Observable, Object) –
Method in class mars.tools.MarsBot

 

update(Observable, Object) –
Method in class mars.tools.ScavengerHunt

 

update(Observable, Object) –
Method in class mars.venus.Coprocessor0Window

Required by Observer interface.

update(Observable, Object) –
Method in class mars.venus.Coprocessor1Window

Required by Observer interface.

update(Observable, Object) –
Method in class mars.venus.DataSegmentWindow

Required by Observer interface.

update(Observable, Object) –
Method in class mars.venus.EditPane

Update, if source code is visible, when Font setting changes.

update(Observable, Object) –
Method in class mars.venus.RegistersWindow

Required by Observer interface.

updateBaseAddressComboBox() –
Method in class mars.venus.DataSegmentWindow

 

updateBasicStatements() –
Method in class mars.venus.TextSegmentWindow

Redisplay the basic statements.

updateBracketHighlight(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

 

updateCell(int, int) –
Method in class mars.venus.DataSegmentWindow

Update data display to show this value (I’m not sure it is being called).

updateCodeAddresses() –
Method in class mars.venus.TextSegmentWindow

Redisplay the addresses.

updateDataAddresses() –
Method in class mars.venus.DataSegmentWindow

Redisplay the addresses.

updateDisplay() –
Method in class mars.tools.AbstractMarsToolAndApplication

Override this method to implement updating of GUI after each MIPS instruction is executed,
while running in “timed” mode (user specifies execution speed on the slider control).

updateDisplay() –
Method in class mars.tools.BitmapDisplay

Updates display immediately after each update (AccessNotice) is processed, after
display configuration changes as needed, and after each execution step when Mars
is running in timed mode.

updateDisplay() –
Method in class mars.tools.CacheSimulator

Updates display immediately after each update (AccessNotice) is processed, after
cache configuration changes as needed, and after each execution step when Mars
is running in timed mode.

updateDisplay() –
Method in class mars.tools.InstructionCounter

 

updateDisplay() –
Method in class mars.tools.InstructionStatistics

updates the text fields and progress bars according to the current counter values.

updateDisplay() –
Method in class mars.tools.MemoryReferenceVisualization

Updates display immediately after each update (AccessNotice) is processed, after
display configuration changes as needed, and after each execution step when Mars
is running in timed mode.

updateDoubleRegisterValue(int, int) –
Method in class mars.venus.Coprocessor1Window

This method handles the updating of the GUI.

updateFloatRegisterValue(int, int, int) –
Method in class mars.venus.Coprocessor1Window

This method handles the updating of the GUI.

updateHexaKeyboard(char) –
Method in class mars.tools.DigitalLabSim

 

updateLabelAddresses() –
Method in class mars.venus.LabelsWindow

Method to update display of label addresses.

updateModelForMemoryRange(int) –
Method in class mars.venus.DataSegmentWindow

Update table model with contents of new memory “chunk”.

updateOneSecondCounter(char) –
Method in class mars.tools.DigitalLabSim

 

updatePrediction(boolean) –
Method in class mars.tools.BHTEntry

Updates the entry’s history and prediction.

updatePredictionAtIdx(int, boolean) –
Method in class mars.tools.BHTableModel

Updates the BHT entry with the outcome of the branch instruction.

updateRedoState() –
Method in class mars.venus.EditPane

Update state of Edit menu’s Redo menu item.

updateRegister(String, int) –
Static method in class mars.mips.hardware.Coprocessor0

Sets the value of the register given to the value given.

updateRegister(int, int) –
Static method in class mars.mips.hardware.Coprocessor0

This method updates the register value who’s number is num.

updateRegister(int, int) –
Static method in class mars.mips.hardware.Coprocessor1

This method updates the FPU register value who’s number is num.

updateRegister(int, int) –
Static method in class mars.mips.hardware.RegisterFile

This method updates the register value who’s number is num.

updateRegister(String, int) –
Static method in class mars.mips.hardware.RegisterFile

Sets the value of the register given to the value given.

updateRegisters() –
Method in class mars.venus.Coprocessor0Window

Update register display using current display base (10 or 16)

updateRegisters(int) –
Method in class mars.venus.Coprocessor0Window

Update register display using specified display base

updateRegisters() –
Method in class mars.venus.Coprocessor1Window

Redisplay registers using current display number base (10 or 16)

updateRegisters(int) –
Method in class mars.venus.Coprocessor1Window

Redisplay registers using specified display number base (10 or 16)

updateRegisters() –
Method in class mars.venus.RegistersWindow

update register display using current number base (10 or 16)

updateRegisters(int) –
Method in class mars.venus.RegistersWindow

update register display using specified number base (10 or 16)

updateRegisterValue(int, int, int) –
Method in class mars.venus.Coprocessor0Window

This method handles the updating of the GUI.

updateRegisterValue(int, int, int) –
Method in class mars.venus.RegistersWindow

This method handles the updating of the GUI.

updateScrollBars() –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Updates the state of the scroll bars.

updateSevenSegment(int, char) –
Method in class mars.tools.DigitalLabSim

 

updateStaticFileStatus() –
Method in class mars.venus.EditPane

Delegates to corresponding FileStatus method

updateStaticFileStatus() –
Method in class mars.venus.FileStatus

Update static FileStatus fields with values from this FileStatus object
To support legacy code that depends on the static.

updateSyntaxStyles() –
Method in class mars.venus.editors.generic.GenericTextArea

Does nothing, but required by the interface.

updateSyntaxStyles() –
Method in class mars.venus.editors.jeditsyntax.JEditBasedTextArea

Update the syntax style table, which is obtained from
SyntaxUtilities.

updateSyntaxStyles() –
Method in interface mars.venus.editors.MARSTextEditingArea

 

updateUndoState() –
Method in class mars.venus.EditPane

Update state of Edit menu’s Undo menu item.

updateValues() –
Method in class mars.venus.DataSegmentWindow

Update data display to show all values

userHighAddress –
Static variable in class mars.mips.hardware.Memory

highest address accessible in user (not kernel) mode.

userInputAlert –
Static variable in class mars.Globals

String to GUI’s RunI/O text area when echoing user input from pop-up dialog.

usingCompactMemoryConfiguration() –
Method in class mars.mips.hardware.Memory

Determine whether the current memory configuration has a maximum address that can be stored
in 16 bits.

V

VADDR –
Static variable in class mars.mips.hardware.Coprocessor0

Coprocessor register names

VenusUI – Class in mars.venus
Top level container for Venus GUI.
VenusUI(String) –
Constructor for class mars.venus.VenusUI

Constructor for the Class.

version –
Static variable in class mars.Globals

The current MARS version number.

vertical –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

visibleLines –
Variable in class mars.venus.editors.jeditsyntax.JEditTextArea

 

W

WARNING –
Static variable in class mars.ErrorMessage

Constant to indicate this message is warning not error

WARNING_MESSAGE_PREFIX –
Static variable in class mars.ErrorList

 

warningCount() –
Method in class mars.ErrorList

Count of number of warning messages in list.

WARNINGS_ARE_ERRORS –
Static variable in class mars.Settings

Flag to determine whether or not assembler warnings are considered errors.

warningsOccurred() –
Method in class mars.ErrorList

Determine whether warning has occured or not.

width –
Variable in class mars.venus.HardcopyWriter

 

willBranch(ProgramStatement) –
Static method in class mars.tools.BHTSimulator

Checks if the branch instruction delivered as parameter will branch or not.

WORD –
Static variable in class mars.assembler.Directives

 

WORD_LENGTH_BYTES –
Static variable in class mars.mips.hardware.Memory

MIPS word length in bytes.

WORD_SIZE –
Static variable in class mars.assembler.DataTypes

Number of bytes occupied by MIPS word is 4.

wordAligned(int) –
Static method in class mars.mips.hardware.Memory

Utility to determine if given address is word-aligned.

WRITE –
Static variable in class mars.mips.hardware.AccessNotice

Indicates the purpose of access was to write.

write(char[], int, int) –
Method in class mars.venus.HardcopyWriter

This is the write( ) method of the stream.

writeToFile(int, byte[], int) –
Static method in class mars.util.SystemIO

Write bytes to file.

X

x0 –
Variable in class mars.venus.HardcopyWriter

 

xToOffset(int, int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Converts an x co-ordinate to an offset within a line.

xyToOffset(int, int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Converts a point to an offset, from the start of the text.

Y

y0 –
Variable in class mars.venus.HardcopyWriter

 

yToLine(int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Converts a y co-ordinate to a line index.

_

_offsetToX(int, int) –
Method in class mars.venus.editors.jeditsyntax.JEditTextArea

Converts an offset in a line into an x co-ordinate.

A B C D E F G H I J K L M N O P Q R S T U V W X Y _

Overview  Package  Class  Tree  Deprecated   Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Deprecated List

Overview  Package  Class  Tree   Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Deprecated API

Contents Deprecated Methods

Deprecated Constructors

Deprecated Methods
mars.Settings.getAssembleAllEnabled()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ALL_ENABLED) 
mars.Settings.getAssembleOnOpenEnabled()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ON_OPEN_ENABLED) 
mars.Settings.getBareMachineEnabled()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.BARE_MACHINE_ENABLED) 
mars.Settings.getDataSegmentHighlighting()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DATA_SEGMENT_HIGHLIGHTING) 
mars.Settings.getDelayedBranchingEnabled()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED) 
mars.Settings.getDisplayAddressesInHex()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_ADDRESSES_IN_HEX) 
mars.Settings.getDisplayValuesInHex()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_VALUES_IN_HEX) 
mars.Settings.getEditorLineNumbersDisplayed()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EDITOR_LINE_NUMBERS_DISPLAYED) 
mars.Settings.getExceptionHandlerEnabled()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EXCEPTION_HANDLER_ENABLED) 
mars.Settings.getExtendedAssemblerEnabled()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EXTENDED_ASSEMBLER_ENABLED) 
mars.Settings.getLabelWindowVisibility()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.LABEL_WINDOW_VISIBILITY) 
mars.Settings.getProgramArguments()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.PROGRAM_ARGUMENTS) 
mars.Settings.getRegistersHighlighting()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.REGISTERS_HIGHLIGHTING) 
mars.Settings.getStartAtMain()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.START_AT_MAIN) 
mars.Settings.getWarningsAreErrors()

          Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.WARNINGS_ARE_ERRORS) 
mars.Settings.setAssembleAllEnabled(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ALL_ENABLED) 
mars.Settings.setAssembleOnOpenEnabled(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ON_OPEN_ENABLED) 
mars.Settings.setDataSegmentHighlighting(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DATA_SEGMENT_HIGHLIGHTING) 
mars.Settings.setDelayedBranchingEnabled(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED) 
mars.Settings.setDelayedBranchingEnabledNonPersistent(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED) 
mars.Settings.setDisplayAddressesInHex(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_ADDRESSES_IN_HEX) 
mars.Settings.setDisplayValuesInHex(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_VALUES_IN_HEX) 
mars.Settings.setEditorLineNumbersDisplayed(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EDITOR_LINE_NUMBERS_DISPLAYED) 
mars.Settings.setExceptionHandlerEnabled(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EXCEPTION_HANDLER_ENABLED) 
mars.Settings.setExtendedAssemblerEnabled(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EXTENDED_ASSEMBLER_ENABLED) 
mars.Settings.setLabelWindowVisibility(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.LABEL_WINDOW_VISIBILITY) 
mars.Settings.setProgramArguments(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.PROGRAM_ARGUMENTS) 
mars.Settings.setRegistersHighlighting(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.REGISTERS_HIGHLIGHTING) 
mars.Settings.setStartAtMain(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.START_AT_MAIN) 
mars.Settings.setWarningsAreErrors(boolean)

          Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.WARNINGS_ARE_ERRORS) 

 

Deprecated Constructors
mars.ErrorMessage(boolean, String, int, int, String, String)

          Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information. 
mars.ErrorMessage(String, int, int, String)

          Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information. 
mars.ErrorMessage(String, int, int, String, String)

          Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information. 

 

Overview  Package  Class  Tree   Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Classes 

Mars

/* Javadoc style sheet */

/* Define colors, fonts and other style attributes here to override the defaults */

/* Page background color */
body { background-color: #FFFFFF; color:#000000 }

/* Headings */
h1 { font-size: 145% }

/* Table colors */
.TableHeadingColor { background: #CCCCFF; color:#000000 } /* Dark mauve */
.TableSubHeadingColor { background: #EEEEFF; color:#000000 } /* Light mauve */
.TableRowColor { background: #FFFFFF; color:#000000 } /* White */

/* Font used in left-hand frame lists */
.FrameTitleFont { font-size: 100%; font-family: Helvetica, Arial, sans-serif; color:#000000 }
.FrameHeadingFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 }
.FrameItemFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 }

/* Navigation bar fonts and colors */
.NavBarCell1 { background-color:#EEEEFF; color:#000000} /* Light mauve */
.NavBarCell1Rev { background-color:#00008B; color:#FFFFFF} /* Dark Blue */
.NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;color:#000000;}
.NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;color:#FFFFFF;}

.NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000}
.NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000}

Overview

 Overview  Package  Class  Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Packages
mars  
mars.assembler  
mars.mips.dump  
mars.mips.hardware  
mars.mips.instructions  
mars.mips.instructions.syscalls  
mars.simulator  
mars.tools  
mars.util  
mars.venus  
mars.venus.editors  
mars.venus.editors.generic  
mars.venus.editors.jeditsyntax  
mars.venus.editors.jeditsyntax.tokenmarker  

 

 Overview  Package  Class  Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

API Help

Overview  Package  Class  Tree  Deprecated  Index   Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.
Overview

The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

Package

Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:
Interfaces (italic)
Classes
Enums
Exceptions
Errors
Annotation Types

Class/Interface

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:
Class inheritance diagram
Direct Subclasses
All Known Subinterfaces
All Known Implementing Classes
Class/interface declaration
Class/interface description

Nested Class Summary
Field Summary
Constructor Summary
Method Summary

Field Detail
Constructor Detail
Method Detail

Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

Annotation Type

Each annotation type has its own separate page with the following sections:
Annotation Type declaration
Annotation Type description
Required Element Summary
Optional Element Summary
Element Detail

Enum

Each enum has its own separate page with the following sections:
Enum declaration
Enum description
Enum Constant Summary
Enum Constant Detail

Tree (Class Hierarchy)

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object. When viewing the Overview page, clicking on “Tree” displays the hierarchy for all packages.
When viewing a particular package, class or interface page, clicking “Tree” displays the hierarchy for only that package.

Deprecated API

The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.

Index

The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

Prev/Next

These links take you to the next or previous class, interface, package, or related page.
Frames/No Frames

These links show and hide the HTML frames. All pages are available with or without frames.

Serialized Form

Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking “Serialized Form” in the “See also” section of the class description.

Constant Field Values

The Constant Field Values page lists the static final fields and their values.

This help file applies to API documentation generated using the standard doclet.

Overview  Package  Class  Tree  Deprecated  Index   Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package

Class Summary
Mars Portal to Mars

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

All Classes

All Classes

AbstractDumpFormat

AbstractFontSettingDialog

AbstractMarsToolAndApplication

AbstractSyscall

AccessNotice

AddressErrorException

AsciiTextDumpFormat

Assembler

BackStepper

BasicInstruction

BasicInstructionFormat

BHTableModel

BHTEntry

BHTSimGUI

BHTSimulator

Binary

BinaryDumpFormat

BinaryTextDumpFormat

BitmapDisplay

CacheSimulator

Coprocessor0

Coprocessor0Window

Coprocessor1

Coprocessor1Window

DataSegmentWindow

DataTypes

DefaultInputHandler

DelayedBranch

DigitalLabSim

Directives

DumpFormat

DumpFormatLoader

EditCopyAction

EditCutAction

EditFindReplaceAction

Editor

EditorFont

EditPane

EditPasteAction

EditRedoAction

EditSelectAllAction

EditTabbedPane

EditUndoAction

ErrorList

ErrorMessage

Exceptions

ExecutePane

ExtendedInstruction

FileCloseAction

FileCloseAllAction

FileDumpMemoryAction

FileExitAction

FilenameFinder

FileNewAction

FileOpenAction

FilePrintAction

FileSaveAction

FileSaveAllAction

FileSaveAsAction

FileStatus

FloatRepresentation

GenericTextArea

Globals

GuiAction

HardcopyWriter

HardcopyWriter.PrintCanceledException

HelpAboutAction

HelpHelpAction

HexTextDumpFormat

InputHandler

InputHandler.backspace

InputHandler.backspace_word

InputHandler.clip_copy

InputHandler.clip_cut

InputHandler.clip_paste

InputHandler.delete

InputHandler.delete_word

InputHandler.document_end

InputHandler.document_home

InputHandler.end

InputHandler.home

InputHandler.insert_break

InputHandler.insert_char

InputHandler.insert_tab

InputHandler.MacroRecorder

InputHandler.next_char

InputHandler.next_line

InputHandler.next_page

InputHandler.next_word

InputHandler.NonRecordable

InputHandler.NonRepeatable

InputHandler.overwrite

InputHandler.prev_char

InputHandler.prev_line

InputHandler.prev_page

InputHandler.prev_word

InputHandler.repeat

InputHandler.select_all

InputHandler.toggle_rect

InputHandler.Wrapper

Instruction

InstructionCounter

InstructionSet

InstructionStatistics

IntelHexDumpFormat

IntroToTools

InvalidRegisterAccessException

JEditBasedTextArea

JEditTextArea

KeyboardAndDisplaySimulator

KeywordMap

LabelsWindow

Macro

MacroPool

MainPane

Mars

MarsBot

MarsLaunch

MarsSplashScreen

MARSTextEditingArea

MarsTool

Memory

MemoryAccessNotice

MemoryConfiguration

MemoryConfigurations

MemoryDump

MemoryReferenceVisualization

MessagesPane

MIFDumpFormat

MIPSprogram

MIPSTokenMarker

NumberDisplayBaseChooser

OperandFormat

PopupHelpItem

PopupListener

ProcessingException

ProgramArgumentList

ProgramStatement

PropertiesFile

RandomStreams

Register

RegisterAccessNotice

RegisterFile

RegistersPane

RegistersWindow

RepeatButton

RunAssembleAction

RunBackstepAction

RunClearBreakpointsAction

RunGoAction

RunPauseAction

RunResetAction

RunSpeedPanel

RunStepAction

RunStopAction

RunToggleBreakpointsAction

ScavengerHunt

ScreenMagnifier

SegmentWindowDumpFormat

Settings

SettingsAddressDisplayBaseAction

SettingsAssembleAllAction

SettingsAssembleOnOpenAction

SettingsDelayedBranchingAction

SettingsEditorAction

SettingsExceptionHandlerAction

SettingsExtendedAction

SettingsHighlightingAction

SettingsLabelAction

SettingsMemoryConfigurationAction

SettingsPopupInputAction

SettingsProgramArgumentsAction

SettingsStartAtMainAction

SettingsValueDisplayBaseAction

SettingsWarningsAreErrorsAction

SimulationCode

Simulator

Simulator.StopListener

SimulatorNotice

SourceLine

SwingWorker

Symbol

SymbolTable

SyntaxDocument

SyntaxStyle

SyntaxUtilities

Syscall

SyscallClose

SyscallConfirmDialog

SyscallExit

SyscallExit2

SyscallInputDialogDouble

SyscallInputDialogFloat

SyscallInputDialogInt

SyscallInputDialogString

SyscallMessageDialog

SyscallMessageDialogDouble

SyscallMessageDialogFloat

SyscallMessageDialogInt

SyscallMessageDialogString

SyscallMidiOut

SyscallMidiOutSync

SyscallNumberOverride

SyscallOpen

SyscallPrintChar

SyscallPrintDouble

SyscallPrintFloat

SyscallPrintInt

SyscallPrintIntBinary

SyscallPrintIntHex

SyscallPrintIntUnsigned

SyscallPrintString

SyscallRandDouble

SyscallRandFloat

SyscallRandInt

SyscallRandIntRange

SyscallRandSeed

SyscallRead

SyscallReadChar

SyscallReadDouble

SyscallReadFloat

SyscallReadInt

SyscallReadString

SyscallSbrk

SyscallSleep

SyscallTime

SyscallWrite

SystemIO

TextAreaDefaults

TextAreaPainter

TextAreaPainter.Highlight

TextSegmentWindow

TextUtilities

Token

Token

Tokenizer

TokenList

TokenMarker

TokenTypes

ToolAction

ToolLoader

TranslationCode

VenusUI

mars
mars.assembler
mars.mips.dump
mars.mips.hardware
mars.mips.instructions
mars.mips.instructions.syscalls
mars.simulator
mars.tools
mars.util
mars.venus
mars.venus.editors
mars.venus.editors.generic
mars.venus.editors.jeditsyntax
mars.venus.editors.jeditsyntax.tokenmarker

Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object Mars

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

IntroToTools

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class IntroToTools

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication
mars.tools.IntroToTools

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

public class IntroToTools
extends AbstractMarsToolAndApplication

The “hello world” of MarsTools!

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener

 

Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class mars.tools.AbstractMarsToolAndApplication
connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
IntroToTools()

          Simple constructor, likely used by the MARS Tools menu mechanism
IntroToTools(java.lang.String title,
java.lang.String heading)

          Simple constructor, likely used to run a stand-alone memory reference visualizer.

 

Method Summary

protected  javax.swing.JComponent buildMainDisplayArea()

          Implementation of the inherited abstract method to build the main
display area of the GUI.

 java.lang.String getName()

          Required method to return Tool name.

static void main(java.lang.String[] args)

          Main provided for pure stand-alone use.

 
Methods inherited from class mars.tools.AbstractMarsToolAndApplication
action, addAsObserver, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, deleteAsObserver, getHelpComponent, go, initializePostGUI, initializePreGUI, isObserving, performSpecialClosingDuties, processMIPSUpdate, reset, update, updateDisplay

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Constructor Detail

IntroToTools

public IntroToTools(java.lang.String title,
java.lang.String heading)

Simple constructor, likely used to run a stand-alone memory reference visualizer.

Parameters:
title – String containing title for title bar
heading – String containing text for heading shown in upper part of window.

IntroToTools

public IntroToTools()

Simple constructor, likely used by the MARS Tools menu mechanism

Method Detail

main

public static void main(java.lang.String[] args)

Main provided for pure stand-alone use. Recommended stand-alone use is to write a
driver program that instantiates a MemoryReferenceVisualization object then invokes its go() method.
“stand-alone” means it is not invoked from the MARS Tools menu. “Pure” means there
is no driver program to invoke the application.

getName

public java.lang.String getName()

Required method to return Tool name.

Specified by:
getName in interface MarsTool
Specified by:
getName in class AbstractMarsToolAndApplication

Returns:
Tool name. MARS will display this in menu item.

buildMainDisplayArea

protected javax.swing.JComponent buildMainDisplayArea()

Implementation of the inherited abstract method to build the main
display area of the GUI. It will be placed in the CENTER area of a
BorderLayout. The title is in the NORTH area, and the controls are
in the SOUTH area.

Specified by:
buildMainDisplayArea in class AbstractMarsToolAndApplication

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DigitalLabSim

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class DigitalLabSim

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication
mars.tools.DigitalLabSim

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

public class DigitalLabSim
extends AbstractMarsToolAndApplication

See Also:
Serialized Form

Nested Class Summary

 class DigitalLabSim.HexaKeyboard

           

 class DigitalLabSim.OneSecondCounter

           

 class DigitalLabSim.SevenSegmentDisplay

           

 class DigitalLabSim.SevenSegmentPanel

           

 
Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener

 

Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

static int EXTERNAL_INTERRUPT_HEXA_KEYBOARD

           

static int EXTERNAL_INTERRUPT_TIMER

           

 
Fields inherited from class mars.tools.AbstractMarsToolAndApplication
connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
DigitalLabSim()

           
DigitalLabSim(java.lang.String title,
java.lang.String heading)

           

 

Method Summary

protected  void addAsObserver()

          Add this app/tool as an Observer of desired MIPS Observables (memory and registers).

protected  javax.swing.JComponent buildMainDisplayArea()

          Abstract method that must be instantiated by subclass to build the main display area
of the GUI.

protected  javax.swing.JComponent getHelpComponent()

          Override this method to provide a JComponent (probably a JButton) of your choice
to be placed just left of the Close/Exit button.

 java.lang.String getName()

          Required MarsTool method to return Tool name.

static void main(java.lang.String[] args)

           

protected  void reset()

          Method that will be called each time the default Reset button is clicked.

 void update(java.util.Observable ressource,
java.lang.Object accessNotice)

          Called when receiving notice of access to MIPS memory or registers.

 void updateHexaKeyboard(char row)

           

 void updateOneSecondCounter(char value)

           

 void updateSevenSegment(int number,
char value)

           

 
Methods inherited from class mars.tools.AbstractMarsToolAndApplication
action, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, deleteAsObserver, go, initializePostGUI, initializePreGUI, isObserving, performSpecialClosingDuties, processMIPSUpdate, updateDisplay

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Field Detail

EXTERNAL_INTERRUPT_TIMER

public static final int EXTERNAL_INTERRUPT_TIMER

See Also:
Constant Field Values

EXTERNAL_INTERRUPT_HEXA_KEYBOARD

public static final int EXTERNAL_INTERRUPT_HEXA_KEYBOARD

See Also:
Constant Field Values

Constructor Detail

DigitalLabSim

public DigitalLabSim(java.lang.String title,
java.lang.String heading)

DigitalLabSim

public DigitalLabSim()

Method Detail

main

public static void main(java.lang.String[] args)

getName

public java.lang.String getName()

Description copied from class: AbstractMarsToolAndApplication
Required MarsTool method to return Tool name. Must be defined by subclass.

Specified by:
getName in interface MarsTool
Specified by:
getName in class AbstractMarsToolAndApplication

Returns:
Tool name. MARS will display this in menu item.

addAsObserver

protected void addAsObserver()

Description copied from class: AbstractMarsToolAndApplication
Add this app/tool as an Observer of desired MIPS Observables (memory and registers).
By default, will add as an Observer of the entire Data Segment in memory.
Override if you want something different. Note that the Memory methods to add an
Observer to memory are flexible (you can register for a range of addresses) but
may throw an AddressErrorException that you need to catch.
This method is called whenever the default “Connect” button on a MarsTool or the
default “Assemble and run” on a stand-alone Mars app is selected. The corresponding
NOTE: if you do not want to register as an Observer of the entire data segment
(starts at address 0x10000000) then override this to either do some alternative
or nothing at all. This method is also overloaded to allow arbitrary memory
subrange.

Overrides:
addAsObserver in class AbstractMarsToolAndApplication

update

public void update(java.util.Observable ressource,
java.lang.Object accessNotice)

Description copied from class: AbstractMarsToolAndApplication
Called when receiving notice of access to MIPS memory or registers. Default
implementation of method required by Observer interface. This method will filter out
notices originating from the MARS GUI or from direct user editing of memory or register
displays. Only notices arising from MIPS program access are allowed in.
It then calls two methods to be overridden by the subclass (since they do
nothing by default): processMIPSUpdate() then updateDisplay().

Specified by:
update in interface java.util.Observer
Overrides:
update in class AbstractMarsToolAndApplication

Parameters:
ressource – the attached MIPS resource
accessNotice – AccessNotice information provided by the resource

reset

protected void reset()

Description copied from class: AbstractMarsToolAndApplication
Method that will be called each time the default Reset button is clicked.
Use it to reset any data structures and/or GUI components. By default it does nothing.

Overrides:
reset in class AbstractMarsToolAndApplication

buildMainDisplayArea

protected javax.swing.JComponent buildMainDisplayArea()

Description copied from class: AbstractMarsToolAndApplication
Abstract method that must be instantiated by subclass to build the main display area
of the GUI. It will be placed in the CENTER area of a BorderLayout. The title
is in the NORTH area, and the controls are in the SOUTH area.

Specified by:
buildMainDisplayArea in class AbstractMarsToolAndApplication

getHelpComponent

protected javax.swing.JComponent getHelpComponent()

Description copied from class: AbstractMarsToolAndApplication
Override this method to provide a JComponent (probably a JButton) of your choice
to be placed just left of the Close/Exit button. Its anticipated use is for a
“help” button that launches a help message or dialog. But it can be any valid
JComponent that doesn’t mind co-existing among a bunch of JButtons.

Overrides:
getHelpComponent in class AbstractMarsToolAndApplication

updateSevenSegment

public void updateSevenSegment(int number,
char value)

updateHexaKeyboard

public void updateHexaKeyboard(char row)

updateOneSecondCounter

public void updateOneSecondCounter(char value)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FloatRepresentation

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class FloatRepresentation

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication
mars.tools.FloatRepresentation

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

public class FloatRepresentation
extends AbstractMarsToolAndApplication

Tool to help students learn about IEEE 754 representation of 32 bit
floating point values. This representation is used by MIPS “float”
directive and instructions and also the Java (and most other languages)
“float” data type. As written, it can ALMOST be adapted to 64 bit by
changing a few constants.

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener

 

Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class mars.tools.AbstractMarsToolAndApplication
connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
FloatRepresentation()

          Simple constructor, likely used by the MARS Tools menu mechanism
FloatRepresentation(java.lang.String title,
java.lang.String heading)

          Simple constructor, likely used to run a stand-alone memory reference visualizer.

 

Method Summary

protected  void addAsObserver()

          Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only.

protected  javax.swing.JComponent buildDisplayArea()

           

protected  javax.swing.JComponent buildMainDisplayArea()

          Method that constructs the main display area.

protected  void deleteAsObserver()

          Delete this app/tool as an Observer of the attached register.

 java.lang.String getName()

          Fetch tool name (for display in MARS Tools menu)

static void main(java.lang.String[] args)

          Main provided for pure stand-alone use.

protected  void reset()

          Method to reset display values to 0 when the Reset button selected.

 void update(java.util.Observable register,
java.lang.Object accessNotice)

          Override inherited update() to update display when “attached” register is modified
either by MIPS program or by user editing it on the MARS user interface.

 
Methods inherited from class mars.tools.AbstractMarsToolAndApplication
action, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, getHelpComponent, go, initializePostGUI, initializePreGUI, isObserving, performSpecialClosingDuties, processMIPSUpdate, updateDisplay

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Constructor Detail

FloatRepresentation

public FloatRepresentation(java.lang.String title,
java.lang.String heading)

Simple constructor, likely used to run a stand-alone memory reference visualizer.

Parameters:
title – String containing title for title bar
heading – String containing text for heading shown in upper part of window.

FloatRepresentation

public FloatRepresentation()

Simple constructor, likely used by the MARS Tools menu mechanism

Method Detail

main

public static void main(java.lang.String[] args)

Main provided for pure stand-alone use. Recommended stand-alone use is to write a
driver program that instantiates a FloatRepresentation object then invokes its go() method.
“stand-alone” means it is not invoked from the MARS Tools menu. “Pure” means there
is no driver program to invoke the application.

getName

public java.lang.String getName()

Fetch tool name (for display in MARS Tools menu)

Specified by:
getName in interface MarsTool
Specified by:
getName in class AbstractMarsToolAndApplication

Returns:
String containing tool name

addAsObserver

protected void addAsObserver()

Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only. This version will register us as observer over the selected
floating point register, if any. If no register is selected, it will not do anything.
If you use the inherited GUI buttons, this method is invoked when you click “Connect” button
on MarsTool or the “Assemble and Run” button on a Mars-based app.

Overrides:
addAsObserver in class AbstractMarsToolAndApplication

deleteAsObserver

protected void deleteAsObserver()

Delete this app/tool as an Observer of the attached register. This overrides
the inherited version which deletes only as an Observer of memory.
This method is called when the default “Disconnect” button on a MarsTool is selected or
when the MIPS program execution triggered by the default “Assemble and run” on a stand-alone
Mars app terminates (e.g. when the button is re-enabled).

Overrides:
deleteAsObserver in class AbstractMarsToolAndApplication

buildMainDisplayArea

protected javax.swing.JComponent buildMainDisplayArea()

Method that constructs the main display area. This will be vertically sandwiched between
the standard heading area at the top and the control area at the bottom.

Specified by:
buildMainDisplayArea in class AbstractMarsToolAndApplication

Returns:
the GUI component containing the application/tool-specific part of the user interface

update

public void update(java.util.Observable register,
java.lang.Object accessNotice)

Override inherited update() to update display when “attached” register is modified
either by MIPS program or by user editing it on the MARS user interface.
The latter is the reason for overriding the inherited update() method.
The inherited method will filter out notices triggered by the MARS GUI or the user.

Specified by:
update in interface java.util.Observer
Overrides:
update in class AbstractMarsToolAndApplication

Parameters:
register – the attached register
accessNotice – information provided by register in RegisterAccessNotice object

reset

protected void reset()

Method to reset display values to 0 when the Reset button selected.
If attached to a MIPS register at the time, the register will be reset as well.
Overrides inherited method that does nothing.

Overrides:
reset in class AbstractMarsToolAndApplication

buildDisplayArea

protected javax.swing.JComponent buildDisplayArea()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

BHTSimulator

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class BHTSimulator

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication
mars.tools.BHTSimulator

All Implemented Interfaces:
java.awt.event.ActionListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

public class BHTSimulator
extends AbstractMarsToolAndApplication
implements java.awt.event.ActionListener

A MARS tool for simulating branch prediction with a Branch History Table (BHT)

The simulation is based on observing the access to the instruction memory area (text segment).
If a branch instruction is encountered, a prediction based on a BHT is performed.
The outcome of the branch is compared with the prediction and the prediction is updated accordingly.
Statistics about the correct and incorrect number of predictions can be obtained for each BHT entry.
The number of entries in the BHT and the history that is considered for each prediction can be configured interactively.
A change of the configuration however causes a re-initialization of the BHT.

The tool can be used to show how branch prediction works in case of loops and how effective such simple methods are.
In case of nested loops the difference of BHT with 1 or 2 Bit history can be explored and visualized.

Author:
ingo. -klu.ac.at
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener

 

Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

static int BHT_DEFAULT_HISTORY

          constant for the default history size

static boolean BHT_DEFAULT_INITVAL

          constant for the default inital value

static int BHT_DEFAULT_SIZE

          constant for the default size of the BHT

static java.lang.String BHT_HEADING

          the heading of the tool

static java.lang.String BHT_NAME

          the name of the tool

static java.lang.String BHT_VERSION

          the version of the tool

 
Fields inherited from class mars.tools.AbstractMarsToolAndApplication
connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
BHTSimulator()

          Creates a BHT Simulator with given name and heading.

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent event)

          Handles the actions when selecting another value in one of the two combo boxes.

protected  void addAsObserver()

          Adds BHTSimulator as observer of the text segment.

protected  javax.swing.JComponent buildMainDisplayArea()

          Creates a GUI and initialize the GUI with the default values.

protected static int extractBranchAddress(ProgramStatement stmt)

          Extracts the target address of the branch.

 java.lang.String getName()

          Returns the name of the tool.

protected  void handleExecBranchInst(int branchInstAddr,
boolean branchTaken)

          Handles the execution of the branch instruction.

protected  void handlePreBranchInst(ProgramStatement stmt)

          Handles the execution branch instruction.

protected static boolean isBranchInstruction(ProgramStatement stmt)

          Determines if the instruction is a branch instruction or not.

protected  void processMIPSUpdate(java.util.Observable resource,
AccessNotice notice)

          Callback for text segment access by the MIPS simulator.

protected  void reset()

          Performs a reset of the simulator.

protected  void resetSimulator()

          Resets the simulator by clearing the GUI elements and resetting the BHT.

protected static boolean willBranch(ProgramStatement stmt)

          Checks if the branch instruction delivered as parameter will branch or not.

 
Methods inherited from class mars.tools.AbstractMarsToolAndApplication
action, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, deleteAsObserver, getHelpComponent, go, initializePostGUI, initializePreGUI, isObserving, performSpecialClosingDuties, update, updateDisplay

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Field Detail

BHT_DEFAULT_SIZE

public static final int BHT_DEFAULT_SIZE

constant for the default size of the BHT

See Also:
Constant Field Values

BHT_DEFAULT_HISTORY

public static final int BHT_DEFAULT_HISTORY

constant for the default history size

See Also:
Constant Field Values

BHT_DEFAULT_INITVAL

public static final boolean BHT_DEFAULT_INITVAL

constant for the default inital value

See Also:
Constant Field Values

BHT_NAME

public static final java.lang.String BHT_NAME

the name of the tool

See Also:
Constant Field Values

BHT_VERSION

public static final java.lang.String BHT_VERSION

the version of the tool

See Also:
Constant Field Values

BHT_HEADING

public static final java.lang.String BHT_HEADING

the heading of the tool

See Also:
Constant Field Values

Constructor Detail

BHTSimulator

public BHTSimulator()

Creates a BHT Simulator with given name and heading.

Method Detail

addAsObserver

protected void addAsObserver()

Adds BHTSimulator as observer of the text segment.

Overrides:
addAsObserver in class AbstractMarsToolAndApplication

buildMainDisplayArea

protected javax.swing.JComponent buildMainDisplayArea()

Creates a GUI and initialize the GUI with the default values.

Specified by:
buildMainDisplayArea in class AbstractMarsToolAndApplication

getName

public java.lang.String getName()

Returns the name of the tool.

Specified by:
getName in interface MarsTool
Specified by:
getName in class AbstractMarsToolAndApplication

Returns:
the tool’s name as String

reset

protected void reset()

Performs a reset of the simulator.
This causes the BHT to be reseted and the log messages to be cleared.

Overrides:
reset in class AbstractMarsToolAndApplication

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent event)

Handles the actions when selecting another value in one of the two combo boxes.
Selecting a different BHT size or history causes a reset of the simulator.

Specified by:
actionPerformed in interface java.awt.event.ActionListener

resetSimulator

protected void resetSimulator()

Resets the simulator by clearing the GUI elements and resetting the BHT.

handlePreBranchInst

protected void handlePreBranchInst(ProgramStatement stmt)

Handles the execution branch instruction.
This method is called each time a branch instruction is executed.
Based on the address of the instruction the corresponding index into the BHT is calculated.
The prediction is obtained from the BHT at the calculated index and is visualized appropriately.

Parameters:
stmt – the branch statement that is executed

handleExecBranchInst

protected void handleExecBranchInst(int branchInstAddr,
boolean branchTaken)

Handles the execution of the branch instruction.
The correctness of the prediction is visualized in both the table and the log message area.
The BHT is updated based on the information if the branch instruction was taken or not.

Parameters:
branchInstAddr – the address of the branch instruction
branchTaken – the information if the branch is taken or not (determined in a step before)

isBranchInstruction

protected static boolean isBranchInstruction(ProgramStatement stmt)

Determines if the instruction is a branch instruction or not.

Parameters:
stmt – the statement to investigate

Returns:
true, if stmt is a branch instruction, otherwise false

willBranch

protected static boolean willBranch(ProgramStatement stmt)

Checks if the branch instruction delivered as parameter will branch or not.

Parameters:
stmt – the branch instruction to be investigated

Returns:
true if the branch will be taken, otherwise false

extractBranchAddress

protected static int extractBranchAddress(ProgramStatement stmt)

Extracts the target address of the branch.

In MIPS the target address is encoded as 16-bit value.
The target address is encoded relative to the address of the instruction after the branch instruction

Parameters:
stmt – the branch instruction

Returns:
the address of the instruction that is executed if the branch is taken

processMIPSUpdate

protected void processMIPSUpdate(java.util.Observable resource,
AccessNotice notice)

Callback for text segment access by the MIPS simulator.

The method is called each time the text segment is accessed to fetch the next instruction.
If the next instruction to execute was a branch instruction, the branch prediction is performed and visualized.
In case the last instruction was a branch instruction, the outcome of the branch prediction is analyzed and visualized.

Overrides:
processMIPSUpdate in class AbstractMarsToolAndApplication

Parameters:
resource – the observed resource
notice – signals the type of access (memory, register etc.)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

KeyboardAndDisplaySimulator

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class KeyboardAndDisplaySimulator

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication
mars.tools.KeyboardAndDisplaySimulator

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

public class KeyboardAndDisplaySimulator
extends AbstractMarsToolAndApplication

Keyboard and Display Simulator. It can be run either as a stand-alone Java application having
access to the mars package, or through MARS as an item in its Tools menu. It makes
maximum use of methods inherited from its abstract superclass AbstractMarsToolAndApplication.
Pete Sanderson

Version 1.0, 24 July 2008.

Version 1.1, 24 November 2008 corrects two omissions: (1) the tool failed to register as an observer
of kernel text memory when counting instruction executions for transmitter ready bit
reset delay, and (2) the tool failed to test the Status register’s Exception Level bit before
raising the exception that results in the interrupt (if the Exception Level bit is 1, that
means an interrupt is being processed, so disable further interrupts).

Version 1.2, 6 August 2009, soft-codes the MMIO register locations for new memory configuration
feature of MARS 3.7. Previously memory segment addresses were fixed and final. Now they
can be modified dynamically so the tool has to get its values dynamically as well.

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener

 

Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

static java.awt.Dimension preferredTextAreaDimension

           

static int RECEIVER_CONTROL

           

static int RECEIVER_DATA

           

static int TRANSMITTER_CONTROL

           

static int TRANSMITTER_DATA

           

 
Fields inherited from class mars.tools.AbstractMarsToolAndApplication
connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
KeyboardAndDisplaySimulator()

          Simple constructor, likely used by the MARS Tools menu mechanism
KeyboardAndDisplaySimulator(java.lang.String title,
java.lang.String heading)

          Simple constructor, likely used to run a stand-alone keyboard/display simulator.

 

Method Summary

protected  void addAsObserver()

          Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only.

protected  javax.swing.JComponent buildMainDisplayArea()

          Method that constructs the main display area.

protected  javax.swing.JComponent getHelpComponent()

          Overrides default method, to provide a Help button for this tool/app.

 java.lang.String getName()

          Required MarsTool method to return Tool name.

protected  void initializePostGUI()

          Initialization code to be executed after the GUI is configured.

protected  void initializePreGUI()

          Method that will be called once just before the GUI is constructed in the go() and action()
methods.

static void main(java.lang.String[] args)

          Main provided for pure stand-alone use.

protected  void processMIPSUpdate(java.util.Observable memory,
AccessNotice accessNotice)

          Update display when connected MIPS program accesses (data) memory.

protected  void reset()

          Method to reset counters and display when the Reset button selected.

 
Methods inherited from class mars.tools.AbstractMarsToolAndApplication
action, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, deleteAsObserver, go, isObserving, performSpecialClosingDuties, update, updateDisplay

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Field Detail

preferredTextAreaDimension

public static java.awt.Dimension preferredTextAreaDimension

RECEIVER_CONTROL

public static int RECEIVER_CONTROL

RECEIVER_DATA

public static int RECEIVER_DATA

TRANSMITTER_CONTROL

public static int TRANSMITTER_CONTROL

TRANSMITTER_DATA

public static int TRANSMITTER_DATA

Constructor Detail

KeyboardAndDisplaySimulator

public KeyboardAndDisplaySimulator(java.lang.String title,
java.lang.String heading)

Simple constructor, likely used to run a stand-alone keyboard/display simulator.

Parameters:
title – String containing title for title bar
heading – String containing text for heading shown in upper part of window.

KeyboardAndDisplaySimulator

public KeyboardAndDisplaySimulator()

Simple constructor, likely used by the MARS Tools menu mechanism

Method Detail

main

public static void main(java.lang.String[] args)

Main provided for pure stand-alone use. Recommended stand-alone use is to write a
driver program that instantiates a KeyboardAndDisplaySimulator object then invokes its go() method.
“stand-alone” means it is not invoked from the MARS Tools menu. “Pure” means there
is no driver program to invoke the application.

getName

public java.lang.String getName()

Required MarsTool method to return Tool name.

Specified by:
getName in interface MarsTool
Specified by:
getName in class AbstractMarsToolAndApplication

Returns:
Tool name. MARS will display this in menu item.

initializePreGUI

protected void initializePreGUI()

Description copied from class: AbstractMarsToolAndApplication
Method that will be called once just before the GUI is constructed in the go() and action()
methods. Use it to initialize any data structures needed for the application whose values
will be needed to determine the initial state of GUI components. By default it does nothing.

Overrides:
initializePreGUI in class AbstractMarsToolAndApplication

addAsObserver

protected void addAsObserver()

Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only.

When user enters keystroke, set RECEIVER_CONTROL and RECEIVER_DATA using the action listener.
When user loads word (lw) from RECEIVER_DATA (we are notified of the read), then clear RECEIVER_CONTROL.
When user stores word (sw) to TRANSMITTER_DATA (we are notified of the write), then clear TRANSMITTER_CONTROL, read TRANSMITTER_DATA,
echo the character to display, wait for delay period, then set TRANSMITTER_CONTROL.

If you use the inherited GUI buttons, this method is invoked when you click “Connect” button on MarsTool or the
“Assemble and Run” button on a Mars-based app.

Overrides:
addAsObserver in class AbstractMarsToolAndApplication

buildMainDisplayArea

protected javax.swing.JComponent buildMainDisplayArea()

Method that constructs the main display area. It is organized vertically
into two major components: the display and the keyboard. The display itself
is a JTextArea and it echoes characters placed into the low order byte of
the Transmitter Data location, 0xffff000c. They keyboard is also a JTextArea
places each typed character into the Receive Data location 0xffff0004.

Specified by:
buildMainDisplayArea in class AbstractMarsToolAndApplication

Returns:
the GUI component containing these two areas

processMIPSUpdate

protected void processMIPSUpdate(java.util.Observable memory,
AccessNotice accessNotice)

Update display when connected MIPS program accesses (data) memory.

Overrides:
processMIPSUpdate in class AbstractMarsToolAndApplication

Parameters:
memory – the attached memory
accessNotice – information provided by memory in MemoryAccessNotice object

initializePostGUI

protected void initializePostGUI()

Initialization code to be executed after the GUI is configured. Overrides inherited default.

Overrides:
initializePostGUI in class AbstractMarsToolAndApplication

reset

protected void reset()

Method to reset counters and display when the Reset button selected.
Overrides inherited method that does nothing.

Overrides:
reset in class AbstractMarsToolAndApplication

getHelpComponent

protected javax.swing.JComponent getHelpComponent()

Overrides default method, to provide a Help button for this tool/app.

Overrides:
getHelpComponent in class AbstractMarsToolAndApplication

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InstructionStatistics

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class InstructionStatistics

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication
mars.tools.InstructionStatistics

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

public class InstructionStatistics
extends AbstractMarsToolAndApplication

A MARS tool for obtaining instruction statistics by instruction category.

The code of this tools is initially based on the Instruction counter tool by Felipe Lassa.

Author:
Ingo Kofler
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener

 

Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

protected  int lastAddress

          The last address we saw.

 
Fields inherited from class mars.tools.AbstractMarsToolAndApplication
connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
InstructionStatistics()

          Simple construction, likely used by the MARS Tools menu mechanism.
InstructionStatistics(java.lang.String title,
java.lang.String heading)

          Simple constructor, likely used to run a stand-alone enhanced instruction counter.

 

Method Summary

protected  void addAsObserver()

          registers the tool as observer for the text segment of the MIPS program

protected  javax.swing.JComponent buildMainDisplayArea()

          creates the display area for the tool as required by the API

protected  int getInstructionCategory(ProgramStatement stmt)

          decodes the instruction and determines the category of the instruction.

 java.lang.String getName()

          returns the name of the tool

protected  void initializePreGUI()

          performs initialization tasks of the counters before the GUI is created.

protected  void processMIPSUpdate(java.util.Observable resource,
AccessNotice notice)

          method that is called each time the MIPS simulator accesses the text segment.

protected  void reset()

          resets the counter values of the tool and updates the display.

protected  void updateDisplay()

          updates the text fields and progress bars according to the current counter values.

 
Methods inherited from class mars.tools.AbstractMarsToolAndApplication
action, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, deleteAsObserver, getHelpComponent, go, initializePostGUI, isObserving, performSpecialClosingDuties, update

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Field Detail

lastAddress

protected int lastAddress

The last address we saw. We ignore it because the only way for a
program to execute twice the same instruction is to enter an infinite
loop, which is not insteresting in the POV of counting instructions.

Constructor Detail

InstructionStatistics

public InstructionStatistics(java.lang.String title,
java.lang.String heading)

Simple constructor, likely used to run a stand-alone enhanced instruction counter.

Parameters:
title – String containing title for title bar
heading – String containing text for heading shown in upper part of window.

InstructionStatistics

public InstructionStatistics()

Simple construction, likely used by the MARS Tools menu mechanism.

Method Detail

getName

public java.lang.String getName()

returns the name of the tool

Specified by:
getName in interface MarsTool
Specified by:
getName in class AbstractMarsToolAndApplication

Returns:
the tools’s name

buildMainDisplayArea

protected javax.swing.JComponent buildMainDisplayArea()

creates the display area for the tool as required by the API

Specified by:
buildMainDisplayArea in class AbstractMarsToolAndApplication

Returns:
a panel that holds the GUI of the tool

addAsObserver

protected void addAsObserver()

registers the tool as observer for the text segment of the MIPS program

Overrides:
addAsObserver in class AbstractMarsToolAndApplication

getInstructionCategory

protected int getInstructionCategory(ProgramStatement stmt)

decodes the instruction and determines the category of the instruction.

The instruction is decoded by extracting the operation and function code of the 32-bit instruction.
Only the most relevant instructions are decoded and categorized.

Parameters:
stmt – the instruction to decode

Returns:
the category of the instruction
See Also:
CATEGORY_ALU,
CATEGORY_JUMP,
CATEGORY_BRANCH,
CATEGORY_MEM,
CATEGORY_OTHER

processMIPSUpdate

protected void processMIPSUpdate(java.util.Observable resource,
AccessNotice notice)

method that is called each time the MIPS simulator accesses the text segment.
Before an instruction is executed by the simulator, the instruction is fetched from the program memory.
This memory access is observed and the corresponding instruction is decoded and categorized by the tool.
According to the category the counter values are increased and the display gets updated.

Overrides:
processMIPSUpdate in class AbstractMarsToolAndApplication

Parameters:
resource – the observed resource
notice – signals the type of access (memory, register etc.)

initializePreGUI

protected void initializePreGUI()

performs initialization tasks of the counters before the GUI is created.

Overrides:
initializePreGUI in class AbstractMarsToolAndApplication

reset

protected void reset()

resets the counter values of the tool and updates the display.

Overrides:
reset in class AbstractMarsToolAndApplication

updateDisplay

protected void updateDisplay()

updates the text fields and progress bars according to the current counter values.

Overrides:
updateDisplay in class AbstractMarsToolAndApplication

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DigitalLabSim.SevenSegmentPanel

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class DigitalLabSim.SevenSegmentPanel

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
mars.tools.DigitalLabSim.SevenSegmentPanel

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible

Enclosing class:
DigitalLabSim

public class DigitalLabSim.SevenSegmentPanel
extends javax.swing.JPanel

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JPanel
javax.swing.JPanel.AccessibleJPanel

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 DigitalLabSim.SevenSegmentDisplay[] display

           

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
DigitalLabSim.SevenSegmentPanel()

           

 

Method Summary

 void modifyDisplay(int num,
char val)

           

 void resetSevenSegment()

           

 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

display

public DigitalLabSim.SevenSegmentDisplay[] display

Constructor Detail

DigitalLabSim.SevenSegmentPanel

public DigitalLabSim.SevenSegmentPanel()

Method Detail

modifyDisplay

public void modifyDisplay(int num,
char val)

resetSevenSegment

public void resetSevenSegment()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InstructionCounter

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class InstructionCounter

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication
mars.tools.InstructionCounter

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

public class InstructionCounter
extends AbstractMarsToolAndApplication

Instruction counter tool. Can be used to know how many instructions
were executed to complete a given program.

Code slightly based on MemoryReferenceVisualization.

Author:
Felipe Lessa
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener

 

Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

protected  int counter

          Number of instructions executed until now.

protected  int counterI

          Number of instructions of type I.

protected  int counterJ

          Number of instructions of type J.

protected  int counterR

          Number of instructions of type R.

protected  int lastAddress

          The last address we saw.

 
Fields inherited from class mars.tools.AbstractMarsToolAndApplication
connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
InstructionCounter()

          Simple construction, likely used by the MARS Tools menu mechanism.
InstructionCounter(java.lang.String title,
java.lang.String heading)

          Simple constructor, likely used to run a stand-alone memory reference visualizer.

 

Method Summary

protected  void addAsObserver()

          Add this app/tool as an Observer of desired MIPS Observables (memory and registers).

protected  javax.swing.JComponent buildMainDisplayArea()

          Abstract method that must be instantiated by subclass to build the main display area
of the GUI.

 java.lang.String getName()

          Required MarsTool method to return Tool name.

protected  void initializePreGUI()

          Method that will be called once just before the GUI is constructed in the go() and action()
methods.

protected  void processMIPSUpdate(java.util.Observable resource,
AccessNotice notice)

          Override this method to process a received notice from MIPS Observable (memory or register)
It will only be called if the notice was generated as the result of MIPS instruction execution.

protected  void reset()

          Method that will be called each time the default Reset button is clicked.

protected  void updateDisplay()

          Override this method to implement updating of GUI after each MIPS instruction is executed,
while running in “timed” mode (user specifies execution speed on the slider control).

 
Methods inherited from class mars.tools.AbstractMarsToolAndApplication
action, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, deleteAsObserver, getHelpComponent, go, initializePostGUI, isObserving, performSpecialClosingDuties, update

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Field Detail

counter

protected int counter

Number of instructions executed until now.

counterR

protected int counterR

Number of instructions of type R.

counterI

protected int counterI

Number of instructions of type I.

counterJ

protected int counterJ

Number of instructions of type J.

lastAddress

protected int lastAddress

The last address we saw. We ignore it because the only way for a
program to execute twice the same instruction is to enter an infinite
loop, which is not insteresting in the POV of counting instructions.

Constructor Detail

InstructionCounter

public InstructionCounter(java.lang.String title,
java.lang.String heading)

Simple constructor, likely used to run a stand-alone memory reference visualizer.

Parameters:
title – String containing title for title bar
heading – String containing text for heading shown in upper part of window.

InstructionCounter

public InstructionCounter()

Simple construction, likely used by the MARS Tools menu mechanism.

Method Detail

getName

public java.lang.String getName()

Description copied from class: AbstractMarsToolAndApplication
Required MarsTool method to return Tool name. Must be defined by subclass.

Specified by:
getName in interface MarsTool
Specified by:
getName in class AbstractMarsToolAndApplication

Returns:
Tool name. MARS will display this in menu item.

buildMainDisplayArea

protected javax.swing.JComponent buildMainDisplayArea()

Description copied from class: AbstractMarsToolAndApplication
Abstract method that must be instantiated by subclass to build the main display area
of the GUI. It will be placed in the CENTER area of a BorderLayout. The title
is in the NORTH area, and the controls are in the SOUTH area.

Specified by:
buildMainDisplayArea in class AbstractMarsToolAndApplication

addAsObserver

protected void addAsObserver()

Description copied from class: AbstractMarsToolAndApplication
Add this app/tool as an Observer of desired MIPS Observables (memory and registers).
By default, will add as an Observer of the entire Data Segment in memory.
Override if you want something different. Note that the Memory methods to add an
Observer to memory are flexible (you can register for a range of addresses) but
may throw an AddressErrorException that you need to catch.
This method is called whenever the default “Connect” button on a MarsTool or the
default “Assemble and run” on a stand-alone Mars app is selected. The corresponding
NOTE: if you do not want to register as an Observer of the entire data segment
(starts at address 0x10000000) then override this to either do some alternative
or nothing at all. This method is also overloaded to allow arbitrary memory
subrange.

Overrides:
addAsObserver in class AbstractMarsToolAndApplication

processMIPSUpdate

protected void processMIPSUpdate(java.util.Observable resource,
AccessNotice notice)

Description copied from class: AbstractMarsToolAndApplication
Override this method to process a received notice from MIPS Observable (memory or register)
It will only be called if the notice was generated as the result of MIPS instruction execution.
By default it does nothing. After this method is complete, the updateDisplay() method will be
invoked automatically.

Overrides:
processMIPSUpdate in class AbstractMarsToolAndApplication

initializePreGUI

protected void initializePreGUI()

Description copied from class: AbstractMarsToolAndApplication
Method that will be called once just before the GUI is constructed in the go() and action()
methods. Use it to initialize any data structures needed for the application whose values
will be needed to determine the initial state of GUI components. By default it does nothing.

Overrides:
initializePreGUI in class AbstractMarsToolAndApplication

reset

protected void reset()

Description copied from class: AbstractMarsToolAndApplication
Method that will be called each time the default Reset button is clicked.
Use it to reset any data structures and/or GUI components. By default it does nothing.

Overrides:
reset in class AbstractMarsToolAndApplication

updateDisplay

protected void updateDisplay()

Description copied from class: AbstractMarsToolAndApplication
Override this method to implement updating of GUI after each MIPS instruction is executed,
while running in “timed” mode (user specifies execution speed on the slider control).
Does nothing by default.

Overrides:
updateDisplay in class AbstractMarsToolAndApplication

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MarsBot

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class MarsBot

java.lang.Object
mars.tools.MarsBot

All Implemented Interfaces:
java.util.Observer, MarsTool

public class MarsBot
extends java.lang.Object
implements java.util.Observer, MarsTool

Simple Demo of Mars tool capability

Constructor Summary
MarsBot()

           

 

Method Summary

 void action()

          Performs tool functions.

 java.lang.String getName()

          Return a name you have chosen for this tool.

 void update(java.util.Observable o,
java.lang.Object arg)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

MarsBot

public MarsBot()

Method Detail

getName

public java.lang.String getName()

Description copied from interface: MarsTool
Return a name you have chosen for this tool. It will appear as the
menu item.

Specified by:
getName in interface MarsTool

action

public void action()

Description copied from interface: MarsTool
Performs tool functions. It will be invoked when the tool is selected
from the Tools menu.

Specified by:
action in interface MarsTool

update

public void update(java.util.Observable o,
java.lang.Object arg)

Specified by:
update in interface java.util.Observer

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

CacheSimulator

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class CacheSimulator

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication
mars.tools.CacheSimulator

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

public class CacheSimulator
extends AbstractMarsToolAndApplication

A data cache simulator. It can be run either as a stand-alone Java application having
access to the mars package, or through MARS as an item in its Tools menu. It makes
maximum use of methods inherited from its abstract superclass AbstractMarsToolOrApp.
Pete Sanderson, v 1.0: 16-18 October 2006, v 1.1: 7 November 2006. v 1.2: 23 December 2010.

Version 1.2 fixes a bug in the hit/miss animator under full or N-way set associative. It was
animating the block of initial access (first block of set). Now it animates the block
of final access (where address found or stored). Also added log display to GUI (previously System.out).

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener

 

Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class mars.tools.AbstractMarsToolAndApplication
connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
CacheSimulator()

          Simple constructor, likely used by the MARS Tools menu mechanism
CacheSimulator(java.lang.String title,
java.lang.String heading)

          Simple constructor, likely used to run a stand-alone cache simulator.

 

Method Summary

protected  javax.swing.JComponent buildMainDisplayArea()

          Method that constructs the main cache simulator display area.

 java.lang.String getName()

          Required MarsTool method to return Tool name.

protected  void initializePostGUI()

          The only post-GUI initialization is to create the initial cache object based on the default settings
of the various combo boxes.

protected  void initializePreGUI()

          Initialize all JComboBox choice structures not already initialized at declaration.

static void main(java.lang.String[] args)

          Main provided for pure stand-alone use.

protected  void processMIPSUpdate(java.util.Observable memory,
AccessNotice accessNotice)

          Apply caching policies and update display when connected MIPS program accesses (data) memory.

protected  void reset()

          Method to reset cache, counters and display when the Reset button selected.

protected  void updateDisplay()

          Updates display immediately after each update (AccessNotice) is processed, after
cache configuration changes as needed, and after each execution step when Mars
is running in timed mode.

 
Methods inherited from class mars.tools.AbstractMarsToolAndApplication
action, addAsObserver, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, deleteAsObserver, getHelpComponent, go, isObserving, performSpecialClosingDuties, update

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Constructor Detail

CacheSimulator

public CacheSimulator(java.lang.String title,
java.lang.String heading)

Simple constructor, likely used to run a stand-alone cache simulator.

Parameters:
title – String containing title for title bar
heading – String containing text for heading shown in upper part of window.

CacheSimulator

public CacheSimulator()

Simple constructor, likely used by the MARS Tools menu mechanism

Method Detail

main

public static void main(java.lang.String[] args)

Main provided for pure stand-alone use. Recommended stand-alone use is to write a
driver program that instantiates a CacheSimulator object then invokes its go() method.
“stand-alone” means it is not invoked from the MARS Tools menu. “Pure” means there
is no driver program to invoke the Cache Simulator.

getName

public java.lang.String getName()

Required MarsTool method to return Tool name.

Specified by:
getName in interface MarsTool
Specified by:
getName in class AbstractMarsToolAndApplication

Returns:
Tool name. MARS will display this in menu item.

buildMainDisplayArea

protected javax.swing.JComponent buildMainDisplayArea()

Method that constructs the main cache simulator display area. It is organized vertically
into three major components: the cache configuration which an be modified
using combo boxes, the cache performance which is updated as the
attached MIPS program executes, and the runtime log which is optionally used
to display log of each cache access.

Specified by:
buildMainDisplayArea in class AbstractMarsToolAndApplication

Returns:
the GUI component containing these three areas

processMIPSUpdate

protected void processMIPSUpdate(java.util.Observable memory,
AccessNotice accessNotice)

Apply caching policies and update display when connected MIPS program accesses (data) memory.

Overrides:
processMIPSUpdate in class AbstractMarsToolAndApplication

Parameters:
memory – the attached memory
accessNotice – information provided by memory in MemoryAccessNotice object

initializePreGUI

protected void initializePreGUI()

Initialize all JComboBox choice structures not already initialized at declaration.
Also creates initial default cache object. Overrides inherited method that does nothing.

Overrides:
initializePreGUI in class AbstractMarsToolAndApplication

initializePostGUI

protected void initializePostGUI()

The only post-GUI initialization is to create the initial cache object based on the default settings
of the various combo boxes. Overrides inherited method that does nothing.

Overrides:
initializePostGUI in class AbstractMarsToolAndApplication

reset

protected void reset()

Method to reset cache, counters and display when the Reset button selected.
Overrides inherited method that does nothing.

Overrides:
reset in class AbstractMarsToolAndApplication

updateDisplay

protected void updateDisplay()

Updates display immediately after each update (AccessNotice) is processed, after
cache configuration changes as needed, and after each execution step when Mars
is running in timed mode. Overrides inherited method that does nothing.

Overrides:
updateDisplay in class AbstractMarsToolAndApplication

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DigitalLabSim.HexaKeyboard.EcouteurClick

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class DigitalLabSim.HexaKeyboard.EcouteurClick

java.lang.Object
mars.tools.DigitalLabSim.HexaKeyboard.EcouteurClick

All Implemented Interfaces:
java.awt.event.MouseListener, java.util.EventListener

Enclosing class:
DigitalLabSim.HexaKeyboard

public class DigitalLabSim.HexaKeyboard.EcouteurClick
extends java.lang.Object
implements java.awt.event.MouseListener

Constructor Summary
DigitalLabSim.HexaKeyboard.EcouteurClick(int val)

           

 

Method Summary

 void mouseClicked(java.awt.event.MouseEvent arg0)

           

 void mouseEntered(java.awt.event.MouseEvent arg0)

           

 void mouseExited(java.awt.event.MouseEvent arg0)

           

 void mousePressed(java.awt.event.MouseEvent arg0)

           

 void mouseReleased(java.awt.event.MouseEvent arg0)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

DigitalLabSim.HexaKeyboard.EcouteurClick

public DigitalLabSim.HexaKeyboard.EcouteurClick(int val)

Method Detail

mouseEntered

public void mouseEntered(java.awt.event.MouseEvent arg0)

Specified by:
mouseEntered in interface java.awt.event.MouseListener

mouseExited

public void mouseExited(java.awt.event.MouseEvent arg0)

Specified by:
mouseExited in interface java.awt.event.MouseListener

mousePressed

public void mousePressed(java.awt.event.MouseEvent arg0)

Specified by:
mousePressed in interface java.awt.event.MouseListener

mouseReleased

public void mouseReleased(java.awt.event.MouseEvent arg0)

Specified by:
mouseReleased in interface java.awt.event.MouseListener

mouseClicked

public void mouseClicked(java.awt.event.MouseEvent arg0)

Specified by:
mouseClicked in interface java.awt.event.MouseListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

ScreenMagnifier

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class ScreenMagnifier

java.lang.Object
mars.tools.ScreenMagnifier

All Implemented Interfaces:
MarsTool

public class ScreenMagnifier
extends java.lang.Object
implements MarsTool

Handy little tool to magnify a selected section of the screen
by a given scale and display it. The screen image snapshot
will be of the screen pixels beneath the tool’s frame. The
scale can be adjusted. The image is displayed in the tool’s
scrollable panel. You can highlight items on the image using
the scribbler (hold down mouse button and move it on the
image). The magnification scale adjustment is on the tool’s
window, but other settings can be modified on a button-
triggered dialog. It will capture the contents of the
underlying MARS graphical user interface, but NOT the
contents of other Mars Tools frames.

Author:
Pete Sanderson

Constructor Summary
ScreenMagnifier()

           

 

Method Summary

 void action()

          Performs tool functions.

 java.lang.String getName()

          Return a name you have chosen for this tool.

static void main(java.lang.String[] args)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

ScreenMagnifier

public ScreenMagnifier()

Method Detail

getName

public java.lang.String getName()

Description copied from interface: MarsTool
Return a name you have chosen for this tool. It will appear as the
menu item.

Specified by:
getName in interface MarsTool

action

public void action()

Description copied from interface: MarsTool
Performs tool functions. It will be invoked when the tool is selected
from the Tools menu.

Specified by:
action in interface MarsTool

main

public static void main(java.lang.String[] args)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

AbstractMarsToolAndApplication.ConnectButton

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class AbstractMarsToolAndApplication.ConnectButton

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.AbstractButton
javax.swing.JButton
mars.tools.AbstractMarsToolAndApplication.ConnectButton

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.ItemSelectable, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.SwingConstants

Enclosing class:
AbstractMarsToolAndApplication

protected class AbstractMarsToolAndApplication.ConnectButton
extends javax.swing.JButton

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JButton
javax.swing.JButton.AccessibleJButton

 

Nested classes/interfaces inherited from class javax.swing.AbstractButton
javax.swing.AbstractButton.AccessibleAbstractButton, javax.swing.AbstractButton.ButtonChangeListener

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.AbstractButton
actionListener, BORDER_PAINTED_CHANGED_PROPERTY, changeEvent, changeListener, CONTENT_AREA_FILLED_CHANGED_PROPERTY, DISABLED_ICON_CHANGED_PROPERTY, DISABLED_SELECTED_ICON_CHANGED_PROPERTY, FOCUS_PAINTED_CHANGED_PROPERTY, HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY, HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY, ICON_CHANGED_PROPERTY, itemListener, MARGIN_CHANGED_PROPERTY, MNEMONIC_CHANGED_PROPERTY, model, MODEL_CHANGED_PROPERTY, PRESSED_ICON_CHANGED_PROPERTY, ROLLOVER_ENABLED_CHANGED_PROPERTY, ROLLOVER_ICON_CHANGED_PROPERTY, ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY, SELECTED_ICON_CHANGED_PROPERTY, TEXT_CHANGED_PROPERTY, VERTICAL_ALIGNMENT_CHANGED_PROPERTY, VERTICAL_TEXT_POSITION_CHANGED_PROPERTY

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
AbstractMarsToolAndApplication.ConnectButton()

           

 

Method Summary

 void connect()

           

 void disconnect()

           

 boolean isConnected()

           

 
Methods inherited from class javax.swing.JButton
getAccessibleContext, getUIClassID, isDefaultButton, isDefaultCapable, paramString, removeNotify, setDefaultCapable, updateUI

 
Methods inherited from class javax.swing.AbstractButton
actionPropertyChanged, addActionListener, addChangeListener, addImpl, addItemListener, checkHorizontalKey, checkVerticalKey, configurePropertiesFromAction, createActionListener, createActionPropertyChangeListener, createChangeListener, createItemListener, doClick, doClick, fireActionPerformed, fireItemStateChanged, fireStateChanged, getAction, getActionCommand, getActionListeners, getChangeListeners, getDisabledIcon, getDisabledSelectedIcon, getDisplayedMnemonicIndex, getHideActionText, getHorizontalAlignment, getHorizontalTextPosition, getIcon, getIconTextGap, getItemListeners, getLabel, getMargin, getMnemonic, getModel, getMultiClickThreshhold, getPressedIcon, getRolloverIcon, getRolloverSelectedIcon, getSelectedIcon, getSelectedObjects, getText, getUI, getVerticalAlignment, getVerticalTextPosition, imageUpdate, init, isBorderPainted, isContentAreaFilled, isFocusPainted, isRolloverEnabled, isSelected, paintBorder, removeActionListener, removeChangeListener, removeItemListener, setAction, setActionCommand, setBorderPainted, setContentAreaFilled, setDisabledIcon, setDisabledSelectedIcon, setDisplayedMnemonicIndex, setEnabled, setFocusPainted, setHideActionText, setHorizontalAlignment, setHorizontalTextPosition, setIcon, setIconTextGap, setLabel, setLayout, setMargin, setMnemonic, setMnemonic, setModel, setMultiClickThreshhold, setPressedIcon, setRolloverEnabled, setRolloverIcon, setRolloverSelectedIcon, setSelected, setSelectedIcon, setText, setUI, setVerticalAlignment, setVerticalTextPosition

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

AbstractMarsToolAndApplication.ConnectButton

public AbstractMarsToolAndApplication.ConnectButton()

Method Detail

connect

public void connect()

disconnect

public void disconnect()

isConnected

public boolean isConnected()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DigitalLabSim.SevenSegmentDisplay

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class DigitalLabSim.SevenSegmentDisplay

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
mars.tools.DigitalLabSim.SevenSegmentDisplay

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable

Enclosing class:
DigitalLabSim

public class DigitalLabSim.SevenSegmentDisplay
extends javax.swing.JComponent

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 char aff

           

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
DigitalLabSim.SevenSegmentDisplay(char aff)

           

 

Method Summary

 void modifyDisplay(char val)

           

 void paint(java.awt.Graphics g)

           

 void SwitchSegment(java.awt.Graphics g,
char segment)

           

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

aff

public char aff

Constructor Detail

DigitalLabSim.SevenSegmentDisplay

public DigitalLabSim.SevenSegmentDisplay(char aff)

Method Detail

modifyDisplay

public void modifyDisplay(char val)

SwitchSegment

public void SwitchSegment(java.awt.Graphics g,
char segment)

paint

public void paint(java.awt.Graphics g)

Overrides:
paint in class javax.swing.JComponent

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MemoryReferenceVisualization

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class MemoryReferenceVisualization

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication
mars.tools.MemoryReferenceVisualization

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

public class MemoryReferenceVisualization
extends AbstractMarsToolAndApplication

Memory reference visualization. It can be run either as a stand-alone Java application having
access to the mars package, or through MARS as an item in its Tools menu. It makes
maximum use of methods inherited from its abstract superclass AbstractMarsToolAndApplication.
Pete Sanderson, verison 1.0, 14 November 2006.

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener

 

Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class mars.tools.AbstractMarsToolAndApplication
connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
MemoryReferenceVisualization()

          Simple constructor, likely used by the MARS Tools menu mechanism
MemoryReferenceVisualization(java.lang.String title,
java.lang.String heading)

          Simple constructor, likely used to run a stand-alone memory reference visualizer.

 

Method Summary

protected  void addAsObserver()

          Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only.

protected  javax.swing.JComponent buildMainDisplayArea()

          Method that constructs the main display area.

protected  javax.swing.JComponent getHelpComponent()

          Overrides default method, to provide a Help button for this tool/app.

 java.lang.String getName()

          Required MarsTool method to return Tool name.

protected  void initializePostGUI()

          The only post-GUI initialization is to create the initial Grid object based on the default settings
of the various combo boxes.

protected  void initializePreGUI()

          Initialize all JComboBox choice structures not already initialized at declaration.

static void main(java.lang.String[] args)

          Main provided for pure stand-alone use.

protected  void processMIPSUpdate(java.util.Observable memory,
AccessNotice accessNotice)

          Update display when connected MIPS program accesses (data) memory.

protected  void reset()

          Method to reset counters and display when the Reset button selected.

protected  void updateDisplay()

          Updates display immediately after each update (AccessNotice) is processed, after
display configuration changes as needed, and after each execution step when Mars
is running in timed mode.

 
Methods inherited from class mars.tools.AbstractMarsToolAndApplication
action, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, deleteAsObserver, go, isObserving, performSpecialClosingDuties, update

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Constructor Detail

MemoryReferenceVisualization

public MemoryReferenceVisualization(java.lang.String title,
java.lang.String heading)

Simple constructor, likely used to run a stand-alone memory reference visualizer.

Parameters:
title – String containing title for title bar
heading – String containing text for heading shown in upper part of window.

MemoryReferenceVisualization

public MemoryReferenceVisualization()

Simple constructor, likely used by the MARS Tools menu mechanism

Method Detail

main

public static void main(java.lang.String[] args)

Main provided for pure stand-alone use. Recommended stand-alone use is to write a
driver program that instantiates a MemoryReferenceVisualization object then invokes its go() method.
“stand-alone” means it is not invoked from the MARS Tools menu. “Pure” means there
is no driver program to invoke the application.

getName

public java.lang.String getName()

Required MarsTool method to return Tool name.

Specified by:
getName in interface MarsTool
Specified by:
getName in class AbstractMarsToolAndApplication

Returns:
Tool name. MARS will display this in menu item.

addAsObserver

protected void addAsObserver()

Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only. This version will register us as observer over the
the memory range as selected by the base address combo box and capacity of the visualization display
(number of visualization elements times the number of memory words each one represents).
It does so by calling the inherited 2-parameter overload of this method.
If you use the inherited GUI buttons, this
method is invoked when you click “Connect” button on MarsTool or the
“Assemble and Run” button on a Mars-based app.

Overrides:
addAsObserver in class AbstractMarsToolAndApplication

buildMainDisplayArea

protected javax.swing.JComponent buildMainDisplayArea()

Method that constructs the main display area. It is organized vertically
into two major components: the display configuration which an be modified
using combo boxes, and the visualization display which is updated as the
attached MIPS program executes.

Specified by:
buildMainDisplayArea in class AbstractMarsToolAndApplication

Returns:
the GUI component containing these two areas

processMIPSUpdate

protected void processMIPSUpdate(java.util.Observable memory,
AccessNotice accessNotice)

Update display when connected MIPS program accesses (data) memory.

Overrides:
processMIPSUpdate in class AbstractMarsToolAndApplication

Parameters:
memory – the attached memory
accessNotice – information provided by memory in MemoryAccessNotice object

initializePreGUI

protected void initializePreGUI()

Initialize all JComboBox choice structures not already initialized at declaration.
Overrides inherited method that does nothing.

Overrides:
initializePreGUI in class AbstractMarsToolAndApplication

initializePostGUI

protected void initializePostGUI()

The only post-GUI initialization is to create the initial Grid object based on the default settings
of the various combo boxes. Overrides inherited method that does nothing.

Overrides:
initializePostGUI in class AbstractMarsToolAndApplication

reset

protected void reset()

Method to reset counters and display when the Reset button selected.
Overrides inherited method that does nothing.

Overrides:
reset in class AbstractMarsToolAndApplication

updateDisplay

protected void updateDisplay()

Updates display immediately after each update (AccessNotice) is processed, after
display configuration changes as needed, and after each execution step when Mars
is running in timed mode. Overrides inherited method that does nothing.

Overrides:
updateDisplay in class AbstractMarsToolAndApplication

getHelpComponent

protected javax.swing.JComponent getHelpComponent()

Overrides default method, to provide a Help button for this tool/app.

Overrides:
getHelpComponent in class AbstractMarsToolAndApplication

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MarsTool

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Interface MarsTool

All Known Implementing Classes:
AbstractMarsToolAndApplication, BHTSimulator, BitmapDisplay, CacheSimulator, DigitalLabSim, FloatRepresentation, InstructionCounter, InstructionStatistics, IntroToTools, KeyboardAndDisplaySimulator, MarsBot, MemoryReferenceVisualization, ScavengerHunt, ScreenMagnifier

public interface MarsTool

Interface for any tool that interacts with an executing MIPS program.
A qualifying tool must be a class in the Tools package that
implements the MarsTool interface, must be compiled into a .class file,
and its .class file must be in the same Tools folder as MarsTool.class.
Mars will detect a qualifying tool upon startup, create an instance
using its no-argument constructor and add it to its Tools menu.
When its menu item is selected, the action() method will be invoked.

A tool may receive communication from MIPS system resources
(registers or memory) by registering as an Observer with
Mars.Memory and/or Mars.Register objects.

It may also
communicate directly with those resources through their
published methods PROVIDED any such communication is
wrapped inside a block synchronized on the
Mars.Globals.memoryAndRegistersLock object.

Method Summary

 void action()

          Performs tool functions.

 java.lang.String getName()

          Return a name you have chosen for this tool.

 

Method Detail

getName

java.lang.String getName()

Return a name you have chosen for this tool. It will appear as the
menu item.

action

void action()

Performs tool functions. It will be invoked when the tool is selected
from the Tools menu.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

mars.tools

Interfaces 

MarsTool

Classes 

AbstractMarsToolAndApplication

BHTableModel

BHTEntry

BHTSimGUI

BHTSimulator

BitmapDisplay

CacheSimulator

DigitalLabSim

FloatRepresentation

InstructionCounter

InstructionStatistics

IntroToTools

KeyboardAndDisplaySimulator

MarsBot

MemoryReferenceVisualization

ScavengerHunt

ScreenMagnifier

BHTSimGUI

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class BHTSimGUI

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
mars.tools.BHTSimGUI

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible

public class BHTSimGUI
extends javax.swing.JPanel

Represents the GUI of the BHT Simulator Tool.

The GUI consists of mainly four parts:

A configuration panel to select the number of entries and the history size

A information panel that displays the most recent branch instruction including its address and BHT index

A table representing the BHT with all entries and their internal state and statistics

A log panel that summarizes the predictions in a textual form

Author:
ingo. -klu.ac.at
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JPanel
javax.swing.JPanel.AccessibleJPanel

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

static java.lang.String BHT_DO_NOT_TAKE_BRANCH

          constant for the String representing “do not take the branch”

static java.lang.String BHT_TAKE_BRANCH

          constant for the String representing “take the branch”

static java.awt.Color COLOR_PREDICTION_CORRECT

          constant for the color to signal a correct prediction

static java.awt.Color COLOR_PREDICTION_INCORRECT

          constant for the color to signal a misprediction

static java.awt.Color COLOR_PREPREDICTION

          constant for the color that highlights the current BHT entry

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
BHTSimGUI()

          Creates the GUI components of the BHT Simulator
The GUI is a subclass of JPanel which is integrated in the GUI of the MARS tool

 

Method Summary

 javax.swing.JComboBox getCbBHTentries()

          Returns the combo box for selecting the number of BHT entries.

 javax.swing.JComboBox getCbBHThistory()

          Returns the combo box for selecting the size of the BHT history.

 javax.swing.JComboBox getCbBHTinitVal()

          Returns the combo box for selecting the initial value of the BHT

 javax.swing.JTable getTabBHT()

          Returns the table representing the BHT.

 javax.swing.JTextArea getTaLog()

          Returns the text area for log purposes.

 javax.swing.JTextField getTfAddress()

          Returns the text field for displaying the address of the most recent branch instruction

 javax.swing.JTextField getTfIndex()

          Returns the text field for displaying the corresponding index into the BHT

 javax.swing.JTextField getTfInstruction()

          Returns the text field for displaying the most recent branch instruction

 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

COLOR_PREPREDICTION

public static final java.awt.Color COLOR_PREPREDICTION

constant for the color that highlights the current BHT entry

COLOR_PREDICTION_CORRECT

public static final java.awt.Color COLOR_PREDICTION_CORRECT

constant for the color to signal a correct prediction

COLOR_PREDICTION_INCORRECT

public static final java.awt.Color COLOR_PREDICTION_INCORRECT

constant for the color to signal a misprediction

BHT_TAKE_BRANCH

public static final java.lang.String BHT_TAKE_BRANCH

constant for the String representing “take the branch”

See Also:
Constant Field Values

BHT_DO_NOT_TAKE_BRANCH

public static final java.lang.String BHT_DO_NOT_TAKE_BRANCH

constant for the String representing “do not take the branch”

See Also:
Constant Field Values

Constructor Detail

BHTSimGUI

public BHTSimGUI()

Creates the GUI components of the BHT Simulator
The GUI is a subclass of JPanel which is integrated in the GUI of the MARS tool

Method Detail

getCbBHTentries

public javax.swing.JComboBox getCbBHTentries()

Returns the combo box for selecting the number of BHT entries.

Returns:
the reference to the combo box

getCbBHThistory

public javax.swing.JComboBox getCbBHThistory()

Returns the combo box for selecting the size of the BHT history.

Returns:
the reference to the combo box

getCbBHTinitVal

public javax.swing.JComboBox getCbBHTinitVal()

Returns the combo box for selecting the initial value of the BHT

Returns:
the reference to the combo box

getTabBHT

public javax.swing.JTable getTabBHT()

Returns the table representing the BHT.

Returns:
the reference to the table

getTaLog

public javax.swing.JTextArea getTaLog()

Returns the text area for log purposes.

Returns:
the reference to the text area

getTfInstruction

public javax.swing.JTextField getTfInstruction()

Returns the text field for displaying the most recent branch instruction

Returns:
the reference to the text field

getTfAddress

public javax.swing.JTextField getTfAddress()

Returns the text field for displaying the address of the most recent branch instruction

Returns:
the reference to the text field

getTfIndex

public javax.swing.JTextField getTfIndex()

Returns the text field for displaying the corresponding index into the BHT

Returns:
the reference to the text field

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

BHTableModel

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class BHTableModel

java.lang.Object
javax.swing.table.AbstractTableModel
mars.tools.BHTableModel

All Implemented Interfaces:
java.io.Serializable, javax.swing.table.TableModel

public class BHTableModel
extends javax.swing.table.AbstractTableModel

Simulates the actual functionality of a Branch History Table (BHT).

The BHT consists of a number of BHT entries which are used to perform branch prediction.
The entries of the BHT are stored as a Vector of BHTEntry objects.
The number of entries is configurable but has to be a power of 2.
The history kept by each BHT entry is also configurable during run-time.
A change of the configuration however causes a complete reset of the BHT.

The typical interaction is as follows:

Construction of a BHT with a certain number of entries with a given history size.
When encountering a branch instruction the index of the relevant BHT entry is calculated via the getIdxForAddress(int) method.
The current prediction of the BHT entry at the calculated index is obtained via the getPredictionAtIdx(int) method.
After detecting if the branch was really taken or not, this feedback is provided to the BHT by the updatePredictionAtIdx(int, boolean) method.

Additionally it serves as TableModel that can be directly used to render the state of the BHT in a JTable.
Feedback provided to the BHT causes a change of the internal state and a repaint of the table(s) associated to this model.

Author:
ingo. -klu.ac.at
See Also:
Serialized Form

Field Summary

 
Fields inherited from class javax.swing.table.AbstractTableModel
listenerList

 

Constructor Summary
BHTableModel(int numEntries,
int historySize,
boolean initVal)

          Constructs a new BHT with given number of entries and history size.

 

Method Summary

 java.lang.Class getColumnClass(int i)

          Returns the class/type of the i-th column of the table.

 int getColumnCount()

          Returns the number of columns.

 java.lang.String getColumnName(int i)

          Returns the name of the i-th column of the table.

 int getIdxForAddress(int address)

          Returns the index into the BHT for a given branch instruction address.

 boolean getPredictionAtIdx(int index)

          Retrieve the prediction for the i-th BHT entry.

 int getRowCount()

          Returns the number of entries of the BHT.

 java.lang.Object getValueAt(int row,
int col)

          Returns the value of the cell at the given row and column
Required by the TableModel interface.

 void initBHT(int numEntries,
int historySize,
boolean initVal)

          Initializes the BHT with the given size and history.

 void updatePredictionAtIdx(int index,
boolean branchTaken)

          Updates the BHT entry with the outcome of the branch instruction.

 
Methods inherited from class javax.swing.table.AbstractTableModel
addTableModelListener, findColumn, fireTableCellUpdated, fireTableChanged, fireTableDataChanged, fireTableRowsDeleted, fireTableRowsInserted, fireTableRowsUpdated, fireTableStructureChanged, getListeners, getTableModelListeners, isCellEditable, removeTableModelListener, setValueAt

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

BHTableModel

public BHTableModel(int numEntries,
int historySize,
boolean initVal)

Constructs a new BHT with given number of entries and history size.

Parameters:
numEntries – number of entries in the BHT
historySize – size of the history (in bits/number of past branches)

Method Detail

getColumnName

public java.lang.String getColumnName(int i)

Returns the name of the i-th column of the table.
Required by the TableModel interface.

Specified by:
getColumnName in interface javax.swing.table.TableModel
Overrides:
getColumnName in class javax.swing.table.AbstractTableModel

Parameters:
i – the index of the column

Returns:
name of the i-th column

getColumnClass

public java.lang.Class getColumnClass(int i)

Returns the class/type of the i-th column of the table.
Required by the TableModel interface.

Specified by:
getColumnClass in interface javax.swing.table.TableModel
Overrides:
getColumnClass in class javax.swing.table.AbstractTableModel

Parameters:
i – the index of the column

Returns:
class representing the type of the i-th column

getColumnCount

public int getColumnCount()

Returns the number of columns.
Required by the TableModel interface.

Returns:
currently the constant 6

getRowCount

public int getRowCount()

Returns the number of entries of the BHT.
Required by the TableModel interface.

Returns:
number of rows / entries of the BHT

getValueAt

public java.lang.Object getValueAt(int row,
int col)

Returns the value of the cell at the given row and column
Required by the TableModel interface.

Parameters:
row – the row index
col – the column index

Returns:
the value of the cell

initBHT

public void initBHT(int numEntries,
int historySize,
boolean initVal)

Initializes the BHT with the given size and history.
All previous data like the BHT entries’ history and statistics will get lost.
A refresh of the table that use this BHT as model will be triggered.

Parameters:
numEntries – number of entries in the BHT (has to be a power of 2)
historySize – size of the history to consider
initVal – initial value for each entry (true means take branch, false do not take branch)

getIdxForAddress

public int getIdxForAddress(int address)

Returns the index into the BHT for a given branch instruction address.
A simple direct mapping is used.

Parameters:
address – the address of the branch instruction

Returns:
the index into the BHT

getPredictionAtIdx

public boolean getPredictionAtIdx(int index)

Retrieve the prediction for the i-th BHT entry.

Parameters:
index – the index of the entry in the BHT

Returns:
the prediction to take (true) or do not take (false) the branch

updatePredictionAtIdx

public void updatePredictionAtIdx(int index,
boolean branchTaken)

Updates the BHT entry with the outcome of the branch instruction.
This causes a change in the model and signals to update the connected table(s).

Parameters:
index – the index of the entry in the BHT
branchTaken –

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.tools

Interface Summary
MarsTool Interface for any tool that interacts with an executing MIPS program.

 

Class Summary
AbstractMarsToolAndApplication An abstract class that provides generic components to facilitate implementation of
a MarsTool and/or stand-alone Mars-based application.
BHTableModel Simulates the actual functionality of a Branch History Table (BHT).
BHTEntry Represents a single entry of the Branch History Table.
BHTSimGUI Represents the GUI of the BHT Simulator Tool.
BHTSimulator A MARS tool for simulating branch prediction with a Branch History Table (BHT)
BitmapDisplay Bitmapp display simulator.
CacheSimulator A data cache simulator.
DigitalLabSim  
FloatRepresentation Tool to help students learn about IEEE 754 representation of 32 bit
floating point values.
InstructionCounter Instruction counter tool.
InstructionStatistics A MARS tool for obtaining instruction statistics by instruction category.
IntroToTools The “hello world” of MarsTools!
KeyboardAndDisplaySimulator Keyboard and Display Simulator.
MarsBot Simple Demo of Mars tool capability
MemoryReferenceVisualization Memory reference visualization.
ScavengerHunt Demo of Mars tool capability.
ScreenMagnifier Handy little tool to magnify a selected section of the screen
by a given scale and display it.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

AbstractMarsToolAndApplication

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class AbstractMarsToolAndApplication

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

Direct Known Subclasses:
BHTSimulator, BitmapDisplay, CacheSimulator, DigitalLabSim, FloatRepresentation, InstructionCounter, InstructionStatistics, IntroToTools, KeyboardAndDisplaySimulator, MemoryReferenceVisualization

public abstract class AbstractMarsToolAndApplication
extends javax.swing.JFrame
implements MarsTool, java.util.Observer

An abstract class that provides generic components to facilitate implementation of
a MarsTool and/or stand-alone Mars-based application. Provides default definitions
of both the action() method required to implement MarsTool and the go() method
conventionally used to launch a Mars-based stand-alone application. It also provides
generic definitions for interactively controlling the application. The generic controls
for MarsTools are 3 buttons: connect/disconnect to MIPS resource (memory and/or
registers), reset, and close (exit). The generic controls for stand-alone Mars apps
include: button that triggers a file open dialog, a text field to display status
messages, the run-speed slider to control execution rate when running a MIPS program,
a button that assembles and runs the current MIPS program, a button to interrupt
the running MIPS program, a reset button, and an exit button.
Pete Sanderson, 14 November 2006.

See Also:
Serialized Form

Nested Class Summary

protected  class AbstractMarsToolAndApplication.ConnectButton

           

protected  class AbstractMarsToolAndApplication.EnterKeyListener

           

 
Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

protected  AbstractMarsToolAndApplication.ConnectButton connectButton

           

protected  boolean isBeingUsedAsAMarsTool

           

protected  java.awt.Window theWindow

           

protected  AbstractMarsToolAndApplication thisMarsApp

           

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary

protected AbstractMarsToolAndApplication(java.lang.String title,
java.lang.String heading)

          Simple constructor

 

Method Summary

 void action()

          Required MarsTool method to carry out Tool functions.

protected  void addAsObserver()

          Add this app/tool as an Observer of desired MIPS Observables (memory and registers).

protected  void addAsObserver(int lowEnd,
int highEnd)

          Add this app/tool as an Observer of the specified subrange of MIPS memory.

protected  void addAsObserver(Register reg)

          Add this app/tool as an Observer of the specified MIPS register.

protected  javax.swing.JComponent buildButtonAreaMarsTool()

          The MarsTool default set of controls has one row of 3 buttons.

protected  javax.swing.JComponent buildButtonAreaStandAlone()

          The Mars stand-alone app default set of controls has two rows of controls.

protected  javax.swing.JComponent buildHeadingArea()

          Constructs GUI header as label with default positioning and font.

protected abstract  javax.swing.JComponent buildMainDisplayArea()

          Abstract method that must be instantiated by subclass to build the main display area
of the GUI.

protected  void deleteAsObserver()

          Delete this app/tool as an Observer of MIPS Observables (memory and registers).

protected  void deleteAsObserver(Register reg)

          Delete this app/tool as an Observer of the specified MIPS register

protected  javax.swing.JComponent getHelpComponent()

          Override this method to provide a JComponent (probably a JButton) of your choice
to be placed just left of the Close/Exit button.

abstract  java.lang.String getName()

          Required MarsTool method to return Tool name.

 void go()

          Run the simulator as stand-alone application.

protected  void initializePostGUI()

          Method that will be called once just after the GUI is constructed in the go() and action()
methods.

protected  void initializePreGUI()

          Method that will be called once just before the GUI is constructed in the go() and action()
methods.

protected  boolean isObserving()

          Query method to let you know if the tool/app is (or could be) currently
“observing” any MIPS resources.

protected  void performSpecialClosingDuties()

          This method is called when tool/app is exited either through the close/exit button or the window’s X box.

protected  void processMIPSUpdate(java.util.Observable resource,
AccessNotice notice)

          Override this method to process a received notice from MIPS Observable (memory or register)
It will only be called if the notice was generated as the result of MIPS instruction execution.

protected  void reset()

          Method that will be called each time the default Reset button is clicked.

 void update(java.util.Observable resource,
java.lang.Object accessNotice)

          Called when receiving notice of access to MIPS memory or registers.

protected  void updateDisplay()

          Override this method to implement updating of GUI after each MIPS instruction is executed,
while running in “timed” mode (user specifies execution speed on the slider control).

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Field Detail

isBeingUsedAsAMarsTool

protected boolean isBeingUsedAsAMarsTool

thisMarsApp

protected AbstractMarsToolAndApplication thisMarsApp

theWindow

protected java.awt.Window theWindow

connectButton

protected AbstractMarsToolAndApplication.ConnectButton connectButton

Constructor Detail

AbstractMarsToolAndApplication

protected AbstractMarsToolAndApplication(java.lang.String title,
java.lang.String heading)

Simple constructor

Parameters:
title – String containing title bar text

Method Detail

getName

public abstract java.lang.String getName()

Required MarsTool method to return Tool name. Must be defined by subclass.

Specified by:
getName in interface MarsTool
Overrides:
getName in class java.awt.Component

Returns:
Tool name. MARS will display this in menu item.

buildMainDisplayArea

protected abstract javax.swing.JComponent buildMainDisplayArea()

Abstract method that must be instantiated by subclass to build the main display area
of the GUI. It will be placed in the CENTER area of a BorderLayout. The title
is in the NORTH area, and the controls are in the SOUTH area.

go

public void go()

Run the simulator as stand-alone application. For this default implementation,
the user-defined main display of the user interface is identical for both stand-alone
and MARS Tools menu use, but the control buttons are different because the stand-alone
must include a mechansim for controlling the opening, assembling, and executing of
an underlying MIPS program. The generic controls include: a button that triggers a
file open dialog, a text field to display status messages, the run-speed slider
to control execution rate when running a MIPS program, a button that assembles and
runs the current MIPS program, a reset button, and an exit button.
This method calls 3 methods that can be defined/overriden in the subclass: initializePreGUI()
for any special initialization that must be completed before building the user
interface (e.g. data structures whose properties determine default GUI settings),
initializePostGUI() for any special initialization that cannot be
completed until after the building the user interface (e.g. data structure whose
properties are determined by default GUI settings), and buildMainDisplayArea()
to contain application-specific displays of parameters and results.

action

public void action()

Required MarsTool method to carry out Tool functions. It is invoked when MARS
user selects this tool from the Tools menu. This default implementation provides
generic definitions for interactively controlling the tool. The generic controls
for MarsTools are 3 buttons: connect/disconnect to MIPS resource (memory and/or
registers), reset, and close (exit). Like “go()” above, this default version
calls 3 methods that can be defined/overriden in the subclass: initializePreGUI()
for any special initialization that must be completed before building the user
interface (e.g. data structures whose properties determine default GUI settings),
initializePostGUI() for any special initialization that cannot be
completed until after the building the user interface (e.g. data structure whose
properties are determined by default GUI settings), and buildMainDisplayArea()
to contain application-specific displays of parameters and results.

Specified by:
action in interface MarsTool

initializePreGUI

protected void initializePreGUI()

Method that will be called once just before the GUI is constructed in the go() and action()
methods. Use it to initialize any data structures needed for the application whose values
will be needed to determine the initial state of GUI components. By default it does nothing.

initializePostGUI

protected void initializePostGUI()

Method that will be called once just after the GUI is constructed in the go() and action()
methods. Use it to initialize data structures needed for the application whose values
may depend on the initial state of GUI components. By default it does nothing.

reset

protected void reset()

Method that will be called each time the default Reset button is clicked.
Use it to reset any data structures and/or GUI components. By default it does nothing.

buildHeadingArea

protected javax.swing.JComponent buildHeadingArea()

Constructs GUI header as label with default positioning and font. May be overridden.

buildButtonAreaMarsTool

protected javax.swing.JComponent buildButtonAreaMarsTool()

The MarsTool default set of controls has one row of 3 buttons. It includes a dual-purpose button to
attach or detach simulator to MIPS memory, a button to reset the cache, and one to close the tool.

buildButtonAreaStandAlone

protected javax.swing.JComponent buildButtonAreaStandAlone()

The Mars stand-alone app default set of controls has two rows of controls. It includes a text field for
displaying status messages, a button to trigger an open file dialog, the MARS run speed slider
to control timed execution, a button to assemble and run the program, a reset button
whose action is determined by the subclass reset() method, and an exit button.

update

public void update(java.util.Observable resource,
java.lang.Object accessNotice)

Called when receiving notice of access to MIPS memory or registers. Default
implementation of method required by Observer interface. This method will filter out
notices originating from the MARS GUI or from direct user editing of memory or register
displays. Only notices arising from MIPS program access are allowed in.
It then calls two methods to be overridden by the subclass (since they do
nothing by default): processMIPSUpdate() then updateDisplay().

Specified by:
update in interface java.util.Observer

Parameters:
resource – the attached MIPS resource
accessNotice – AccessNotice information provided by the resource

processMIPSUpdate

protected void processMIPSUpdate(java.util.Observable resource,
AccessNotice notice)

Override this method to process a received notice from MIPS Observable (memory or register)
It will only be called if the notice was generated as the result of MIPS instruction execution.
By default it does nothing. After this method is complete, the updateDisplay() method will be
invoked automatically.

performSpecialClosingDuties

protected void performSpecialClosingDuties()

This method is called when tool/app is exited either through the close/exit button or the window’s X box.
Override it to perform any special housecleaning needed. By default it does nothing.

addAsObserver

protected void addAsObserver()

Add this app/tool as an Observer of desired MIPS Observables (memory and registers).
By default, will add as an Observer of the entire Data Segment in memory.
Override if you want something different. Note that the Memory methods to add an
Observer to memory are flexible (you can register for a range of addresses) but
may throw an AddressErrorException that you need to catch.
This method is called whenever the default “Connect” button on a MarsTool or the
default “Assemble and run” on a stand-alone Mars app is selected. The corresponding
NOTE: if you do not want to register as an Observer of the entire data segment
(starts at address 0x10000000) then override this to either do some alternative
or nothing at all. This method is also overloaded to allow arbitrary memory
subrange.

addAsObserver

protected void addAsObserver(int lowEnd,
int highEnd)

Add this app/tool as an Observer of the specified subrange of MIPS memory. Note
that this method is not invoked automatically like the no-argument version, but
if you use this method, you can still take advantage of provided default deleteAsObserver()
since it will remove the app as a memory observer regardless of the subrange
or number of subranges it is registered for.

Parameters:
lowEnd – low end of memory address range.
highEnd – high end of memory address range; must be >= lowEnd

addAsObserver

protected void addAsObserver(Register reg)

Add this app/tool as an Observer of the specified MIPS register.

deleteAsObserver

protected void deleteAsObserver()

Delete this app/tool as an Observer of MIPS Observables (memory and registers).
By default, will delete as an Observer of memory.
Override if you want something different.
This method is called when the default “Disconnect” button on a MarsTool is selected or
when the MIPS program execution triggered by the default “Assemble and run” on a stand-alone
Mars app terminates (e.g. when the button is re-enabled).

deleteAsObserver

protected void deleteAsObserver(Register reg)

Delete this app/tool as an Observer of the specified MIPS register

isObserving

protected boolean isObserving()

Query method to let you know if the tool/app is (or could be) currently
“observing” any MIPS resources. When running as a MarsTool, this
will be true by default after clicking the “Connect to MIPS” button until “Disconnect
from MIPS” is clicked. When running as a stand-alone app, this will be
true by default after clicking the “Assemble and Run” button until until
program execution has terminated either normally or by clicking the “Stop”
button. The phrase “or could be” was added above because depending on how
the tool/app operates, it may be possible to run the MIPS program without
first registering as an Observer — i.e. addAsObserver() is overridden and
takes no action.

Returns:
true if tool/app is (or could be) currently active as an Observer.

updateDisplay

protected void updateDisplay()

Override this method to implement updating of GUI after each MIPS instruction is executed,
while running in “timed” mode (user specifies execution speed on the slider control).
Does nothing by default.

getHelpComponent

protected javax.swing.JComponent getHelpComponent()

Override this method to provide a JComponent (probably a JButton) of your choice
to be placed just left of the Close/Exit button. Its anticipated use is for a
“help” button that launches a help message or dialog. But it can be any valid
JComponent that doesn’t mind co-existing among a bunch of JButtons.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.tools

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object javax.swing.table.AbstractTableModel (implements java.io.Serializable, javax.swing.table.TableModel)
mars.tools.BHTableModel

mars.tools.BHTEntry
java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
java.awt.Container javax.swing.JComponent (implements java.io.Serializable)
javax.swing.AbstractButton (implements java.awt.ItemSelectable, javax.swing.SwingConstants)
javax.swing.JButton (implements javax.accessibility.Accessible)
mars.tools.AbstractMarsToolAndApplication.ConnectButton

mars.tools.DigitalLabSim.SevenSegmentDisplay
javax.swing.JPanel (implements javax.accessibility.Accessible)
mars.tools.BHTSimGUI
mars.tools.DigitalLabSim.HexaKeyboard
mars.tools.DigitalLabSim.SevenSegmentPanel

java.awt.Window (implements javax.accessibility.Accessible)
java.awt.Frame (implements java.awt.MenuContainer)
javax.swing.JFrame (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants)
mars.tools.AbstractMarsToolAndApplication (implements mars.tools.MarsTool, java.util.Observer)
mars.tools.BHTSimulator (implements java.awt.event.ActionListener)

mars.tools.BitmapDisplay
mars.tools.CacheSimulator
mars.tools.DigitalLabSim
mars.tools.FloatRepresentation
mars.tools.InstructionCounter
mars.tools.InstructionStatistics
mars.tools.IntroToTools
mars.tools.KeyboardAndDisplaySimulator
mars.tools.MemoryReferenceVisualization

mars.tools.DigitalLabSim.HexaKeyboard.EcouteurClick (implements java.awt.event.MouseListener)

mars.tools.DigitalLabSim.OneSecondCounter
java.awt.event.KeyAdapter (implements java.awt.event.KeyListener)
mars.tools.AbstractMarsToolAndApplication.EnterKeyListener

mars.tools.MarsBot (implements mars.tools.MarsTool, java.util.Observer)

mars.tools.ScavengerHunt (implements mars.tools.MarsTool, java.util.Observer)

mars.tools.ScreenMagnifier (implements mars.tools.MarsTool)

Interface Hierarchy

mars.tools.MarsTool

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

ScavengerHunt

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class ScavengerHunt

java.lang.Object
mars.tools.ScavengerHunt

All Implemented Interfaces:
java.util.Observer, MarsTool

public class ScavengerHunt
extends java.lang.Object
implements java.util.Observer, MarsTool

Demo of Mars tool capability. Ken Vollmar, 27 Oct 2006
This tool displays movements by a series of players in a game of ScavengerHunt.
Players will read and write MIPS memory-mapped locations to move and regain energy.
See accompanying documentation for memory-mapped addresses, rules of the game, etc.

Constructor Summary
ScavengerHunt()

           

 

Method Summary

 void action()

          Performs tool functions.

 java.lang.String getName()

          Return a name you have chosen for this tool.

 void update(java.util.Observable o,
java.lang.Object arg)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

ScavengerHunt

public ScavengerHunt()

Method Detail

getName

public java.lang.String getName()

Description copied from interface: MarsTool
Return a name you have chosen for this tool. It will appear as the
menu item.

Specified by:
getName in interface MarsTool

action

public void action()

Description copied from interface: MarsTool
Performs tool functions. It will be invoked when the tool is selected
from the Tools menu.

Specified by:
action in interface MarsTool

update

public void update(java.util.Observable o,
java.lang.Object arg)

Specified by:
update in interface java.util.Observer

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DigitalLabSim.OneSecondCounter

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class DigitalLabSim.OneSecondCounter

java.lang.Object
mars.tools.DigitalLabSim.OneSecondCounter

Enclosing class:
DigitalLabSim

public class DigitalLabSim.OneSecondCounter
extends java.lang.Object

Constructor Summary
DigitalLabSim.OneSecondCounter()

           

 

Method Summary

 void resetOneSecondCounter()

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

DigitalLabSim.OneSecondCounter

public DigitalLabSim.OneSecondCounter()

Method Detail

resetOneSecondCounter

public void resetOneSecondCounter()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

BHTEntry

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class BHTEntry

java.lang.Object
mars.tools.BHTEntry

public class BHTEntry
extends java.lang.Object

Represents a single entry of the Branch History Table.

The entry holds the information about former branch predictions and outcomes.
The number of past branch outcomes can be configured and is called the history.
The semantics of the history of size n is as follows.
The entry will change its prediction, if it mispredicts the branch n times in series.
The prediction of the entry can be obtained by the getPrediction() method.
Feedback of taken or not taken branches is provided to the entry via the updatePrediction(boolean) method.
This causes the history and the prediction to be updated.

Additionally the entry keeps track about how many times the prediction was correct or incorrect.
The statistics can be obtained by the methods getStatsPredCorrect(), getStatsPredIncorrect() and getStatsPredPrecision().

Author:
ingo. -klu.ac.at

Constructor Summary
BHTEntry(int historySize,
boolean initVal)

          Constructs a BHT entry with a given history size.

 

Method Summary

 java.lang.String getHistoryAsStr()

          Builds a string representation of the BHT entry’s history.

 boolean getPrediction()

          Returns the branch prediction based on the history.

 java.lang.String getPredictionAsStr()

          Returns a string representation of the BHT entry’s current prediction.

 int getStatsPredCorrect()

          Get the absolute number of correct predictions.

 int getStatsPredIncorrect()

          Get the absolute number of mispredictions.

 double getStatsPredPrecision()

          Get the percentage of correct predictions.

 void updatePrediction(boolean branchTaken)

          Updates the entry’s history and prediction.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

BHTEntry

public BHTEntry(int historySize,
boolean initVal)

Constructs a BHT entry with a given history size.

The size of the history can only be set via the constructor and cannot be changed afterwards.

Parameters:
historySize – number of past branch outcomes to remember
initVal – the initial value of the entry (take or do not take)

Method Detail

getPrediction

public boolean getPrediction()

Returns the branch prediction based on the history.

Returns:
true if prediction is to take the branch, false otherwise

updatePrediction

public void updatePrediction(boolean branchTaken)

Updates the entry’s history and prediction.
This method provides feedback for a prediction.
The history and the statistics are updated accordingly.
Based on the updated history a new prediction is calculated

Parameters:
branchTaken – signals if the branch was taken (true) or not (false)

getStatsPredIncorrect

public int getStatsPredIncorrect()

Get the absolute number of mispredictions.

Returns:
number of incorrect predictions (mispredictions)

getStatsPredCorrect

public int getStatsPredCorrect()

Get the absolute number of correct predictions.

Returns:
number of correct predictions

getStatsPredPrecision

public double getStatsPredPrecision()

Get the percentage of correct predictions.

Returns:
the percentage of correct predictions

getHistoryAsStr

public java.lang.String getHistoryAsStr()

Builds a string representation of the BHT entry’s history.
The history is a sequence of flags that signal if the branch was taken (T) or not taken (NT).

Returns:
a string representation of the BHT entry’s history

getPredictionAsStr

public java.lang.String getPredictionAsStr()

Returns a string representation of the BHT entry’s current prediction.
The prediction can be either to TAKE or do NOT TAKE the branch.

Returns:
a string representation of the BHT entry’s current prediction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

AbstractMarsToolAndApplication.EnterKeyListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class AbstractMarsToolAndApplication.EnterKeyListener

java.lang.Object
java.awt.event.KeyAdapter
mars.tools.AbstractMarsToolAndApplication.EnterKeyListener

All Implemented Interfaces:
java.awt.event.KeyListener, java.util.EventListener

Enclosing class:
AbstractMarsToolAndApplication

protected class AbstractMarsToolAndApplication.EnterKeyListener
extends java.awt.event.KeyAdapter

Constructor Summary
AbstractMarsToolAndApplication.EnterKeyListener(javax.swing.AbstractButton who)

           

 

Method Summary

 void keyPressed(java.awt.event.KeyEvent e)

           

 
Methods inherited from class java.awt.event.KeyAdapter
keyReleased, keyTyped

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

AbstractMarsToolAndApplication.EnterKeyListener

public AbstractMarsToolAndApplication.EnterKeyListener(javax.swing.AbstractButton who)

Method Detail

keyPressed

public void keyPressed(java.awt.event.KeyEvent e)

Specified by:
keyPressed in interface java.awt.event.KeyListener
Overrides:
keyPressed in class java.awt.event.KeyAdapter

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

BitmapDisplay

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class BitmapDisplay

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.tools.AbstractMarsToolAndApplication
mars.tools.BitmapDisplay

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants, MarsTool

public class BitmapDisplay
extends AbstractMarsToolAndApplication

Bitmapp display simulator. It can be run either as a stand-alone Java application having
access to the mars package, or through MARS as an item in its Tools menu. It makes
maximum use of methods inherited from its abstract superclass AbstractMarsToolAndApplication.
Pete Sanderson, verison 1.0, 23 December 2010.

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.tools.AbstractMarsToolAndApplication
AbstractMarsToolAndApplication.ConnectButton, AbstractMarsToolAndApplication.EnterKeyListener

 

Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class mars.tools.AbstractMarsToolAndApplication
connectButton, isBeingUsedAsAMarsTool, theWindow, thisMarsApp

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
BitmapDisplay()

          Simple constructor, likely used by the MARS Tools menu mechanism
BitmapDisplay(java.lang.String title,
java.lang.String heading)

          Simple constructor, likely used to run a stand-alone bitmap display tool.

 

Method Summary

protected  void addAsObserver()

          Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only.

protected  javax.swing.JComponent buildMainDisplayArea()

          Method that constructs the main display area.

protected  javax.swing.JComponent getHelpComponent()

          Overrides default method, to provide a Help button for this tool/app.

 java.lang.String getName()

          Required MarsTool method to return Tool name.

protected  void initializePostGUI()

          The only post-GUI initialization is to create the initial Grid object based on the default settings
of the various combo boxes.

protected  void initializePreGUI()

          Initialize all JComboBox choice structures not already initialized at declaration.

static void main(java.lang.String[] args)

          Main provided for pure stand-alone use.

protected  void processMIPSUpdate(java.util.Observable memory,
AccessNotice accessNotice)

          Update display when connected MIPS program accesses (data) memory.

protected  void reset()

          Method to reset counters and display when the Reset button selected.

protected  void updateDisplay()

          Updates display immediately after each update (AccessNotice) is processed, after
display configuration changes as needed, and after each execution step when Mars
is running in timed mode.

 
Methods inherited from class mars.tools.AbstractMarsToolAndApplication
action, addAsObserver, addAsObserver, buildButtonAreaMarsTool, buildButtonAreaStandAlone, buildHeadingArea, deleteAsObserver, deleteAsObserver, go, isObserving, performSpecialClosingDuties, update

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Constructor Detail

BitmapDisplay

public BitmapDisplay(java.lang.String title,
java.lang.String heading)

Simple constructor, likely used to run a stand-alone bitmap display tool.

Parameters:
title – String containing title for title bar
heading – String containing text for heading shown in upper part of window.

BitmapDisplay

public BitmapDisplay()

Simple constructor, likely used by the MARS Tools menu mechanism

Method Detail

main

public static void main(java.lang.String[] args)

Main provided for pure stand-alone use. Recommended stand-alone use is to write a
driver program that instantiates a Bitmap object then invokes its go() method.
“stand-alone” means it is not invoked from the MARS Tools menu. “Pure” means there
is no driver program to invoke the application.

getName

public java.lang.String getName()

Required MarsTool method to return Tool name.

Specified by:
getName in interface MarsTool
Specified by:
getName in class AbstractMarsToolAndApplication

Returns:
Tool name. MARS will display this in menu item.

addAsObserver

protected void addAsObserver()

Override the inherited method, which registers us as an Observer over the static data segment
(starting address 0x10010000) only. This version will register us as observer over the
the memory range as selected by the base address combo box and capacity of the visualization display
(number of visualization elements times the number of memory words each one represents).
It does so by calling the inherited 2-parameter overload of this method.
If you use the inherited GUI buttons, this
method is invoked when you click “Connect” button on MarsTool or the
“Assemble and Run” button on a Mars-based app.

Overrides:
addAsObserver in class AbstractMarsToolAndApplication

buildMainDisplayArea

protected javax.swing.JComponent buildMainDisplayArea()

Method that constructs the main display area. It is organized vertically
into two major components: the display configuration which an be modified
using combo boxes, and the visualization display which is updated as the
attached MIPS program executes.

Specified by:
buildMainDisplayArea in class AbstractMarsToolAndApplication

Returns:
the GUI component containing these two areas

processMIPSUpdate

protected void processMIPSUpdate(java.util.Observable memory,
AccessNotice accessNotice)

Update display when connected MIPS program accesses (data) memory.

Overrides:
processMIPSUpdate in class AbstractMarsToolAndApplication

Parameters:
memory – the attached memory
accessNotice – information provided by memory in MemoryAccessNotice object

initializePreGUI

protected void initializePreGUI()

Initialize all JComboBox choice structures not already initialized at declaration.
Overrides inherited method that does nothing.

Overrides:
initializePreGUI in class AbstractMarsToolAndApplication

initializePostGUI

protected void initializePostGUI()

The only post-GUI initialization is to create the initial Grid object based on the default settings
of the various combo boxes. Overrides inherited method that does nothing.

Overrides:
initializePostGUI in class AbstractMarsToolAndApplication

reset

protected void reset()

Method to reset counters and display when the Reset button selected.
Overrides inherited method that does nothing.

Overrides:
reset in class AbstractMarsToolAndApplication

updateDisplay

protected void updateDisplay()

Updates display immediately after each update (AccessNotice) is processed, after
display configuration changes as needed, and after each execution step when Mars
is running in timed mode. Overrides inherited method that does nothing.

Overrides:
updateDisplay in class AbstractMarsToolAndApplication

getHelpComponent

protected javax.swing.JComponent getHelpComponent()

Overrides default method, to provide a Help button for this tool/app.

Overrides:
getHelpComponent in class AbstractMarsToolAndApplication

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DigitalLabSim.HexaKeyboard

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.tools

Class DigitalLabSim.HexaKeyboard

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
mars.tools.DigitalLabSim.HexaKeyboard

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible

Enclosing class:
DigitalLabSim

public class DigitalLabSim.HexaKeyboard
extends javax.swing.JPanel

See Also:
Serialized Form

Nested Class Summary

 class DigitalLabSim.HexaKeyboard.EcouteurClick

           

 
Nested classes/interfaces inherited from class javax.swing.JPanel
javax.swing.JPanel.AccessibleJPanel

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 javax.swing.JButton[] button

           

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
DigitalLabSim.HexaKeyboard()

           

 

Method Summary

 void resetHexaKeyboard()

           

 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

button

public javax.swing.JButton[] button

Constructor Detail

DigitalLabSim.HexaKeyboard

public DigitalLabSim.HexaKeyboard()

Method Detail

resetHexaKeyboard

public void resetHexaKeyboard()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MacroPool

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class MacroPool

java.lang.Object
mars.assembler.MacroPool

public class MacroPool
extends java.lang.Object

Stores information of macros defined by now.

Will be used in first pass of assembling MIPS source code. When reached
.macro directive, parser calls
MacroPool#BeginMacro(String, int) and skips source code lines until
reaches .end_macro directive. then calls
MacroPool#CommitMacro(int) and the macro information stored in a
Macro instance will be added to macroList.

Each MIPSprogram will have one MacroPool

NOTE: Forward referencing macros (macro expansion before its definition in
source code) and Nested macro definition (defining a macro inside other macro
definition) are not supported.

Author:
M.H.Sekhavat

Constructor Summary
MacroPool(MIPSprogram mipsProgram)

          Create an empty MacroPool for given program

 

Method Summary

 void beginMacro(Token nameToken)

          This method will be called by parser when reached .macro
directive.

Instantiates a new Macro object and stores it in current
.

 void commitMacro(Token endToken)

          This method will be called by parser when reached .end_macro
directive.

 java.util.ArrayList getCallStack()

           

 Macro getCurrent()

           

 java.lang.String getExpansionHistory()

           

 Macro getMatchingMacro(TokenList tokens,
int callerLine)

          Will be called by parser when reaches a macro expansion call

 int getNextCounter()

          counter will be set to 0 on construction of this class and will
be incremented by each call.

 boolean matchesAnyMacroName(java.lang.String value)

           

 void popFromCallStack()

           

 boolean pushOnCallStack(Token token)

           

 void setCurrent(Macro current)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

MacroPool

public MacroPool(MIPSprogram mipsProgram)

Create an empty MacroPool for given program

Parameters:
mipsProgram – associated MIPS program

Method Detail

beginMacro

public void beginMacro(Token nameToken)

This method will be called by parser when reached .macro
directive.

Instantiates a new Macro object and stores it in current
. current will be added to macroList by
#CommitMacro(int)

Parameters:
nameToken – Token containing name of macro after .macro directive

commitMacro

public void commitMacro(Token endToken)

This method will be called by parser when reached .end_macro
directive.

Adds/Replaces current macro into the macroList.

Parameters:
endToken – Token containing .end_macro directive in source code

getMatchingMacro

public Macro getMatchingMacro(TokenList tokens,
int callerLine)

Will be called by parser when reaches a macro expansion call

Parameters:
tokens – tokens passed to macro expansion call

Returns:
Macro object matching the name and argument count of
tokens passed

matchesAnyMacroName

public boolean matchesAnyMacroName(java.lang.String value)

Parameters:
value –

Returns:
true if any macros have been defined with name value
by now, not concerning arguments count.

getCurrent

public Macro getCurrent()

setCurrent

public void setCurrent(Macro current)

getNextCounter

public int getNextCounter()

counter will be set to 0 on construction of this class and will
be incremented by each call. parser calls this method once for every
expansions. it will be a unique id for each expansion of macro in a file

Returns:
counter value

getCallStack

public java.util.ArrayList getCallStack()

pushOnCallStack

public boolean pushOnCallStack(Token token)

popFromCallStack

public void popFromCallStack()

getExpansionHistory

public java.lang.String getExpansionHistory()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Directives

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class Directives

java.lang.Object
mars.assembler.Directives

public final class Directives
extends java.lang.Object

Class representing MIPS assembler directives. If Java had enumerated types, these
would probably be implemented that way. Each directive is represented by a unique object.
The directive name is indicative of the directive it represents. For example, DATA
represents the MIPS .data directive.

Author:
Pete Sanderson

Field Summary

static Directives ALIGN

           

static Directives ASCII

           

static Directives ASCIIZ

           

static Directives BYTE

           

static Directives DATA

           

static Directives DOUBLE

           

static Directives END_MACRO

           

static Directives EQV

           

static Directives EXTERN

           

static Directives FLOAT

           

static Directives GLOBL

           

static Directives HALF

           

static Directives INCLUDE

           

static Directives KDATA

           

static Directives KTEXT

           

static Directives MACRO

           

static Directives SET

           

static Directives SPACE

           

static Directives TEXT

           

static Directives WORD

           

 

Method Summary

 java.lang.String getDescription()

          Get description of this Directives object

static java.util.ArrayList getDirectiveList()

          Produces List of Directive objects

 java.lang.String getName()

          Get name of this Directives object

static boolean isFloatingDirective(Directives direct)

          Lets you know whether given directive is for floating number (FLOAT,DOUBLE).

static boolean isIntegerDirective(Directives direct)

          Lets you know whether given directive is for integer (WORD,HALF,BYTE).

static Directives matchDirective(java.lang.String str)

          Find Directive object, if any, which matches the given String.

static java.util.ArrayList prefixMatchDirectives(java.lang.String str)

          Find Directive object, if any, which contains the given string as a prefix.

 java.lang.String toString()

          Produces String-ified version of Directive object

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

DATA

public static final Directives DATA

TEXT

public static final Directives TEXT

WORD

public static final Directives WORD

ASCII

public static final Directives ASCII

ASCIIZ

public static final Directives ASCIIZ

BYTE

public static final Directives BYTE

ALIGN

public static final Directives ALIGN

HALF

public static final Directives HALF

SPACE

public static final Directives SPACE

DOUBLE

public static final Directives DOUBLE

FLOAT

public static final Directives FLOAT

EXTERN

public static final Directives EXTERN

KDATA

public static final Directives KDATA

KTEXT

public static final Directives KTEXT

GLOBL

public static final Directives GLOBL

SET

public static final Directives SET

EQV

public static final Directives EQV

MACRO

public static final Directives MACRO

END_MACRO

public static final Directives END_MACRO

INCLUDE

public static final Directives INCLUDE

Method Detail

matchDirective

public static Directives matchDirective(java.lang.String str)

Find Directive object, if any, which matches the given String.

Parameters:
str – A String containing candidate directive name (e.g. “.ascii”)

Returns:
If match is found, returns matching Directives object, else returns null.

prefixMatchDirectives

public static java.util.ArrayList prefixMatchDirectives(java.lang.String str)

Find Directive object, if any, which contains the given string as a prefix. For example,
“.a” will match “.ascii”, “.asciiz” and “.align”

Parameters:
str – A String

Returns:
If match is found, returns ArrayList of matching Directives objects, else returns null.

toString

public java.lang.String toString()

Produces String-ified version of Directive object

Overrides:
toString in class java.lang.Object

Returns:
String representing Directive: its MIPS name

getName

public java.lang.String getName()

Get name of this Directives object

Returns:
name of this MIPS directive as a String

getDescription

public java.lang.String getDescription()

Get description of this Directives object

Returns:
description of this MIPS directive (for help purposes)

getDirectiveList

public static java.util.ArrayList getDirectiveList()

Produces List of Directive objects

Returns:
MIPS Directive

isIntegerDirective

public static boolean isIntegerDirective(Directives direct)

Lets you know whether given directive is for integer (WORD,HALF,BYTE).

Parameters:
direct – a MIPS directive

Returns:
true if given directive is FLOAT or DOUBLE, false otherwise

isFloatingDirective

public static boolean isFloatingDirective(Directives direct)

Lets you know whether given directive is for floating number (FLOAT,DOUBLE).

Parameters:
direct – a MIPS directive

Returns:
true if given directive is FLOAT or DOUBLE, false otherwise.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SourceLine

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class SourceLine

java.lang.Object
mars.assembler.SourceLine

public class SourceLine
extends java.lang.Object

Handy class to represent, for a given line of source code, the code
itself, the program containing it, and its line number within that program.
This is used to separately keep track of the original file/position of
a given line of code. When .include is used, it will migrate to a different
line and possibly different program but the migration should not be visible
to the user.

Constructor Summary
SourceLine(java.lang.String source,
MIPSprogram mipsProgram,
int lineNumber)

          SourceLine constructor

 

Method Summary

 java.lang.String getFilename()

          Retrieve name of file containing source statement

 int getLineNumber()

          Retrieve line number of source statement

 MIPSprogram getMIPSprogram()

          Retrieve MIPSprogram object containing source statement

 java.lang.String getSource()

          Retrieve source statement itself

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SourceLine

public SourceLine(java.lang.String source,
MIPSprogram mipsProgram,
int lineNumber)

SourceLine constructor

Parameters:
source – The source code itself
mipsProgram – The program (object representing source file) containing that line
lineNumber – The line number within that program where source appears.

Method Detail

getSource

public java.lang.String getSource()

Retrieve source statement itself

Returns:
Source statement as String

getFilename

public java.lang.String getFilename()

Retrieve name of file containing source statement

Returns:
File name as String

getLineNumber

public int getLineNumber()

Retrieve line number of source statement

Returns:
Line number of source statement

getMIPSprogram

public MIPSprogram getMIPSprogram()

Retrieve MIPSprogram object containing source statement

Returns:
program as MIPSprogram object

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SymbolTable

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class SymbolTable

java.lang.Object
mars.assembler.SymbolTable

public class SymbolTable
extends java.lang.Object

Creats a table of Symbol objects.

Author:
Jason Bumgarner, Jason Shrewsbury

Field Summary

static int NOT_FOUND

           

 

Constructor Summary
SymbolTable(java.lang.String filename)

          Create a new empty symbol table for given file

 

Method Summary

 void addSymbol(Token token,
int address,
boolean b,
ErrorList errors)

          Adds a Symbol object into the array of Symbols.

 void clear()

          Creates a fresh arrayList for a new table.

 void fixSymbolTableAddress(int originalAddress,
int replacementAddress)

          Fix address in symbol table entry.

 int getAddress(java.lang.String s)

          Method to return the address associated with the given label.

 int getAddressLocalOrGlobal(java.lang.String s)

          Method to return the address associated with the given label.

 java.util.ArrayList getAllSymbols()

          For obtaining all the Symbols.

 java.util.ArrayList getDataSymbols()

          For obtaining the Data Symbols.

 int getSize()

          Get the count of entries currently in the table.

static java.lang.String getStartLabel()

          Fetches the text segment label (symbol) which, if declared global, indicates
the starting address for execution.

 Symbol getSymbol(java.lang.String s)

          Produce Symbol object from symbol table that corresponds to given String.

 Symbol getSymbolGivenAddress(java.lang.String s)

          Produce Symbol object from symbol table that has the given address.

 Symbol getSymbolGivenAddressLocalOrGlobal(java.lang.String s)

          Produce Symbol object from either local or global symbol table that has the
given address.

 java.util.ArrayList getTextSymbols()

          For obtaining the Text Symbols.

 void removeSymbol(Token token)

          Removes a symbol from the Symbol table.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

NOT_FOUND

public static final int NOT_FOUND

See Also:
Constant Field Values

Constructor Detail

SymbolTable

public SymbolTable(java.lang.String filename)

Create a new empty symbol table for given file

Parameters:
filename – name of file this symbol table is associated with. Will be
used only for output/display so it can be any descriptive string.

Method Detail

addSymbol

public void addSymbol(Token token,
int address,
boolean b,
ErrorList errors)

Adds a Symbol object into the array of Symbols.

Parameters:
token – The token representing the Symbol.
address – The address of the Symbol.
b – The type of Symbol, true for data, false for text.
errors – List to which to add any processing errors that occur.

removeSymbol

public void removeSymbol(Token token)

Removes a symbol from the Symbol table. If not found, it does nothing.
This will rarely happen (only when variable is declared .globl after already
being defined in the local symbol table).

Parameters:
token – The token representing the Symbol.

getAddress

public int getAddress(java.lang.String s)

Method to return the address associated with the given label.

Parameters:
s – The label.

Returns:
The memory address of the label given, or NOT_FOUND if not found in symbol table.

getAddressLocalOrGlobal

public int getAddressLocalOrGlobal(java.lang.String s)

Method to return the address associated with the given label. Look first
in this (local) symbol table then in symbol table of labels declared
global (.globl directive).

Parameters:
s – The label.

Returns:
The memory address of the label given, or NOT_FOUND if not found in symbol table.

getSymbol

public Symbol getSymbol(java.lang.String s)

Produce Symbol object from symbol table that corresponds to given String.

Parameters:
s – target String

Returns:
Symbol object for requested target, null if not found in symbol table.

getSymbolGivenAddress

public Symbol getSymbolGivenAddress(java.lang.String s)

Produce Symbol object from symbol table that has the given address.

Parameters:
s – String representing address

Returns:
Symbol object having requested address, null if address not found in symbol table.

getSymbolGivenAddressLocalOrGlobal

public Symbol getSymbolGivenAddressLocalOrGlobal(java.lang.String s)

Produce Symbol object from either local or global symbol table that has the
given address.

Parameters:
s – String representing address

Returns:
Symbol object having requested address, null if address not found in symbol table.

getDataSymbols

public java.util.ArrayList getDataSymbols()

For obtaining the Data Symbols.

Returns:
An ArrayList of Symbol objects.

getTextSymbols

public java.util.ArrayList getTextSymbols()

For obtaining the Text Symbols.

Returns:
An ArrayList of Symbol objects.

getAllSymbols

public java.util.ArrayList getAllSymbols()

For obtaining all the Symbols.

Returns:
An ArrayList of Symbol objects.

getSize

public int getSize()

Get the count of entries currently in the table.

Returns:
Number of symbol table entries.

clear

public void clear()

Creates a fresh arrayList for a new table.

fixSymbolTableAddress

public void fixSymbolTableAddress(int originalAddress,
int replacementAddress)

Fix address in symbol table entry. Any and all entries that match the original
address will be modified to contain the replacement address. There is no effect,
if none of the addresses matches.

Parameters:
originalAddress – Address associated with 0 or more symtab entries.
replacementAddress – Any entry that has originalAddress will have its
address updated to this value. Does nothing if none do.

getStartLabel

public static java.lang.String getStartLabel()

Fetches the text segment label (symbol) which, if declared global, indicates
the starting address for execution.

Returns:
String containing global label whose text segment address is starting address for program execution.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

TokenTypes

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class TokenTypes

java.lang.Object
mars.assembler.TokenTypes

public final class TokenTypes
extends java.lang.Object

Constants to identify the types of tokens found in MIPS programs. If Java had
enumerated types, that’s how these would probably be implemented.

Author:
Pete Sanderson

Field Summary

static TokenTypes COLON

           

static TokenTypes COMMENT

           

static TokenTypes DELIMITER

           

static TokenTypes DIRECTIVE

           

static TokenTypes ERROR

           

static TokenTypes FP_REGISTER_NAME

           

static TokenTypes IDENTIFIER

           

static TokenTypes INTEGER_16

           

static TokenTypes INTEGER_16U

           

static TokenTypes INTEGER_32

           

static TokenTypes INTEGER_5

           

static TokenTypes LEFT_PAREN

           

static TokenTypes MACRO_PARAMETER

           

static TokenTypes MINUS

           

static TokenTypes OPERATOR

           

static TokenTypes PLUS

           

static TokenTypes QUOTED_STRING

           

static TokenTypes REAL_NUMBER

           

static TokenTypes REGISTER_NAME

          note: REGISTER_NAME is token of form $zero whereas REGISTER_NUMBER is token
of form $0.

static TokenTypes REGISTER_NUMBER

           

static TokenTypes RIGHT_PAREN

           

static java.lang.String TOKEN_DELIMITERS

           

 

Method Summary

static boolean isFloatingTokenType(TokenTypes type)

          Lets you know if given tokentype is for floating point numbers (REAL_NUMBER).

static boolean isIntegerTokenType(TokenTypes type)

          Lets you know if given tokentype is for integers (INTGER_5, INTEGER_16, INTEGER_32).

static boolean isValidIdentifier(java.lang.String value)

           

static TokenTypes matchTokenType(java.lang.String value)

          Classifies the given token into one of the MIPS types.

 java.lang.String toString()

          Produces String equivalent of this token type, which is its name.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

TOKEN_DELIMITERS

public static final java.lang.String TOKEN_DELIMITERS

See Also:
Constant Field Values

COMMENT

public static final TokenTypes COMMENT

DIRECTIVE

public static final TokenTypes DIRECTIVE

OPERATOR

public static final TokenTypes OPERATOR

DELIMITER

public static final TokenTypes DELIMITER

REGISTER_NAME

public static final TokenTypes REGISTER_NAME

note: REGISTER_NAME is token of form $zero whereas REGISTER_NUMBER is token
of form $0. The former is part of extended assembler, and latter is part
of basic assembler.

REGISTER_NUMBER

public static final TokenTypes REGISTER_NUMBER

FP_REGISTER_NAME

public static final TokenTypes FP_REGISTER_NAME

IDENTIFIER

public static final TokenTypes IDENTIFIER

LEFT_PAREN

public static final TokenTypes LEFT_PAREN

RIGHT_PAREN

public static final TokenTypes RIGHT_PAREN

INTEGER_5

public static final TokenTypes INTEGER_5

INTEGER_16

public static final TokenTypes INTEGER_16

INTEGER_16U

public static final TokenTypes INTEGER_16U

INTEGER_32

public static final TokenTypes INTEGER_32

REAL_NUMBER

public static final TokenTypes REAL_NUMBER

QUOTED_STRING

public static final TokenTypes QUOTED_STRING

PLUS

public static final TokenTypes PLUS

MINUS

public static final TokenTypes MINUS

COLON

public static final TokenTypes COLON

ERROR

public static final TokenTypes ERROR

MACRO_PARAMETER

public static final TokenTypes MACRO_PARAMETER

Method Detail

toString

public java.lang.String toString()

Produces String equivalent of this token type, which is its name.

Overrides:
toString in class java.lang.Object

Returns:
String containing descriptive name for token type.

matchTokenType

public static TokenTypes matchTokenType(java.lang.String value)

Classifies the given token into one of the MIPS types.

Parameters:
value – String containing candidate language element, extracted from MIPS program.

Returns:
Returns the corresponding TokenTypes object if the parameter matches a
defined MIPS token type, else returns null.

isIntegerTokenType

public static boolean isIntegerTokenType(TokenTypes type)

Lets you know if given tokentype is for integers (INTGER_5, INTEGER_16, INTEGER_32).

Parameters:
type – the TokenType of interest

Returns:
true if type is an integer type, false otherwise.

isFloatingTokenType

public static boolean isFloatingTokenType(TokenTypes type)

Lets you know if given tokentype is for floating point numbers (REAL_NUMBER).

Parameters:
type – the TokenType of interest

Returns:
true if type is an floating point type, false otherwise.

isValidIdentifier

public static boolean isValidIdentifier(java.lang.String value)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

OperandFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class OperandFormat

java.lang.Object
mars.assembler.OperandFormat

public class OperandFormat
extends java.lang.Object

Provides utility method related to MIPS operand formats.

Author:
Pete Sanderson

Method Summary

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

TokenList

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class TokenList

java.lang.Object
mars.assembler.TokenList

All Implemented Interfaces:
java.lang.Cloneable

public class TokenList
extends java.lang.Object
implements java.lang.Cloneable

Represents the list of tokens in a single line of MIPS code. It uses, but is not
a subclass of, ArrayList.

Author:
Pete Sanderson

Constructor Summary
TokenList()

          Constructor for objects of class TokenList

 

Method Summary

 void add(Token token)

          Adds a Token object to the end of the list.

 java.lang.Object clone()

          Makes clone (shallow copy) of this token list object.

 Token get(int pos)

          Returns requested token given position number (starting at 0).

 java.lang.String getProcessedLine()

          Retrieve the source line String associated with this
token list.

 boolean isEmpty()

          Returns empty/non-empty status of list.

 void remove(int pos)

          Removes Token object at specified list position.

 void set(int pos,
Token replacement)

          Replaces token at position with different one.

 void setProcessedLine(java.lang.String line)

          Use this to record the source line String for this token list
after possible modification (textual substitution) during
assembly preprocessing.

 int size()

          Returns number of tokens in list.

 java.lang.String toString()

          Get a String representing the token list.

 java.lang.String toTypeString()

          Get a String representing the sequence of token types for this list.

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

TokenList

public TokenList()

Constructor for objects of class TokenList

Method Detail

setProcessedLine

public void setProcessedLine(java.lang.String line)

Use this to record the source line String for this token list
after possible modification (textual substitution) during
assembly preprocessing. The modified source will be displayed in
the Text Segment Display.

Parameters:
line – The source line, possibly modified (possibly not)

getProcessedLine

public java.lang.String getProcessedLine()

Retrieve the source line String associated with this
token list. It may or may not have been modified during
assembly preprocessing.

Returns:
The source line for this token list.

get

public Token get(int pos)

Returns requested token given position number (starting at 0).

Parameters:
pos – Position in token list.

Returns:
the requested token, or ArrayIndexOutOfBounds exception

set

public void set(int pos,
Token replacement)

Replaces token at position with different one. Will throw
ArrayIndexOutOfBounds exception if position does not exist.

Parameters:
pos – Position in token list.
replacement – Replacement token

size

public int size()

Returns number of tokens in list.

Returns:
token count.

add

public void add(Token token)

Adds a Token object to the end of the list.

Parameters:
token – Token object to be added.

remove

public void remove(int pos)

Removes Token object at specified list position. Uses ArrayList remove method.

Parameters:
pos – Position in token list. Subsequent Tokens are shifted one position left.

Throws:

java.lang.IndexOutOfBoundsException – if pos is < 0 or >= size()

isEmpty

public boolean isEmpty()

Returns empty/non-empty status of list.

Returns:
true if list has no tokens, else false.

toString

public java.lang.String toString()

Get a String representing the token list.

Overrides:
toString in class java.lang.Object

Returns:
String version of the token list
(a blank is inserted after each token).

toTypeString

public java.lang.String toTypeString()

Get a String representing the sequence of token types for this list.

Returns:
String version of the token types for this list
(a blank is inserted after each token type).

clone

public java.lang.Object clone()

Makes clone (shallow copy) of this token list object.

Overrides:
clone in class java.lang.Object

Returns:
the cloned list.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

TranslationCode

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Interface TranslationCode

public interface TranslationCode

This interface is intended for use by ExtendedInstruction objects to define, using
the translate() method, how to translate the extended (pseudo) instruction into
a sequence of one or more basic instructions, which can then be translated into
binary machine code.

Author:
Pete Sanderson

Method Summary

 void translate()

          This is a callback method defined in anonymous class specified as
argument to ExtendedInstruction constructor.

 

Method Detail

translate

void translate()

This is a callback method defined in anonymous class specified as
argument to ExtendedInstruction constructor. It is called when
assembler finds a program statement matching that ExtendedInstruction,

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

mars.assembler

Interfaces 

TranslationCode

Classes 

Assembler

DataTypes

Directives

Macro

MacroPool

OperandFormat

SourceLine

Symbol

SymbolTable

Token

Tokenizer

TokenList

TokenTypes

Assembler

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class Assembler

java.lang.Object
mars.assembler.Assembler

public class Assembler
extends java.lang.Object

An Assembler is capable of assembling a MIPS program. It has only one public
method, assemble(), which implements a two-pass assembler. It
translates MIPS source code into binary machine code.

Author:
Pete Sanderson

Constructor Summary
Assembler()

           

 

Method Summary

 java.util.ArrayList assemble(java.util.ArrayList tokenizedProgramFiles,
boolean extendedAssemblerEnabled)

          Parse and generate machine code for the given MIPS program.

 java.util.ArrayList assemble(java.util.ArrayList tokenizedProgramFiles,
boolean extendedAssemblerEnabled,
boolean warningsAreErrors)

          Parse and generate machine code for the given MIPS program.

 java.util.ArrayList assemble(MIPSprogram p,
boolean extendedAssemblerEnabled)

          Parse and generate machine code for the given MIPS program.

 java.util.ArrayList assemble(MIPSprogram p,
boolean extendedAssemblerEnabled,
boolean warningsAreErrors)

          Parse and generate machine code for the given MIPS program.

 ErrorList getErrorList()

          Get list of assembler errors and warnings

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

Assembler

public Assembler()

Method Detail

assemble

public java.util.ArrayList assemble(MIPSprogram p,
boolean extendedAssemblerEnabled)
throws ProcessingException

Parse and generate machine code for the given MIPS program. It must have
already been tokenized. Warnings are not considered errors.

Parameters:
p – A MIPSprogram object representing the program source.
extendedAssemblerEnabled – A boolean value that if true permits use of extended (pseudo)
instructions in the source code. If false, these are flagged
as errors.

Returns:
An ArrayList representing the assembled program. Each member of
the list is a ProgramStatement object containing the source,
intermediate, and machine binary representations of a program
statement.

Throws:

ProcessingException
See Also:
ProgramStatement

assemble

public java.util.ArrayList assemble(MIPSprogram p,
boolean extendedAssemblerEnabled,
boolean warningsAreErrors)
throws ProcessingException

Parse and generate machine code for the given MIPS program. It must have
already been tokenized.

Parameters:
p – A MIPSprogram object representing the program source.
extendedAssemblerEnabled – A boolean value that if true permits use of extended (pseudo)
instructions in the source code. If false, these are flagged
as errors.
warningsAreErrors – A boolean value – true means assembler warnings will be
considered errors and terminate the assemble; false means the
assembler will produce warning message but otherwise ignore
warnings.

Returns:
An ArrayList representing the assembled program. Each member of
the list is a ProgramStatement object containing the source,
intermediate, and machine binary representations of a program
statement.

Throws:

ProcessingException
See Also:
ProgramStatement

getErrorList

public ErrorList getErrorList()

Get list of assembler errors and warnings

Returns:
ErrorList of any assembler errors and warnings.

assemble

public java.util.ArrayList assemble(java.util.ArrayList tokenizedProgramFiles,
boolean extendedAssemblerEnabled)
throws ProcessingException

Parse and generate machine code for the given MIPS program. All source
files must have already been tokenized. Warnings will not be considered
errors.

Parameters:
tokenizedProgramFiles – An ArrayList of MIPSprogram objects, each produced from a
different source code file, representing the program source.
extendedAssemblerEnabled – A boolean value that if true permits use of extended (pseudo)
instructions in the source code. If false, these are flagged
as errors.

Returns:
An ArrayList representing the assembled program. Each member of
the list is a ProgramStatement object containing the source,
intermediate, and machine binary representations of a program
statement. Returns null if incoming array list is null or empty.

Throws:

ProcessingException
See Also:
ProgramStatement

assemble

public java.util.ArrayList assemble(java.util.ArrayList tokenizedProgramFiles,
boolean extendedAssemblerEnabled,
boolean warningsAreErrors)
throws ProcessingException

Parse and generate machine code for the given MIPS program. All source
files must have already been tokenized.

Parameters:
tokenizedProgramFiles – An ArrayList of MIPSprogram objects, each produced from a
different source code file, representing the program source.
extendedAssemblerEnabled – A boolean value that if true permits use of extended (pseudo)
instructions in the source code. If false, these are flagged
as errors.
warningsAreErrors – A boolean value – true means assembler warnings will be
considered errors and terminate the assemble; false means the
assembler will produce warning message but otherwise ignore
warnings.

Returns:
An ArrayList representing the assembled program. Each member of
the list is a ProgramStatement object containing the source,
intermediate, and machine binary representations of a program
statement. Returns null if incoming array list is null or empty.

Throws:

ProcessingException
See Also:
ProgramStatement

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Tokenizer

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class Tokenizer

java.lang.Object
mars.assembler.Tokenizer

public class Tokenizer
extends java.lang.Object

A tokenizer is capable of tokenizing a complete MIPS program, or a given line from
a MIPS program. Since MIPS is line-oriented, each line defines a complete statement.
Tokenizing is the process of analyzing the input MIPS program for the purpose of
recognizing each MIPS language element. The types of language elements are known as “tokens”.
MIPS tokens are defined in the TokenTypes class.

Example:

The MIPS statement here: lw $t3, 8($t4) #load third member of array

generates the following token list

IDENTIFIER, COLON, OPERATOR, REGISTER_NAME, COMMA, INTEGER_5, LEFT_PAREN,
REGISTER_NAME, RIGHT_PAREN, COMMENT

Author:
Pete Sanderson

Constructor Summary
Tokenizer()

          Simple constructor.
Tokenizer(MIPSprogram program)

          Constructor for use with existing MIPSprogram.

 

Method Summary

 ErrorList getErrors()

          Fetch this Tokenizer’s error list.

 java.util.ArrayList tokenize(MIPSprogram p)

          Will tokenize a complete MIPS program.

 TokenList tokenizeExampleInstruction(java.lang.String example)

          Used only to create a token list for the example provided with each instruction
specification.

 TokenList tokenizeLine(int lineNum,
java.lang.String theLine)

          Will tokenize one line of source code.

 TokenList tokenizeLine(int lineNum,
java.lang.String theLine,
ErrorList callerErrorList)

          Will tokenize one line of source code.

 TokenList tokenizeLine(MIPSprogram program,
int lineNum,
java.lang.String theLine)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

Tokenizer

public Tokenizer()

Simple constructor. Initializes empty error list.

Tokenizer

public Tokenizer(MIPSprogram program)

Constructor for use with existing MIPSprogram. Designed to be used with Macro feature.

Parameters:
program – A previously-existing MIPSprogram object or null if none.

Method Detail

tokenize

public java.util.ArrayList tokenize(MIPSprogram p)
throws ProcessingException

Will tokenize a complete MIPS program. MIPS is line oriented (not free format),
so we will be line-oriented too.

Parameters:
p – The MIPSprogram to be tokenized.

Returns:
An ArrayList representing the tokenized program. Each list member is a TokenList
that represents a tokenized source statement from the MIPS program.

Throws:

ProcessingException

tokenizeExampleInstruction

public TokenList tokenizeExampleInstruction(java.lang.String example)
throws ProcessingException

Used only to create a token list for the example provided with each instruction
specification.

Parameters:
example – The example MIPS instruction to be tokenized.

Returns:
An TokenList representing the tokenized instruction. Each list member is a Token
that represents one language element.

Throws:

ProcessingException – This occurs only if the instruction specification itself
contains one or more lexical (i.e. token) errors.

tokenizeLine

public TokenList tokenizeLine(int lineNum,
java.lang.String theLine)

Will tokenize one line of source code. If lexical errors are discovered,
they are noted in an ErrorMessage object which is added to the ErrorList.
Will NOT throw an exception yet because we want to persevere beyond first error.

Parameters:
lineNum – line number from source code (used in error message)
theLine – String containing source code

Returns:
the generated token list for that line

tokenizeLine

public TokenList tokenizeLine(MIPSprogram program,
int lineNum,
java.lang.String theLine)

tokenizeLine

public TokenList tokenizeLine(int lineNum,
java.lang.String theLine,
ErrorList callerErrorList)

Will tokenize one line of source code. If lexical errors are discovered,
they are noted in an ErrorMessage object which is added to the provided ErrorList
instead of the Tokenizer’s error list. Will NOT throw an exception.

Parameters:
lineNum – line number from source code (used in error message)
theLine – String containing source code
callerErrorList – errors will go into this list instead of tokenizer’s list.

Returns:
the generated token list for that line

getErrors

public ErrorList getErrors()

Fetch this Tokenizer’s error list.

Returns:
the error list

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Symbol

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class Symbol

java.lang.Object
mars.assembler.Symbol

public class Symbol
extends java.lang.Object

Represents a MIPS program identifier to be stored in the symbol table.

Author:
Jason Bumgarner, Jason Shrewsbury

Field Summary

static boolean DATA_SYMBOL

           

static boolean TEXT_SYMBOL

           

 

Constructor Summary
Symbol(java.lang.String name,
int address,
boolean data)

          Basic constructor, creates a symbol object.

 

Method Summary

 int getAddress()

          Returns the address of the the Symbol.

 java.lang.String getName()

          Returns the label of the the Symbol.

 boolean getType()

          Finds the type of symbol, text or data.

 void setAddress(int newAddress)

          Sets (replaces) the address of the the Symbol.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

TEXT_SYMBOL

public static final boolean TEXT_SYMBOL

See Also:
Constant Field Values

DATA_SYMBOL

public static final boolean DATA_SYMBOL

See Also:
Constant Field Values

Constructor Detail

Symbol

public Symbol(java.lang.String name,
int address,
boolean data)

Basic constructor, creates a symbol object.

Parameters:
name – The name of the Symbol.
address – The memroy address that the Symbol refers to.
data – The type of Symbol that it is.

Method Detail

getAddress

public int getAddress()

Returns the address of the the Symbol.

Returns:
The address of the Symbol.

getName

public java.lang.String getName()

Returns the label of the the Symbol.

Returns:
The label of the Symbol.

getType

public boolean getType()

Finds the type of symbol, text or data.

Returns:
The type of the data.

setAddress

public void setAddress(int newAddress)

Sets (replaces) the address of the the Symbol.

Parameters:
newAddress – The revised address of the Symbol.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.assembler

Interface Summary
TranslationCode This interface is intended for use by ExtendedInstruction objects to define, using
the translate() method, how to translate the extended (pseudo) instruction into
a sequence of one or more basic instructions, which can then be translated into
binary machine code.

 

Class Summary
Assembler An Assembler is capable of assembling a MIPS program.
DataTypes Information about MIPS data types.
Directives Class representing MIPS assembler directives.
Macro Stores information of a macro definition.
MacroPool Stores information of macros defined by now.
OperandFormat Provides utility method related to MIPS operand formats.
SourceLine Handy class to represent, for a given line of source code, the code
itself, the program containing it, and its line number within that program.
Symbol Represents a MIPS program identifier to be stored in the symbol table.
SymbolTable Creats a table of Symbol objects.
Token Represents one token in the input MIPS program.
Tokenizer A tokenizer is capable of tokenizing a complete MIPS program, or a given line from
a MIPS program.
TokenList Represents the list of tokens in a single line of MIPS code.
TokenTypes Constants to identify the types of tokens found in MIPS programs.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Macro

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class Macro

java.lang.Object
mars.assembler.Macro

public class Macro
extends java.lang.Object

Stores information of a macro definition.

Author:
M.H.Sekhavat

Constructor Summary
Macro()

           

 

Method Summary

 void addArg(java.lang.String value)

           

 void addLabel(java.lang.String value)

           

 boolean equals(java.lang.Object obj)

           

 java.util.ArrayList getArgs()

           

 int getFromLine()

           

 java.lang.String getName()

           

 int getOriginalFromLine()

           

 int getOriginalToLine()

           

 MIPSprogram getProgram()

           

 java.lang.String getSubstitutedLine(int line,
TokenList args,
long counter,
ErrorList errors)

          Substitutes macro arguments in a line of source code inside macro
definition to be parsed after macro expansion.

 int getToLine()

           

 void readyForCommit()

          Operations to be done on this macro before it is committed in macro pool.

 void setArgs(java.util.ArrayList args)

           

 void setFromLine(int fromLine)

           

 void setName(java.lang.String name)

           

 void setOriginalFromLine(int origFromLine)

           

 void setOriginalToLine(int origToLine)

           

 void setProgram(MIPSprogram program)

           

 void setToLine(int toLine)

           

static boolean tokenIsMacroParameter(java.lang.String tokenValue,
boolean acceptSpimStyleParameters)

          returns whether tokenValue is macro parameter or not

 
Methods inherited from class java.lang.Object
clone, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

Macro

public Macro()

Method Detail

getName

public java.lang.String getName()

setName

public void setName(java.lang.String name)

getProgram

public MIPSprogram getProgram()

setProgram

public void setProgram(MIPSprogram program)

getFromLine

public int getFromLine()

getOriginalFromLine

public int getOriginalFromLine()

setFromLine

public void setFromLine(int fromLine)

setOriginalFromLine

public void setOriginalFromLine(int origFromLine)

getToLine

public int getToLine()

getOriginalToLine

public int getOriginalToLine()

setToLine

public void setToLine(int toLine)

setOriginalToLine

public void setOriginalToLine(int origToLine)

getArgs

public java.util.ArrayList getArgs()

setArgs

public void setArgs(java.util.ArrayList args)

equals

public boolean equals(java.lang.Object obj)

Overrides:
equals in class java.lang.Object

Parameters:
obj – Macro object to check if their name and count of
arguments are same

addArg

public void addArg(java.lang.String value)

getSubstitutedLine

public java.lang.String getSubstitutedLine(int line,
TokenList args,
long counter,
ErrorList errors)

Substitutes macro arguments in a line of source code inside macro
definition to be parsed after macro expansion.

Also appends “_M#” to all labels defined inside macro body where # is value of counter

Parameters:
line – source line number in macro definition to be substituted
args –
counter – unique macro expansion id
errors –

Returns:
line-th line of source code, with substituted
arguments

tokenIsMacroParameter

public static boolean tokenIsMacroParameter(java.lang.String tokenValue,
boolean acceptSpimStyleParameters)

returns whether tokenValue is macro parameter or not

Parameters:
tokenValue –
acceptSpimStyleParameters – accepts SPIM-style parameters which begin with ‘$’ if true

Returns:

addLabel

public void addLabel(java.lang.String value)

readyForCommit

public void readyForCommit()

Operations to be done on this macro before it is committed in macro pool.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DataTypes

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class DataTypes

java.lang.Object
mars.assembler.DataTypes

public final class DataTypes
extends java.lang.Object

Information about MIPS data types.

Author:
Pete Sanderson

Field Summary

static int BYTE_SIZE

          Number of bytes occupied by MIPS byte is 1.

static int CHAR_SIZE

          Number of bytes occupied by MIPS character is 1.

static int DOUBLE_SIZE

          Number of bytes occupied by MIPS double is 8.

static int FLOAT_SIZE

          Number of bytes occupied by MIPS float is 4.

static int HALF_SIZE

          Number of bytes occupied by MIPS halfword is 2.

static double LOW_DOUBLE_VALUE

          Largest magnitude negative value that can be stored in a MIPS double(negative of the max)

static double LOW_FLOAT_VALUE

          Largest magnitude negative value that can be stored in a MIPS float (negative of the max)

static int MAX_BYTE_VALUE

          Maximum value that can be stored in a MIPS byte is 27-1

static double MAX_DOUBLE_VALUE

          Maximum positive finite value that can be stored in a MIPS double is same as Java Double

static double MAX_FLOAT_VALUE

          Maximum positive finite value that can be stored in a MIPS float is same as Java Float

static int MAX_HALF_VALUE

          Maximum value that can be stored in a MIPS halfword is 215-1

static int MAX_UHALF_VALUE

          Maximum value that can be stored in an unsigned MIPS halfword is 216-1

static int MAX_WORD_VALUE

          Maximum value that can be stored in a MIPS word is 231-1

static int MIN_BYTE_VALUE

          Lowest value that can be stored in a MIPS byte is -27

static int MIN_HALF_VALUE

          Lowest value that can be stored in a MIPS halfword is -215

static int MIN_UHALF_VALUE

          Lowest value that can be stored in na unsigned MIPS halfword is 0

static int MIN_WORD_VALUE

          Lowest value that can be stored in a MIPS word is -231

static int WORD_SIZE

          Number of bytes occupied by MIPS word is 4.

 

Constructor Summary
DataTypes()

           

 

Method Summary

static int getLengthInBytes(Directives direct)

          Get length in bytes for numeric MIPS directives.

static boolean outOfRange(Directives direct,
double value)

          Determines whether given floating point value falls within value range for given directive.

static boolean outOfRange(Directives direct,
int value)

          Determines whether given integer value falls within value range for given directive.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

DOUBLE_SIZE

public static final int DOUBLE_SIZE

Number of bytes occupied by MIPS double is 8.

See Also:
Constant Field Values

FLOAT_SIZE

public static final int FLOAT_SIZE

Number of bytes occupied by MIPS float is 4.

See Also:
Constant Field Values

WORD_SIZE

public static final int WORD_SIZE

Number of bytes occupied by MIPS word is 4.

See Also:
Constant Field Values

HALF_SIZE

public static final int HALF_SIZE

Number of bytes occupied by MIPS halfword is 2.

See Also:
Constant Field Values

BYTE_SIZE

public static final int BYTE_SIZE

Number of bytes occupied by MIPS byte is 1.

See Also:
Constant Field Values

CHAR_SIZE

public static final int CHAR_SIZE

Number of bytes occupied by MIPS character is 1.

See Also:
Constant Field Values

MAX_WORD_VALUE

public static final int MAX_WORD_VALUE

Maximum value that can be stored in a MIPS word is 231-1

See Also:
Constant Field Values

MIN_WORD_VALUE

public static final int MIN_WORD_VALUE

Lowest value that can be stored in a MIPS word is -231

See Also:
Constant Field Values

MAX_HALF_VALUE

public static final int MAX_HALF_VALUE

Maximum value that can be stored in a MIPS halfword is 215-1

See Also:
Constant Field Values

MIN_HALF_VALUE

public static final int MIN_HALF_VALUE

Lowest value that can be stored in a MIPS halfword is -215

See Also:
Constant Field Values

MAX_UHALF_VALUE

public static final int MAX_UHALF_VALUE

Maximum value that can be stored in an unsigned MIPS halfword is 216-1

See Also:
Constant Field Values

MIN_UHALF_VALUE

public static final int MIN_UHALF_VALUE

Lowest value that can be stored in na unsigned MIPS halfword is 0

See Also:
Constant Field Values

MAX_BYTE_VALUE

public static final int MAX_BYTE_VALUE

Maximum value that can be stored in a MIPS byte is 27-1

See Also:
Constant Field Values

MIN_BYTE_VALUE

public static final int MIN_BYTE_VALUE

Lowest value that can be stored in a MIPS byte is -27

See Also:
Constant Field Values

MAX_FLOAT_VALUE

public static final double MAX_FLOAT_VALUE

Maximum positive finite value that can be stored in a MIPS float is same as Java Float

See Also:
Constant Field Values

LOW_FLOAT_VALUE

public static final double LOW_FLOAT_VALUE

Largest magnitude negative value that can be stored in a MIPS float (negative of the max)

See Also:
Constant Field Values

MAX_DOUBLE_VALUE

public static final double MAX_DOUBLE_VALUE

Maximum positive finite value that can be stored in a MIPS double is same as Java Double

See Also:
Constant Field Values

LOW_DOUBLE_VALUE

public static final double LOW_DOUBLE_VALUE

Largest magnitude negative value that can be stored in a MIPS double(negative of the max)

See Also:
Constant Field Values

Constructor Detail

DataTypes

public DataTypes()

Method Detail

getLengthInBytes

public static int getLengthInBytes(Directives direct)

Get length in bytes for numeric MIPS directives.

Parameters:
direct – Directive to be measured.

Returns:
Returns length in bytes for values of that type. If type is not numeric
(or not implemented yet), returns 0.

outOfRange

public static boolean outOfRange(Directives direct,
int value)

Determines whether given integer value falls within value range for given directive.

Parameters:
direct – Directive that controls storage allocation for value.
value – The value to be stored.

Returns:
Returns true if value can be stored in the number of bytes allowed
by the given directive (.word, .half, .byte), false otherwise.

outOfRange

public static boolean outOfRange(Directives direct,
double value)

Determines whether given floating point value falls within value range for given directive.
For float, this refers to range of the data type, not precision. Example: 1.23456789012345
be stored in a float with loss of precision. It’s within the range. But 1.23e500 cannot be
stored in a float because the exponent 500 is too large (float allows 8 bits for exponent).

Parameters:
direct – Directive that controls storage allocation for value.
value – The value to be stored.

Returns:
Returns true if value is within range of
the given directive (.float, .double), false otherwise.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.assembler

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object mars.assembler.Assembler
mars.assembler.DataTypes
mars.assembler.Directives
mars.assembler.Macro
mars.assembler.MacroPool
mars.assembler.OperandFormat
mars.assembler.SourceLine
mars.assembler.Symbol
mars.assembler.SymbolTable
mars.assembler.Token
mars.assembler.Tokenizer
mars.assembler.TokenList (implements java.lang.Cloneable)

mars.assembler.TokenTypes

Interface Hierarchy

mars.assembler.TranslationCode

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Token

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.assembler

Class Token

java.lang.Object
mars.assembler.Token

public class Token
extends java.lang.Object

Represents one token in the input MIPS program. Each Token carries, along with its
type and value, the position (line, column) in which its source appears in the MIPS program.

Author:
Pete Sanderson

Constructor Summary
Token(TokenTypes type,
java.lang.String value,
MIPSprogram sourceMIPSprogram,
int line,
int start)

          Constructor for Token class.

 

Method Summary

 MIPSprogram getOriginalProgram()

          Produces original program containing this token.

 int getOriginalSourceLine()

          Produces original line number of this token.

 int getSourceLine()

          Produces line number of MIPS program of this token.

 MIPSprogram getSourceMIPSprogram()

          Produces MIPSprogram object associated with this token.

 int getStartPos()

          Produces position within source line of this token.

 TokenTypes getType()

          Produces token type of this token.

 java.lang.String getValue()

          Produces source code of this token.

 void setOriginal(MIPSprogram origProgram,
int origSourceLine)

          Set original program and line number for this token.

 void setType(TokenTypes type)

          Set or modify token type.

 java.lang.String toString()

          Get a String representing the token.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

Token

public Token(TokenTypes type,
java.lang.String value,
MIPSprogram sourceMIPSprogram,
int line,
int start)

Constructor for Token class.

Parameters:
type – The token type that this token has. (e.g. REGISTER_NAME)
value – The source value for this token (e.g. $t3)
sourceMIPSprogram – The MIPSprogram object containing this token
line – The line number in source program in which this token appears.
start – The starting position in that line number of this token’s source value.
See Also:
TokenTypes

Method Detail

setOriginal

public void setOriginal(MIPSprogram origProgram,
int origSourceLine)

Set original program and line number for this token.
Line number or both may change during pre-assembly as a result
of the “.include” directive, and we need to keep the original
for later reference (error messages, text segment display).

Parameters:
origProgram – MIPS program containing this token.
origSourceLine – Line within that program of this token.

getOriginalProgram

public MIPSprogram getOriginalProgram()

Produces original program containing this token.

Returns:
MIPSprogram of origin for this token.

getOriginalSourceLine

public int getOriginalSourceLine()

Produces original line number of this token. It could change as result
of “.include”

Returns:
original line number of this token.

getType

public TokenTypes getType()

Produces token type of this token.

Returns:
TokenType of this token.

setType

public void setType(TokenTypes type)

Set or modify token type. Generally used to note that
an identifier that matches an instruction name is
actually being used as a label.

Parameters:
type – new TokenTypes for this token.

getValue

public java.lang.String getValue()

Produces source code of this token.

Returns:
String containing source code of this token.

toString

public java.lang.String toString()

Get a String representing the token. This method is
equivalent to getValue().

Overrides:
toString in class java.lang.Object

Returns:
String version of the token.

getSourceMIPSprogram

public MIPSprogram getSourceMIPSprogram()

Produces MIPSprogram object associated with this token.

Returns:
MIPSprogram object associated with this token.

getSourceLine

public int getSourceLine()

Produces line number of MIPS program of this token.

Returns:
line number in source program of this token.

getStartPos

public int getStartPos()

Produces position within source line of this token.

Returns:
first character position within source program line of this token.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

PropertiesFile

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.util

Class PropertiesFile

java.lang.Object
mars.util.PropertiesFile

public class PropertiesFile
extends java.lang.Object

Provides means to work with “.properties” files which are used to store
various MARS settings.

Author:
Pete Sanderson

Constructor Summary
PropertiesFile()

           

 

Method Summary

static java.util.Properties loadPropertiesFromFile(java.lang.String file)

          Produce Properties (a Hashtable) object containing key-value pairs
from specified properties file.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

PropertiesFile

public PropertiesFile()

Method Detail

loadPropertiesFromFile

public static java.util.Properties loadPropertiesFromFile(java.lang.String file)

Produce Properties (a Hashtable) object containing key-value pairs
from specified properties file. This may be used as an alternative
to readPropertiesFile() which uses a different implementation.

Parameters:
file – Properties filename. Do NOT include the file extension as
it is assumed to be “.properties” and is added here.

Returns:
Properties (Hashtable) of key-value pairs read from the file.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Binary

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.util

Class Binary

java.lang.Object
mars.util.Binary

public class Binary
extends java.lang.Object

Some utility methods for working with binary representations.

Author:
Pete Sanderson, Ken Vollmar, and Jason Bumgarner

Constructor Summary
Binary()

           

 

Method Summary

static char binaryStringToHexDigit(java.lang.String value)

          Translate String consisting of ‘1’s and ‘0’s into char equivalent of the corresponding
hexadecimal digit.

static java.lang.String binaryStringToHexString(java.lang.String value)

          Translate String consisting of ‘1’s and ‘0’s into String equivalent of the corresponding
hexadecimal value.

static int binaryStringToInt(java.lang.String value)

          Translate String consisting of ‘1’s and ‘0’s into an int value having that binary representation.

static long binaryStringToLong(java.lang.String value)

          Translate String consisting of ‘1’s and ‘0’s into a long value having that binary representation.

static int bitValue(int value,
int bit)

          Returns the bit value of the given bit position of the given int value.

static int bitValue(long value,
int bit)

          Returns the bit value of the given bit position of the given long value.

static int clearBit(int value,
int bit)

          Sets the specified bit of the specified value to 0, and returns the result.

static int getByte(int value,
int bite)

          Gets the specified byte of the specified value.

static java.lang.String hexStringToBinaryString(java.lang.String value)

          Translate String consisting of hexadecimal digits into String consisting of
corresponding binary digits (‘1’s and ‘0’s).

static int highOrderLongToInt(long longValue)

          Returns int representing the bit values of the high order 32 bits of given
64 bit long value.

static java.lang.String intToAscii(int d)

          Produce ASCII string equivalent of integer value, interpreting it as 4 one-byte
characters.

static java.lang.String intToBinaryString(int value)

          Translate int value into a String consisting of ‘1’s and ‘0’s.

static java.lang.String intToBinaryString(int value,
int length)

          Translate int value into a String consisting of ‘1’s and ‘0’s.

static java.lang.String intToHalfHexString(int d)

          Returns a 6 character string representing the 16-bit hexadecimal equivalent of the
given integer value.

static java.lang.String intToHexString(int d)

          Prefix a hexadecimal-indicating string “0x” to the string which is
returned by the method “Integer.toHexString”.

static boolean isHex(java.lang.String v)

          Parsing method to see if a string represents a hex number.

static boolean isOctal(java.lang.String v)

          Parsing method to see if a string represents an octal number.

static java.lang.String longToBinaryString(long value)

          Translate long value into a String consisting of ‘1’s and ‘0’s.

static java.lang.String longToBinaryString(long value,
int length)

          Translate long value into a String consisting of ‘1’s and ‘0’s.

static java.lang.String longToHexString(long value)

          Prefix a hexadecimal-indicating string “0x” to the string equivalent to the
hexadecimal value in the long parameter.

static int lowOrderLongToInt(long longValue)

          Returns int representing the bit values of the low order 32 bits of given
64 bit long value.

static int setBit(int value,
int bit)

          Sets the specified bit of the specified value to 1, and returns the result.

static int setByte(int value,
int bite,
int replace)

          Sets the specified byte of the specified value to the low order 8 bits of
specified replacement value, and returns the result.

static int stringToInt(java.lang.String s)

          Attempt to validate given string whose characters represent a 32 bit integer.

static long stringToLong(java.lang.String s)

          Attempt to validate given string whose characters represent a 64 bit long.

static long twoIntsToLong(int highOrder,
int lowOrder)

          Returns long (64 bit integer) combining the bit values of two given 32 bit
integer values.

static java.lang.String unsignedIntToIntString(int d)

          Produce String equivalent of integer value interpreting it as an unsigned integer.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

Binary

public Binary()

Method Detail

intToBinaryString

public static java.lang.String intToBinaryString(int value,
int length)

Translate int value into a String consisting of ‘1’s and ‘0’s.

Parameters:
value – The int value to convert.
length – The number of bit positions, starting at least significant, to process.

Returns:
String consisting of ‘1’ and ‘0’ characters corresponding to the requested binary sequence.

intToBinaryString

public static java.lang.String intToBinaryString(int value)

Translate int value into a String consisting of ‘1’s and ‘0’s. Assumes all 32 bits are
to be translated.

Parameters:
value – The int value to convert.

Returns:
String consisting of ‘1’ and ‘0’ characters corresponding to the requested binary sequence.

longToBinaryString

public static java.lang.String longToBinaryString(long value,
int length)

Translate long value into a String consisting of ‘1’s and ‘0’s.

Parameters:
value – The long value to convert.
length – The number of bit positions, starting at least significant, to process.

Returns:
String consisting of ‘1’ and ‘0’ characters corresponding to the requested binary sequence.

longToBinaryString

public static java.lang.String longToBinaryString(long value)

Translate long value into a String consisting of ‘1’s and ‘0’s. Assumes all 64 bits are
to be translated.

Parameters:
value – The long value to convert.

Returns:
String consisting of ‘1’ and ‘0’ characters corresponding to the requested binary sequence.

binaryStringToInt

public static int binaryStringToInt(java.lang.String value)

Translate String consisting of ‘1’s and ‘0’s into an int value having that binary representation.
The String is assumed to be at most 32 characters long. No error checking is performed.
String position 0 has most-significant bit, position length-1 has least-significant.

Parameters:
value – The String value to convert.

Returns:
int whose binary value corresponds to decoded String.

binaryStringToLong

public static long binaryStringToLong(java.lang.String value)

Translate String consisting of ‘1’s and ‘0’s into a long value having that binary representation.
The String is assumed to be at most 64 characters long. No error checking is performed.
String position 0 has most-significant bit, position length-1 has least-significant.

Parameters:
value – The String value to convert.

Returns:
long whose binary value corresponds to decoded String.

binaryStringToHexString

public static java.lang.String binaryStringToHexString(java.lang.String value)

Translate String consisting of ‘1’s and ‘0’s into String equivalent of the corresponding
hexadecimal value. No length limit.
String position 0 has most-significant bit, position length-1 has least-significant.

Parameters:
value – The String value to convert.

Returns:
String containing ‘0’, ‘1’, …’F’ characters which form hexadecimal
equivalent of decoded String.

hexStringToBinaryString

public static java.lang.String hexStringToBinaryString(java.lang.String value)

Translate String consisting of hexadecimal digits into String consisting of
corresponding binary digits (‘1’s and ‘0’s). No length limit.
String position 0 will have most-significant bit, position length-1 has least-significant.

Parameters:
value – String containing ‘0’, ‘1’, …’f’
characters which form hexadecimal. Letters may be either upper or lower case.
Works either with or without leading “Ox”.

Returns:
String with equivalent value in binary.

binaryStringToHexDigit

public static char binaryStringToHexDigit(java.lang.String value)

Translate String consisting of ‘1’s and ‘0’s into char equivalent of the corresponding
hexadecimal digit. String limited to length 4.
String position 0 has most-significant bit, position length-1 has least-significant.

Parameters:
value – The String value to convert.

Returns:
char ‘0’, ‘1’, …’F’ which form hexadecimal equivalent of decoded String.
If string length > 4, returns ‘0’.

intToHexString

public static java.lang.String intToHexString(int d)

Prefix a hexadecimal-indicating string “0x” to the string which is
returned by the method “Integer.toHexString”. Prepend leading zeroes
to that string as necessary to make it always eight hexadecimal digits.

Parameters:
d – The int value to convert.

Returns:
String containing ‘0’, ‘1’, …’F’ which form hexadecimal equivalent of int.

intToHalfHexString

public static java.lang.String intToHalfHexString(int d)

Returns a 6 character string representing the 16-bit hexadecimal equivalent of the
given integer value. First two characters are “0x”. It assumes value will “fit”
in 16 bits. If non-negative, prepend leading zeroes to that string as necessary
to make it always four hexadecimal digits. If negative, chop off the first
four ‘f’ digits so result is always four hexadecimal digits

Parameters:
d – The int value to convert.

Returns:
String containing ‘0’, ‘1’, …’F’ which form hexadecimal equivalent of int.

longToHexString

public static java.lang.String longToHexString(long value)

Prefix a hexadecimal-indicating string “0x” to the string equivalent to the
hexadecimal value in the long parameter. Prepend leading zeroes
to that string as necessary to make it always sixteen hexadecimal digits.

Parameters:
value – The long value to convert.

Returns:
String containing ‘0’, ‘1’, …’F’ which form hexadecimal equivalent of long.

unsignedIntToIntString

public static java.lang.String unsignedIntToIntString(int d)

Produce String equivalent of integer value interpreting it as an unsigned integer.
For instance, -1 (0xffffffff) produces “4294967295” instead of “-1”.

Parameters:
d – The int value to interpret.

Returns:
String which forms unsigned 32 bit equivalent of int.

intToAscii

public static java.lang.String intToAscii(int d)

Produce ASCII string equivalent of integer value, interpreting it as 4 one-byte
characters. If the value in a given byte does not correspond to a printable
character, it will be assigned a default character (defined in config.properties)
for a placeholder.

Parameters:
d – The int value to interpret

Returns:
String that represents ASCII equivalent

stringToInt

public static int stringToInt(java.lang.String s)
throws java.lang.NumberFormatException

Attempt to validate given string whose characters represent a 32 bit integer.
Integer.decode() is insufficient because it will not allow incorporation of
hex two’s complement (i.e. 0x80…0 through 0xff…f). Allows
optional negative (-) sign but no embedded spaces.

Parameters:
s – candidate string

Returns:
returns int value represented by given string

Throws:

java.lang.NumberFormatException – if string cannot be translated into an int

stringToLong

public static long stringToLong(java.lang.String s)
throws java.lang.NumberFormatException

Attempt to validate given string whose characters represent a 64 bit long.
Long.decode() is insufficient because it will not allow incorporation of
hex two’s complement (i.e. 0x80…0 through 0xff…f). Allows
optional negative (-) sign but no embedded spaces.

Parameters:
s – candidate string

Returns:
returns long value represented by given string

Throws:

java.lang.NumberFormatException – if string cannot be translated into a long

highOrderLongToInt

public static int highOrderLongToInt(long longValue)

Returns int representing the bit values of the high order 32 bits of given
64 bit long value.

Parameters:
longValue – The long value from which to extract bits.

Returns:
int containing high order 32 bits of argument

lowOrderLongToInt

public static int lowOrderLongToInt(long longValue)

Returns int representing the bit values of the low order 32 bits of given
64 bit long value.

Parameters:
longValue – The long value from which to extract bits.

Returns:
int containing low order 32 bits of argument

twoIntsToLong

public static long twoIntsToLong(int highOrder,
int lowOrder)

Returns long (64 bit integer) combining the bit values of two given 32 bit
integer values.

Parameters:
highOrder – Integer to form the high-order 32 bits of result.
lowOrder – Integer to form the high-order 32 bits of result.

Returns:
long containing concatenated 32 bit int values.

bitValue

public static int bitValue(int value,
int bit)

Returns the bit value of the given bit position of the given int value.

Parameters:
value – The value to read the bit from.
bit – bit position in range 0 (least significant) to 31 (most)

Returns:
0 if the bit position contains 0, and 1 otherwise.

bitValue

public static int bitValue(long value,
int bit)

Returns the bit value of the given bit position of the given long value.

Parameters:
value – The value to read the bit from.
bit – bit position in range 0 (least significant) to 63 (most)

Returns:
0 if the bit position contains 0, and 1 otherwise.

setBit

public static int setBit(int value,
int bit)

Sets the specified bit of the specified value to 1, and returns the result.

Parameters:
value – The value in which the bit is to be set.
bit – bit position in range 0 (least significant) to 31 (most)

Returns:
value possibly modified with given bit set to 1.

clearBit

public static int clearBit(int value,
int bit)

Sets the specified bit of the specified value to 0, and returns the result.

Parameters:
value – The value in which the bit is to be set.
bit – bit position in range 0 (least significant) to 31 (most)

Returns:
value possibly modified with given bit set to 0.

setByte

public static int setByte(int value,
int bite,
int replace)

Sets the specified byte of the specified value to the low order 8 bits of
specified replacement value, and returns the result.

Parameters:
value – The value in which the byte is to be set.
bite – byte position in range 0 (least significant) to 3 (most)
replace – value to place into that byte position – use low order 8 bits

Returns:
value modified value.

getByte

public static int getByte(int value,
int bite)

Gets the specified byte of the specified value.

Parameters:
value – The value in which the byte is to be retrieved.
bite – byte position in range 0 (least significant) to 3 (most)

Returns:
zero-extended byte value in low order byte.

isHex

public static boolean isHex(java.lang.String v)

Parsing method to see if a string represents a hex number.
As per http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html#decode(java.lang.String),
a string represents a hex number if the string is in the forms:
Signopt 0x HexDigits
Signopt 0X HexDigits
Signopt # HexDigits

Parameters:
v – String containing numeric digits (could be decimal, octal, or hex)

Returns:
Returns true if string represents a hex number, else returns false.

isOctal

public static boolean isOctal(java.lang.String v)

Parsing method to see if a string represents an octal number.
As per http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html#decode(java.lang.String),
a string represents an octal number if the string is in the forms:
Signopt 0 OctalDigits

Parameters:
v – String containing numeric digits (could be decimal, octal, or hex)

Returns:
Returns true if string represents an octal number, else returns false.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FilenameFinder

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.util

Class FilenameFinder

java.lang.Object
mars.util.FilenameFinder

public class FilenameFinder
extends java.lang.Object

Utility class to perform necessary file-related search
operations. One is to find file names in JAR file,
another is to find names of files in given directory
of normal file system.

Author:
Pete Sanderson

Field Summary

static java.lang.String MATCH_ALL_EXTENSIONS

           

 

Constructor Summary
FilenameFinder()

           

 

Method Summary

static boolean fileExtensionMatch(java.lang.String name,
java.lang.String extension)

          Determine if given filename ends with given extension.

static java.lang.String getExtension(java.io.File file)

          Get the filename extension of the specified File.

static javax.swing.filechooser.FileFilter getFileFilter(java.util.ArrayList extensions,
java.lang.String description)

          Get a FileFilter that will filter files based on the given list of filename extensions.

static javax.swing.filechooser.FileFilter getFileFilter(java.util.ArrayList extensions,
java.lang.String description,
boolean acceptDirectories)

          Get a FileFilter that will filter files based on the given list of filename extensions.

static javax.swing.filechooser.FileFilter getFileFilter(java.lang.String extension,
java.lang.String description)

          Get a FileFilter that will filter files based on the given filename extension.

static javax.swing.filechooser.FileFilter getFileFilter(java.lang.String extension,
java.lang.String description,
boolean acceptDirectories)

          Get a FileFilter that will filter files based on the given filename extension.

static java.util.ArrayList getFilenameList(java.util.ArrayList nameList,
java.util.ArrayList fileExtensions)

          Return list of file names.

static java.util.ArrayList getFilenameList(java.util.ArrayList nameList,
java.lang.String fileExtension)

          Return list of file names.

static java.util.ArrayList getFilenameList(java.lang.ClassLoader classLoader,
java.lang.String directoryPath,
java.util.ArrayList fileExtensions)

          Locate files and return list of file names.

static java.util.ArrayList getFilenameList(java.lang.ClassLoader classLoader,
java.lang.String directoryPath,
java.lang.String fileExtension)

          Locate files and return list of file names.

static java.util.ArrayList getFilenameList(java.lang.String directoryPath,
java.util.ArrayList fileExtensions)

          Locate files and return list of file names.

static java.util.ArrayList getFilenameList(java.lang.String directoryPath,
java.lang.String fileExtension)

          Locate files and return list of file names.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

MATCH_ALL_EXTENSIONS

public static java.lang.String MATCH_ALL_EXTENSIONS

Constructor Detail

FilenameFinder

public FilenameFinder()

Method Detail

getFilenameList

public static java.util.ArrayList getFilenameList(java.lang.ClassLoader classLoader,
java.lang.String directoryPath,
java.lang.String fileExtension)

Locate files and return list of file names. Given a known relative directory path,
it will locate it and build list of all names of files in that directory
having the given file extension. If the “known file path” doesn’t work
because MARS is running from an executable JAR file, it will locate the
directory in the JAR file and proceed from there. NOTE: since this uses
the class loader to get the resource, the directory path needs to be
relative to classpath, not absolute. To work with an arbitrary file system,
use the other version of this overloaded method. Will NOT match directories
that happen to have the desired extension.

Parameters:
classLoader – class loader to use
directoryPath – Search will be confined to this directory. Use “/” as
separator but do NOT include starting or ending “/” (e.g. mars/tools)
fileExtension – Only files with this extension will be added
to the list. Do NOT include the “.” in extension.

Returns:
array list of matching file names as Strings. If none, list is empty.

getFilenameList

public static java.util.ArrayList getFilenameList(java.lang.ClassLoader classLoader,
java.lang.String directoryPath,
java.util.ArrayList fileExtensions)

Locate files and return list of file names. Given a known relative directory path,
it will locate it and build list of all names of files in that directory
having the given file extension. If the “known file path” doesn’t work
because MARS is running from an executable JAR file, it will locate the
directory in the JAR file and proceed from there. NOTE: since this uses
the class loader to get the resource, the directory path needs to be
relative to classpath, not absolute. To work with an arbitrary file system,
use the other version of this overloaded method.

Parameters:
classLoader – class loader to use
directoryPath – Search will be confined to this directory. Use “/” as
separator but do NOT include starting or ending “/” (e.g. mars/tools)
fileExtensions – ArrayList of Strings containing file extensions.
Only files with an extension in this list will be added to the list.
Do NOT include the “.”, eg “class” not “.class”. If Arraylist or
extension null or empty, all files are added.

Returns:
array list of matching file names as Strings. If none, list is empty.

getFilenameList

public static java.util.ArrayList getFilenameList(java.lang.String directoryPath,
java.lang.String fileExtension)

Locate files and return list of file names. Given a known directory path,
it will locate it and build list of all names of files in that directory
having the given file extension. If file extenion is null or empty, all
filenames are returned. Returned list contains absolute filename paths.

Parameters:
directoryPath – Search will be confined to this directory.
fileExtension – Only files with this extension will be added to the list.
Do NOT include “.” in extension.
If null or empty string, all files are added.

Returns:
array list of matching file names (absolute path). If none, list is empty.

getFilenameList

public static java.util.ArrayList getFilenameList(java.lang.String directoryPath,
java.util.ArrayList fileExtensions)

Locate files and return list of file names. Given a known directory path,
it will locate it and build list of all names of files in that directory
having the given file extension. If file extenion is null or empty, all
filenames are returned. Returned list contains absolute filename paths.

Parameters:
directoryPath – Search will be confined to this directory.
fileExtensions – ArrayList of Strings containing file extensions.
Only files with an extension in this list will be added
to the list. Do NOT include the “.” in extensions. If Arraylist or
extension null or empty, all files are added.

Returns:
array list of matching file names (absolute path). If none, list is empty.

getFilenameList

public static java.util.ArrayList getFilenameList(java.util.ArrayList nameList,
java.lang.String fileExtension)

Return list of file names. Given a list of file names, it will return the list
of all having the given file extension. If file extenion is null or empty, all
filenames are returned. Returned list contains absolute filename paths.

Parameters:
nameList – ArrayList of String containing file names.
fileExtension – Only files with this extension will be added to the list.
If null or empty string, all files are added. Do NOT include “.” in extension.

Returns:
array list of matching file names (absolute path). If none, list is empty.

getFilenameList

public static java.util.ArrayList getFilenameList(java.util.ArrayList nameList,
java.util.ArrayList fileExtensions)

Return list of file names. Given a list of file names, it will return the list
of all having the given file extension. If file extenion is null or empty, all
filenames are returned. Returned list contains absolute filename paths.

Parameters:
nameList – ArrayList of String containing file names.
fileExtensions – ArrayList of Strings containing file extensions.
Only files with an extension in this list will be added
to the list. Do NOT include the “.” in extensions. If Arraylist or
extension null or empty, all files are added.

Returns:
array list of matching file names (absolute path). If none, list is empty.

getExtension

public static java.lang.String getExtension(java.io.File file)

Get the filename extension of the specified File.

Parameters:
file – the File object representing the file of interest

Returns:
The filename extension (everything that follows
last ‘.’ in filename) or null if none.

getFileFilter

public static javax.swing.filechooser.FileFilter getFileFilter(java.util.ArrayList extensions,
java.lang.String description,
boolean acceptDirectories)

Get a FileFilter that will filter files based on the given list of filename extensions.

Parameters:
extensions – ArrayList of Strings, each string is acceptable filename extension.
description – String containing description to be added in parentheses after list of extensions.
acceptDirectories – boolean value true if directories are accepted by the filter, false otherwise.

Returns:
a FileFilter object that accepts files with given extensions, and directories if so indicated.

getFileFilter

public static javax.swing.filechooser.FileFilter getFileFilter(java.util.ArrayList extensions,
java.lang.String description)

Get a FileFilter that will filter files based on the given list of filename extensions.
All directories are accepted by the filter.

Parameters:
extensions – ArrayList of Strings, each string is acceptable filename extension
description – String containing description to be added in parentheses after list of extensions.

Returns:
a FileFilter object that accepts files with given extensions, and directories if so indicated.

getFileFilter

public static javax.swing.filechooser.FileFilter getFileFilter(java.lang.String extension,
java.lang.String description,
boolean acceptDirectories)

Get a FileFilter that will filter files based on the given filename extension.

Parameters:
extension – String containing acceptable filename extension.
description – String containing description to be added in parentheses after list of extensions.
acceptDirectories – boolean value true if directories are accepted by the filter, false otherwise.

Returns:
a FileFilter object that accepts files with given extensions, and directories if so indicated.

getFileFilter

public static javax.swing.filechooser.FileFilter getFileFilter(java.lang.String extension,
java.lang.String description)

Get a FileFilter that will filter files based on the given filename extension.
All directories are accepted by the filter.

Parameters:
extension – String containing acceptable filename extension
description – String containing description to be added in parentheses after list of extensions.

Returns:
a FileFilter object that accepts files with given extensions, and directories if so indicated.

fileExtensionMatch

public static boolean fileExtensionMatch(java.lang.String name,
java.lang.String extension)

Determine if given filename ends with given extension.

Parameters:
name – A String containing the file name
extension – A String containing the file extension. Leading period is optional.

Returns:
Returns true if filename ends with given extension, false otherwise.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.util

mars.util

Classes 

Binary

EditorFont

FilenameFinder

MemoryDump

PropertiesFile

SystemIO

EditorFont

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.util

Class EditorFont

java.lang.Object
mars.util.EditorFont

public class EditorFont
extends java.lang.Object

Specialized Font class designed to be used by both the
settings menu methods and the Settings class.

Author:
Pete Sanderson

Field Summary

static int DEFAULT_SIZE

           

static int DEFAULT_STYLE_INT

           

static java.lang.String DEFAULT_STYLE_STRING

           

static int MAX_SIZE

           

static int MIN_SIZE

           

 

Constructor Summary
EditorFont()

           

 

Method Summary

static java.awt.Font createFontFromStringValues(java.lang.String family,
java.lang.String style,
java.lang.String size)

          Creates a new Font object based on the given String specifications.

static java.lang.String[] getAllFamilies()

          Obtain an array of all available font family names.

static java.lang.String[] getCommonFamilies()

          Obtain an array of common font family names.

static java.lang.String[] getFontStyleStrings()

          Get array containing String values for font style names.

static java.lang.String sizeIntToSizeString(int size)

          Given an int representing font size, returns corresponding string.

static int sizeStringToSizeInt(java.lang.String size)

          Given a String representing font size, returns corresponding int.

static java.lang.String styleIntToStyleString(int style)

          Given an int that represents a font style from the Font class,
returns the corresponding String.

static int styleStringToStyleInt(java.lang.String style)

          Given a string that represents a font style, returns the
corresponding final int defined in Font: PLAIN, BOLD, ITALIC.

static java.lang.String substituteSpacesForTabs(java.lang.String string)

           

static java.lang.String substituteSpacesForTabs(java.lang.String string,
int tabSize)

          Handy utility to produce a string that substitutes spaces for all tab characters
in the given string.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

DEFAULT_STYLE_STRING

public static final java.lang.String DEFAULT_STYLE_STRING

DEFAULT_STYLE_INT

public static final int DEFAULT_STYLE_INT

MIN_SIZE

public static final int MIN_SIZE

See Also:
Constant Field Values

MAX_SIZE

public static final int MAX_SIZE

See Also:
Constant Field Values

DEFAULT_SIZE

public static final int DEFAULT_SIZE

See Also:
Constant Field Values

Constructor Detail

EditorFont

public EditorFont()

Method Detail

getCommonFamilies

public static java.lang.String[] getCommonFamilies()

Obtain an array of common font family names. These are guaranteed to
be available at runtime, as they were checked against the local
GraphicsEnvironment.

Returns:
Array of strings, each is a common and available font family name.

getAllFamilies

public static java.lang.String[] getAllFamilies()

Obtain an array of all available font family names. These are guaranteed to
be available at runtime, as they come from the local GraphicsEnvironment.

Returns:
Array of strings, each is an available font family name.

getFontStyleStrings

public static java.lang.String[] getFontStyleStrings()

Get array containing String values for font style names.

styleStringToStyleInt

public static int styleStringToStyleInt(java.lang.String style)

Given a string that represents a font style, returns the
corresponding final int defined in Font: PLAIN, BOLD, ITALIC. It
is not case-sensitive.

Parameters:
style – String representing the font style name

Returns:
The int value of the corresponding Font style constant. If the
string does not match any style name, returns Font.PLAIN.

styleIntToStyleString

public static java.lang.String styleIntToStyleString(int style)

Given an int that represents a font style from the Font class,
returns the corresponding String.

Parameters:
style – Must be one of Font.PLAIN, Font.BOLD, Font.ITALIC.

Returns:
The String representation of that style. If the parameter
is not one of the above, returns “Plain”.

sizeIntToSizeString

public static java.lang.String sizeIntToSizeString(int size)

Given an int representing font size, returns corresponding string.

Parameters:
size – Int representing size.

Returns:
String value of parameter, unless it is less than MIN_SIZE (returns MIN_SIZE
as String) or greater than MAX_SIZE (returns MAX_SIZE as String).

sizeStringToSizeInt

public static int sizeStringToSizeInt(java.lang.String size)

Given a String representing font size, returns corresponding int.

Parameters:
size – String representing size.

Returns:
int value of parameter, unless it is less than MIN_SIZE (returns
MIN_SIZE) or greater than MAX_SIZE (returns MAX_SIZE). If the string
cannot be parsed as a decimal integer, it returns DEFAULT_SIZE.

createFontFromStringValues

public static java.awt.Font createFontFromStringValues(java.lang.String family,
java.lang.String style,
java.lang.String size)

Creates a new Font object based on the given String specifications. This
is different than Font’s constructor, which requires ints for style and size.
It assures that defaults and size limits are applied when necessary.

Parameters:
family – String containing font family.
style – String containing font style. A list of available styles can
be obtained from getFontStyleStrings(). The default of styleStringToStyleInt()
is substituted if necessary.
size – String containing font size. The defaults and limits of
sizeStringToSizeInt() are substituted if necessary.

substituteSpacesForTabs

public static java.lang.String substituteSpacesForTabs(java.lang.String string)

substituteSpacesForTabs

public static java.lang.String substituteSpacesForTabs(java.lang.String string,
int tabSize)

Handy utility to produce a string that substitutes spaces for all tab characters
in the given string. The number of spaces generated is based on the position of
the tab character and the specified tab size.

Parameters:
string – The original string
tabSize – The number of spaces each tab character represents

Returns:
New string in which spaces are substituted for tabs

Throws:

java.lang.NullPointerException – if string is null

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.util

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.util

Class Summary
Binary Some utility methods for working with binary representations.
EditorFont Specialized Font class designed to be used by both the
settings menu methods and the Settings class.
FilenameFinder Utility class to perform necessary file-related search
operations.
MemoryDump  
PropertiesFile Provides means to work with “.properties” files which are used to store
various MARS settings.
SystemIO Provides standard i/o services needed to simulate the MIPS syscall
routines.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

mars.util Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.util

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object mars.util.Binary
mars.util.EditorFont
mars.util.FilenameFinder
mars.util.MemoryDump
mars.util.PropertiesFile
mars.util.SystemIO

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

SystemIO

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.util

Class SystemIO

java.lang.Object
mars.util.SystemIO

public class SystemIO
extends java.lang.Object

Provides standard i/o services needed to simulate the MIPS syscall
routines. These methods will detect whether the simulator is being
run from the command line or through the GUI, then do I/O to
System.in and System.out in the former situation, and interact with
the GUI in the latter.

Author:
Pete Sanderson and Ken Vollmar

Field Summary

static java.lang.String fileErrorString

          String used for description of file error

static int SYSCALL_BUFSIZE

          Buffer size for syscalls for file I/O

static int SYSCALL_MAXFILES

          Maximum number of files that can be open

 

Constructor Summary
SystemIO()

           

 

Method Summary

static void closeFile(int fd)

          Close the file with specified file descriptor

static java.lang.String getFileErrorMessage()

          Retrieve file operation or error message

static int openFile(java.lang.String filename,
int flags)

          Open a file for either reading or writing.

static void printString(java.lang.String string)

          Implements syscall having 4 in $v0, to print a string.

static int readChar(int serviceNumber)

          Implements syscall having 12 in $v0, to read a char value.

static double readDouble(int serviceNumber)

          Implements syscall to read a double value.

static float readFloat(int serviceNumber)

          Implements syscall to read a float value.

static int readFromFile(int fd,
byte[] myBuffer,
int lengthRequested)

          Read bytes from file.

static int readInteger(int serviceNumber)

          Implements syscall to read an integer value.

static java.lang.String readString(int serviceNumber,
int maxLength)

          Implements syscall to read a string.

static void resetFiles()

          Reset all files — clears out the file descriptor table.

static int writeToFile(int fd,
byte[] myBuffer,
int lengthRequested)

          Write bytes to file.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

SYSCALL_BUFSIZE

public static final int SYSCALL_BUFSIZE

Buffer size for syscalls for file I/O

See Also:
Constant Field Values

SYSCALL_MAXFILES

public static final int SYSCALL_MAXFILES

Maximum number of files that can be open

See Also:
Constant Field Values

fileErrorString

public static java.lang.String fileErrorString

String used for description of file error

Constructor Detail

SystemIO

public SystemIO()

Method Detail

readInteger

public static int readInteger(int serviceNumber)

Implements syscall to read an integer value.
Client is responsible for catching NumberFormatException.

Parameters:
serviceNumber – the number assigned to Read Int syscall (default 5)

Returns:
int value corresponding to user input

readFloat

public static float readFloat(int serviceNumber)

Implements syscall to read a float value.
Client is responsible for catching NumberFormatException.

Parameters:
serviceNumber – the number assigned to Read Float syscall (default 6)

Returns:
float value corresponding to user input
Feb 14 2005 Ken Vollmar

readDouble

public static double readDouble(int serviceNumber)

Implements syscall to read a double value.
Client is responsible for catching NumberFormatException.

Parameters:
serviceNumber – the number assigned to Read Double syscall (default 7)

Returns:
double value corresponding to user input
1 Aug 2005 DPS, based on Ken Vollmar’s readFloat

printString

public static void printString(java.lang.String string)

Implements syscall having 4 in $v0, to print a string.

readString

public static java.lang.String readString(int serviceNumber,
int maxLength)

Implements syscall to read a string.

Parameters:
serviceNumber – the number assigned to Read String syscall (default 8)
maxLength – the maximum string length

Returns:
the entered string, truncated to maximum length if necessary

readChar

public static int readChar(int serviceNumber)

Implements syscall having 12 in $v0, to read a char value.

Parameters:
serviceNumber – the number assigned to Read Char syscall (default 12)

Returns:
int value with lowest byte corresponding to user input

writeToFile

public static int writeToFile(int fd,
byte[] myBuffer,
int lengthRequested)

Write bytes to file.

Parameters:
fd – file descriptor
myBuffer – byte array containing characters to write
lengthRequested – number of bytes to write

Returns:
number of bytes written, or -1 on error

readFromFile

public static int readFromFile(int fd,
byte[] myBuffer,
int lengthRequested)

Read bytes from file.

Parameters:
fd – file descriptor
myBuffer – byte array to contain bytes read
lengthRequested – number of bytes to read

Returns:
number of bytes read, 0 on EOF, or -1 on error

openFile

public static int openFile(java.lang.String filename,
int flags)

Open a file for either reading or writing. Note that read/write flag is NOT
IMPLEMENTED. Also note that file permission modes are also NOT IMPLEMENTED.

Parameters:
filename – string containing filename
flag – 0 for read, 1 for write

Returns:
file descriptor in the range 0 to SYSCALL_MAXFILES-1, or -1 if error

closeFile

public static void closeFile(int fd)

Close the file with specified file descriptor

Parameters:
fd – the file descriptor of an open file

resetFiles

public static void resetFiles()

Reset all files — clears out the file descriptor table.

getFileErrorMessage

public static java.lang.String getFileErrorMessage()

Retrieve file operation or error message

Returns:
string containing message

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MemoryDump

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.util

Class MemoryDump

java.lang.Object
mars.util.MemoryDump

public class MemoryDump
extends java.lang.Object

Field Summary

static java.util.ArrayList dumpTriples

          A list of segmentname/dumpformat/filename triples which should be dumped

 

Constructor Summary
MemoryDump()

           

 

Method Summary

static int getAddressOfFirstNull(int baseAddress,
int limitAddress)

          Look for first “null” memory value in an address range.

static int[] getBaseAddresses(java.lang.String[] segments)

          Get the MIPS memory base address(es) of the specified segment name(s).

static int[] getLimitAddresses(java.lang.String[] segments)

          Get the MIPS memory limit address(es) of the specified segment name(s).

static java.lang.Integer[] getSegmentBounds(java.lang.String segment)

          Return array with segment address bounds for specified segment.

static java.lang.String[] getSegmentNames()

          Get the names of segments available for memory dump.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

dumpTriples

public static java.util.ArrayList dumpTriples

A list of segmentname/dumpformat/filename triples which should be dumped

Constructor Detail

MemoryDump

public MemoryDump()

Method Detail

getSegmentBounds

public static java.lang.Integer[] getSegmentBounds(java.lang.String segment)

Return array with segment address bounds for specified segment.

Parameters:
segment – String with segment name (initially “.text” and “.data”)

Returns:
array of two Integer, the base and limit address for that segment. Null if parameter
name does not match a known segment name.

getSegmentNames

public static java.lang.String[] getSegmentNames()

Get the names of segments available for memory dump.

Returns:
array of Strings, each string is segment name (e.g. “.text”, “.data”)

getBaseAddresses

public static int[] getBaseAddresses(java.lang.String[] segments)

Get the MIPS memory base address(es) of the specified segment name(s).
If invalid segment name is provided, will throw NullPointerException, so
I recommend getting segment names from getSegmentNames().

Parameters:
segments – Array of Strings containing segment names (“.text”, “.data”)

Returns:
Array of int containing corresponding base addresses.

getLimitAddresses

public static int[] getLimitAddresses(java.lang.String[] segments)

Get the MIPS memory limit address(es) of the specified segment name(s).
If invalid segment name is provided, will throw NullPointerException, so
I recommend getting segment names from getSegmentNames().

Parameters:
segments – Array of Strings containing segment names (“.text”, “.data”)

Returns:
Array of int containing corresponding limit addresses.

getAddressOfFirstNull

public static int getAddressOfFirstNull(int baseAddress,
int limitAddress)
throws AddressErrorException

Look for first “null” memory value in an address range. For text segment (binary code), this
represents a word that does not contain an instruction. Normally use this to find the end of
the program. For data segment, this represents the first block of simulated memory (block length
currently 4K words) that has not been referenced by an assembled/executing program.

Parameters:
baseAddress – lowest MIPS address to be searched; the starting point
limitAddress – highest MIPS address to be searched

Returns:
lowest address within specified range that contains “null” value as described above.

Throws:

AddressErrorException – if the base address is not on a word boundary

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MarsSplashScreen

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

Class MarsSplashScreen

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
javax.swing.JWindow
mars.MarsSplashScreen

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.RootPaneContainer

public class MarsSplashScreen
extends javax.swing.JWindow

Produces MARS splash screen.

Adapted from http://www.java-tips.org/content/view/1267/2/

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JWindow
javax.swing.JWindow.AccessibleJWindow

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JWindow
accessibleContext, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
MarsSplashScreen(int d)

           

 

Method Summary

 void showSplash()

          A simple little method to show a title screen in the center
of the screen for the amount of time given in the constructor

 
Methods inherited from class javax.swing.JWindow
addImpl, createRootPane, getAccessibleContext, getContentPane, getGlassPane, getGraphics, getLayeredPane, getRootPane, getTransferHandler, isRootPaneCheckingEnabled, paramString, remove, repaint, setContentPane, setGlassPane, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update, windowInit

 
Methods inherited from class java.awt.Window
addNotify, addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowEvent, processWindowFocusEvent, processWindowStateEvent, removeNotify, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImage, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

MarsSplashScreen

public MarsSplashScreen(int d)

Method Detail

showSplash

public void showSplash()

A simple little method to show a title screen in the center
of the screen for the amount of time given in the constructor

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FileStatus

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FileStatus

java.lang.Object
mars.venus.FileStatus

public class FileStatus
extends java.lang.Object

Used to store and return information on the status of the current ASM file that
is being edited in the program.

Author:
Team JSpim

Field Summary

static int EDITED

          open/saved edit window with unsaved edits

static int NEW_EDITED

          New edit window with unsaved edits

static int NEW_NOT_EDITED

          New edit window with no edits

static int NO_FILE

          initial state or after close

static int NOT_EDITED

          open/saved edit window with no edits

static int OPENING

          file is being opened.

static int RUNNABLE

          successful assembly

static int RUNNING

          execution is under way

static int TERMINATED

          execution terminated

 

Constructor Summary
FileStatus()

          Create a FileStatus object with FileStatis.NO_FILE for status and null for file getters.
FileStatus(int status,
java.lang.String pathname)

          Create a FileStatus object with given status and file pathname.

 

Method Summary

static int get()

          Get file status

static java.io.File getFile()

          Returns the ASM file.

 java.lang.String getFilename()

          Get file name with no path information.

 int getFileStatus()

          Get editing status of this file.

static java.lang.String getName()

          Returns the name of the file.

 java.lang.String getParent()

          Get file parent pathname.

 java.lang.String getPathname()

          Get full file pathname.

 boolean hasUnsavedEdits()

          Determine if file has been modified since last save or, if not yet saved, since
being created using New or Open.

static boolean isAssembled()

          Tells whether the file has been assembled.

static boolean isEdited()

          Tells whether the file has been edited since it has been saved.

 boolean isNew()

          Determine if file is “new”, which means created using New but not yet saved.

static boolean isSaved()

          Tells whether the file has been saved.

static void reset()

          Resets all the values in FileStatus

static void set(int newStatus)

          Set file status.

static void setAssembled(boolean b)

          Changes the value of assenbked to the parameter given.

static void setEdited(boolean b)

          Changes the value of edited to the parameter given.

static void setFile(java.io.File f)

          Sets the file to the ASM file passed.

 void setFileStatus(int newStatus)

          Set editing status of this file.

static void setName(java.lang.String s)

          Changes the value of name to the parameter given.

 void setPathname(java.lang.String newPath)

          Set full file pathname.

 void setPathname(java.lang.String parent,
java.lang.String name)

          Set full file pathname.

static void setSaved(boolean b)

          Changes the value of saved to the parameter given.

 void updateStaticFileStatus()

          Update static FileStatus fields with values from this FileStatus object
To support legacy code that depends on the static.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

NO_FILE

public static final int NO_FILE

initial state or after close

See Also:
Constant Field Values

NEW_NOT_EDITED

public static final int NEW_NOT_EDITED

New edit window with no edits

See Also:
Constant Field Values

NEW_EDITED

public static final int NEW_EDITED

New edit window with unsaved edits

See Also:
Constant Field Values

NOT_EDITED

public static final int NOT_EDITED

open/saved edit window with no edits

See Also:
Constant Field Values

EDITED

public static final int EDITED

open/saved edit window with unsaved edits

See Also:
Constant Field Values

RUNNABLE

public static final int RUNNABLE

successful assembly

See Also:
Constant Field Values

RUNNING

public static final int RUNNING

execution is under way

See Also:
Constant Field Values

TERMINATED

public static final int TERMINATED

execution terminated

See Also:
Constant Field Values

OPENING

public static final int OPENING

file is being opened. DPS 9-Aug-2011

See Also:
Constant Field Values

Constructor Detail

FileStatus

public FileStatus()

Create a FileStatus object with FileStatis.NO_FILE for status and null for file getters.

FileStatus

public FileStatus(int status,
java.lang.String pathname)

Create a FileStatus object with given status and file pathname.

Parameters:
status – Initial file status. See FileStatus static constants.
pathname – Full file pathname. See setPathname(String newPath) below.

Method Detail

set

public static void set(int newStatus)

Set file status. Also updates menu state accordingly.

Parameters:
newStatus – New status: EDITED, RUNNABLE, etc, see list above.

get

public static int get()

Get file status

Returns:
file status EDITED, RUNNABLE, etc, see list above

setAssembled

public static void setAssembled(boolean b)

Changes the value of assenbked to the parameter given.

Parameters:
b – boolean variable that tells what to set assembled to.

setSaved

public static void setSaved(boolean b)

Changes the value of saved to the parameter given.

Parameters:
b – boolean variable that tells what to set saved to .

setEdited

public static void setEdited(boolean b)

Changes the value of edited to the parameter given.

Parameters:
b – boolean variable that tells what to set edited to.

setName

public static void setName(java.lang.String s)

Changes the value of name to the parameter given.

Parameters:
s – string variable tells what to set the name of the file to .

setFile

public static void setFile(java.io.File f)

Sets the file to the ASM file passed.

Parameters:
f – file object variable that stores the ASM file.

getFile

public static java.io.File getFile()

Returns the ASM file.

Returns:
The ASM file.

getName

public static java.lang.String getName()

Returns the name of the file.

Returns:
The name of the ASM file.

isAssembled

public static boolean isAssembled()

Tells whether the file has been assembled.

Returns:
Boolean value that is true if the ASM file has been assembled.

isSaved

public static boolean isSaved()

Tells whether the file has been saved.

Returns:
Boolean variable that is true if the ASM file has been saved

isEdited

public static boolean isEdited()

Tells whether the file has been edited since it has been saved.

Returns:
Boolean value that returns true if the ASM file has been edited.

reset

public static void reset()

Resets all the values in FileStatus

setFileStatus

public void setFileStatus(int newStatus)

Set editing status of this file. See FileStatus static constants.

Parameters:
newStatus – the new status

getFileStatus

public int getFileStatus()

Get editing status of this file.

Returns:
current editing status. See FileStatus static constants.

isNew

public boolean isNew()

Determine if file is “new”, which means created using New but not yet saved.
If created using Open, it is not new.

Returns:
true if file was created using New and has not yet been saved, false otherwise.

hasUnsavedEdits

public boolean hasUnsavedEdits()

Determine if file has been modified since last save or, if not yet saved, since
being created using New or Open.

Returns:
true if file has been modified since save or creation, false otherwise.

setPathname

public void setPathname(java.lang.String newPath)

Set full file pathname. See java.io.File(String pathname) for parameter specs.

Parameters:
newPath – the new pathname. If no directory path, getParent() will return null.

setPathname

public void setPathname(java.lang.String parent,
java.lang.String name)

Set full file pathname. See java.io.File(String parent, String child) for parameter specs.

Parameters:
parent – the parent directory of the file. If null, getParent() will return null.
name – the name of the file (no directory path)

getPathname

public java.lang.String getPathname()

Get full file pathname. See java.io.File.getPath()

Returns:
full pathname as a String. Null if

getFilename

public java.lang.String getFilename()

Get file name with no path information. See java.io.File.getName()

Returns:
filename as a String

getParent

public java.lang.String getParent()

Get file parent pathname. See java.io.File.getParent()

Returns:
parent full pathname as a String

updateStaticFileStatus

public void updateStaticFileStatus()

Update static FileStatus fields with values from this FileStatus object
To support legacy code that depends on the static.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsAssembleAllAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsAssembleAllAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsAssembleAllAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsAssembleAllAction
extends GuiAction

Action class for the Settings menu item to determine whether assemble operation applies
only to current file or to all files in its directory.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsAssembleAllAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsAssembleAllAction

public SettingsAssembleAllAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FilePrintAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FilePrintAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.FilePrintAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class FilePrintAction
extends GuiAction

Action for the File -> Print menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
FilePrintAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          Uses the HardcopyWriter class developed by David Flanagan for the book
“Java Examples in a Nutshell”.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

FilePrintAction

public FilePrintAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Uses the HardcopyWriter class developed by David Flanagan for the book
“Java Examples in a Nutshell”. It will do basic printing of multipage
text documents. It displays a print dialog but does not act on any
changes the user may have specified there, such as number of copies.

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Parameters:
e – component triggering this call

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FileExitAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FileExitAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.FileExitAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class FileExitAction
extends GuiAction

Action for the File -> Exit menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
FileExitAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          Exit MARS, unless one or more files have unsaved edits and user cancels.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

FileExitAction

public FileExitAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Exit MARS, unless one or more files have unsaved edits and user cancels.

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

EditSelectAllAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class EditSelectAllAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.EditSelectAllAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class EditSelectAllAction
extends GuiAction

Action for the Edit -> Copy menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
EditSelectAllAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

EditSelectAllAction

public EditSelectAllAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RunToggleBreakpointsAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RunToggleBreakpointsAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.RunToggleBreakpointsAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class RunToggleBreakpointsAction
extends GuiAction

Action class for the Run menu item to clear execution breakpoints that have been set.
It is a listener and is notified whenever a breakpoint is added or removed, thus will
set its enabled status true or false depending on whether breakpoints remain after that action.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
RunToggleBreakpointsAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

          Create the object and register with text segment window as a listener on its table model.

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          When this option is selected, tell text segment window to clear breakpoints in its table model.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

RunToggleBreakpointsAction

public RunToggleBreakpointsAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Create the object and register with text segment window as a listener on its table model.
The table model has not been created yet, so text segment window will hang onto this
registration info and transfer it to the table model upon creation (which happens with
each successful assembly).

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

When this option is selected, tell text segment window to clear breakpoints in its table model.

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

HelpAboutAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class HelpAboutAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.HelpAboutAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class HelpAboutAction
extends GuiAction

Action for the Help -> About menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
HelpAboutAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

HelpAboutAction

public HelpAboutAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

TextSegmentWindow

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class TextSegmentWindow

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JInternalFrame
mars.venus.TextSegmentWindow

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants

public class TextSegmentWindow
extends javax.swing.JInternalFrame

Creates the Text Segment window in the Execute tab of the UI

Author:
Team JSpim
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JInternalFrame
javax.swing.JInternalFrame.AccessibleJInternalFrame, javax.swing.JInternalFrame.JDesktopIcon

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JInternalFrame
closable, CONTENT_PANE_PROPERTY, desktopIcon, FRAME_ICON_PROPERTY, frameIcon, GLASS_PANE_PROPERTY, iconable, IS_CLOSED_PROPERTY, IS_ICON_PROPERTY, IS_MAXIMUM_PROPERTY, IS_SELECTED_PROPERTY, isClosed, isIcon, isMaximum, isSelected, LAYERED_PANE_PROPERTY, maximizable, MENU_BAR_PROPERTY, resizable, ROOT_PANE_PROPERTY, rootPane, rootPaneCheckingEnabled, title, TITLE_PROPERTY

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, EXIT_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
TextSegmentWindow()

          Constructor, sets up a new JInternalFrame.

 

Method Summary

 void addProgramArgumentsPanel()

           

 void clearAllBreakpoints()

          Clears all breakpoints that have been set since last assemble, and
updates the display of the breakpoint column.

 void clearWindow()

          remove all components

 int getBreakpointCount()

          Returns number of breakpoints currently set.

 boolean getCodeHighlighting()

          Get code highlighting status.

 java.lang.String getProgramArguments()

          Get program arguments from text field in south border of text segment window.

 int[] getSortedBreakPointsArray()

          Returns array of current breakpoints, each represented by a MIPS program counter address.

 void highlightStepAtAddress(int address)

          Highlights the source code line whose address matches the given
text segment address.

 void highlightStepAtAddress(int address,
boolean inDelaySlot)

          Highlights the source code line whose address matches the given
text segment address.

 void highlightStepAtPC()

          Highlights the source code line whose address matches the current
program counter value.

 void highlightStepAtPC(boolean inDelaySlot)

          Highlights the source code line whose address matches the current
program counter value.

 void registerTableModelListener(javax.swing.event.TableModelListener tml)

          Assign listener to Table model.

 void removeProgramArgumentsPanel()

           

 void setCodeHighlighting(boolean highlightSetting)

          Used to enable or disable source code highlighting.

 void setupTable()

          Method to be called once the user compiles the program.

 void toggleBreakpoints()

          Enable or disable all items in the Breakpoints column.

 void unhighlightAllSteps()

          If any steps are highlighted, this erases the highlighting.

 void updateBasicStatements()

          Redisplay the basic statements.

 void updateCodeAddresses()

          Redisplay the addresses.

 
Methods inherited from class javax.swing.JInternalFrame
addImpl, addInternalFrameListener, createRootPane, dispose, doDefaultCloseAction, fireInternalFrameEvent, getAccessibleContext, getContentPane, getDefaultCloseOperation, getDesktopIcon, getDesktopPane, getFocusCycleRootAncestor, getFocusOwner, getFrameIcon, getGlassPane, getInternalFrameListeners, getJMenuBar, getLastCursor, getLayer, getLayeredPane, getMenuBar, getMostRecentFocusOwner, getNormalBounds, getRootPane, getTitle, getUI, getUIClassID, getWarningString, hide, isClosable, isClosed, isFocusCycleRoot, isIcon, isIconifiable, isMaximizable, isMaximum, isResizable, isRootPaneCheckingEnabled, isSelected, moveToBack, moveToFront, pack, paintComponent, paramString, remove, removeInternalFrameListener, reshape, restoreSubcomponentFocus, setClosable, setClosed, setContentPane, setCursor, setDefaultCloseOperation, setDesktopIcon, setFocusCycleRoot, setFrameIcon, setGlassPane, setIcon, setIconifiable, setJMenuBar, setLayer, setLayer, setLayeredPane, setLayout, setMaximizable, setMaximum, setMenuBar, setNormalBounds, setResizable, setRootPane, setRootPaneCheckingEnabled, setSelected, setTitle, setUI, show, toBack, toFront, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

TextSegmentWindow

public TextSegmentWindow()

Constructor, sets up a new JInternalFrame.

Method Detail

setupTable

public void setupTable()

Method to be called once the user compiles the program.
Should convert the lines of code over to the table rows and columns.

getProgramArguments

public java.lang.String getProgramArguments()

Get program arguments from text field in south border of text segment window.

Returns:
String containing program arguments

addProgramArgumentsPanel

public void addProgramArgumentsPanel()

removeProgramArgumentsPanel

public void removeProgramArgumentsPanel()

clearWindow

public void clearWindow()

remove all components

registerTableModelListener

public void registerTableModelListener(javax.swing.event.TableModelListener tml)

Assign listener to Table model. Used for breakpoints, since that is the only editable
column in the table. Since table model objects are transient (get a new one with each
successful assemble), this method will simply keep the identity of the listener then
add it as a listener each time a new table model object is created. Limit 1 listener.

updateCodeAddresses

public void updateCodeAddresses()

Redisplay the addresses. This should only be done when address display base is
modified (e.g. between base 16 hex and base 10 dec).

updateBasicStatements

public void updateBasicStatements()

Redisplay the basic statements. This should only be done when address or value display base is
modified (e.g. between base 16 hex and base 10 dec).

getBreakpointCount

public int getBreakpointCount()

Returns number of breakpoints currently set.

Returns:
number of current breakpoints

getSortedBreakPointsArray

public int[] getSortedBreakPointsArray()

Returns array of current breakpoints, each represented by a MIPS program counter address.
These are stored in the BREAK_COLUMN of the table model.

Returns:
int array of breakpoints, sorted by PC address, or null if there are none.

clearAllBreakpoints

public void clearAllBreakpoints()

Clears all breakpoints that have been set since last assemble, and
updates the display of the breakpoint column.

highlightStepAtPC

public void highlightStepAtPC()

Highlights the source code line whose address matches the current
program counter value. This is used for stepping through code
execution and when reaching breakpoints.

highlightStepAtPC

public void highlightStepAtPC(boolean inDelaySlot)

Highlights the source code line whose address matches the current
program counter value. This is used for stepping through code
execution and when reaching breakpoints.

Parameters:
inDelaySlot – Set true if delayed branching is enabled and the
instruction at this address is executing in the delay slot, false
otherwise.

highlightStepAtAddress

public void highlightStepAtAddress(int address)

Highlights the source code line whose address matches the given
text segment address.

Parameters:
address – text segment address of instruction to be highlighted.

highlightStepAtAddress

public void highlightStepAtAddress(int address,
boolean inDelaySlot)

Highlights the source code line whose address matches the given
text segment address.

Parameters:
address – Text segment address of instruction to be highlighted.
inDelaySlot – Set true if delayed branching is enabled and the
instruction at this address is executing in the delay slot, false
otherwise.

setCodeHighlighting

public void setCodeHighlighting(boolean highlightSetting)

Used to enable or disable source code highlighting. If true (normally while
stepping through execution) then MIPS statement at current program counter
is highlighted. The code column’s cell renderer tests this variable.

Parameters:
highlightSetting – true to enable highlighting, false to disable.

getCodeHighlighting

public boolean getCodeHighlighting()

Get code highlighting status.

Returns:
true if code highlighting currently enabled, false otherwise.

unhighlightAllSteps

public void unhighlightAllSteps()

If any steps are highlighted, this erases the highlighting.

toggleBreakpoints

public void toggleBreakpoints()

Enable or disable all items in the Breakpoints column.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RunGoAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RunGoAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.RunGoAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class RunGoAction
extends GuiAction

Action class for the Run -> Go menu item (and toolbar icon)

See Also:
Serialized Form

Field Summary

static int defaultMaxSteps

           

static int maxSteps

           

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
RunGoAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          Action to take when GO is selected — run the MIPS program!

 void paused(boolean done,
int pauseReason,
ProcessingException pe)

          Method to be called when Pause is selected through menu/toolbar/shortcut.

static void resetMaxSteps()

          Reset max steps limit to default value at termination of a simulated execution.

 void stopped(ProcessingException pe,
int reason)

          Method to be called when Stop is selected through menu/toolbar/shortcut.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

defaultMaxSteps

public static int defaultMaxSteps

maxSteps

public static int maxSteps

Constructor Detail

RunGoAction

public RunGoAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Action to take when GO is selected — run the MIPS program!

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

paused

public void paused(boolean done,
int pauseReason,
ProcessingException pe)

Method to be called when Pause is selected through menu/toolbar/shortcut. This should only
happen when MIPS program is running (FileStatus.RUNNING). See VenusUI.java for enabled
status of menu items based on FileStatus. Set GUI as if at breakpoint or executing
step by step.

stopped

public void stopped(ProcessingException pe,
int reason)

Method to be called when Stop is selected through menu/toolbar/shortcut. This should only
happen when MIPS program is running (FileStatus.RUNNING). See VenusUI.java for enabled
status of menu items based on FileStatus. Display finalized values as if execution
terminated due to completion or exception.

resetMaxSteps

public static void resetMaxSteps()

Reset max steps limit to default value at termination of a simulated execution.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

ToolAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class ToolAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.ToolAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class ToolAction
extends javax.swing.AbstractAction

Connects a MarsTool class (class that implements MarsTool interface) to
the Mars menu system by supplying the response to that tool’s menu item
selection.

Author:
Pete Sanderson
See Also:
Serialized Form

Field Summary

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
ToolAction(java.lang.Class toolClass,
java.lang.String toolName)

          Simple constructor.

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          Response when tool’s item selected from menu.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

ToolAction

public ToolAction(java.lang.Class toolClass,
java.lang.String toolName)

Simple constructor.

Parameters:
toolClass – Class object for the associated MarsTool subclass
toolName – Name of this tool, for the menu.

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Response when tool’s item selected from menu. Invokes tool’s action() method.

Parameters:
e – the ActionEvent that triggered this call

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Coprocessor1Window

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class Coprocessor1Window

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
mars.venus.Coprocessor1Window

All Implemented Interfaces:
java.awt.event.ActionListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, java.util.Observer, javax.accessibility.Accessible

public class Coprocessor1Window
extends javax.swing.JPanel
implements java.awt.event.ActionListener, java.util.Observer

Sets up a window to display Coprocessor 1 registers in the Registers pane of the UI.

Author:
Pete Sanderson 2005
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JPanel
javax.swing.JPanel.AccessibleJPanel

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
Coprocessor1Window()

          Constructor which sets up a fresh window with a table that contains the register values.

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          Called when user clicks on a condition flag checkbox.

 void clearHighlighting()

          Clear highlight background color from any row currently highlighted.

 void clearWindow()

          Reset and redisplay registers.

 void refresh()

          Refresh the table, triggering re-rendering.

 java.lang.Object[][] setupWindow()

          Sets up the data for the window.

 void update(java.util.Observable observable,
java.lang.Object obj)

          Required by Observer interface.

 void updateDoubleRegisterValue(int number,
int base)

          This method handles the updating of the GUI.

 void updateFloatRegisterValue(int number,
int val,
int base)

          This method handles the updating of the GUI.

 void updateRegisters()

          Redisplay registers using current display number base (10 or 16)

 void updateRegisters(int base)

          Redisplay registers using specified display number base (10 or 16)

 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

Coprocessor1Window

public Coprocessor1Window()

Constructor which sets up a fresh window with a table that contains the register values.

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Called when user clicks on a condition flag checkbox.
Updates both the display and the underlying Coprocessor 1 flag.

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Parameters:
e – component that triggered this call

setupWindow

public java.lang.Object[][] setupWindow()

Sets up the data for the window.

Returns:
The array object with the data for the window.

clearWindow

public void clearWindow()

Reset and redisplay registers.

clearHighlighting

public void clearHighlighting()

Clear highlight background color from any row currently highlighted.

refresh

public void refresh()

Refresh the table, triggering re-rendering.

updateRegisters

public void updateRegisters()

Redisplay registers using current display number base (10 or 16)

updateRegisters

public void updateRegisters(int base)

Redisplay registers using specified display number base (10 or 16)

Parameters:
base – number base for display (10 or 16)

updateFloatRegisterValue

public void updateFloatRegisterValue(int number,
int val,
int base)

This method handles the updating of the GUI. Does not affect actual register.

Parameters:
number – The number of the float register whose display to update.
val – New value.
base – the number base for display (e.g. 10, 16)

updateDoubleRegisterValue

public void updateDoubleRegisterValue(int number,
int base)

This method handles the updating of the GUI. Does not affect actual register.

Parameters:
number – The number of the double register to update.
base – the number base for display (e.g. 10, 16)

update

public void update(java.util.Observable observable,
java.lang.Object obj)

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.

Specified by:
update in interface java.util.Observer

Parameters:
observable – The Observable object who is notifying us
obj – Auxiliary object with additional information.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DataSegmentWindow

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class DataSegmentWindow

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JInternalFrame
mars.venus.DataSegmentWindow

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants

public class DataSegmentWindow
extends javax.swing.JInternalFrame
implements java.util.Observer

Represents the Data Segment window, which is a type of JInternalFrame.

Author:
Sanderson and Bumgarner
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JInternalFrame
javax.swing.JInternalFrame.AccessibleJInternalFrame, javax.swing.JInternalFrame.JDesktopIcon

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JInternalFrame
closable, CONTENT_PANE_PROPERTY, desktopIcon, FRAME_ICON_PROPERTY, frameIcon, GLASS_PANE_PROPERTY, iconable, IS_CLOSED_PROPERTY, IS_ICON_PROPERTY, IS_MAXIMUM_PROPERTY, IS_SELECTED_PROPERTY, isClosed, isIcon, isMaximum, isSelected, LAYERED_PANE_PROPERTY, maximizable, MENU_BAR_PROPERTY, resizable, ROOT_PANE_PROPERTY, rootPane, rootPaneCheckingEnabled, title, TITLE_PROPERTY

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, EXIT_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
DataSegmentWindow(NumberDisplayBaseChooser[] choosers)

          Constructor for the Data Segment window.

 

Method Summary

 void clearHighlighting()

          Clear highlight background color from any cell currently highlighted.

 void clearWindow()

          Removes the table from its frame, typically done when a file is closed.

 void resetMemoryRange()

          Reset range of memory addresses to base address of currently selected segment and update display.

 void resetValues()

          Reset all data display values to 0

 void setupTable()

          Generates and displays fresh table, typically done upon successful assembly.

 void update(java.util.Observable observable,
java.lang.Object obj)

          Required by Observer interface.

 void updateBaseAddressComboBox()

           

 void updateCell(int address,
int value)

          Update data display to show this value (I’m not sure it is being called).

 void updateDataAddresses()

          Redisplay the addresses.

 void updateModelForMemoryRange(int firstAddr)

          Update table model with contents of new memory “chunk”.

 void updateValues()

          Update data display to show all values

 
Methods inherited from class javax.swing.JInternalFrame
addImpl, addInternalFrameListener, createRootPane, dispose, doDefaultCloseAction, fireInternalFrameEvent, getAccessibleContext, getContentPane, getDefaultCloseOperation, getDesktopIcon, getDesktopPane, getFocusCycleRootAncestor, getFocusOwner, getFrameIcon, getGlassPane, getInternalFrameListeners, getJMenuBar, getLastCursor, getLayer, getLayeredPane, getMenuBar, getMostRecentFocusOwner, getNormalBounds, getRootPane, getTitle, getUI, getUIClassID, getWarningString, hide, isClosable, isClosed, isFocusCycleRoot, isIcon, isIconifiable, isMaximizable, isMaximum, isResizable, isRootPaneCheckingEnabled, isSelected, moveToBack, moveToFront, pack, paintComponent, paramString, remove, removeInternalFrameListener, reshape, restoreSubcomponentFocus, setClosable, setClosed, setContentPane, setCursor, setDefaultCloseOperation, setDesktopIcon, setFocusCycleRoot, setFrameIcon, setGlassPane, setIcon, setIconifiable, setJMenuBar, setLayer, setLayer, setLayeredPane, setLayout, setMaximizable, setMaximum, setMenuBar, setNormalBounds, setResizable, setRootPane, setRootPaneCheckingEnabled, setSelected, setTitle, setUI, show, toBack, toFront, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

DataSegmentWindow

public DataSegmentWindow(NumberDisplayBaseChooser[] choosers)

Constructor for the Data Segment window.

Parameters:
choosers – an array of objects used by user to select number display base (10 or 16)

Method Detail

updateBaseAddressComboBox

public void updateBaseAddressComboBox()

setupTable

public void setupTable()

Generates and displays fresh table, typically done upon successful assembly.

clearWindow

public void clearWindow()

Removes the table from its frame, typically done when a file is closed.

clearHighlighting

public void clearHighlighting()

Clear highlight background color from any cell currently highlighted.

updateModelForMemoryRange

public void updateModelForMemoryRange(int firstAddr)

Update table model with contents of new memory “chunk”. Mars supports megabytes of
data segment space so we only plug a “chunk” at a time into the table.

Parameters:
firstAddr – the first address in the memory range to be placed in the model.

updateCell

public void updateCell(int address,
int value)

Update data display to show this value (I’m not sure it is being called).

updateDataAddresses

public void updateDataAddresses()

Redisplay the addresses. This should only be done when address display base is
modified (e.g. between base 16, hex, and base 10, dec).

updateValues

public void updateValues()

Update data display to show all values

resetMemoryRange

public void resetMemoryRange()

Reset range of memory addresses to base address of currently selected segment and update display.

resetValues

public void resetValues()

Reset all data display values to 0

update

public void update(java.util.Observable observable,
java.lang.Object obj)

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 delegate of the Memory object, which lets us know of memory operations
The Simulator keeps us informed of when simulated MIPS execution is active.
This is the only time we care about memory operations.

Specified by:
update in interface java.util.Observer

Parameters:
observable – The Observable object who is notifying us
obj – Auxiliary object with additional information.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FileNewAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FileNewAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.FileNewAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class FileNewAction
extends GuiAction

Action for the File -> New menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
FileNewAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          Code to create a new document.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

FileNewAction

public FileNewAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Code to create a new document. It clears the source code window.

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Parameters:
e – component triggering this call

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RunAssembleAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RunAssembleAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.RunAssembleAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class RunAssembleAction
extends GuiAction

Action class for the Run -> Assemble menu item (and toolbar icon)

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
RunAssembleAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

RunAssembleAction

public RunAssembleAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

EditRedoAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class EditRedoAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.EditRedoAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class EditRedoAction
extends GuiAction

Action for the Edit -> Redo menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
EditRedoAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          Adapted from TextComponentDemo.java in the
Java Tutorial “Text Component Features”

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

EditRedoAction

public EditRedoAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Adapted from TextComponentDemo.java in the
Java Tutorial “Text Component Features”

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsStartAtMainAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsStartAtMainAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsStartAtMainAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsStartAtMainAction
extends GuiAction

Action class for the Settings menu item to control whether or not
assembler warnings are considered errors. If so, a program generating
warnings but not errors will not assemble.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsStartAtMainAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsStartAtMainAction

public SettingsStartAtMainAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

EditTabbedPane

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class EditTabbedPane

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JTabbedPane
mars.venus.EditTabbedPane

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.SwingConstants

public class EditTabbedPane
extends javax.swing.JTabbedPane

Tabbed pane for the editor. Each of its tabs represents an open file.

Author:
Sanderson
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JTabbedPane
javax.swing.JTabbedPane.AccessibleJTabbedPane, javax.swing.JTabbedPane.ModelListener

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JTabbedPane
changeEvent, changeListener, model, SCROLL_TAB_LAYOUT, tabPlacement, WRAP_TAB_LAYOUT

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
EditTabbedPane(VenusUI appFrame,
Editor editor,
MainPane mainPane)

          Constructor for the EditTabbedPane class.

 

Method Summary

 boolean closeAllFiles()

          Carries out all necessary operations to implement
the Close All operation from the File menu.

 boolean closeCurrentFile()

          Carries out all necessary operations to implement
the Close operation from the File menu.

 boolean editsSavedOrAbandoned()

          Check whether file has unsaved edits and, if so, check with user about saving them.

 EditPane getCurrentEditTab()

          The current EditPane representing a file.

 EditPane getCurrentEditTabForFile(java.io.File file)

          If the given file is open in the tabbed pane, make it the
current tab.

 EditPane getEditPaneForFile(java.lang.String pathname)

          If there is an EditPane for the given file pathname, return it else return null.

 void newFile()

          Carries out all necessary operations to implement
the New operation from the File menu.

 boolean openFile()

          Carries out all necessary operations to implement
the Open operation from the File menu.

 boolean openFile(java.io.File file)

          Carries out all necessary operations to open the
specified file in the editor.

 void remove(EditPane editPane)

          Remove the pane and update menu status

 boolean saveAllFiles()

          Saves all files currently open in the editor.

 boolean saveAsCurrentFile()

          Pops up a dialog box to do “Save As” operation.

 boolean saveCurrentFile()

          Saves file under existing name.

 void setCurrentEditTab(EditPane editPane)

          Select the specified EditPane to be the current tab.

 
Methods inherited from class javax.swing.JTabbedPane
add, add, add, add, add, addChangeListener, addTab, addTab, addTab, createChangeListener, fireStateChanged, getAccessibleContext, getBackgroundAt, getBoundsAt, getChangeListeners, getComponentAt, getDisabledIconAt, getDisplayedMnemonicIndexAt, getForegroundAt, getIconAt, getMnemonicAt, getModel, getSelectedComponent, getSelectedIndex, getTabComponentAt, getTabCount, getTabLayoutPolicy, getTabPlacement, getTabRunCount, getTitleAt, getToolTipText, getToolTipTextAt, getUI, getUIClassID, indexAtLocation, indexOfComponent, indexOfTab, indexOfTab, indexOfTabComponent, insertTab, isEnabledAt, paramString, remove, remove, removeAll, removeChangeListener, removeTabAt, setBackgroundAt, setComponentAt, setDisabledIconAt, setDisplayedMnemonicIndexAt, setEnabledAt, setForegroundAt, setIconAt, setMnemonicAt, setModel, setSelectedComponent, setSelectedIndex, setTabComponentAt, setTabLayoutPolicy, setTabPlacement, setTitleAt, setToolTipTextAt, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

EditTabbedPane

public EditTabbedPane(VenusUI appFrame,
Editor editor,
MainPane mainPane)

Constructor for the EditTabbedPane class.

Method Detail

getCurrentEditTab

public EditPane getCurrentEditTab()

The current EditPane representing a file. Returns null if
no files open.

Returns:
the current editor pane

setCurrentEditTab

public void setCurrentEditTab(EditPane editPane)

Select the specified EditPane to be the current tab.

Parameters:
editPane – The EditPane tab to become current.

getCurrentEditTabForFile

public EditPane getCurrentEditTabForFile(java.io.File file)

If the given file is open in the tabbed pane, make it the
current tab. If not opened, open it in a new tab and make
it the current tab. If file is unable to be opened,
leave current tab as is.

Parameters:
file – File object for the desired file.

Returns:
EditPane for the specified file, or null if file is unable to be opened in an EditPane

newFile

public void newFile()

Carries out all necessary operations to implement
the New operation from the File menu.

openFile

public boolean openFile()

Carries out all necessary operations to implement
the Open operation from the File menu. This
begins with an Open File dialog.

Returns:
true if file was opened, false otherwise.

openFile

public boolean openFile(java.io.File file)

Carries out all necessary operations to open the
specified file in the editor.

Returns:
true if file was opened, false otherwise.

closeCurrentFile

public boolean closeCurrentFile()

Carries out all necessary operations to implement
the Close operation from the File menu. May return
false, for instance when file has unsaved changes
and user selects Cancel from the warning dialog.

Returns:
true if file was closed, false otherwise.

closeAllFiles

public boolean closeAllFiles()

Carries out all necessary operations to implement
the Close All operation from the File menu.

Returns:
true if files closed, false otherwise.

saveCurrentFile

public boolean saveCurrentFile()

Saves file under existing name. If no name, will invoke Save As.

Returns:
true if the file was actually saved.

saveAsCurrentFile

public boolean saveAsCurrentFile()

Pops up a dialog box to do “Save As” operation. If necessary
an additional overwrite dialog is performed.

Returns:
true if the file was actually saved.

saveAllFiles

public boolean saveAllFiles()

Saves all files currently open in the editor.

Returns:
true if operation succeeded otherwise false.

remove

public void remove(EditPane editPane)

Remove the pane and update menu status

getEditPaneForFile

public EditPane getEditPaneForFile(java.lang.String pathname)

If there is an EditPane for the given file pathname, return it else return null.

Parameters:
pathname – Pathname for desired file

Returns:
the EditPane for this file if it is open in the editor, or null if not.

editsSavedOrAbandoned

public boolean editsSavedOrAbandoned()

Check whether file has unsaved edits and, if so, check with user about saving them.

Returns:
true if no unsaved edits or if user chooses to save them or not; false
if there are unsaved edits and user cancels the operation.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

HardcopyWriter

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class HardcopyWriter

java.lang.Object
java.io.Writer
mars.venus.HardcopyWriter

All Implemented Interfaces:
java.io.Closeable, java.io.Flushable, java.lang.Appendable

public class HardcopyWriter
extends java.io.Writer

Nested Class Summary

static class HardcopyWriter.PrintCanceledException

          This is the exception class that the HardcopyWriter constructor
throws when the user clicks “Cancel” in the print dialog box.

 

Field Summary

protected  int charnum

           

protected  int chars_per_line

           

protected  int chars_per_tab

           

protected  int charwidth

           

protected  java.awt.Font font

           

protected  int fontsize

           

protected  java.awt.Font headerfont

           

protected  java.awt.FontMetrics headermetrics

           

protected  int headery

           

protected  int height

           

protected  java.awt.PrintJob job

           

protected  java.lang.String jobname

           

protected  int lineascent

           

protected  int lineheight

           

protected  int linenum

           

protected  int lines_per_page

           

protected  java.awt.FontMetrics metrics

           

protected  java.awt.Graphics page

           

protected  int pagedpi

           

protected  int pagenum

           

protected  java.awt.Dimension pagesize

           

protected static java.util.Properties printprops

           

protected  java.lang.String time

           

protected  int width

           

protected  int x0

           

protected  int y0

           

 
Fields inherited from class java.io.Writer
lock

 

Constructor Summary
HardcopyWriter(java.awt.Frame frame,
java.lang.String jobname,
int fontsize,
double leftmargin,
double rightmargin,
double topmargin,
double bottommargin)

          The constructor for this class has a bunch of arguments:
The frame argument is required for all printing in Java.

 

Method Summary

 void close()

          This is the close( ) method that all Writer subclasses must implement.

 void flush()

          This is the flush( ) method that all Writer subclasses must implement.

 int getCharactersPerLine()

          Return the number of columns of characters that fit on the page

 int getLinesPerPage()

          Return the number of lines that fit on a page

static void main(java.lang.String[] args)

          A program that prints the specified file using HardcopyWriter

protected  void newline()

          This internal method begins a new line

protected  void newpage()

          This internal method begins a new page and prints the header.

 void pageBreak()

          End the current page.

 void setFontStyle(int style)

          Set the font style.

 void write(char[] buffer,
int index,
int len)

          This is the write( ) method of the stream.

 
Methods inherited from class java.io.Writer
append, append, append, write, write, write, write

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

job

protected java.awt.PrintJob job

page

protected java.awt.Graphics page

jobname

protected java.lang.String jobname

fontsize

protected int fontsize

time

protected java.lang.String time

pagesize

protected java.awt.Dimension pagesize

pagedpi

protected int pagedpi

font

protected java.awt.Font font

headerfont

protected java.awt.Font headerfont

metrics

protected java.awt.FontMetrics metrics

headermetrics

protected java.awt.FontMetrics headermetrics

x0

protected int x0

y0

protected int y0

width

protected int width

height

protected int height

headery

protected int headery

charwidth

protected int charwidth

lineheight

protected int lineheight

lineascent

protected int lineascent

chars_per_line

protected int chars_per_line

lines_per_page

protected int lines_per_page

chars_per_tab

protected int chars_per_tab

charnum

protected int charnum

linenum

protected int linenum

pagenum

protected int pagenum

printprops

protected static java.util.Properties printprops

Constructor Detail

HardcopyWriter

public HardcopyWriter(java.awt.Frame frame,
java.lang.String jobname,
int fontsize,
double leftmargin,
double rightmargin,
double topmargin,
double bottommargin)
throws HardcopyWriter.PrintCanceledException

The constructor for this class has a bunch of arguments:
The frame argument is required for all printing in Java.
The jobname appears left justified at the top of each printed page.
The font size is specified in points, as on-screen font sizes are.
The margins are specified in inches (or fractions of inches).

Throws:

HardcopyWriter.PrintCanceledException

Method Detail

write

public void write(char[] buffer,
int index,
int len)

This is the write( ) method of the stream. All Writer subclasses
implement this. All other versions of write( ) are variants of this one

Specified by:
write in class java.io.Writer

flush

public void flush()

This is the flush( ) method that all Writer subclasses must implement.
There is no way to flush a PrintJob without prematurely printing the
page, so we don’t do anything.

Specified by:
flush in interface java.io.Flushable
Specified by:
flush in class java.io.Writer

close

public void close()

This is the close( ) method that all Writer subclasses must implement.
Print the pending page (if any) and terminate the PrintJob.

Specified by:
close in interface java.io.Closeable
Specified by:
close in class java.io.Writer

setFontStyle

public void setFontStyle(int style)

Set the font style. The argument should be one of the font style
constants defined by the java.awt.Font class. All subsequent output
will be in that style. This method relies on all styles of the
Monospaced font having the same metrics.

pageBreak

public void pageBreak()

End the current page. Subsequent output will be on a new page.

getCharactersPerLine

public int getCharactersPerLine()

Return the number of columns of characters that fit on the page

getLinesPerPage

public int getLinesPerPage()

Return the number of lines that fit on a page

newline

protected void newline()

This internal method begins a new line

newpage

protected void newpage()

This internal method begins a new page and prints the header.

main

public static void main(java.lang.String[] args)

A program that prints the specified file using HardcopyWriter

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsEditorAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsEditorAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsEditorAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsEditorAction
extends GuiAction

Action class for the Settings menu item for text editor settings.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsEditorAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

          Create a new SettingsEditorAction.

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          When this action is triggered, launch a dialog to view and modify
editor settings.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsEditorAction

public SettingsEditorAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Create a new SettingsEditorAction. Has all the GuiAction parameters.

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

When this action is triggered, launch a dialog to view and modify
editor settings.

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsMemoryConfigurationAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsMemoryConfigurationAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsMemoryConfigurationAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsMemoryConfigurationAction
extends GuiAction

Action class for the Settings menu item for text editor settings.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsMemoryConfigurationAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

          Create a new SettingsEditorAction.

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          When this action is triggered, launch a dialog to view and modify
editor settings.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsMemoryConfigurationAction

public SettingsMemoryConfigurationAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Create a new SettingsEditorAction. Has all the GuiAction parameters.

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

When this action is triggered, launch a dialog to view and modify
editor settings.

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsAddressDisplayBaseAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsAddressDisplayBaseAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsAddressDisplayBaseAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsAddressDisplayBaseAction
extends GuiAction

Action class for the Settings menu item to control number base (10 or 16) of memory addresses.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsAddressDisplayBaseAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsAddressDisplayBaseAction

public SettingsAddressDisplayBaseAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RunResetAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RunResetAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.RunResetAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class RunResetAction
extends GuiAction

Action for the Run -> Reset menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
RunResetAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          reset GUI components and MIPS resources

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

RunResetAction

public RunResetAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

reset GUI components and MIPS resources

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

EditPasteAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class EditPasteAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.EditPasteAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class EditPasteAction
extends GuiAction

Action for the Edit -> Paste menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
EditPasteAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

EditPasteAction

public EditPasteAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FileOpenAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FileOpenAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.FileOpenAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class FileOpenAction
extends GuiAction

Action for the File -> Open menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
FileOpenAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          Launch a file chooser for name of file to open

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

FileOpenAction

public FileOpenAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Launch a file chooser for name of file to open

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Parameters:
e – component triggering this call

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RunPauseAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RunPauseAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.RunPauseAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class RunPauseAction
extends GuiAction

Action class for the Run -> Pause menu item (and toolbar icon)

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
RunPauseAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

RunPauseAction

public RunPauseAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors

mars.venus.editors

Interfaces 

MARSTextEditingArea

TextAreaPainter

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class TextAreaPainter

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
mars.venus.editors.jeditsyntax.TextAreaPainter

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.swing.text.TabExpander

public class TextAreaPainter
extends javax.swing.JComponent
implements javax.swing.text.TabExpander

The text area repaint manager. It performs double buffering and paints
lines of text.

Author:
Slava Pestov
See Also:
Serialized Form

Nested Class Summary

static interface TextAreaPainter.Highlight

          Highlight interface.

 
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

protected  boolean blockCaret

           

protected  boolean bracketHighlight

           

protected  java.awt.Color bracketHighlightColor

           

protected  java.awt.Color caretColor

           

protected  int cols

           

protected  java.awt.Color eolMarkerColor

           

protected  boolean eolMarkers

           

protected  java.awt.FontMetrics fm

           

protected  TextAreaPainter.Highlight highlights

           

protected  boolean lineHighlight

           

protected  java.awt.Color lineHighlightColor

           

protected  boolean paintInvalid

           

protected  int rows

           

protected  java.awt.Color selectionColor

           

protected  SyntaxStyle[] styles

           

protected  int tabSize

           

protected  int tabSizeChars

           

protected  JEditTextArea textArea

           

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
TextAreaPainter(JEditTextArea textArea,
TextAreaDefaults defaults)

          Creates a new repaint manager.

 

Method Summary

 void addCustomHighlight(TextAreaPainter.Highlight highlight)

          Adds a custom highlight painter.

 java.awt.Color getBracketHighlightColor()

          Returns the bracket highlight color.

 java.awt.Color getCaretColor()

          Returns the caret color.

 java.awt.Color getEOLMarkerColor()

          Returns the EOL marker color.

 boolean getEOLMarkersPainted()

          Returns true if EOL markers are drawn, false otherwise.

 java.awt.FontMetrics getFontMetrics()

          Returns the font metrics used by this component.

 boolean getInvalidLinesPainted()

          Returns true if invalid lines are painted as red tildes (~),
false otherwise.

 java.awt.Color getLineHighlightColor()

          Returns the line highlight color.

 java.awt.Dimension getMinimumSize()

          Returns the painter’s minimum size.

 java.awt.Dimension getPreferredSize()

          Returns the painter’s preferred size.

 java.awt.Color getSelectionColor()

          Returns the selection color.

 SyntaxStyle[] getStyles()

          Returns the syntax styles used to paint colorized text.

 int getTabSize()

          Fetch the tab size in characters.

 java.lang.String getToolTipText(java.awt.event.MouseEvent evt)

          Returns the tool tip to display at the specified location.

 void invalidateLine(int line)

          Marks a line as needing a repaint.

 void invalidateLineRange(int firstLine,
int lastLine)

          Marks a range of lines as needing a repaint.

 void invalidateSelectedLines()

          Repaints the lines containing the selection.

 boolean isBlockCaretEnabled()

          Returns true if the caret should be drawn as a block, false otherwise.

 boolean isBracketHighlightEnabled()

          Returns true if bracket highlighting is enabled, false otherwise.

 boolean isLineHighlightEnabled()

          Returns true if line highlight is enabled, false otherwise.

 boolean isManagingFocus()

          Returns if this component can be traversed by pressing the
Tab key.

 float nextTabStop(float x,
int tabOffset)

          Implementation of TabExpander interface.

 void paint(java.awt.Graphics gfx)

          Repaints the text.

protected  void paintBracketHighlight(java.awt.Graphics gfx,
int line,
int y)

           

protected  void paintCaret(java.awt.Graphics gfx,
int line,
int y)

           

protected  void paintHighlight(java.awt.Graphics gfx,
int line,
int y)

           

protected  void paintLine(java.awt.Graphics gfx,
TokenMarker tokenMarker,
int line,
int x)

           

protected  void paintLineHighlight(java.awt.Graphics gfx,
int line,
int y)

           

protected  void paintPlainLine(java.awt.Graphics gfx,
int line,
java.awt.Font defaultFont,
java.awt.Color defaultColor,
int x,
int y)

           

protected  void paintSyntaxLine(java.awt.Graphics gfx,
TokenMarker tokenMarker,
int line,
java.awt.Font defaultFont,
java.awt.Color defaultColor,
int x,
int y)

           

 void setBlockCaretEnabled(boolean blockCaret)

          Sets if the caret should be drawn as a block, false otherwise.

 void setBracketHighlightColor(java.awt.Color bracketHighlightColor)

          Sets the bracket highlight color.

 void setBracketHighlightEnabled(boolean bracketHighlight)

          Enables or disables bracket highlighting.

 void setCaretColor(java.awt.Color caretColor)

          Sets the caret color.

 void setEOLMarkerColor(java.awt.Color eolMarkerColor)

          Sets the EOL marker color.

 void setEOLMarkersPainted(boolean eolMarkers)

          Sets if EOL markers are to be drawn.

 void setFont(java.awt.Font font)

          Sets the font for this component.

 void setInvalidLinesPainted(boolean paintInvalid)

          Sets if invalid lines are to be painted as red tildes.

 void setLineHighlightColor(java.awt.Color lineHighlightColor)

          Sets the line highlight color.

 void setLineHighlightEnabled(boolean lineHighlight)

          Enables or disables current line highlighting.

 void setSelectionColor(java.awt.Color selectionColor)

          Sets the selection color.

 void setStyles(SyntaxStyle[] styles)

          Sets the syntax styles used to paint colorized text.

 void setTabSize(int size)

          Set the tab size in characters.

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getNextFocusableComponent, getPopupLocation, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

textArea

protected JEditTextArea textArea

styles

protected SyntaxStyle[] styles

caretColor

protected java.awt.Color caretColor

selectionColor

protected java.awt.Color selectionColor

lineHighlightColor

protected java.awt.Color lineHighlightColor

bracketHighlightColor

protected java.awt.Color bracketHighlightColor

eolMarkerColor

protected java.awt.Color eolMarkerColor

blockCaret

protected boolean blockCaret

lineHighlight

protected boolean lineHighlight

bracketHighlight

protected boolean bracketHighlight

paintInvalid

protected boolean paintInvalid

eolMarkers

protected boolean eolMarkers

cols

protected int cols

rows

protected int rows

tabSize

protected int tabSize

tabSizeChars

protected int tabSizeChars

fm

protected java.awt.FontMetrics fm

highlights

protected TextAreaPainter.Highlight highlights

Constructor Detail

TextAreaPainter

public TextAreaPainter(JEditTextArea textArea,
TextAreaDefaults defaults)

Creates a new repaint manager. This should be not be called
directly.

Method Detail

isManagingFocus

public final boolean isManagingFocus()

Returns if this component can be traversed by pressing the
Tab key. This returns false.

NOTE: as of Java 1.4 this method is deprecated and no longer
has the desired effect because the focus subsystem does not
call it. I’ve implemented a KeyEventDispatcher in JEditTextArea
to handle Tabs. DPS 12-May-2010

Overrides:
isManagingFocus in class javax.swing.JComponent

getTabSize

public int getTabSize()

Fetch the tab size in characters. DPS 12-May-2010.

Returns:
int tab size in characters

setTabSize

public void setTabSize(int size)

Set the tab size in characters. DPS 12-May-2010.
Originally it was fixed at PlainDocument property
value (8).

Parameters:
size – tab size in characters

getStyles

public final SyntaxStyle[] getStyles()

Returns the syntax styles used to paint colorized text. Entry n
will be used to paint tokens with id = n.

See Also:
org.syntax.jedit.Token

setStyles

public final void setStyles(SyntaxStyle[] styles)

Sets the syntax styles used to paint colorized text. Entry n
will be used to paint tokens with id = n.

Parameters:
styles – The syntax styles
See Also:
org.syntax.jedit.Token

getCaretColor

public final java.awt.Color getCaretColor()

Returns the caret color.

setCaretColor

public final void setCaretColor(java.awt.Color caretColor)

Sets the caret color.

Parameters:
caretColor – The caret color

getSelectionColor

public final java.awt.Color getSelectionColor()

Returns the selection color.

setSelectionColor

public final void setSelectionColor(java.awt.Color selectionColor)

Sets the selection color.

Parameters:
selectionColor – The selection color

getLineHighlightColor

public final java.awt.Color getLineHighlightColor()

Returns the line highlight color.

setLineHighlightColor

public final void setLineHighlightColor(java.awt.Color lineHighlightColor)

Sets the line highlight color.

Parameters:
lineHighlightColor – The line highlight color

isLineHighlightEnabled

public final boolean isLineHighlightEnabled()

Returns true if line highlight is enabled, false otherwise.

setLineHighlightEnabled

public final void setLineHighlightEnabled(boolean lineHighlight)

Enables or disables current line highlighting.

Parameters:
lineHighlight – True if current line highlight should be enabled,
false otherwise

getBracketHighlightColor

public final java.awt.Color getBracketHighlightColor()

Returns the bracket highlight color.

setBracketHighlightColor

public final void setBracketHighlightColor(java.awt.Color bracketHighlightColor)

Sets the bracket highlight color.

Parameters:
bracketHighlightColor – The bracket highlight color

isBracketHighlightEnabled

public final boolean isBracketHighlightEnabled()

Returns true if bracket highlighting is enabled, false otherwise.
When bracket highlighting is enabled, the bracket matching the
one before the caret (if any) is highlighted.

setBracketHighlightEnabled

public final void setBracketHighlightEnabled(boolean bracketHighlight)

Enables or disables bracket highlighting.
When bracket highlighting is enabled, the bracket matching the
one before the caret (if any) is highlighted.

Parameters:
bracketHighlight – True if bracket highlighting should be
enabled, false otherwise

isBlockCaretEnabled

public final boolean isBlockCaretEnabled()

Returns true if the caret should be drawn as a block, false otherwise.

setBlockCaretEnabled

public final void setBlockCaretEnabled(boolean blockCaret)

Sets if the caret should be drawn as a block, false otherwise.

Parameters:
blockCaret – True if the caret should be drawn as a block,
false otherwise.

getEOLMarkerColor

public final java.awt.Color getEOLMarkerColor()

Returns the EOL marker color.

setEOLMarkerColor

public final void setEOLMarkerColor(java.awt.Color eolMarkerColor)

Sets the EOL marker color.

Parameters:
eolMarkerColor – The EOL marker color

getEOLMarkersPainted

public final boolean getEOLMarkersPainted()

Returns true if EOL markers are drawn, false otherwise.

setEOLMarkersPainted

public final void setEOLMarkersPainted(boolean eolMarkers)

Sets if EOL markers are to be drawn.

Parameters:
eolMarkers – True if EOL markers should be drawn, false otherwise

getInvalidLinesPainted

public boolean getInvalidLinesPainted()

Returns true if invalid lines are painted as red tildes (~),
false otherwise.

setInvalidLinesPainted

public void setInvalidLinesPainted(boolean paintInvalid)

Sets if invalid lines are to be painted as red tildes.

Parameters:
paintInvalid – True if invalid lines should be drawn, false otherwise

addCustomHighlight

public void addCustomHighlight(TextAreaPainter.Highlight highlight)

Adds a custom highlight painter.

Parameters:
highlight – The highlight

getToolTipText

public java.lang.String getToolTipText(java.awt.event.MouseEvent evt)

Returns the tool tip to display at the specified location.

Overrides:
getToolTipText in class javax.swing.JComponent

Parameters:
evt – The mouse event

getFontMetrics

public java.awt.FontMetrics getFontMetrics()

Returns the font metrics used by this component.

setFont

public void setFont(java.awt.Font font)

Sets the font for this component. This is overridden to update the
cached font metrics and to recalculate which lines are visible.

Overrides:
setFont in class javax.swing.JComponent

Parameters:
font – The font

paint

public void paint(java.awt.Graphics gfx)

Repaints the text.

Overrides:
paint in class javax.swing.JComponent

Parameters:
gfx – The graphics context

invalidateLine

public final void invalidateLine(int line)

Marks a line as needing a repaint.

Parameters:
line – The line to invalidate

invalidateLineRange

public final void invalidateLineRange(int firstLine,
int lastLine)

Marks a range of lines as needing a repaint.

Parameters:
firstLine – The first line to invalidate
lastLine – The last line to invalidate

invalidateSelectedLines

public final void invalidateSelectedLines()

Repaints the lines containing the selection.

nextTabStop

public float nextTabStop(float x,
int tabOffset)

Implementation of TabExpander interface. Returns next tab stop after
a specified point.

Specified by:
nextTabStop in interface javax.swing.text.TabExpander

Parameters:
x – The x co-ordinate
tabOffset – Ignored

Returns:
The next tab stop after x

getPreferredSize

public java.awt.Dimension getPreferredSize()

Returns the painter’s preferred size.

Overrides:
getPreferredSize in class javax.swing.JComponent

getMinimumSize

public java.awt.Dimension getMinimumSize()

Returns the painter’s minimum size.

Overrides:
getMinimumSize in class javax.swing.JComponent

paintLine

protected void paintLine(java.awt.Graphics gfx,
TokenMarker tokenMarker,
int line,
int x)

paintPlainLine

protected void paintPlainLine(java.awt.Graphics gfx,
int line,
java.awt.Font defaultFont,
java.awt.Color defaultColor,
int x,
int y)

paintSyntaxLine

protected void paintSyntaxLine(java.awt.Graphics gfx,
TokenMarker tokenMarker,
int line,
java.awt.Font defaultFont,
java.awt.Color defaultColor,
int x,
int y)

paintHighlight

protected void paintHighlight(java.awt.Graphics gfx,
int line,
int y)

paintLineHighlight

protected void paintLineHighlight(java.awt.Graphics gfx,
int line,
int y)

paintBracketHighlight

protected void paintBracketHighlight(java.awt.Graphics gfx,
int line,
int y)

paintCaret

protected void paintCaret(java.awt.Graphics gfx,
int line,
int y)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.next_line

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.next_line

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.next_line

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.next_line
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.next_line(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.next_line

public InputHandler.next_line(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.overwrite

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.overwrite

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.overwrite

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.overwrite
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.overwrite()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.overwrite

public InputHandler.overwrite()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyntaxDocument

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class SyntaxDocument

java.lang.Object
javax.swing.text.AbstractDocument
javax.swing.text.PlainDocument
mars.venus.editors.jeditsyntax.SyntaxDocument

All Implemented Interfaces:
java.io.Serializable, javax.swing.text.Document

public class SyntaxDocument
extends javax.swing.text.PlainDocument

A document implementation that can be tokenized by the syntax highlighting
system.

Author:
Slava Pestov
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.text.AbstractDocument
javax.swing.text.AbstractDocument.AbstractElement, javax.swing.text.AbstractDocument.AttributeContext, javax.swing.text.AbstractDocument.BranchElement, javax.swing.text.AbstractDocument.Content, javax.swing.text.AbstractDocument.DefaultDocumentEvent, javax.swing.text.AbstractDocument.ElementEdit, javax.swing.text.AbstractDocument.LeafElement

 

Field Summary

protected  TokenMarker tokenMarker

           

 
Fields inherited from class javax.swing.text.PlainDocument
lineLimitAttribute, tabSizeAttribute

 
Fields inherited from class javax.swing.text.AbstractDocument
BAD_LOCATION, BidiElementName, ContentElementName, ElementNameAttribute, listenerList, ParagraphElementName, SectionElementName

 
Fields inherited from interface javax.swing.text.Document
StreamDescriptionProperty, TitleProperty

 

Constructor Summary
SyntaxDocument()

           

 

Method Summary

 void addUndoableEdit(javax.swing.undo.UndoableEdit edit)

          Adds an undoable edit to this document’s undo list.

 void beginCompoundEdit()

          Starts a compound edit that can be undone in one operation.

 void endCompoundEdit()

          Ends a compound edit that can be undone in one operation.

protected  void fireInsertUpdate(javax.swing.event.DocumentEvent evt)

          We overwrite this method to update the token marker
state immediately so that any event listeners get a
consistent token marker.

protected  void fireRemoveUpdate(javax.swing.event.DocumentEvent evt)

          We overwrite this method to update the token marker
state immediately so that any event listeners get a
consistent token marker.

 TokenMarker getTokenMarker()

          Returns the token marker that is to be used to split lines
of this document up into tokens.

 void setTokenMarker(TokenMarker tm)

          Sets the token marker that is to be used to split lines of
this document up into tokens.

 void tokenizeLines()

          Reparses the document, by passing all lines to the token
marker.

 void tokenizeLines(int start,
int len)

          Reparses the document, by passing the specified lines to the
token marker.

 
Methods inherited from class javax.swing.text.PlainDocument
createDefaultRoot, getDefaultRootElement, getParagraphElement, insertString, insertUpdate, removeUpdate

 
Methods inherited from class javax.swing.text.AbstractDocument
addDocumentListener, addUndoableEditListener, createBranchElement, createLeafElement, createPosition, dump, fireChangedUpdate, fireUndoableEditUpdate, getAsynchronousLoadPriority, getAttributeContext, getBidiRootElement, getContent, getCurrentWriter, getDocumentFilter, getDocumentListeners, getDocumentProperties, getEndPosition, getLength, getListeners, getProperty, getRootElements, getStartPosition, getText, getText, getUndoableEditListeners, postRemoveUpdate, putProperty, readLock, readUnlock, remove, removeDocumentListener, removeUndoableEditListener, render, replace, setAsynchronousLoadPriority, setDocumentFilter, setDocumentProperties, writeLock, writeUnlock

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

tokenMarker

protected TokenMarker tokenMarker

Constructor Detail

SyntaxDocument

public SyntaxDocument()

Method Detail

getTokenMarker

public TokenMarker getTokenMarker()

Returns the token marker that is to be used to split lines
of this document up into tokens. May return null if this
document is not to be colorized.

setTokenMarker

public void setTokenMarker(TokenMarker tm)

Sets the token marker that is to be used to split lines of
this document up into tokens. May throw an exception if
this is not supported for this type of document.

Parameters:
tm – The new token marker

tokenizeLines

public void tokenizeLines()

Reparses the document, by passing all lines to the token
marker. This should be called after the document is first
loaded.

tokenizeLines

public void tokenizeLines(int start,
int len)

Reparses the document, by passing the specified lines to the
token marker. This should be called after a large quantity of
text is first inserted.

Parameters:
start – The first line to parse
len – The number of lines, after the first one to parse

beginCompoundEdit

public void beginCompoundEdit()

Starts a compound edit that can be undone in one operation.
Subclasses that implement undo should override this method;
this class has no undo functionality so this method is
empty.

endCompoundEdit

public void endCompoundEdit()

Ends a compound edit that can be undone in one operation.
Subclasses that implement undo should override this method;
this class has no undo functionality so this method is
empty.

addUndoableEdit

public void addUndoableEdit(javax.swing.undo.UndoableEdit edit)

Adds an undoable edit to this document’s undo list. The edit
should be ignored if something is currently being undone.

Parameters:
edit – The undoable edit
Since:
jEdit 2.2pre1

fireInsertUpdate

protected void fireInsertUpdate(javax.swing.event.DocumentEvent evt)

We overwrite this method to update the token marker
state immediately so that any event listeners get a
consistent token marker.

Overrides:
fireInsertUpdate in class javax.swing.text.AbstractDocument

fireRemoveUpdate

protected void fireRemoveUpdate(javax.swing.event.DocumentEvent evt)

We overwrite this method to update the token marker
state immediately so that any event listeners get a
consistent token marker.

Overrides:
fireRemoveUpdate in class javax.swing.text.AbstractDocument

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.backspace_word

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.backspace_word

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.backspace_word

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.backspace_word
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.backspace_word()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.backspace_word

public InputHandler.backspace_word()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

KeywordMap

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class KeywordMap

java.lang.Object
mars.venus.editors.jeditsyntax.KeywordMap

public class KeywordMap
extends java.lang.Object

A KeywordMap is similar to a hashtable in that it maps keys
to values. However, the `keys’ are Swing segments. This allows lookups of
text substrings without the overhead of creating a new string object.

This class is used by CTokenMarker to map keywords to ids.

Author:
Slava Pestov, Mike Dillon

Field Summary

protected  int mapLength

           

 

Constructor Summary
KeywordMap(boolean ignoreCase)

          Creates a new KeywordMap.
KeywordMap(boolean ignoreCase,
int mapLength)

          Creates a new KeywordMap.

 

Method Summary

 void add(java.lang.String keyword,
byte id)

          Adds a key-value mapping.

 boolean getIgnoreCase()

          Returns true if the keyword map is set to be case insensitive,
false otherwise.

protected  int getSegmentMapKey(javax.swing.text.Segment s,
int off,
int len)

           

protected  int getStringMapKey(java.lang.String s)

           

 byte lookup(javax.swing.text.Segment text,
int offset,
int length)

          Looks up a key.

 void setIgnoreCase(boolean ignoreCase)

          Sets if the keyword map should be case insensitive.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

mapLength

protected int mapLength

Constructor Detail

KeywordMap

public KeywordMap(boolean ignoreCase)

Creates a new KeywordMap.

Parameters:
ignoreCase – True if keys are case insensitive

KeywordMap

public KeywordMap(boolean ignoreCase,
int mapLength)

Creates a new KeywordMap.

Parameters:
ignoreCase – True if the keys are case insensitive
mapLength – The number of `buckets’ to create.
A value of 52 will give good performance for most maps.

Method Detail

lookup

public byte lookup(javax.swing.text.Segment text,
int offset,
int length)

Looks up a key.

Parameters:
text – The text segment
offset – The offset of the substring within the text segment
length – The length of the substring

add

public void add(java.lang.String keyword,
byte id)

Adds a key-value mapping.

Parameters:
keyword – The key

getIgnoreCase

public boolean getIgnoreCase()

Returns true if the keyword map is set to be case insensitive,
false otherwise.

setIgnoreCase

public void setIgnoreCase(boolean ignoreCase)

Sets if the keyword map should be case insensitive.

Parameters:
ignoreCase – True if the keyword map should be case
insensitive, false otherwise

getStringMapKey

protected int getStringMapKey(java.lang.String s)

getSegmentMapKey

protected int getSegmentMapKey(javax.swing.text.Segment s,
int off,
int len)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.prev_page

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.prev_page

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.prev_page

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.prev_page
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.prev_page(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.prev_page

public InputHandler.prev_page(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.insert_tab

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.insert_tab

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.insert_tab

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.insert_tab
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.insert_tab()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.insert_tab

public InputHandler.insert_tab()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

JEditTextArea

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class JEditTextArea

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
mars.venus.editors.jeditsyntax.JEditTextArea

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable

Direct Known Subclasses:
JEditBasedTextArea

public class JEditTextArea
extends javax.swing.JComponent

jEdit’s text area component. It is more suited for editing program
source code than JEditorPane, because it drops the unnecessary features
(images, variable-width lines, and so on) and adds a whole bunch of
useful goodies such as:

More flexible key binding scheme

Supports macro recorders

Rectangular selection

Bracket highlighting

Syntax highlighting

Command repetition

Block caret can be enabled

It is also faster and doesn’t have as many problems. It can be used
in other applications; the only other part of jEdit it depends on is
the syntax package.

To use it in your app, treat it like any other component, for example:

JEditTextArea ta = new JEditTextArea();
ta.setTokenMarker(new JavaTokenMarker());
ta.setText(“public class Test {\n”
+ ” public static void main(String[] args) {\n”
+ ” System.out.println(\”Hello World\”);\n”
+ ” }\n”
+ “}”);

Author:
Slava Pestov
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

protected  boolean biasLeft

           

protected  boolean blink

           

protected static java.lang.String BOTTOM

           

protected  int bracketLine

           

protected  int bracketPosition

           

protected  int caretBlinkRate

           

protected  boolean caretBlinks

           

protected  mars.venus.editors.jeditsyntax.JEditTextArea.MutableCaretEvent caretEvent

           

protected static javax.swing.Timer caretTimer

           

protected  boolean caretVisible

           

protected static java.lang.String CENTER

           

protected  SyntaxDocument document

           

protected  mars.venus.editors.jeditsyntax.JEditTextArea.DocumentHandler documentHandler

           

protected  boolean editable

           

protected  int electricScroll

           

protected  int firstLine

           

protected static JEditTextArea focusedComponent

           

protected  javax.swing.JScrollBar horizontal

           

protected  int horizontalOffset

           

protected  InputHandler inputHandler

           

static java.lang.String LEFT_OF_SCROLLBAR

          Adding components with this name to the text area will place
them left of the horizontal scroll bar.

protected  javax.swing.text.Segment lineSegment

           

protected  javax.swing.event.EventListenerList listenerList

           

protected  int magicCaret

           

protected  boolean overwrite

           

protected  TextAreaPainter painter

           

protected  javax.swing.JPopupMenu popup

           

protected  boolean rectSelect

           

protected static java.lang.String RIGHT

           

protected  boolean scrollBarsInitialized

           

protected  int selectionEnd

           

protected  int selectionEndLine

           

protected  int selectionStart

           

protected  int selectionStartLine

           

protected  boolean unredoing

           

protected  javax.swing.JScrollBar vertical

           

protected  int visibleLines

           

 
Fields inherited from class javax.swing.JComponent
accessibleContext, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
JEditTextArea(javax.swing.JComponent lineNumbers)

          Creates a new JEditTextArea with the default settings.
JEditTextArea(TextAreaDefaults defaults,
javax.swing.JComponent lineNumbers)

           

 

Method Summary

 int _offsetToX(int line,
int offset)

          Converts an offset in a line into an x co-ordinate.

 void addCaretListener(javax.swing.event.CaretListener listener)

          Adds a caret change listener to this text area.

 void blinkCaret()

          Blinks the caret.

 void copy()

          Places the selected text into the clipboard.

 void cut()

          Deletes the selected text from the text area and places it
into the clipboard.

protected  void documentChanged(javax.swing.event.DocumentEvent evt)

           

protected  void fireCaretEvent()

           

 java.lang.String getAutoIndent()

          Constructs string for auto-indent feature.

 int getBracketLine()

          Returns the line of the highlighted bracket (the bracket
matching the one before the caret)

 int getBracketPosition()

          Returns the position of the highlighted bracket (the bracket
matching the one before the caret)

 int getCaretLine()

          Returns the caret line.

 int getCaretPosition()

          Returns the caret position.

 javax.swing.text.Document getDocument()

          Returns the document this text area is editing.

 int getDocumentLength()

          Returns the length of the document.

 int getElectricScroll()

          Returns the number of lines from the top and button of the
text area that are always visible.

 int getFirstLine()

          Returns the line displayed at the text area’s origin.

 int getHorizontalOffset()

          Returns the horizontal offset of drawn lines.

 InputHandler getInputHandler()

          Returns the input handler.

 java.lang.String getLeadingWhiteSpace()

          Makes a copy of leading white space (tab or space) from the current line and
returns it.

 int getLineCount()

          Returns the number of lines in the document.

 int getLineEndOffset(int line)

          Returns the end offset of the specified line.

 int getLineLength(int line)

          Returns the length of the specified line.

 int getLineOfOffset(int offset)

          Returns the line containing the specified offset.

 int getLineStartOffset(int line)

          Returns the start offset of the specified line.

 java.lang.String getLineText(int lineIndex)

          Returns the text on the specified line.

 void getLineText(int lineIndex,
javax.swing.text.Segment segment)

          Copies the text on the specified line into a segment.

 int getMagicCaretPosition()

          Returns the `magic’ caret position.

 int getMarkLine()

          Returns the mark line.

 int getMarkPosition()

          Returns the mark position.

 TextAreaPainter getPainter()

          Returns the object responsible for painting this text area.

 javax.swing.JPopupMenu getRightClickPopup()

          Returns the right click popup menu.

 java.lang.String getSelectedText()

          Returns the selected text, or null if no selection is active.

 int getSelectionEnd()

          Returns the selection end offset.

 int getSelectionEnd(int line)

          Returns the offset where the selection ends on the specified
line.

 int getSelectionEndLine()

          Returns the selection end line.

 int getSelectionStart()

          Returns the selection start offset.

 int getSelectionStart(int line)

          Returns the offset where the selection starts on the specified
line.

 int getSelectionStartLine()

          Returns the selection start line.

 java.lang.String getSyntaxSensitiveToolTipText(int x,
int y)

          Return any relevant tool tip text for token at specified position.

 java.lang.String getText()

          Returns the entire text of this text area.

 java.lang.String getText(int start,
int len)

          Returns the specified substring of the document.

 void getText(int start,
int len,
javax.swing.text.Segment segment)

          Copies the specified substring of the document into a segment.

 TokenMarker getTokenMarker()

          Returns the document’s token marker.

 int getVisibleLines()

          Returns the number of lines visible in this text area.

 boolean isCaretBlinkEnabled()

          Returns true if the caret is blinking, false otherwise.

 boolean isCaretVisible()

          Returns true if the caret is visible, false otherwise.

 boolean isEditable()

          Returns true if this text area is editable, false otherwise.

 boolean isOverwriteEnabled()

          Returns true if overwrite mode is enabled, false otherwise.

 boolean isSelectionRectangular()

          Returns true if the selection is rectangular, false otherwise.

 int lineToY(int line)

          Converts a line index to a y co-ordinate.

 int offsetToX(int line,
int offset)

          Converts an offset in a line into an x co-ordinate.

 void overwriteSetSelectedText(java.lang.String str)

          Similar to setSelectedText(), but overstrikes the
appropriate number of characters if overwrite mode is enabled.

 void paste()

          Inserts the clipboard contents into the text.

 void processKeyEvent(java.awt.event.KeyEvent evt)

          Forwards key events directly to the input handler.

 void recalculateVisibleLines()

          Recalculates the number of visible lines.

 void removeCaretListener(javax.swing.event.CaretListener listener)

          Removes a caret change listener from this text area.

 void removeNotify()

          Called by the AWT when this component is removed from it’s parent.

 boolean scrollTo(int line,
int offset)

          Ensures that the specified line and offset is visible by scrolling
the text area if necessary.

 boolean scrollToCaret()

          Ensures that the caret is visible by scrolling the text area if
necessary.

 void select(int start,
int end)

          Selects from the start offset to the end offset.

 void selectAll()

          Selects all text in the document.

 void selectNone()

          Moves the mark to the caret position.

 void setCaretBlinkEnabled(boolean caretBlinks)

          Toggles caret blinking.

 void setCaretPosition(int caret)

          Sets the caret position.

 void setCaretVisible(boolean caretVisible)

          Sets if the caret should be visible.

 void setDocument(SyntaxDocument document)

          Sets the document this text area is editing.

 void setEditable(boolean editable)

          Sets if this component is editable.

 void setElectricScroll(int electricScroll)

          Sets the number of lines from the top and bottom of the text
area that are always visible

 void setFirstLine(int firstLine)

          Sets the line displayed at the text area’s origin and
updates the scroll bars.

 void setHorizontalOffset(int horizontalOffset)

          Sets the horizontal offset of drawn lines.

 void setInputHandler(InputHandler inputHandler)

          Sets the input handler.

 void setMagicCaretPosition(int magicCaret)

          Sets the `magic’ caret position.

 boolean setOrigin(int firstLine,
int horizontalOffset)

          A fast way of changing both the first line and horizontal
offset.

 void setOverwriteEnabled(boolean overwrite)

          Sets if overwrite mode should be enabled.

 void setRightClickPopup(javax.swing.JPopupMenu popup)

          Sets the right click popup menu.

 void setSelectedText(java.lang.String selectedText)

          Replaces the selection with the specified text.

 void setSelectionEnd(int selectionEnd)

          Sets the selection end.

 void setSelectionRectangular(boolean rectSelect)

          Sets if the selection should be rectangular.

 void setSelectionStart(int selectionStart)

          Sets the selection start.

 void setText(java.lang.String text)

          Sets the entire text of this text area.

 void setTokenMarker(TokenMarker tokenMarker)

          Sets the document’s token marker.

protected  void updateBracketHighlight(int newCaretPosition)

           

 void updateScrollBars()

          Updates the state of the scroll bars.

 int xToOffset(int line,
int x)

          Converts an x co-ordinate to an offset within a line.

 int xyToOffset(int x,
int y)

          Converts a point to an offset, from the start of the text.

 int yToLine(int y)

          Converts a y co-ordinate to a line index.

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

LEFT_OF_SCROLLBAR

public static java.lang.String LEFT_OF_SCROLLBAR

Adding components with this name to the text area will place
them left of the horizontal scroll bar. In jEdit, the status
bar is added this way.

CENTER

protected static java.lang.String CENTER

RIGHT

protected static java.lang.String RIGHT

BOTTOM

protected static java.lang.String BOTTOM

focusedComponent

protected static JEditTextArea focusedComponent

caretTimer

protected static javax.swing.Timer caretTimer

painter

protected TextAreaPainter painter

popup

protected javax.swing.JPopupMenu popup

listenerList

protected javax.swing.event.EventListenerList listenerList

caretEvent

protected mars.venus.editors.jeditsyntax.JEditTextArea.MutableCaretEvent caretEvent

caretBlinks

protected boolean caretBlinks

caretVisible

protected boolean caretVisible

blink

protected boolean blink

editable

protected boolean editable

caretBlinkRate

protected int caretBlinkRate

firstLine

protected int firstLine

visibleLines

protected int visibleLines

electricScroll

protected int electricScroll

horizontalOffset

protected int horizontalOffset

vertical

protected javax.swing.JScrollBar vertical

horizontal

protected javax.swing.JScrollBar horizontal

scrollBarsInitialized

protected boolean scrollBarsInitialized

inputHandler

protected InputHandler inputHandler

document

protected SyntaxDocument document

documentHandler

protected mars.venus.editors.jeditsyntax.JEditTextArea.DocumentHandler documentHandler

lineSegment

protected javax.swing.text.Segment lineSegment

selectionStart

protected int selectionStart

selectionStartLine

protected int selectionStartLine

selectionEnd

protected int selectionEnd

selectionEndLine

protected int selectionEndLine

biasLeft

protected boolean biasLeft

bracketPosition

protected int bracketPosition

bracketLine

protected int bracketLine

magicCaret

protected int magicCaret

overwrite

protected boolean overwrite

rectSelect

protected boolean rectSelect

unredoing

protected boolean unredoing

Constructor Detail

JEditTextArea

public JEditTextArea(javax.swing.JComponent lineNumbers)

Creates a new JEditTextArea with the default settings.

JEditTextArea

public JEditTextArea(TextAreaDefaults defaults,
javax.swing.JComponent lineNumbers)

Method Detail

getPainter

public final TextAreaPainter getPainter()

Returns the object responsible for painting this text area.

getInputHandler

public final InputHandler getInputHandler()

Returns the input handler.

setInputHandler

public void setInputHandler(InputHandler inputHandler)

Sets the input handler.

Parameters:
inputHandler – The new input handler

isCaretBlinkEnabled

public final boolean isCaretBlinkEnabled()

Returns true if the caret is blinking, false otherwise.

setCaretBlinkEnabled

public void setCaretBlinkEnabled(boolean caretBlinks)

Toggles caret blinking.

Parameters:
caretBlinks – True if the caret should blink, false otherwise

isCaretVisible

public final boolean isCaretVisible()

Returns true if the caret is visible, false otherwise.

setCaretVisible

public void setCaretVisible(boolean caretVisible)

Sets if the caret should be visible.

Parameters:
caretVisible – True if the caret should be visible, false
otherwise

blinkCaret

public final void blinkCaret()

Blinks the caret.

getElectricScroll

public final int getElectricScroll()

Returns the number of lines from the top and button of the
text area that are always visible.

setElectricScroll

public final void setElectricScroll(int electricScroll)

Sets the number of lines from the top and bottom of the text
area that are always visible

Parameters:
electricScroll – The number of lines always visible from
the top or bottom

updateScrollBars

public void updateScrollBars()

Updates the state of the scroll bars. This should be called
if the number of lines in the document changes, or when the
size of the text are changes.

getFirstLine

public final int getFirstLine()

Returns the line displayed at the text area’s origin.

setFirstLine

public void setFirstLine(int firstLine)

Sets the line displayed at the text area’s origin and
updates the scroll bars.

getVisibleLines

public final int getVisibleLines()

Returns the number of lines visible in this text area.

recalculateVisibleLines

public final void recalculateVisibleLines()

Recalculates the number of visible lines. This should not
be called directly.

getHorizontalOffset

public final int getHorizontalOffset()

Returns the horizontal offset of drawn lines.

setHorizontalOffset

public void setHorizontalOffset(int horizontalOffset)

Sets the horizontal offset of drawn lines. This can be used to
implement horizontal scrolling.

Parameters:
horizontalOffset – offset The new horizontal offset

setOrigin

public boolean setOrigin(int firstLine,
int horizontalOffset)

A fast way of changing both the first line and horizontal
offset.

Parameters:
firstLine – The new first line
horizontalOffset – The new horizontal offset

Returns:
True if any of the values were changed, false otherwise

scrollToCaret

public boolean scrollToCaret()

Ensures that the caret is visible by scrolling the text area if
necessary.

Returns:
True if scrolling was actually performed, false if the
caret was already visible

scrollTo

public boolean scrollTo(int line,
int offset)

Ensures that the specified line and offset is visible by scrolling
the text area if necessary.

Parameters:
line – The line to scroll to
offset – The offset in the line to scroll to

Returns:
True if scrolling was actually performed, false if the
line and offset was already visible

lineToY

public int lineToY(int line)

Converts a line index to a y co-ordinate.

Parameters:
line – The line

yToLine

public int yToLine(int y)

Converts a y co-ordinate to a line index.

Parameters:
y – The y co-ordinate

offsetToX

public final int offsetToX(int line,
int offset)

Converts an offset in a line into an x co-ordinate. This is a
slow version that can be used any time.

Parameters:
line – The line
offset – The offset, from the start of the line

_offsetToX

public int _offsetToX(int line,
int offset)

Converts an offset in a line into an x co-ordinate. This is a
fast version that should only be used if no changes were made
to the text since the last repaint.

Parameters:
line – The line
offset – The offset, from the start of the line

xToOffset

public int xToOffset(int line,
int x)

Converts an x co-ordinate to an offset within a line.

Parameters:
line – The line
x – The x co-ordinate

xyToOffset

public int xyToOffset(int x,
int y)

Converts a point to an offset, from the start of the text.

Parameters:
x – The x co-ordinate of the point
y – The y co-ordinate of the point

getDocument

public final javax.swing.text.Document getDocument()

Returns the document this text area is editing.

setDocument

public void setDocument(SyntaxDocument document)

Sets the document this text area is editing.

Parameters:
document – The document

getTokenMarker

public final TokenMarker getTokenMarker()

Returns the document’s token marker. Equivalent to calling
getDocument().getTokenMarker().

setTokenMarker

public final void setTokenMarker(TokenMarker tokenMarker)

Sets the document’s token marker. Equivalent to caling
getDocument().setTokenMarker().

Parameters:
tokenMarker – The token marker

getDocumentLength

public final int getDocumentLength()

Returns the length of the document. Equivalent to calling
getDocument().getLength().

getLineCount

public final int getLineCount()

Returns the number of lines in the document.

getLineOfOffset

public final int getLineOfOffset(int offset)

Returns the line containing the specified offset.

Parameters:
offset – The offset

getLineStartOffset

public int getLineStartOffset(int line)

Returns the start offset of the specified line.

Parameters:
line – The line

Returns:
The start offset of the specified line, or -1 if the line is
invalid

getLineEndOffset

public int getLineEndOffset(int line)

Returns the end offset of the specified line.

Parameters:
line – The line

Returns:
The end offset of the specified line, or -1 if the line is
invalid.

getLineLength

public int getLineLength(int line)

Returns the length of the specified line.

Parameters:
line – The line

getText

public java.lang.String getText()

Returns the entire text of this text area.

setText

public void setText(java.lang.String text)

Sets the entire text of this text area.

getText

public final java.lang.String getText(int start,
int len)

Returns the specified substring of the document.

Parameters:
start – The start offset
len – The length of the substring

Returns:
The substring, or null if the offsets are invalid

getText

public final void getText(int start,
int len,
javax.swing.text.Segment segment)

Copies the specified substring of the document into a segment.
If the offsets are invalid, the segment will contain a null string.

Parameters:
start – The start offset
len – The length of the substring
segment – The segment

getLineText

public final java.lang.String getLineText(int lineIndex)

Returns the text on the specified line.

Parameters:
lineIndex – The line

Returns:
The text, or null if the line is invalid

getLineText

public final void getLineText(int lineIndex,
javax.swing.text.Segment segment)

Copies the text on the specified line into a segment. If the line
is invalid, the segment will contain a null string.

Parameters:
lineIndex – The line

getSelectionStart

public final int getSelectionStart()

Returns the selection start offset.

getSelectionStart

public int getSelectionStart(int line)

Returns the offset where the selection starts on the specified
line.

getSelectionStartLine

public final int getSelectionStartLine()

Returns the selection start line.

setSelectionStart

public final void setSelectionStart(int selectionStart)

Sets the selection start. The new selection will be the new
selection start and the old selection end.

Parameters:
selectionStart – The selection start
See Also:
select(int,int)

getSelectionEnd

public final int getSelectionEnd()

Returns the selection end offset.

getSelectionEnd

public int getSelectionEnd(int line)

Returns the offset where the selection ends on the specified
line.

getSelectionEndLine

public final int getSelectionEndLine()

Returns the selection end line.

setSelectionEnd

public final void setSelectionEnd(int selectionEnd)

Sets the selection end. The new selection will be the old
selection start and the new selection end.

Parameters:
selectionEnd – The selection end
See Also:
select(int,int)

getCaretPosition

public final int getCaretPosition()

Returns the caret position. This will either be the selection
start or the selection end, depending on which direction the
selection was made in.

getCaretLine

public final int getCaretLine()

Returns the caret line.

getMarkPosition

public final int getMarkPosition()

Returns the mark position. This will be the opposite selection
bound to the caret position.

See Also:
getCaretPosition()

getMarkLine

public final int getMarkLine()

Returns the mark line.

setCaretPosition

public final void setCaretPosition(int caret)

Sets the caret position. The new selection will consist of the
caret position only (hence no text will be selected)

Parameters:
caret – The caret position
See Also:
select(int,int)

selectAll

public final void selectAll()

Selects all text in the document.

selectNone

public final void selectNone()

Moves the mark to the caret position.

select

public void select(int start,
int end)

Selects from the start offset to the end offset. This is the
general selection method used by all other selecting methods.
The caret position will be start if start < end, and end if end > start.

Parameters:
start – The start offset
end – The end offset

getSelectedText

public final java.lang.String getSelectedText()

Returns the selected text, or null if no selection is active.

setSelectedText

public void setSelectedText(java.lang.String selectedText)

Replaces the selection with the specified text.

Parameters:
selectedText – The replacement text for the selection

isEditable

public final boolean isEditable()

Returns true if this text area is editable, false otherwise.

setEditable

public final void setEditable(boolean editable)

Sets if this component is editable.

Parameters:
editable – True if this text area should be editable,
false otherwise

getRightClickPopup

public final javax.swing.JPopupMenu getRightClickPopup()

Returns the right click popup menu.

setRightClickPopup

public final void setRightClickPopup(javax.swing.JPopupMenu popup)

Sets the right click popup menu.

Parameters:
popup – The popup

getMagicCaretPosition

public final int getMagicCaretPosition()

Returns the `magic’ caret position. This can be used to preserve
the column position when moving up and down lines.

setMagicCaretPosition

public final void setMagicCaretPosition(int magicCaret)

Sets the `magic’ caret position. This can be used to preserve
the column position when moving up and down lines.

Parameters:
magicCaret – The magic caret position

overwriteSetSelectedText

public void overwriteSetSelectedText(java.lang.String str)

Similar to setSelectedText(), but overstrikes the
appropriate number of characters if overwrite mode is enabled.

Parameters:
str – The string
See Also:
setSelectedText(String),
isOverwriteEnabled()

isOverwriteEnabled

public final boolean isOverwriteEnabled()

Returns true if overwrite mode is enabled, false otherwise.

setOverwriteEnabled

public final void setOverwriteEnabled(boolean overwrite)

Sets if overwrite mode should be enabled.

Parameters:
overwrite – True if overwrite mode should be enabled,
false otherwise.

isSelectionRectangular

public final boolean isSelectionRectangular()

Returns true if the selection is rectangular, false otherwise.

setSelectionRectangular

public final void setSelectionRectangular(boolean rectSelect)

Sets if the selection should be rectangular.

Parameters:
overwrite – True if the selection should be rectangular,
false otherwise.

getBracketPosition

public final int getBracketPosition()

Returns the position of the highlighted bracket (the bracket
matching the one before the caret)

getBracketLine

public final int getBracketLine()

Returns the line of the highlighted bracket (the bracket
matching the one before the caret)

addCaretListener

public final void addCaretListener(javax.swing.event.CaretListener listener)

Adds a caret change listener to this text area.

Parameters:
listener – The listener

removeCaretListener

public final void removeCaretListener(javax.swing.event.CaretListener listener)

Removes a caret change listener from this text area.

Parameters:
listener – The listener

cut

public void cut()

Deletes the selected text from the text area and places it
into the clipboard.

copy

public void copy()

Places the selected text into the clipboard.

paste

public void paste()

Inserts the clipboard contents into the text.

removeNotify

public void removeNotify()

Called by the AWT when this component is removed from it’s parent.
This stops clears the currently focused component.

Overrides:
removeNotify in class javax.swing.JComponent

processKeyEvent

public void processKeyEvent(java.awt.event.KeyEvent evt)

Forwards key events directly to the input handler.
This is slightly faster than using a KeyListener
because some Swing overhead is avoided.

Overrides:
processKeyEvent in class javax.swing.JComponent

fireCaretEvent

protected void fireCaretEvent()

updateBracketHighlight

protected void updateBracketHighlight(int newCaretPosition)

documentChanged

protected void documentChanged(javax.swing.event.DocumentEvent evt)

getSyntaxSensitiveToolTipText

public java.lang.String getSyntaxSensitiveToolTipText(int x,
int y)

Return any relevant tool tip text for token at specified position. Keyword match
must be exact. DPS 24-May-2010

Parameters:
x – x-coordinate of current position
y – y-coordinate of current position

Returns:
String containing appropriate tool tip text. Possibly HTML-encoded.

getAutoIndent

public java.lang.String getAutoIndent()

Constructs string for auto-indent feature. Returns empty string
if auto-intent is disabled or if line has no leading white space.
Uses getLeadingWhiteSpace(). Is used by InputHandler when processing
key press for Enter key. DPS 31-Dec-2010

Returns:
String containing auto-indent characters to be inserted into text

getLeadingWhiteSpace

public java.lang.String getLeadingWhiteSpace()

Makes a copy of leading white space (tab or space) from the current line and
returns it. DPS 31-Dec-2010

Returns:
String containing leading white space of current line. Empty string if none.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.repeat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.repeat

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.repeat

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener, InputHandler.NonRecordable

Enclosing class:
InputHandler

public static class InputHandler.repeat
extends java.lang.Object
implements java.awt.event.ActionListener, InputHandler.NonRecordable

Constructor Summary
InputHandler.repeat()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.repeat

public InputHandler.repeat()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.end

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.end

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.end

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.end
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.end(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.end

public InputHandler.end(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.prev_word

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.prev_word

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.prev_word

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.prev_word
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.prev_word(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.prev_word

public InputHandler.prev_word(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

TextAreaPainter.Highlight

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Interface TextAreaPainter.Highlight

Enclosing class:
TextAreaPainter

public static interface TextAreaPainter.Highlight

Highlight interface.

Method Summary

 java.lang.String getToolTipText(java.awt.event.MouseEvent evt)

          Returns the tool tip to display at the specified
location.

 void init(JEditTextArea textArea,
TextAreaPainter.Highlight next)

          Called after the highlight painter has been added.

 void paintHighlight(java.awt.Graphics gfx,
int line,
int y)

          This should paint the highlight and delgate to the
next highlight painter.

 

Method Detail

init

void init(JEditTextArea textArea,
TextAreaPainter.Highlight next)

Called after the highlight painter has been added.

Parameters:
textArea – The text area
next – The painter this one should delegate to

paintHighlight

void paintHighlight(java.awt.Graphics gfx,
int line,
int y)

This should paint the highlight and delgate to the
next highlight painter.

Parameters:
gfx – The graphics context
line – The line number
y – The y co-ordinate of the line

getToolTipText

java.lang.String getToolTipText(java.awt.event.MouseEvent evt)

Returns the tool tip to display at the specified
location. If this highlighter doesn’t know what to
display, it should delegate to the next highlight
painter.

Parameters:
evt – The mouse event

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.backspace

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.backspace

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.backspace

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.backspace
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.backspace()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.backspace

public InputHandler.backspace()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

JEditBasedTextArea

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class JEditBasedTextArea

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
mars.venus.editors.jeditsyntax.JEditTextArea
mars.venus.editors.jeditsyntax.JEditBasedTextArea

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, javax.swing.event.CaretListener, MARSTextEditingArea

public class JEditBasedTextArea
extends JEditTextArea
implements MARSTextEditingArea, javax.swing.event.CaretListener

Adaptor subclass for JEditTextArea

Provides those methods required by the MARSTextEditingArea interface
that are not defined by JEditTextArea. This permits JEditTextArea
to be used within MARS largely without modification. DPS 4-20-2010

Since:
4.0
Author:
Pete Sanderson
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class mars.venus.editors.jeditsyntax.JEditTextArea
biasLeft, blink, BOTTOM, bracketLine, bracketPosition, caretBlinkRate, caretBlinks, caretEvent, caretTimer, caretVisible, CENTER, document, documentHandler, editable, electricScroll, firstLine, focusedComponent, horizontal, horizontalOffset, inputHandler, LEFT_OF_SCROLLBAR, lineSegment, listenerList, magicCaret, overwrite, painter, popup, rectSelect, RIGHT, scrollBarsInitialized, selectionEnd, selectionEndLine, selectionStart, selectionStartLine, unredoing, vertical, visibleLines

 
Fields inherited from class javax.swing.JComponent
accessibleContext, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface mars.venus.editors.MARSTextEditingArea
TEXT_FOUND, TEXT_NOT_FOUND, TEXT_REPLACED_FOUND_NEXT, TEXT_REPLACED_NOT_FOUND_NEXT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
JEditBasedTextArea(EditPane editPain,
javax.swing.JComponent lineNumbers)

           

 

Method Summary

 void caretUpdate(javax.swing.event.CaretEvent e)

          Display caret position on the edit pane.

 void discardAllUndoableEdits()

          Get rid of any accumulated undoable edits.

 int doFindText(java.lang.String find,
boolean caseSensitive)

          Finds next occurrence of text in a forward search of a string.

 int doReplace(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

          Finds and replaces next occurrence of text in a string in a forward search.

 int doReplaceAll(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

          Finds and replaces ALL occurrences of text in a string in a forward search.

 java.awt.Font getFont()

           

 java.awt.Component getOuterComponent()

           

 javax.swing.undo.UndoManager getUndoManager()

          Returns the undo manager for this editing area

 int nextIndex(java.lang.String input,
java.lang.String find,
int start,
boolean caseSensitive)

          Returns next posn of word in text – forward search.

 void redo()

          Redo previous edit

 void replaceSelection(java.lang.String replacementText)

          Same as setSelectedText but named for compatibility with
JTextComponent method replaceSelection.

 void setCaretBlinkRate(int rate)

          Set the caret blinking rate in milliseconds.

 void setFont(java.awt.Font f)

           

 void setLineHighlightEnabled(boolean highlight)

          Use for highlighting the line currently being edited.

 void setSelectionVisible(boolean vis)

           

 void setSourceCode(java.lang.String s,
boolean editable)

           

 void setTabSize(int chars)

          Set the number of characters a tab will expand to.

 void undo()

          Undo previous edit

 void updateSyntaxStyles()

          Update the syntax style table, which is obtained from
SyntaxUtilities.

 
Methods inherited from class mars.venus.editors.jeditsyntax.JEditTextArea
_offsetToX, addCaretListener, blinkCaret, copy, cut, documentChanged, fireCaretEvent, getAutoIndent, getBracketLine, getBracketPosition, getCaretLine, getCaretPosition, getDocument, getDocumentLength, getElectricScroll, getFirstLine, getHorizontalOffset, getInputHandler, getLeadingWhiteSpace, getLineCount, getLineEndOffset, getLineLength, getLineOfOffset, getLineStartOffset, getLineText, getLineText, getMagicCaretPosition, getMarkLine, getMarkPosition, getPainter, getRightClickPopup, getSelectedText, getSelectionEnd, getSelectionEnd, getSelectionEndLine, getSelectionStart, getSelectionStart, getSelectionStartLine, getSyntaxSensitiveToolTipText, getText, getText, getText, getTokenMarker, getVisibleLines, isCaretBlinkEnabled, isCaretVisible, isEditable, isOverwriteEnabled, isSelectionRectangular, lineToY, offsetToX, overwriteSetSelectedText, paste, processKeyEvent, recalculateVisibleLines, removeCaretListener, removeNotify, scrollTo, scrollToCaret, select, selectAll, selectNone, setCaretBlinkEnabled, setCaretPosition, setCaretVisible, setDocument, setEditable, setElectricScroll, setFirstLine, setHorizontalOffset, setInputHandler, setMagicCaretPosition, setOrigin, setOverwriteEnabled, setRightClickPopup, setSelectedText, setSelectionEnd, setSelectionRectangular, setSelectionStart, setText, setTokenMarker, updateBracketHighlight, updateScrollBars, xToOffset, xyToOffset, yToLine

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface mars.venus.editors.MARSTextEditingArea
copy, cut, getCaretPosition, getDocument, getFontMetrics, getSelectedText, getSelectionEnd, getSelectionStart, getText, grabFocus, paste, requestFocusInWindow, revalidate, select, selectAll, setBackground, setCaretPosition, setCaretVisible, setEditable, setEnabled, setSelectionEnd, setSelectionStart, setText

 

Constructor Detail

JEditBasedTextArea

public JEditBasedTextArea(EditPane editPain,
javax.swing.JComponent lineNumbers)

Method Detail

setFont

public void setFont(java.awt.Font f)

Specified by:
setFont in interface MARSTextEditingArea
Overrides:
setFont in class javax.swing.JComponent

getFont

public java.awt.Font getFont()

Specified by:
getFont in interface java.awt.MenuContainer
Specified by:
getFont in interface MARSTextEditingArea
Overrides:
getFont in class java.awt.Component

setLineHighlightEnabled

public void setLineHighlightEnabled(boolean highlight)

Use for highlighting the line currently being edited.

Specified by:
setLineHighlightEnabled in interface MARSTextEditingArea

Parameters:
highlight – true to enable line highlighting, false to disable.

setCaretBlinkRate

public void setCaretBlinkRate(int rate)

Set the caret blinking rate in milliseconds. If rate is 0
will disable blinking. If negative, do nothing.

Specified by:
setCaretBlinkRate in interface MARSTextEditingArea

Parameters:
rate – blinking rate in milliseconds

setTabSize

public void setTabSize(int chars)

Set the number of characters a tab will expand to.

Specified by:
setTabSize in interface MARSTextEditingArea

Parameters:
chars – number of characters

updateSyntaxStyles

public void updateSyntaxStyles()

Update the syntax style table, which is obtained from
SyntaxUtilities.

Specified by:
updateSyntaxStyles in interface MARSTextEditingArea

getOuterComponent

public java.awt.Component getOuterComponent()

Specified by:
getOuterComponent in interface MARSTextEditingArea

discardAllUndoableEdits

public void discardAllUndoableEdits()

Get rid of any accumulated undoable edits. It is useful to call
this method after opening a file into the text area. The
act of setting its text content upon reading the file will generate
an undoable edit. Normally you don’t want a freshly-opened file
to appear with its Undo action enabled. But it will unless you
call this after setting the text.

Specified by:
discardAllUndoableEdits in interface MARSTextEditingArea

caretUpdate

public void caretUpdate(javax.swing.event.CaretEvent e)

Display caret position on the edit pane.

Specified by:
caretUpdate in interface javax.swing.event.CaretListener

Parameters:
e – A CaretEvent

replaceSelection

public void replaceSelection(java.lang.String replacementText)

Same as setSelectedText but named for compatibility with
JTextComponent method replaceSelection.
DPS, 14 Apr 2010

Specified by:
replaceSelection in interface MARSTextEditingArea

Parameters:
replacementText – The replacement text for the selection

setSelectionVisible

public void setSelectionVisible(boolean vis)

Specified by:
setSelectionVisible in interface MARSTextEditingArea

setSourceCode

public void setSourceCode(java.lang.String s,
boolean editable)

Specified by:
setSourceCode in interface MARSTextEditingArea

getUndoManager

public javax.swing.undo.UndoManager getUndoManager()

Returns the undo manager for this editing area

Specified by:
getUndoManager in interface MARSTextEditingArea

Returns:
the undo manager

undo

public void undo()

Undo previous edit

Specified by:
undo in interface MARSTextEditingArea

redo

public void redo()

Redo previous edit

Specified by:
redo in interface MARSTextEditingArea

doFindText

public int doFindText(java.lang.String find,
boolean caseSensitive)

Finds next occurrence of text in a forward search of a string. Search begins
at the current cursor location, and wraps around when the end of the string
is reached.

Specified by:
doFindText in interface MARSTextEditingArea

Parameters:
find – the text to locate in the string
caseSensitive – true if search is to be case-sensitive, false otherwise

Returns:
TEXT_FOUND or TEXT_NOT_FOUND, depending on the result.

nextIndex

public int nextIndex(java.lang.String input,
java.lang.String find,
int start,
boolean caseSensitive)

Returns next posn of word in text – forward search. If end of string is
reached during the search, will wrap around to the beginning one time.

Parameters:
input – the string to search
find – the string to find
start – the character position to start the search
caseSensitive – true for case sensitive. false to ignore case

Returns:
next indexed position of found text or -1 if not found

doReplace

public int doReplace(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

Finds and replaces next occurrence of text in a string in a forward search.
If cursor is initially at end
of matching selection, will immediately replace then find and select the
next occurrence if any. Otherwise it performs a find operation. The replace
can be undone with one undo operation.

Specified by:
doReplace in interface MARSTextEditingArea

Parameters:
find – the text to locate in the string
replace – the text to replace the find text with – if the find text exists
caseSensitive – true for case sensitive. false to ignore case

Returns:
Returns TEXT_FOUND if not initially at end of selected match and matching
occurrence is found. Returns TEXT_NOT_FOUND if the text is not matched.
Returns TEXT_REPLACED_NOT_FOUND_NEXT if replacement is successful but there are
no additional matches. Returns TEXT_REPLACED_FOUND_NEXT if reaplacement is
successful and there is at least one additional match.

doReplaceAll

public int doReplaceAll(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

Finds and replaces ALL occurrences of text in a string in a forward search.
All replacements are bundled into one CompoundEdit, so one Undo operation will
undo all of them.

Specified by:
doReplaceAll in interface MARSTextEditingArea

Parameters:
find – the text to locate in the string
replace – the text to replace the find text with – if the find text exists
caseSensitive – true for case sensitive. false to ignore case

Returns:
the number of occurrences that were matched and replaced.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

PopupHelpItem

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class PopupHelpItem

java.lang.Object
mars.venus.editors.jeditsyntax.PopupHelpItem

public class PopupHelpItem
extends java.lang.Object

Handly little class to contain help information for a popupMenu or
tool tip item.

Constructor Summary
PopupHelpItem(java.lang.String tokenText,
java.lang.String example,
java.lang.String description)

          Create popup help item, where match is result of an exact-match search.
PopupHelpItem(java.lang.String tokenText,
java.lang.String example,
java.lang.String description,
boolean exact)

          Create popup help item.

 

Method Summary

 java.lang.String getDescription()

           

 boolean getExact()

          Determines whether match occurred in an exact-match or prefix-match search.

 java.lang.String getExample()

           

 int getExampleLength()

           

 java.lang.String getExamplePaddedToLength(int length)

           

 java.lang.String getTokenText()

          The document text that mached this item

static int maxExampleLength(java.util.ArrayList matches)

           

 void setDescription(java.lang.String description)

           

 void setExample(java.lang.String example)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

PopupHelpItem

public PopupHelpItem(java.lang.String tokenText,
java.lang.String example,
java.lang.String description,
boolean exact)

Create popup help item. This is created as result of either an exact-match or
prefix-match search. Note that prefix-match search includes exact as well as partial matches.

Parameters:
tokenText – The document text that matched
example – An example instruction
description – A textual description of the instruction
exact – True if match occurred as result of exact-match search, false otherwise.

PopupHelpItem

public PopupHelpItem(java.lang.String tokenText,
java.lang.String example,
java.lang.String description)

Create popup help item, where match is result of an exact-match search.

Parameters:
tokenText – The document text that matched
example – An example instruction
description – A textual description of the instruction

Method Detail

getTokenText

public java.lang.String getTokenText()

The document text that mached this item

getExample

public java.lang.String getExample()

getDescription

public java.lang.String getDescription()

getExact

public boolean getExact()

Determines whether match occurred in an exact-match or prefix-match search.
Note this can return false even if the match is exact because prefix-match also
includes exact match results. E.g. prefix match on “lw” will match both “lwl” and “lw”.

Returns:
True if exact-match search, false otherwise.

getExampleLength

public int getExampleLength()

getExamplePaddedToLength

public java.lang.String getExamplePaddedToLength(int length)

setExample

public void setExample(java.lang.String example)

setDescription

public void setDescription(java.lang.String description)

maxExampleLength

public static int maxExampleLength(java.util.ArrayList matches)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DefaultInputHandler

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class DefaultInputHandler

java.lang.Object
java.awt.event.KeyAdapter
mars.venus.editors.jeditsyntax.InputHandler
mars.venus.editors.jeditsyntax.DefaultInputHandler

All Implemented Interfaces:
java.awt.event.KeyListener, java.util.EventListener

public class DefaultInputHandler
extends InputHandler

The default input handler. It maps sequences of keystrokes into actions
and inserts key typed events into the text area.

Author:
Slava Pestov

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.venus.editors.jeditsyntax.InputHandler
InputHandler.backspace, InputHandler.backspace_word, InputHandler.clip_copy, InputHandler.clip_cut, InputHandler.clip_paste, InputHandler.delete, InputHandler.delete_word, InputHandler.document_end, InputHandler.document_home, InputHandler.end, InputHandler.home, InputHandler.insert_break, InputHandler.insert_char, InputHandler.insert_tab, InputHandler.MacroRecorder, InputHandler.next_char, InputHandler.next_line, InputHandler.next_page, InputHandler.next_word, InputHandler.NonRecordable, InputHandler.NonRepeatable, InputHandler.overwrite, InputHandler.prev_char, InputHandler.prev_line, InputHandler.prev_page, InputHandler.prev_word, InputHandler.repeat, InputHandler.select_all, InputHandler.toggle_rect, InputHandler.Wrapper

 

Field Summary

 
Fields inherited from class mars.venus.editors.jeditsyntax.InputHandler
BACKSPACE, BACKSPACE_WORD, CLIP_COPY, CLIP_CUT, CLIP_PASTE, DELETE, DELETE_WORD, DOCUMENT_END, DOCUMENT_HOME, END, grabAction, HOME, INSERT_BREAK, INSERT_CHAR, INSERT_TAB, NEXT_CHAR, NEXT_LINE, NEXT_PAGE, NEXT_WORD, OVERWRITE, PREV_CHAR, PREV_LINE, PREV_PAGE, PREV_WORD, recorder, repeat, REPEAT, repeatCount, SELECT_ALL, SELECT_DOC_END, SELECT_DOC_HOME, SELECT_END, SELECT_HOME, SELECT_NEXT_CHAR, SELECT_NEXT_LINE, SELECT_NEXT_PAGE, SELECT_NEXT_WORD, SELECT_PREV_CHAR, SELECT_PREV_LINE, SELECT_PREV_PAGE, SELECT_PREV_WORD, SMART_HOME_END_PROPERTY, TOGGLE_RECT

 

Constructor Summary
DefaultInputHandler()

          Creates a new input handler with no key bindings defined.

 

Method Summary

 void addDefaultKeyBindings()

          Sets up the default key bindings.

 void addKeyBinding(java.lang.String keyBinding,
java.awt.event.ActionListener action)

          Adds a key binding to this input handler.

 InputHandler copy()

          Returns a copy of this input handler that shares the same
key bindings.

 void keyPressed(java.awt.event.KeyEvent evt)

          Handle a key pressed event.

 void keyTyped(java.awt.event.KeyEvent evt)

          Handle a key typed event.

static javax.swing.KeyStroke parseKeyStroke(java.lang.String keyStroke)

          Converts a string to a keystroke.

 void removeAllKeyBindings()

          Removes all key bindings from this input handler.

 void removeKeyBinding(java.lang.String keyBinding)

          Removes a key binding from this input handler.

 
Methods inherited from class mars.venus.editors.jeditsyntax.InputHandler
executeAction, getAction, getActionName, getActions, getMacroRecorder, getRepeatCount, getTextArea, grabNextKeyStroke, handleGrabAction, isRepeatEnabled, setMacroRecorder, setRepeatCount, setRepeatEnabled

 
Methods inherited from class java.awt.event.KeyAdapter
keyReleased

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

DefaultInputHandler

public DefaultInputHandler()

Creates a new input handler with no key bindings defined.

Method Detail

addDefaultKeyBindings

public void addDefaultKeyBindings()

Sets up the default key bindings.

Specified by:
addDefaultKeyBindings in class InputHandler

addKeyBinding

public void addKeyBinding(java.lang.String keyBinding,
java.awt.event.ActionListener action)

Adds a key binding to this input handler. The key binding is
a list of white space separated key strokes of the form
[modifiers+]key where modifier is C for Control, A for Alt,
or S for Shift, and key is either a character (a-z) or a field
name in the KeyEvent class prefixed with VK_ (e.g., BACK_SPACE)

Specified by:
addKeyBinding in class InputHandler

Parameters:
keyBinding – The key binding
action – The action

removeKeyBinding

public void removeKeyBinding(java.lang.String keyBinding)

Removes a key binding from this input handler. This is not yet
implemented.

Specified by:
removeKeyBinding in class InputHandler

Parameters:
keyBinding – The key binding

removeAllKeyBindings

public void removeAllKeyBindings()

Removes all key bindings from this input handler.

Specified by:
removeAllKeyBindings in class InputHandler

copy

public InputHandler copy()

Returns a copy of this input handler that shares the same
key bindings. Setting key bindings in the copy will also
set them in the original.

Specified by:
copy in class InputHandler

keyPressed

public void keyPressed(java.awt.event.KeyEvent evt)

Handle a key pressed event. This will look up the binding for
the key stroke and execute it.

Specified by:
keyPressed in interface java.awt.event.KeyListener
Overrides:
keyPressed in class java.awt.event.KeyAdapter

keyTyped

public void keyTyped(java.awt.event.KeyEvent evt)

Handle a key typed event. This inserts the key into the text area.

Specified by:
keyTyped in interface java.awt.event.KeyListener
Overrides:
keyTyped in class java.awt.event.KeyAdapter

parseKeyStroke

public static javax.swing.KeyStroke parseKeyStroke(java.lang.String keyStroke)

Converts a string to a keystroke. The string should be of the
form modifiers+shortcut where modifiers
is any combination of A for Alt, C for Control, S for Shift
or M for Meta, and shortcut is either a single character,
or a keycode name from the KeyEvent class, without
the VK_ prefix.

Parameters:
keyStroke – A string description of the key stroke

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

TokenMarker

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax.tokenmarker

Class TokenMarker

java.lang.Object
mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker

Direct Known Subclasses:
MIPSTokenMarker

public abstract class TokenMarker
extends java.lang.Object

A token marker that splits lines of text into tokens. Each token carries
a length field and an indentification tag that can be mapped to a color
for painting that token.

For performance reasons, the linked list of tokens is reused after each
line is tokenized. Therefore, the return value of markTokens
should only be used for immediate painting. Notably, it cannot be
cached.

Author:
Slava Pestov
See Also:
org.syntax.jedit.Token

Nested Class Summary

 class TokenMarker.LineInfo

          Inner class for storing information about tokenized lines.

 

Field Summary

protected  Token firstToken

          The first token in the list.

protected  int lastLine

          The last tokenized line.

protected  Token lastToken

          The last token in the list.

protected  int length

          The number of lines in the model being tokenized.

protected  TokenMarker.LineInfo[] lineInfo

          An array for storing information about lines.

protected  boolean nextLineRequested

          True if the next line should be painted.

 

Constructor Summary

protected TokenMarker()

          Creates a new TokenMarker.

 

Method Summary

protected  void addToken(int length,
byte id)

          Adds a token to the token list.

 void deleteLines(int index,
int lines)

          Informs the token marker that line have been deleted from
the document.

protected  void ensureCapacity(int index)

          Ensures that the lineInfo array can contain the
specified index.

 int getLineCount()

          Returns the number of lines in this token marker.

 java.util.ArrayList getTokenExactMatchHelp(Token token,
java.lang.String tokenText)

          Construct and return any appropriate help information for
the given token.

 java.util.ArrayList getTokenPrefixMatchHelp(java.lang.String line,
Token tokenList,
Token tokenAtOffset,
java.lang.String tokenText)

          Construct and return any appropriate help information for
the given token or “token prefix”.

 void insertLines(int index,
int lines)

          Informs the token marker that lines have been inserted into
the document.

 boolean isNextLineRequested()

          Returns true if the next line should be repainted.

 Token markTokens(javax.swing.text.Segment line,
int lineIndex)

          A wrapper for the lower-level markTokensImpl method
that is called to split a line up into tokens.

protected abstract  byte markTokensImpl(byte token,
javax.swing.text.Segment line,
int lineIndex)

          An abstract method that splits a line up into tokens.

 boolean supportsMultilineTokens()

          Returns if the token marker supports tokens that span multiple
lines.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

firstToken

protected Token firstToken

The first token in the list. This should be used as the return
value from markTokens().

lastToken

protected Token lastToken

The last token in the list. New tokens are added here.
This should be set to null before a new line is to be tokenized.

lineInfo

protected TokenMarker.LineInfo[] lineInfo

An array for storing information about lines. It is enlarged and
shrunk automatically by the insertLines() and
deleteLines() methods.

length

protected int length

The number of lines in the model being tokenized. This can be
less than the length of the lineInfo array.

lastLine

protected int lastLine

The last tokenized line.

nextLineRequested

protected boolean nextLineRequested

True if the next line should be painted.

Constructor Detail

TokenMarker

protected TokenMarker()

Creates a new TokenMarker. This DOES NOT create
a lineInfo array; an initial call to insertLines()
does that.

Method Detail

markTokens

public Token markTokens(javax.swing.text.Segment line,
int lineIndex)

A wrapper for the lower-level markTokensImpl method
that is called to split a line up into tokens.

Parameters:
line – The line
lineIndex – The line number

markTokensImpl

protected abstract byte markTokensImpl(byte token,
javax.swing.text.Segment line,
int lineIndex)

An abstract method that splits a line up into tokens. It
should parse the line, and call addToken() to
add syntax tokens to the token list. Then, it should return
the initial token type for the next line.

For example if the current line contains the start of a
multiline comment that doesn’t end on that line, this method
should return the comment token type so that it continues on
the next line.

Parameters:
token – The initial token type for this line
line – The line to be tokenized
lineIndex – The index of the line in the document, starting at 0

Returns:
The initial token type for the next line

supportsMultilineTokens

public boolean supportsMultilineTokens()

Returns if the token marker supports tokens that span multiple
lines. If this is true, the object using this token marker is
required to pass all lines in the document to the
markTokens() method (in turn).

The default implementation returns true; it should be overridden
to return false on simpler token markers for increased speed.

insertLines

public void insertLines(int index,
int lines)

Informs the token marker that lines have been inserted into
the document. This inserts a gap in the lineInfo
array.

Parameters:
index – The first line number
lines – The number of lines

deleteLines

public void deleteLines(int index,
int lines)

Informs the token marker that line have been deleted from
the document. This removes the lines in question from the
lineInfo array.

Parameters:
index – The first line number
lines – The number of lines

getLineCount

public int getLineCount()

Returns the number of lines in this token marker.

isNextLineRequested

public boolean isNextLineRequested()

Returns true if the next line should be repainted. This
will return true after a line has been tokenized that starts
a multiline token that continues onto the next line.

getTokenExactMatchHelp

public java.util.ArrayList getTokenExactMatchHelp(Token token,
java.lang.String tokenText)

Construct and return any appropriate help information for
the given token. This default definition returns null;
override it in language-specific subclasses.

Parameters:
token – the pertinent Token object
tokenText – the source String that matched to the token

Returns:
ArrayList containing PopupHelpItem objects, one per match.

getTokenPrefixMatchHelp

public java.util.ArrayList getTokenPrefixMatchHelp(java.lang.String line,
Token tokenList,
Token tokenAtOffset,
java.lang.String tokenText)

Construct and return any appropriate help information for
the given token or “token prefix”. Will match instruction prefixes, e.g. “s” matches “sw”.
This default definition returns null;
override it in language-specific subclasses.

Parameters:
line – String containing current line
tokenList – first Token on the current line
token – the pertinent Token object
tokenText – the source String that matched to the token

Returns:
ArrayList containing PopupHelpItem objects, one per match.

ensureCapacity

protected void ensureCapacity(int index)

Ensures that the lineInfo array can contain the
specified index. This enlarges it if necessary. No action is
taken if the array is large enough already.

It should be unnecessary to call this under normal
circumstances; insertLine() should take care of
enlarging the line info array automatically.

Parameters:
index – The array index

addToken

protected void addToken(int length,
byte id)

Adds a token to the token list.

Parameters:
length – The length of the token
id – The id of the token

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MIPSTokenMarker

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax.tokenmarker

Class MIPSTokenMarker

java.lang.Object
mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker
mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

public class MIPSTokenMarker
extends TokenMarker

MIPS token marker.

Author:
Pete Sanderson (2010) and Slava Pestov (1999)

Nested Class Summary

 
Nested classes/interfaces inherited from class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker
TokenMarker.LineInfo

 

Field Summary

 
Fields inherited from class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker
firstToken, lastLine, lastToken, length, lineInfo, nextLineRequested

 

Constructor Summary
MIPSTokenMarker()

           
MIPSTokenMarker(KeywordMap keywords)

           

 

Method Summary

static KeywordMap getKeywords()

          Get KeywordMap containing all MIPS key words.

static java.lang.String[] getMIPSTokenExamples()

           

static java.lang.String[] getMIPSTokenLabels()

           

 java.util.ArrayList getTokenExactMatchHelp(Token token,
java.lang.String tokenText)

          Construct and return any appropriate help information for
the given token.

 java.util.ArrayList getTokenPrefixMatchHelp(java.lang.String line,
Token tokenList,
Token token,
java.lang.String tokenText)

          Construct and return any appropriate help information for
prefix match based on current line’s token list.

 byte markTokensImpl(byte token,
javax.swing.text.Segment line,
int lineIndex)

          An abstract method that splits a line up into tokens.

 
Methods inherited from class mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker
addToken, deleteLines, ensureCapacity, getLineCount, insertLines, isNextLineRequested, markTokens, supportsMultilineTokens

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

MIPSTokenMarker

public MIPSTokenMarker()

MIPSTokenMarker

public MIPSTokenMarker(KeywordMap keywords)

Method Detail

getMIPSTokenLabels

public static java.lang.String[] getMIPSTokenLabels()

getMIPSTokenExamples

public static java.lang.String[] getMIPSTokenExamples()

markTokensImpl

public byte markTokensImpl(byte token,
javax.swing.text.Segment line,
int lineIndex)

Description copied from class: TokenMarker
An abstract method that splits a line up into tokens. It
should parse the line, and call addToken() to
add syntax tokens to the token list. Then, it should return
the initial token type for the next line.

For example if the current line contains the start of a
multiline comment that doesn’t end on that line, this method
should return the comment token type so that it continues on
the next line.

Specified by:
markTokensImpl in class TokenMarker

Parameters:
token – The initial token type for this line
line – The line to be tokenized
lineIndex – The index of the line in the document, starting at 0

Returns:
The initial token type for the next line

getTokenExactMatchHelp

public java.util.ArrayList getTokenExactMatchHelp(Token token,
java.lang.String tokenText)

Construct and return any appropriate help information for
the given token.

Overrides:
getTokenExactMatchHelp in class TokenMarker

Parameters:
token – the pertinent Token object
tokenText – the source String that matched to the token

Returns:
ArrayList of PopupHelpItem objects, one per match.

getTokenPrefixMatchHelp

public java.util.ArrayList getTokenPrefixMatchHelp(java.lang.String line,
Token tokenList,
Token token,
java.lang.String tokenText)

Construct and return any appropriate help information for
prefix match based on current line’s token list.

Overrides:
getTokenPrefixMatchHelp in class TokenMarker

Parameters:
line – String containing current line
tokenList – first Token on current line (head of linked list)
token – the pertinent Token object
tokenText – the source String that matched to the token in previous parameter

Returns:
ArrayList of PopupHelpItem objects, one per match.

getKeywords

public static KeywordMap getKeywords()

Get KeywordMap containing all MIPS key words. This includes all instruction mnemonics,
assembler directives, and register names.

Returns:
KeywordMap where key is the keyword and associated value is the token type (e.g. Token.KEYWORD1).

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax.tokenmarker

mars.venus.editors.jeditsyntax.tokenmarker

Classes 

MIPSTokenMarker

Token

TokenMarker

mars.venus.editors.jeditsyntax.tokenmarker

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.venus.editors.jeditsyntax.tokenmarker

Class Summary
MIPSTokenMarker MIPS token marker.
Token A linked list of tokens.
TokenMarker A token marker that splits lines of text into tokens.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

TokenMarker.LineInfo

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax.tokenmarker

Class TokenMarker.LineInfo

java.lang.Object
mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker.LineInfo

Enclosing class:
TokenMarker

public class TokenMarker.LineInfo
extends java.lang.Object

Inner class for storing information about tokenized lines.

Field Summary

 java.lang.Object obj

          This is for use by the token marker implementations
themselves.

 byte token

          The id of the last token of the line.

 

Constructor Summary
TokenMarker.LineInfo()

          Creates a new LineInfo object with token = Token.NULL
and obj = null.
TokenMarker.LineInfo(byte token,
java.lang.Object obj)

          Creates a new LineInfo object with the specified
parameters.

 

Method Summary

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

token

public byte token

The id of the last token of the line.

obj

public java.lang.Object obj

This is for use by the token marker implementations
themselves. It can be used to store anything that
is an object and that needs to exist on a per-line
basis.

Constructor Detail

TokenMarker.LineInfo

public TokenMarker.LineInfo()

Creates a new LineInfo object with token = Token.NULL
and obj = null.

TokenMarker.LineInfo

public TokenMarker.LineInfo(byte token,
java.lang.Object obj)

Creates a new LineInfo object with the specified
parameters.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax.tokenmarker Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.venus.editors.jeditsyntax.tokenmarker

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object mars.venus.editors.jeditsyntax.tokenmarker.Token
mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker mars.venus.editors.jeditsyntax.tokenmarker.MIPSTokenMarker

mars.venus.editors.jeditsyntax.tokenmarker.TokenMarker.LineInfo

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Token

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax.tokenmarker

Class Token

java.lang.Object
mars.venus.editors.jeditsyntax.tokenmarker.Token

public class Token
extends java.lang.Object

A linked list of tokens. Each token has three fields – a token
identifier, which is a byte value that can be looked up in the
array returned by SyntaxDocument.getColors()
to get a color value, a length value which is the length of the
token in the text, and a pointer to the next token in the list.

Author:
Slava Pestov

Field Summary

static byte COMMENT1

          Comment 1 token id.

static byte COMMENT2

          Comment 2 token id.

static byte END

          The token type, that along with a length of 0
marks the end of the token list.

 byte id

          The id of this token.

static byte ID_COUNT

          The total number of defined token ids.

static byte INTERNAL_FIRST

          The first id that can be used for internal state
in a token marker.

static byte INTERNAL_LAST

          The last id that can be used for internal state
in a token marker.

static byte INVALID

          Invalid token id.

static byte KEYWORD1

          Keyword 1 token id.

static byte KEYWORD2

          Keyword 2 token id.

static byte KEYWORD3

          Keyword 3 token id.

static byte LABEL

          Label token id.

 int length

          The length of this token.

static byte LITERAL1

          Literal 1 token id.

static byte LITERAL2

          Literal 2 token id.

static byte MACRO_ARG

          Macro parameter token.

 Token next

          The next token in the linked list.

static byte NULL

          Normal text token id.

static byte OPERATOR

          Operator token id.

 

Constructor Summary
Token(int length,
byte id)

          Creates a new token.

 

Method Summary

 java.lang.String toString()

          Returns a string representation of this token.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

NULL

public static final byte NULL

Normal text token id. This should be used to mark
normal text.

See Also:
Constant Field Values

COMMENT1

public static final byte COMMENT1

Comment 1 token id. This can be used to mark a comment.

See Also:
Constant Field Values

COMMENT2

public static final byte COMMENT2

Comment 2 token id. This can be used to mark a comment.

See Also:
Constant Field Values

LITERAL1

public static final byte LITERAL1

Literal 1 token id. This can be used to mark a string
literal (eg, C mode uses this to mark “…” literals)

See Also:
Constant Field Values

LITERAL2

public static final byte LITERAL2

Literal 2 token id. This can be used to mark an object
literal (eg, Java mode uses this to mark true, false, etc)

See Also:
Constant Field Values

LABEL

public static final byte LABEL

Label token id. This can be used to mark labels
(eg, C mode uses this to mark …: sequences)

See Also:
Constant Field Values

KEYWORD1

public static final byte KEYWORD1

Keyword 1 token id. This can be used to mark a
keyword. This should be used for general language
constructs.

See Also:
Constant Field Values

KEYWORD2

public static final byte KEYWORD2

Keyword 2 token id. This can be used to mark a
keyword. This should be used for preprocessor
commands, or variables.

See Also:
Constant Field Values

KEYWORD3

public static final byte KEYWORD3

Keyword 3 token id. This can be used to mark a
keyword. This should be used for data types.

See Also:
Constant Field Values

OPERATOR

public static final byte OPERATOR

Operator token id. This can be used to mark an
operator. (eg, SQL mode marks +, -, etc with this
token type)

See Also:
Constant Field Values

INVALID

public static final byte INVALID

Invalid token id. This can be used to mark invalid
or incomplete tokens, so the user can easily spot
syntax errors.

See Also:
Constant Field Values

MACRO_ARG

public static final byte MACRO_ARG

Macro parameter token. Added for MARS 4.3.

See Also:
Constant Field Values

ID_COUNT

public static final byte ID_COUNT

The total number of defined token ids.

See Also:
Constant Field Values

INTERNAL_FIRST

public static final byte INTERNAL_FIRST

The first id that can be used for internal state
in a token marker.

See Also:
Constant Field Values

INTERNAL_LAST

public static final byte INTERNAL_LAST

The last id that can be used for internal state
in a token marker.

See Also:
Constant Field Values

END

public static final byte END

The token type, that along with a length of 0
marks the end of the token list.

See Also:
Constant Field Values

length

public int length

The length of this token.

id

public byte id

The id of this token.

next

public Token next

The next token in the linked list.

Constructor Detail

Token

public Token(int length,
byte id)

Creates a new token.

Parameters:
length – The length of the token
id – The id of the token

Method Detail

toString

public java.lang.String toString()

Returns a string representation of this token.

Overrides:
toString in class java.lang.Object

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.NonRepeatable

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Interface InputHandler.NonRepeatable

All Known Implementing Classes:
InputHandler.insert_char

Enclosing class:
InputHandler

public static interface InputHandler.NonRepeatable

If an action implements this interface, it should not be repeated.
Instead, it will handle the repetition itself.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.next_char

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.next_char

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.next_char

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.next_char
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.next_char(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.next_char

public InputHandler.next_char(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.prev_char

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.prev_char

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.prev_char

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.prev_char
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.prev_char(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.prev_char

public InputHandler.prev_char(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.clip_paste

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.clip_paste

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.clip_paste

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.clip_paste
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.clip_paste()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.clip_paste

public InputHandler.clip_paste()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler

java.lang.Object
java.awt.event.KeyAdapter
mars.venus.editors.jeditsyntax.InputHandler

All Implemented Interfaces:
java.awt.event.KeyListener, java.util.EventListener

Direct Known Subclasses:
DefaultInputHandler

public abstract class InputHandler
extends java.awt.event.KeyAdapter

An input handler converts the user’s key strokes into concrete actions.
It also takes care of macro recording and action repetition.

This class provides all the necessary support code for an input
handler, but doesn’t actually do any key binding logic. It is up
to the implementations of this class to do so.

Author:
Slava Pestov
See Also:
08/12/2002 Clipboard actions (Oliver Henning)

Nested Class Summary

static class InputHandler.backspace

           

static class InputHandler.backspace_word

           

static class InputHandler.clip_copy

           

static class InputHandler.clip_cut

           

static class InputHandler.clip_paste

           

static class InputHandler.delete

           

static class InputHandler.delete_word

           

static class InputHandler.document_end

           

static class InputHandler.document_home

           

static class InputHandler.end

           

static class InputHandler.home

           

static class InputHandler.insert_break

           

static class InputHandler.insert_char

           

static class InputHandler.insert_tab

           

static interface InputHandler.MacroRecorder

          Macro recorder.

static class InputHandler.next_char

           

static class InputHandler.next_line

           

static class InputHandler.next_page

           

static class InputHandler.next_word

           

static interface InputHandler.NonRecordable

          If an action implements this interface, it should not be recorded
by the macro recorder.

static interface InputHandler.NonRepeatable

          If an action implements this interface, it should not be repeated.

static class InputHandler.overwrite

           

static class InputHandler.prev_char

           

static class InputHandler.prev_line

           

static class InputHandler.prev_page

           

static class InputHandler.prev_word

           

static class InputHandler.repeat

           

static class InputHandler.select_all

           

static class InputHandler.toggle_rect

           

static interface InputHandler.Wrapper

          For use by EditAction.Wrapper only.

 

Field Summary

static java.awt.event.ActionListener BACKSPACE

           

static java.awt.event.ActionListener BACKSPACE_WORD

           

static java.awt.event.ActionListener CLIP_COPY

           

static java.awt.event.ActionListener CLIP_CUT

           

static java.awt.event.ActionListener CLIP_PASTE

           

static java.awt.event.ActionListener DELETE

           

static java.awt.event.ActionListener DELETE_WORD

           

static java.awt.event.ActionListener DOCUMENT_END

           

static java.awt.event.ActionListener DOCUMENT_HOME

           

static java.awt.event.ActionListener END

           

protected  java.awt.event.ActionListener grabAction

           

static java.awt.event.ActionListener HOME

           

static java.awt.event.ActionListener INSERT_BREAK

           

static java.awt.event.ActionListener INSERT_CHAR

           

static java.awt.event.ActionListener INSERT_TAB

           

static java.awt.event.ActionListener NEXT_CHAR

           

static java.awt.event.ActionListener NEXT_LINE

           

static java.awt.event.ActionListener NEXT_PAGE

           

static java.awt.event.ActionListener NEXT_WORD

           

static java.awt.event.ActionListener OVERWRITE

           

static java.awt.event.ActionListener PREV_CHAR

           

static java.awt.event.ActionListener PREV_LINE

           

static java.awt.event.ActionListener PREV_PAGE

           

static java.awt.event.ActionListener PREV_WORD

           

protected  InputHandler.MacroRecorder recorder

           

protected  boolean repeat

           

static java.awt.event.ActionListener REPEAT

           

protected  int repeatCount

           

static java.awt.event.ActionListener SELECT_ALL

           

static java.awt.event.ActionListener SELECT_DOC_END

           

static java.awt.event.ActionListener SELECT_DOC_HOME

           

static java.awt.event.ActionListener SELECT_END

           

static java.awt.event.ActionListener SELECT_HOME

           

static java.awt.event.ActionListener SELECT_NEXT_CHAR

           

static java.awt.event.ActionListener SELECT_NEXT_LINE

           

static java.awt.event.ActionListener SELECT_NEXT_PAGE

           

static java.awt.event.ActionListener SELECT_NEXT_WORD

           

static java.awt.event.ActionListener SELECT_PREV_CHAR

           

static java.awt.event.ActionListener SELECT_PREV_LINE

           

static java.awt.event.ActionListener SELECT_PREV_PAGE

           

static java.awt.event.ActionListener SELECT_PREV_WORD

           

static java.lang.String SMART_HOME_END_PROPERTY

          If this client property is set to Boolean.TRUE on the text area,
the home/end keys will support ‘smart’ BRIEF-like behaviour
(one press = start/end of line, two presses = start/end of
viewscreen, three presses = start/end of document).

static java.awt.event.ActionListener TOGGLE_RECT

           

 

Constructor Summary
InputHandler()

           

 

Method Summary

abstract  void addDefaultKeyBindings()

          Adds the default key bindings to this input handler.

abstract  void addKeyBinding(java.lang.String keyBinding,
java.awt.event.ActionListener action)

          Adds a key binding to this input handler.

abstract  InputHandler copy()

          Returns a copy of this input handler that shares the same
key bindings.

 void executeAction(java.awt.event.ActionListener listener,
java.lang.Object source,
java.lang.String actionCommand)

          Executes the specified action, repeating and recording it as
necessary.

static java.awt.event.ActionListener getAction(java.lang.String name)

          Returns a named text area action.

static java.lang.String getActionName(java.awt.event.ActionListener listener)

          Returns the name of the specified text area action.

static java.util.Enumeration getActions()

          Returns an enumeration of all available actions.

 InputHandler.MacroRecorder getMacroRecorder()

          Returns the macro recorder.

 int getRepeatCount()

          Returns the number of times the next action will be repeated.

static JEditTextArea getTextArea(java.util.EventObject evt)

          Returns the text area that fired the specified event.

 void grabNextKeyStroke(java.awt.event.ActionListener listener)

          Grabs the next key typed event and invokes the specified
action with the key as a the action command.

protected  void handleGrabAction(java.awt.event.KeyEvent evt)

          If a key is being grabbed, this method should be called with
the appropriate key event.

 boolean isRepeatEnabled()

          Returns if repeating is enabled.

abstract  void removeAllKeyBindings()

          Removes all key bindings from this input handler.

abstract  void removeKeyBinding(java.lang.String keyBinding)

          Removes a key binding from this input handler.

 void setMacroRecorder(InputHandler.MacroRecorder recorder)

          Sets the macro recorder.

 void setRepeatCount(int repeatCount)

          Sets the number of times the next action will be repeated.

 void setRepeatEnabled(boolean repeat)

          Enables repeating.

 
Methods inherited from class java.awt.event.KeyAdapter
keyPressed, keyReleased, keyTyped

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

SMART_HOME_END_PROPERTY

public static final java.lang.String SMART_HOME_END_PROPERTY

If this client property is set to Boolean.TRUE on the text area,
the home/end keys will support ‘smart’ BRIEF-like behaviour
(one press = start/end of line, two presses = start/end of
viewscreen, three presses = start/end of document). By default,
this property is not set.

See Also:
Constant Field Values

BACKSPACE

public static final java.awt.event.ActionListener BACKSPACE

BACKSPACE_WORD

public static final java.awt.event.ActionListener BACKSPACE_WORD

DELETE

public static final java.awt.event.ActionListener DELETE

DELETE_WORD

public static final java.awt.event.ActionListener DELETE_WORD

END

public static final java.awt.event.ActionListener END

DOCUMENT_END

public static final java.awt.event.ActionListener DOCUMENT_END

SELECT_ALL

public static final java.awt.event.ActionListener SELECT_ALL

SELECT_END

public static final java.awt.event.ActionListener SELECT_END

SELECT_DOC_END

public static final java.awt.event.ActionListener SELECT_DOC_END

INSERT_BREAK

public static final java.awt.event.ActionListener INSERT_BREAK

INSERT_TAB

public static final java.awt.event.ActionListener INSERT_TAB

HOME

public static final java.awt.event.ActionListener HOME

DOCUMENT_HOME

public static final java.awt.event.ActionListener DOCUMENT_HOME

SELECT_HOME

public static final java.awt.event.ActionListener SELECT_HOME

SELECT_DOC_HOME

public static final java.awt.event.ActionListener SELECT_DOC_HOME

NEXT_CHAR

public static final java.awt.event.ActionListener NEXT_CHAR

NEXT_LINE

public static final java.awt.event.ActionListener NEXT_LINE

NEXT_PAGE

public static final java.awt.event.ActionListener NEXT_PAGE

NEXT_WORD

public static final java.awt.event.ActionListener NEXT_WORD

SELECT_NEXT_CHAR

public static final java.awt.event.ActionListener SELECT_NEXT_CHAR

SELECT_NEXT_LINE

public static final java.awt.event.ActionListener SELECT_NEXT_LINE

SELECT_NEXT_PAGE

public static final java.awt.event.ActionListener SELECT_NEXT_PAGE

SELECT_NEXT_WORD

public static final java.awt.event.ActionListener SELECT_NEXT_WORD

OVERWRITE

public static final java.awt.event.ActionListener OVERWRITE

PREV_CHAR

public static final java.awt.event.ActionListener PREV_CHAR

PREV_LINE

public static final java.awt.event.ActionListener PREV_LINE

PREV_PAGE

public static final java.awt.event.ActionListener PREV_PAGE

PREV_WORD

public static final java.awt.event.ActionListener PREV_WORD

SELECT_PREV_CHAR

public static final java.awt.event.ActionListener SELECT_PREV_CHAR

SELECT_PREV_LINE

public static final java.awt.event.ActionListener SELECT_PREV_LINE

SELECT_PREV_PAGE

public static final java.awt.event.ActionListener SELECT_PREV_PAGE

SELECT_PREV_WORD

public static final java.awt.event.ActionListener SELECT_PREV_WORD

REPEAT

public static final java.awt.event.ActionListener REPEAT

TOGGLE_RECT

public static final java.awt.event.ActionListener TOGGLE_RECT

CLIP_COPY

public static final java.awt.event.ActionListener CLIP_COPY

CLIP_PASTE

public static final java.awt.event.ActionListener CLIP_PASTE

CLIP_CUT

public static final java.awt.event.ActionListener CLIP_CUT

INSERT_CHAR

public static final java.awt.event.ActionListener INSERT_CHAR

grabAction

protected java.awt.event.ActionListener grabAction

repeat

protected boolean repeat

repeatCount

protected int repeatCount

recorder

protected InputHandler.MacroRecorder recorder

Constructor Detail

InputHandler

public InputHandler()

Method Detail

getAction

public static java.awt.event.ActionListener getAction(java.lang.String name)

Returns a named text area action.

Parameters:
name – The action name

getActionName

public static java.lang.String getActionName(java.awt.event.ActionListener listener)

Returns the name of the specified text area action.

Parameters:
listener – The action

getActions

public static java.util.Enumeration getActions()

Returns an enumeration of all available actions.

addDefaultKeyBindings

public abstract void addDefaultKeyBindings()

Adds the default key bindings to this input handler.
This should not be called in the constructor of this
input handler, because applications might load the
key bindings from a file, etc.

addKeyBinding

public abstract void addKeyBinding(java.lang.String keyBinding,
java.awt.event.ActionListener action)

Adds a key binding to this input handler.

Parameters:
keyBinding – The key binding (the format of this is
input-handler specific)
action – The action

removeKeyBinding

public abstract void removeKeyBinding(java.lang.String keyBinding)

Removes a key binding from this input handler.

Parameters:
keyBinding – The key binding

removeAllKeyBindings

public abstract void removeAllKeyBindings()

Removes all key bindings from this input handler.

grabNextKeyStroke

public void grabNextKeyStroke(java.awt.event.ActionListener listener)

Grabs the next key typed event and invokes the specified
action with the key as a the action command.

Parameters:
action – The action

isRepeatEnabled

public boolean isRepeatEnabled()

Returns if repeating is enabled. When repeating is enabled,
actions will be executed multiple times. This is usually
invoked with a special key stroke in the input handler.

setRepeatEnabled

public void setRepeatEnabled(boolean repeat)

Enables repeating. When repeating is enabled, actions will be
executed multiple times. Once repeating is enabled, the input
handler should read a number from the keyboard.

getRepeatCount

public int getRepeatCount()

Returns the number of times the next action will be repeated.

setRepeatCount

public void setRepeatCount(int repeatCount)

Sets the number of times the next action will be repeated.

Parameters:
repeatCount – The repeat count

getMacroRecorder

public InputHandler.MacroRecorder getMacroRecorder()

Returns the macro recorder. If this is non-null, all executed
actions should be forwarded to the recorder.

setMacroRecorder

public void setMacroRecorder(InputHandler.MacroRecorder recorder)

Sets the macro recorder. If this is non-null, all executed
actions should be forwarded to the recorder.

Parameters:
recorder – The macro recorder

copy

public abstract InputHandler copy()

Returns a copy of this input handler that shares the same
key bindings. Setting key bindings in the copy will also
set them in the original.

executeAction

public void executeAction(java.awt.event.ActionListener listener,
java.lang.Object source,
java.lang.String actionCommand)

Executes the specified action, repeating and recording it as
necessary.

Parameters:
listener – The action listener
source – The event source
actionCommand – The action command

getTextArea

public static JEditTextArea getTextArea(java.util.EventObject evt)

Returns the text area that fired the specified event.

Parameters:
evt – The event

handleGrabAction

protected void handleGrabAction(java.awt.event.KeyEvent evt)

If a key is being grabbed, this method should be called with
the appropriate key event. It executes the grab action with
the typed character as the parameter.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.clip_copy

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.clip_copy

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.clip_copy

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.clip_copy
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.clip_copy()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.clip_copy

public InputHandler.clip_copy()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

TextAreaDefaults

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class TextAreaDefaults

java.lang.Object
mars.venus.editors.jeditsyntax.TextAreaDefaults

public class TextAreaDefaults
extends java.lang.Object

Encapsulates default settings for a text area. This can be passed
to the constructor once the necessary fields have been filled out.
The advantage of doing this over calling lots of set() methods after
creating the text area is that this method is faster.

Field Summary

 boolean blockCaret

           

 boolean bracketHighlight

           

 java.awt.Color bracketHighlightColor

           

 int caretBlinkRate

           

 boolean caretBlinks

           

 java.awt.Color caretColor

           

 boolean caretVisible

           

 int cols

           

 SyntaxDocument document

           

 boolean editable

           

 int electricScroll

           

 java.awt.Color eolMarkerColor

           

 boolean eolMarkers

           

 InputHandler inputHandler

           

 boolean lineHighlight

           

 java.awt.Color lineHighlightColor

           

 boolean paintInvalid

           

 javax.swing.JPopupMenu popup

           

 int rows

           

 java.awt.Color selectionColor

           

 SyntaxStyle[] styles

           

 int tabSize

           

 

Constructor Summary
TextAreaDefaults()

           

 

Method Summary

static TextAreaDefaults getDefaults()

          Returns a new TextAreaDefaults object with the default values filled
in.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

inputHandler

public InputHandler inputHandler

document

public SyntaxDocument document

editable

public boolean editable

caretVisible

public boolean caretVisible

caretBlinks

public boolean caretBlinks

blockCaret

public boolean blockCaret

caretBlinkRate

public int caretBlinkRate

electricScroll

public int electricScroll

tabSize

public int tabSize

cols

public int cols

rows

public int rows

styles

public SyntaxStyle[] styles

caretColor

public java.awt.Color caretColor

selectionColor

public java.awt.Color selectionColor

lineHighlightColor

public java.awt.Color lineHighlightColor

lineHighlight

public boolean lineHighlight

bracketHighlightColor

public java.awt.Color bracketHighlightColor

bracketHighlight

public boolean bracketHighlight

eolMarkerColor

public java.awt.Color eolMarkerColor

eolMarkers

public boolean eolMarkers

paintInvalid

public boolean paintInvalid

popup

public javax.swing.JPopupMenu popup

Constructor Detail

TextAreaDefaults

public TextAreaDefaults()

Method Detail

getDefaults

public static TextAreaDefaults getDefaults()

Returns a new TextAreaDefaults object with the default values filled
in.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

mars.venus.editors.jeditsyntax

Interfaces 

InputHandler.MacroRecorder

InputHandler.NonRecordable

InputHandler.NonRepeatable

InputHandler.Wrapper

TextAreaPainter.Highlight

Classes 

DefaultInputHandler

InputHandler

InputHandler.backspace

InputHandler.backspace_word

InputHandler.clip_copy

InputHandler.clip_cut

InputHandler.clip_paste

InputHandler.delete

InputHandler.delete_word

InputHandler.document_end

InputHandler.document_home

InputHandler.end

InputHandler.home

InputHandler.insert_break

InputHandler.insert_char

InputHandler.insert_tab

InputHandler.next_char

InputHandler.next_line

InputHandler.next_page

InputHandler.next_word

InputHandler.overwrite

InputHandler.prev_char

InputHandler.prev_line

InputHandler.prev_page

InputHandler.prev_word

InputHandler.repeat

InputHandler.select_all

InputHandler.toggle_rect

JEditBasedTextArea

JEditTextArea

KeywordMap

PopupHelpItem

SyntaxDocument

SyntaxStyle

SyntaxUtilities

TextAreaDefaults

TextAreaPainter

TextUtilities

SyntaxStyle

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class SyntaxStyle

java.lang.Object
mars.venus.editors.jeditsyntax.SyntaxStyle

public class SyntaxStyle
extends java.lang.Object

A simple text style class. It can specify the color, italic flag,
and bold flag of a run of text.

Author:
Slava Pestov

Constructor Summary
SyntaxStyle(java.awt.Color color,
boolean italic,
boolean bold)

          Creates a new SyntaxStyle.

 

Method Summary

 java.awt.Color getColor()

          Returns the color specified in this style.

 java.lang.String getColorAsHexString()

          Returns the color coded as Stringified 32-bit hex with
Red in bits 16-23, Green in bits 8-15, Blue in bits 0-7
e.g.

 java.awt.FontMetrics getFontMetrics(java.awt.Font font)

          Returns the font metrics for the styled font.

 java.awt.Font getStyledFont(java.awt.Font font)

          Returns the specified font, but with the style’s bold and
italic flags applied.

 boolean isBold()

          Returns true if boldface is enabled for this style.

 boolean isItalic()

          Returns true if italics is enabled for this style.

 boolean isPlain()

          Returns true if no font styles are enabled.

 void setGraphicsFlags(java.awt.Graphics gfx,
java.awt.Font font)

          Sets the foreground color and font of the specified graphics
context to that specified in this style.

 java.lang.String toString()

          Returns a string representation of this object.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

SyntaxStyle

public SyntaxStyle(java.awt.Color color,
boolean italic,
boolean bold)

Creates a new SyntaxStyle.

Parameters:
color – The text color
italic – True if the text should be italics
bold – True if the text should be bold

Method Detail

getColor

public java.awt.Color getColor()

Returns the color specified in this style.

getColorAsHexString

public java.lang.String getColorAsHexString()

Returns the color coded as Stringified 32-bit hex with
Red in bits 16-23, Green in bits 8-15, Blue in bits 0-7
e.g. “0x00FF3366” where Red is FF, Green is 33, Blue is 66.
This is used by Settings initialization to avoid direct
use of Color class. Long story. DPS 13-May-2010

Returns:
String containing hex-coded color value.

isPlain

public boolean isPlain()

Returns true if no font styles are enabled.

isItalic

public boolean isItalic()

Returns true if italics is enabled for this style.

isBold

public boolean isBold()

Returns true if boldface is enabled for this style.

getStyledFont

public java.awt.Font getStyledFont(java.awt.Font font)

Returns the specified font, but with the style’s bold and
italic flags applied.

getFontMetrics

public java.awt.FontMetrics getFontMetrics(java.awt.Font font)

Returns the font metrics for the styled font.

setGraphicsFlags

public void setGraphicsFlags(java.awt.Graphics gfx,
java.awt.Font font)

Sets the foreground color and font of the specified graphics
context to that specified in this style.

Parameters:
gfx – The graphics context
font – The font to add the styles to

toString

public java.lang.String toString()

Returns a string representation of this object.

Overrides:
toString in class java.lang.Object

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.insert_break

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.insert_break

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.insert_break

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.insert_break
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.insert_break()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.insert_break

public InputHandler.insert_break()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.venus.editors.jeditsyntax

Interface Summary
InputHandler.MacroRecorder Macro recorder.
InputHandler.NonRecordable If an action implements this interface, it should not be recorded
by the macro recorder.
InputHandler.NonRepeatable If an action implements this interface, it should not be repeated.
InputHandler.Wrapper For use by EditAction.Wrapper only.
TextAreaPainter.Highlight Highlight interface.

 

Class Summary
DefaultInputHandler The default input handler.
InputHandler An input handler converts the user’s key strokes into concrete actions.
InputHandler.backspace  
InputHandler.backspace_word  
InputHandler.clip_copy  
InputHandler.clip_cut  
InputHandler.clip_paste  
InputHandler.delete  
InputHandler.delete_word  
InputHandler.document_end  
InputHandler.document_home  
InputHandler.end  
InputHandler.home  
InputHandler.insert_break  
InputHandler.insert_char  
InputHandler.insert_tab  
InputHandler.next_char  
InputHandler.next_line  
InputHandler.next_page  
InputHandler.next_word  
InputHandler.overwrite  
InputHandler.prev_char  
InputHandler.prev_line  
InputHandler.prev_page  
InputHandler.prev_word  
InputHandler.repeat  
InputHandler.select_all  
InputHandler.toggle_rect  
JEditBasedTextArea Adaptor subclass for JEditTextArea

Provides those methods required by the MARSTextEditingArea interface
that are not defined by JEditTextArea.
JEditTextArea jEdit’s text area component.
KeywordMap A KeywordMap is similar to a hashtable in that it maps keys
to values.
PopupHelpItem Handly little class to contain help information for a popupMenu or
tool tip item.
SyntaxDocument A document implementation that can be tokenized by the syntax highlighting
system.
SyntaxStyle A simple text style class.
SyntaxUtilities Class with several utility functions used by jEdit’s syntax colorizing
subsystem.
TextAreaDefaults Encapsulates default settings for a text area.
TextAreaPainter The text area repaint manager.
TextUtilities Class with several utility functions used by the text area component.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

InputHandler.select_all

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.select_all

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.select_all

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.select_all
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.select_all()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.select_all

public InputHandler.select_all()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.delete_word

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.delete_word

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.delete_word

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.delete_word
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.delete_word()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.delete_word

public InputHandler.delete_word()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

TextUtilities

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class TextUtilities

java.lang.Object
mars.venus.editors.jeditsyntax.TextUtilities

public class TextUtilities
extends java.lang.Object

Class with several utility functions used by the text area component.

Author:
Slava Pestov

Constructor Summary
TextUtilities()

           

 

Method Summary

static int findMatchingBracket(javax.swing.text.Document doc,
int offset)

          Returns the offset of the bracket matching the one at the
specified offset of the document, or -1 if the bracket is
unmatched (or if the character is not a bracket).

static int findWordEnd(java.lang.String line,
int pos,
java.lang.String noWordSep)

          Locates the end of the word at the specified position.

static int findWordStart(java.lang.String line,
int pos,
java.lang.String noWordSep)

          Locates the start of the word at the specified position.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

TextUtilities

public TextUtilities()

Method Detail

findMatchingBracket

public static int findMatchingBracket(javax.swing.text.Document doc,
int offset)
throws javax.swing.text.BadLocationException

Returns the offset of the bracket matching the one at the
specified offset of the document, or -1 if the bracket is
unmatched (or if the character is not a bracket).

Parameters:
doc – The document
offset – The offset

Throws:

javax.swing.text.BadLocationException – If an out-of-bounds access
was attempted on the document text

findWordStart

public static int findWordStart(java.lang.String line,
int pos,
java.lang.String noWordSep)

Locates the start of the word at the specified position.

Parameters:
line – The text
pos – The position

findWordEnd

public static int findWordEnd(java.lang.String line,
int pos,
java.lang.String noWordSep)

Locates the end of the word at the specified position.

Parameters:
line – The text
pos – The position

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.next_word

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.next_word

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.next_word

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.next_word
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.next_word(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.next_word

public InputHandler.next_word(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.venus.editors.jeditsyntax

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object javax.swing.text.AbstractDocument (implements javax.swing.text.Document, java.io.Serializable)
javax.swing.text.PlainDocument mars.venus.editors.jeditsyntax.SyntaxDocument

java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
java.awt.Container javax.swing.JComponent (implements java.io.Serializable)
mars.venus.editors.jeditsyntax.JEditTextArea mars.venus.editors.jeditsyntax.JEditBasedTextArea (implements javax.swing.event.CaretListener, mars.venus.editors.MARSTextEditingArea)

mars.venus.editors.jeditsyntax.TextAreaPainter (implements javax.swing.text.TabExpander)

mars.venus.editors.jeditsyntax.InputHandler.backspace (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.backspace_word (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.clip_copy (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.clip_cut (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.clip_paste (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.delete (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.delete_word (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.document_end (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.document_home (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.end (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.home (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.insert_break (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.insert_char (implements java.awt.event.ActionListener, mars.venus.editors.jeditsyntax.InputHandler.NonRepeatable)

mars.venus.editors.jeditsyntax.InputHandler.insert_tab (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.next_char (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.next_line (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.next_page (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.next_word (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.overwrite (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.prev_char (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.prev_line (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.prev_page (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.prev_word (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.repeat (implements java.awt.event.ActionListener, mars.venus.editors.jeditsyntax.InputHandler.NonRecordable)

mars.venus.editors.jeditsyntax.InputHandler.select_all (implements java.awt.event.ActionListener)

mars.venus.editors.jeditsyntax.InputHandler.toggle_rect (implements java.awt.event.ActionListener)

java.awt.event.KeyAdapter (implements java.awt.event.KeyListener)
mars.venus.editors.jeditsyntax.InputHandler mars.venus.editors.jeditsyntax.DefaultInputHandler

mars.venus.editors.jeditsyntax.KeywordMap
mars.venus.editors.jeditsyntax.PopupHelpItem
mars.venus.editors.jeditsyntax.SyntaxStyle
mars.venus.editors.jeditsyntax.SyntaxUtilities
mars.venus.editors.jeditsyntax.TextAreaDefaults
mars.venus.editors.jeditsyntax.TextUtilities

Interface Hierarchy

mars.venus.editors.jeditsyntax.InputHandler.MacroRecorder
mars.venus.editors.jeditsyntax.InputHandler.NonRecordable
mars.venus.editors.jeditsyntax.InputHandler.NonRepeatable
mars.venus.editors.jeditsyntax.InputHandler.Wrapper
mars.venus.editors.jeditsyntax.TextAreaPainter.Highlight

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

SyntaxUtilities

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class SyntaxUtilities

java.lang.Object
mars.venus.editors.jeditsyntax.SyntaxUtilities

public class SyntaxUtilities
extends java.lang.Object

Class with several utility functions used by jEdit’s syntax colorizing
subsystem.

Author:
Slava Pestov

Field Summary

static javax.swing.Popup popup

           

static boolean popupShowing

          Paints the specified line onto the graphics context.

 

Method Summary

static SyntaxStyle[] getCurrentSyntaxStyles()

          Returns the CURRENT style table.

static SyntaxStyle[] getDefaultSyntaxStyles()

          Returns the default style table.

static int paintSyntaxLine(javax.swing.text.Segment line,
Token tokens,
SyntaxStyle[] styles,
javax.swing.text.TabExpander expander,
java.awt.Graphics gfx,
int x,
int y)

           

static boolean regionMatches(boolean ignoreCase,
javax.swing.text.Segment text,
int offset,
char[] match)

          Checks if a subregion of a Segment is equal to a
character array.

static boolean regionMatches(boolean ignoreCase,
javax.swing.text.Segment text,
int offset,
java.lang.String match)

          Checks if a subregion of a Segment is equal to a
string.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

popupShowing

public static boolean popupShowing

Paints the specified line onto the graphics context. Note that this
method munges the offset and count values of the segment.

popup

public static javax.swing.Popup popup

Method Detail

regionMatches

public static boolean regionMatches(boolean ignoreCase,
javax.swing.text.Segment text,
int offset,
java.lang.String match)

Checks if a subregion of a Segment is equal to a
string.

Parameters:
ignoreCase – True if case should be ignored, false otherwise
text – The segment
offset – The offset into the segment
match – The string to match

regionMatches

public static boolean regionMatches(boolean ignoreCase,
javax.swing.text.Segment text,
int offset,
char[] match)

Checks if a subregion of a Segment is equal to a
character array.

Parameters:
ignoreCase – True if case should be ignored, false otherwise
text – The segment
offset – The offset into the segment
match – The character array to match

getDefaultSyntaxStyles

public static SyntaxStyle[] getDefaultSyntaxStyles()

Returns the default style table. This can be passed to the
setStyles() method of SyntaxDocument
to use the default syntax styles.

getCurrentSyntaxStyles

public static SyntaxStyle[] getCurrentSyntaxStyles()

Returns the CURRENT style table. This can be passed to the
setStyles() method of SyntaxDocument
to use the current syntax styles. If changes have been made
via MARS Settings menu, the current settings will not be the
same as the default settings.

paintSyntaxLine

public static int paintSyntaxLine(javax.swing.text.Segment line,
Token tokens,
SyntaxStyle[] styles,
javax.swing.text.TabExpander expander,
java.awt.Graphics gfx,
int x,
int y)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.Wrapper

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Interface InputHandler.Wrapper

Enclosing class:
InputHandler

public static interface InputHandler.Wrapper

For use by EditAction.Wrapper only.

Since:
jEdit 2.2final

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.next_page

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.next_page

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.next_page

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.next_page
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.next_page(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.next_page

public InputHandler.next_page(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.prev_line

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.prev_line

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.prev_line

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.prev_line
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.prev_line(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.prev_line

public InputHandler.prev_line(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.MacroRecorder

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Interface InputHandler.MacroRecorder

Enclosing class:
InputHandler

public static interface InputHandler.MacroRecorder

Macro recorder.

Method Summary

 void actionPerformed(java.awt.event.ActionListener listener,
java.lang.String actionCommand)

           

 

Method Detail

actionPerformed

void actionPerformed(java.awt.event.ActionListener listener,
java.lang.String actionCommand)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.document_home

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.document_home

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.document_home

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.document_home
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.document_home(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.document_home

public InputHandler.document_home(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.delete

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.delete

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.delete

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.delete
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.delete()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.delete

public InputHandler.delete()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.home

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.home

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.home

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.home
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.home(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.home

public InputHandler.home(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.insert_char

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.insert_char

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.insert_char

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener, InputHandler.NonRepeatable

Enclosing class:
InputHandler

public static class InputHandler.insert_char
extends java.lang.Object
implements java.awt.event.ActionListener, InputHandler.NonRepeatable

Constructor Summary
InputHandler.insert_char()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.insert_char

public InputHandler.insert_char()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.clip_cut

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.clip_cut

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.clip_cut

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.clip_cut
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.clip_cut()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.clip_cut

public InputHandler.clip_cut()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.NonRecordable

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Interface InputHandler.NonRecordable

All Known Implementing Classes:
InputHandler.repeat

Enclosing class:
InputHandler

public static interface InputHandler.NonRecordable

If an action implements this interface, it should not be recorded
by the macro recorder. Instead, it will do its own recording.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.toggle_rect

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.toggle_rect

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.toggle_rect

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.toggle_rect
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.toggle_rect()

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.toggle_rect

public InputHandler.toggle_rect()

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InputHandler.document_end

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.jeditsyntax

Class InputHandler.document_end

java.lang.Object
mars.venus.editors.jeditsyntax.InputHandler.document_end

All Implemented Interfaces:
java.awt.event.ActionListener, java.util.EventListener

Enclosing class:
InputHandler

public static class InputHandler.document_end
extends java.lang.Object
implements java.awt.event.ActionListener

Constructor Summary
InputHandler.document_end(boolean select)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent evt)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InputHandler.document_end

public InputHandler.document_end(boolean select)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent evt)

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.venus.editors

Interface Summary
MARSTextEditingArea Specifies capabilities that any test editor used in MARS must have.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

mars.venus.editors.generic

mars.venus.editors.generic

Classes 

GenericTextArea

mars.venus.editors.generic

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.venus.editors.generic

Class Summary
GenericTextArea  

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

mars.venus.editors.generic Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.venus.editors.generic

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
java.awt.Container javax.swing.JComponent (implements java.io.Serializable)
javax.swing.text.JTextComponent (implements javax.accessibility.Accessible, javax.swing.Scrollable)
javax.swing.JTextArea mars.venus.editors.generic.GenericTextArea (implements mars.venus.editors.MARSTextEditingArea)

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

GenericTextArea

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors.generic

Class GenericTextArea

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.text.JTextComponent
javax.swing.JTextArea
mars.venus.editors.generic.GenericTextArea

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.Scrollable, MARSTextEditingArea

public class GenericTextArea
extends javax.swing.JTextArea
implements MARSTextEditingArea

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JTextArea
javax.swing.JTextArea.AccessibleJTextArea

 

Nested classes/interfaces inherited from class javax.swing.text.JTextComponent
javax.swing.text.JTextComponent.AccessibleJTextComponent, javax.swing.text.JTextComponent.DropLocation, javax.swing.text.JTextComponent.KeyBinding

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.text.JTextComponent
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface mars.venus.editors.MARSTextEditingArea
TEXT_FOUND, TEXT_NOT_FOUND, TEXT_REPLACED_FOUND_NEXT, TEXT_REPLACED_NOT_FOUND_NEXT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
GenericTextArea(EditPane editPain,
javax.swing.JComponent lineNumbers)

           

 

Method Summary

 void discardAllUndoableEdits()

          Tell UndoManager to discard all its collected undoable edits.

 int doFindText(java.lang.String find,
boolean caseSensitive)

          Finds next occurrence of text in a forward search of a string.

 int doReplace(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

          Finds and replaces next occurrence of text in a string in a forward search.

 int doReplaceAll(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

          Finds and replaces ALL occurrences of text in a string in a forward search.

 java.awt.Component getOuterComponent()

           

 javax.swing.undo.UndoManager getUndoManager()

          Returns the undo manager for this editing area

 int nextIndex(java.lang.String input,
java.lang.String find,
int start,
boolean caseSensitive)

          Returns next posn of word in text – forward search.

 void redo()

          Redo previous edit

 void setCaretBlinkRate(int rate)

          Set the caret blinking rate in milliseconds.

 void setCaretVisible(boolean vis)

          Control caret visibility

 void setLineHighlightEnabled(boolean highlight)

          Does nothing, but required by the interface.

 void setSelectionVisible(boolean vis)

          Control selection visibility

 void setSourceCode(java.lang.String s,
boolean editable)

          For initalizing the source code when opening an ASM file

 void setText(java.lang.String s)

          Override inherited setText to temporarily remove UndoableEditListener because this
operation is not undoable.

 void undo()

          Undo previous edit

 void updateSyntaxStyles()

          Does nothing, but required by the interface.

 
Methods inherited from class javax.swing.JTextArea
append, createDefaultModel, getAccessibleContext, getColumns, getColumnWidth, getLineCount, getLineEndOffset, getLineOfOffset, getLineStartOffset, getLineWrap, getPreferredScrollableViewportSize, getPreferredSize, getRowHeight, getRows, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getTabSize, getUIClassID, getWrapStyleWord, insert, paramString, replaceRange, setColumns, setFont, setLineWrap, setRows, setTabSize, setWrapStyleWord

 
Methods inherited from class javax.swing.text.JTextComponent
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getActions, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getDropLocation, getDropMode, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPrintable, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, moveCaretPosition, paste, print, print, print, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, replaceSelection, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDocument, setDragEnabled, setDropMode, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setUI, updateUI, viewToModel, write

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface mars.venus.editors.MARSTextEditingArea
copy, cut, getCaretPosition, getDocument, getFont, getFontMetrics, getSelectedText, getSelectionEnd, getSelectionStart, getText, grabFocus, paste, replaceSelection, requestFocusInWindow, revalidate, select, selectAll, setBackground, setCaretPosition, setEditable, setEnabled, setFont, setSelectionEnd, setSelectionStart, setTabSize

 

Constructor Detail

GenericTextArea

public GenericTextArea(EditPane editPain,
javax.swing.JComponent lineNumbers)

Method Detail

setLineHighlightEnabled

public void setLineHighlightEnabled(boolean highlight)

Does nothing, but required by the interface. This editor does not support
highlighting of the line currently being edited.

Specified by:
setLineHighlightEnabled in interface MARSTextEditingArea

updateSyntaxStyles

public void updateSyntaxStyles()

Does nothing, but required by the interface. This editor does not support
syntax styling (colors, bold/italic).

Specified by:
updateSyntaxStyles in interface MARSTextEditingArea

setCaretBlinkRate

public void setCaretBlinkRate(int rate)

Set the caret blinking rate in milliseconds. If rate is 0
it will not blink. If negative, do nothing.

Specified by:
setCaretBlinkRate in interface MARSTextEditingArea

Parameters:
rate – blinking rate in milliseconds

getOuterComponent

public java.awt.Component getOuterComponent()

Specified by:
getOuterComponent in interface MARSTextEditingArea

setSourceCode

public void setSourceCode(java.lang.String s,
boolean editable)

For initalizing the source code when opening an ASM file

Specified by:
setSourceCode in interface MARSTextEditingArea

Parameters:
s – String containing text
editable – set true if code is editable else false

discardAllUndoableEdits

public void discardAllUndoableEdits()

Tell UndoManager to discard all its collected undoable edits.

Specified by:
discardAllUndoableEdits in interface MARSTextEditingArea

setText

public void setText(java.lang.String s)

Override inherited setText to temporarily remove UndoableEditListener because this
operation is not undoable.

Specified by:
setText in interface MARSTextEditingArea
Overrides:
setText in class javax.swing.text.JTextComponent

Parameters:
s – String with new contents for the editing area. Replaces current content.

setCaretVisible

public void setCaretVisible(boolean vis)

Control caret visibility

Specified by:
setCaretVisible in interface MARSTextEditingArea

Parameters:
vis – true to display caret, false to hide it

setSelectionVisible

public void setSelectionVisible(boolean vis)

Control selection visibility

Specified by:
setSelectionVisible in interface MARSTextEditingArea

Parameters:
vis – true to display selection, false to hide it

getUndoManager

public javax.swing.undo.UndoManager getUndoManager()

Returns the undo manager for this editing area

Specified by:
getUndoManager in interface MARSTextEditingArea

Returns:
the undo manager

undo

public void undo()

Undo previous edit

Specified by:
undo in interface MARSTextEditingArea

redo

public void redo()

Redo previous edit

Specified by:
redo in interface MARSTextEditingArea

doFindText

public int doFindText(java.lang.String find,
boolean caseSensitive)

Finds next occurrence of text in a forward search of a string. Search begins
at the current cursor location, and wraps around when the end of the string
is reached.

Specified by:
doFindText in interface MARSTextEditingArea

Parameters:
find – the text to locate in the string
caseSensitive – true if search is to be case-sensitive, false otherwise

Returns:
TEXT_FOUND or TEXT_NOT_FOUND, depending on the result.

nextIndex

public int nextIndex(java.lang.String input,
java.lang.String find,
int start,
boolean caseSensitive)

Returns next posn of word in text – forward search. If end of string is
reached during the search, will wrap around to the beginning one time.

Parameters:
input – the string to search
find – the string to find
start – the character position to start the search
caseSensitive – true for case sensitive. false to ignore case

Returns:
next indexed position of found text or -1 if not found

doReplace

public int doReplace(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

Finds and replaces next occurrence of text in a string in a forward search.
If cursor is initially at end
of matching selection, will immediately replace then find and select the
next occurrence if any. Otherwise it performs a find operation. The replace
can be undone with one undo operation.

Specified by:
doReplace in interface MARSTextEditingArea

Parameters:
find – the text to locate in the string
replace – the text to replace the find text with – if the find text exists
caseSensitive – true for case sensitive. false to ignore case

Returns:
Returns TEXT_FOUND if not initially at end of selected match and matching
occurrence is found. Returns TEXT_NOT_FOUND if the text is not matched.
Returns TEXT_REPLACED_NOT_FOUND_NEXT if replacement is successful but there are
no additional matches. Returns TEXT_REPLACED_FOUND_NEXT if reaplacement is
successful and there is at least one additional match.

doReplaceAll

public int doReplaceAll(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

Finds and replaces ALL occurrences of text in a string in a forward search.
All replacements are bundled into one CompoundEdit, so one Undo operation will
undo all of them.

Specified by:
doReplaceAll in interface MARSTextEditingArea

Parameters:
find – the text to locate in the string
replace – the text to replace the find text with – if the find text exists
caseSensitive – true for case sensitive. false to ignore case

Returns:
the number of occurrences that were matched and replaced.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.venus.editors

Package Hierarchies:
All Packages

Interface Hierarchy

mars.venus.editors.MARSTextEditingArea

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

MARSTextEditingArea

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus.editors

Interface MARSTextEditingArea

All Known Implementing Classes:
GenericTextArea, JEditBasedTextArea

public interface MARSTextEditingArea

Specifies capabilities that any test editor used in MARS must have.

Field Summary

static int TEXT_FOUND

           

static int TEXT_NOT_FOUND

           

static int TEXT_REPLACED_FOUND_NEXT

           

static int TEXT_REPLACED_NOT_FOUND_NEXT

           

 

Method Summary

 void copy()

           

 void cut()

           

 void discardAllUndoableEdits()

           

 int doFindText(java.lang.String find,
boolean caseSensitive)

           

 int doReplace(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

           

 int doReplaceAll(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

           

 int getCaretPosition()

           

 javax.swing.text.Document getDocument()

           

 java.awt.Font getFont()

           

 java.awt.FontMetrics getFontMetrics(java.awt.Font f)

           

 java.awt.Component getOuterComponent()

           

 java.lang.String getSelectedText()

           

 int getSelectionEnd()

           

 int getSelectionStart()

           

 java.lang.String getText()

           

 javax.swing.undo.UndoManager getUndoManager()

           

 void grabFocus()

           

 void paste()

           

 void redo()

           

 void replaceSelection(java.lang.String str)

           

 boolean requestFocusInWindow()

           

 void revalidate()

           

 void select(int selectionStart,
int selectionEnd)

           

 void selectAll()

           

 void setBackground(java.awt.Color c)

           

 void setCaretBlinkRate(int rate)

           

 void setCaretPosition(int position)

           

 void setCaretVisible(boolean vis)

           

 void setEditable(boolean editable)

           

 void setEnabled(boolean enabled)

           

 void setFont(java.awt.Font f)

           

 void setLineHighlightEnabled(boolean highlight)

           

 void setSelectionEnd(int pos)

           

 void setSelectionStart(int pos)

           

 void setSelectionVisible(boolean vis)

           

 void setSourceCode(java.lang.String code,
boolean editable)

           

 void setTabSize(int chars)

           

 void setText(java.lang.String text)

           

 void undo()

           

 void updateSyntaxStyles()

           

 

Field Detail

TEXT_NOT_FOUND

static final int TEXT_NOT_FOUND

See Also:
Constant Field Values

TEXT_FOUND

static final int TEXT_FOUND

See Also:
Constant Field Values

TEXT_REPLACED_FOUND_NEXT

static final int TEXT_REPLACED_FOUND_NEXT

See Also:
Constant Field Values

TEXT_REPLACED_NOT_FOUND_NEXT

static final int TEXT_REPLACED_NOT_FOUND_NEXT

See Also:
Constant Field Values

Method Detail

copy

void copy()

cut

void cut()

doFindText

int doFindText(java.lang.String find,
boolean caseSensitive)

doReplace

int doReplace(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

doReplaceAll

int doReplaceAll(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

getCaretPosition

int getCaretPosition()

getDocument

javax.swing.text.Document getDocument()

getSelectedText

java.lang.String getSelectedText()

getSelectionEnd

int getSelectionEnd()

getSelectionStart

int getSelectionStart()

select

void select(int selectionStart,
int selectionEnd)

selectAll

void selectAll()

getText

java.lang.String getText()

getUndoManager

javax.swing.undo.UndoManager getUndoManager()

paste

void paste()

replaceSelection

void replaceSelection(java.lang.String str)

setCaretPosition

void setCaretPosition(int position)

setEditable

void setEditable(boolean editable)

setSelectionEnd

void setSelectionEnd(int pos)

setSelectionStart

void setSelectionStart(int pos)

setText

void setText(java.lang.String text)

setFont

void setFont(java.awt.Font f)

getFont

java.awt.Font getFont()

requestFocusInWindow

boolean requestFocusInWindow()

getFontMetrics

java.awt.FontMetrics getFontMetrics(java.awt.Font f)

setBackground

void setBackground(java.awt.Color c)

setEnabled

void setEnabled(boolean enabled)

grabFocus

void grabFocus()

redo

void redo()

revalidate

void revalidate()

setSourceCode

void setSourceCode(java.lang.String code,
boolean editable)

setCaretVisible

void setCaretVisible(boolean vis)

setSelectionVisible

void setSelectionVisible(boolean vis)

undo

void undo()

discardAllUndoableEdits

void discardAllUndoableEdits()

setLineHighlightEnabled

void setLineHighlightEnabled(boolean highlight)

setCaretBlinkRate

void setCaretBlinkRate(int rate)

setTabSize

void setTabSize(int chars)

updateSyntaxStyles

void updateSyntaxStyles()

getOuterComponent

java.awt.Component getOuterComponent()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RegistersWindow

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RegistersWindow

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
mars.venus.RegistersWindow

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible

public class RegistersWindow
extends javax.swing.JPanel
implements java.util.Observer

Sets up a window to display registers in the UI.

Author:
Sanderson, Bumgarner
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JPanel
javax.swing.JPanel.AccessibleJPanel

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
RegistersWindow()

          Constructor which sets up a fresh window with a table that contains the register values.

 

Method Summary

 void clearHighlighting()

          Clear highlight background color from any cell currently highlighted.

 void clearWindow()

          clear and redisplay registers

 void refresh()

          Refresh the table, triggering re-rendering.

 java.lang.Object[][] setupWindow()

          Sets up the data for the window.

 void update(java.util.Observable observable,
java.lang.Object obj)

          Required by Observer interface.

 void updateRegisters()

          update register display using current number base (10 or 16)

 void updateRegisters(int base)

          update register display using specified number base (10 or 16)

 void updateRegisterValue(int number,
int val,
int base)

          This method handles the updating of the GUI.

 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

RegistersWindow

public RegistersWindow()

Constructor which sets up a fresh window with a table that contains the register values.

Method Detail

setupWindow

public java.lang.Object[][] setupWindow()

Sets up the data for the window.

Returns:
The array object with the data for the window.

clearWindow

public void clearWindow()

clear and redisplay registers

clearHighlighting

public void clearHighlighting()

Clear highlight background color from any cell currently highlighted.

refresh

public void refresh()

Refresh the table, triggering re-rendering.

updateRegisters

public void updateRegisters()

update register display using current number base (10 or 16)

updateRegisters

public void updateRegisters(int base)

update register display using specified number base (10 or 16)

Parameters:
base – desired number base

updateRegisterValue

public void updateRegisterValue(int number,
int val,
int base)

This method handles the updating of the GUI.

Parameters:
number – The number of the register to update.
val – New value.

update

public void update(java.util.Observable observable,
java.lang.Object obj)

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.

Specified by:
update in interface java.util.Observer

Parameters:
observable – The Observable object who is notifying us
obj – Auxiliary object with additional information.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

EditUndoAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class EditUndoAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.EditUndoAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class EditUndoAction
extends GuiAction

Action for the Edit -> Undo menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
EditUndoAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          Adapted from TextComponentDemo.java in the
Java Tutorial “Text Component Features”

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

EditUndoAction

public EditUndoAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Adapted from TextComponentDemo.java in the
Java Tutorial “Text Component Features”

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FileSaveAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FileSaveAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.FileSaveAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class FileSaveAction
extends GuiAction

Action for the File -> Save menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
FileSaveAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          saves the file, if not alredy saved it will do a saveAs

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

FileSaveAction

public FileSaveAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

saves the file, if not alredy saved it will do a saveAs

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

PopupListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class PopupListener

java.lang.Object
java.awt.event.MouseAdapter
mars.venus.PopupListener

All Implemented Interfaces:
java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.MouseWheelListener, java.util.EventListener

public class PopupListener
extends java.awt.event.MouseAdapter

Constructor Summary
PopupListener(javax.swing.JPopupMenu p)

           

 

Method Summary

 void mousePressed(java.awt.event.MouseEvent e)

           

 void mouseReleased(java.awt.event.MouseEvent e)

           

 
Methods inherited from class java.awt.event.MouseAdapter
mouseClicked, mouseDragged, mouseEntered, mouseExited, mouseMoved, mouseWheelMoved

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

PopupListener

public PopupListener(javax.swing.JPopupMenu p)

Method Detail

mousePressed

public void mousePressed(java.awt.event.MouseEvent e)

Specified by:
mousePressed in interface java.awt.event.MouseListener
Overrides:
mousePressed in class java.awt.event.MouseAdapter

mouseReleased

public void mouseReleased(java.awt.event.MouseEvent e)

Specified by:
mouseReleased in interface java.awt.event.MouseListener
Overrides:
mouseReleased in class java.awt.event.MouseAdapter

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsExtendedAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsExtendedAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsExtendedAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsExtendedAction
extends GuiAction

Action class for the Settings menu item to control use of extended (pseudo) instructions or formats.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsExtendedAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsExtendedAction

public SettingsExtendedAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

EditFindReplaceAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class EditFindReplaceAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.EditFindReplaceAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class EditFindReplaceAction
extends GuiAction

Action for the Edit -> Find/Replace menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
EditFindReplaceAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

EditFindReplaceAction

public EditFindReplaceAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Editor

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class Editor

java.lang.Object
mars.venus.Editor

public class Editor
extends java.lang.Object

Manage the file being edited.
Currently only manages one file at a time, but can be expanded.

Field Summary

static int MAX_BLINK_RATE

           

static int MAX_TAB_SIZE

           

static int MIN_BLINK_RATE

           

static int MIN_TAB_SIZE

           

 

Constructor Summary
Editor(VenusUI ui)

          Create editor.

 

Method Summary

 boolean close()

          Perform “close” operation on current tab’s file.

 boolean closeAll()

          Close all currently open files.

 boolean editsSavedOrAbandoned()

          Called by several of the Action objects when there is potential
loss of editing changes.

 java.lang.String getCurrentOpenDirectory()

          Get name of current directory for Open operation.

 java.lang.String getCurrentSaveDirectory()

          Get name of current directory for Save or Save As operation.

 java.lang.String getNextDefaultFilename()

          Generates a default file name

 void newFile()

          Perform “new” operation to create an empty tab.

 boolean open()

          Open file in a new tab.

 boolean save()

          Perform “save” operation on current tab’s file.

 boolean saveAll()

          Perform save operation on all open files (tabs).

 boolean saveAs()

          Perform “save as” operation on current tab’s file.

 void setEditTabbedPane(EditTabbedPane editTabbedPane)

          Set associated EditTabbedPane.

 void setTitle(java.lang.String path,
java.lang.String name,
int status)

          Places name of file currently being edited into its edit tab and
the application’s title bar.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

MIN_TAB_SIZE

public static final int MIN_TAB_SIZE

See Also:
Constant Field Values

MAX_TAB_SIZE

public static final int MAX_TAB_SIZE

See Also:
Constant Field Values

MIN_BLINK_RATE

public static final int MIN_BLINK_RATE

See Also:
Constant Field Values

MAX_BLINK_RATE

public static final int MAX_BLINK_RATE

See Also:
Constant Field Values

Constructor Detail

Editor

public Editor(VenusUI ui)

Create editor.

Parameters:
ui – the GUI that owns this editor

Method Detail

setEditTabbedPane

public void setEditTabbedPane(EditTabbedPane editTabbedPane)

Set associated EditTabbedPane. This is container for any/all open files.

Parameters:
editTabbedPane – an existing editTabbedPane object

getCurrentOpenDirectory

public java.lang.String getCurrentOpenDirectory()

Get name of current directory for Open operation.

Returns:
String containing directory pathname. Returns null if there is
no EditTabbedPane. Returns default, directory MARS is launched from, if
no Opens have been performed.

getCurrentSaveDirectory

public java.lang.String getCurrentSaveDirectory()

Get name of current directory for Save or Save As operation.

Returns:
String containing directory pathname. Returns null if there is
no EditTabbedPane. Returns default, directory MARS is launched from, if
no Save or Save As operations have been performed.

getNextDefaultFilename

public java.lang.String getNextDefaultFilename()

Generates a default file name

Returns:
returns string mipsN.asm, where N is 1,2,3,…

setTitle

public void setTitle(java.lang.String path,
java.lang.String name,
int status)

Places name of file currently being edited into its edit tab and
the application’s title bar. The edit tab will contain only
the filename, the title bar will contain full pathname.
If file has been modified since created, opened or saved, as
indicated by value of the status parameter, the name and path
will be followed with an ‘*’. If newly-created file has not
yet been saved, the title bar will show (temporary) file name
but not path.

Parameters:
path – Full pathname for file
name – Name of file (last component of path)
status – Edit status of file. See FileStatus static constants.

newFile

public void newFile()

Perform “new” operation to create an empty tab.

close

public boolean close()

Perform “close” operation on current tab’s file.

Returns:
true if succeeded, else false.

closeAll

public boolean closeAll()

Close all currently open files.

Returns:
true if succeeded, else false.

save

public boolean save()

Perform “save” operation on current tab’s file.

Returns:
true if succeeded, else false.

saveAs

public boolean saveAs()

Perform “save as” operation on current tab’s file.

Returns:
true if succeeded, else false.

saveAll

public boolean saveAll()

Perform save operation on all open files (tabs).

Returns:
true if succeeded, else false.

open

public boolean open()

Open file in a new tab.

Returns:
true if succeeded, else false.

editsSavedOrAbandoned

public boolean editsSavedOrAbandoned()

Called by several of the Action objects when there is potential
loss of editing changes. Specifically: if there is a current
file open for editing and its modify flag is true, then give user
a dialog box with choice to save, discard edits, or cancel and
carry out the decision. This applies to File->New, File->Open,
File->Close, and File->Exit.

Returns:
false means user selected Cancel so caller should do that.
Return of true means caller can proceed (edits were saved or discarded).

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FileCloseAllAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FileCloseAllAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.FileCloseAllAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class FileCloseAllAction
extends GuiAction

Action for the File -> Close All menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
FileCloseAllAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

FileCloseAllAction

public FileCloseAllAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsLabelAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsLabelAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsLabelAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsLabelAction
extends GuiAction

Action class for the Settings menu item to control display of Labels window (symbol table).

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsLabelAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsLabelAction

public SettingsLabelAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsDelayedBranchingAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsDelayedBranchingAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsDelayedBranchingAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsDelayedBranchingAction
extends GuiAction

Action class for the Settings menu item to control delayed branching.
Note: Changing this setting while the current program is runnable
(assembled, or stepped execution) or terminated triggers a re-assembly.
This is necessary to maintain consistency because the machine
code assembled for branch instructions differs depending on
this setting — would branch to incorrect address if setting
were changed between assembly and execution.
Note: This action is disabled while the MIPS program is running.
The user need only pause or stop execution to re-enable it.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsDelayedBranchingAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsDelayedBranchingAction

public SettingsDelayedBranchingAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

HardcopyWriter.PrintCanceledException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class HardcopyWriter.PrintCanceledException

java.lang.Object
java.lang.Throwable
java.lang.Exception
mars.venus.HardcopyWriter.PrintCanceledException

All Implemented Interfaces:
java.io.Serializable

Enclosing class:
HardcopyWriter

public static class HardcopyWriter.PrintCanceledException
extends java.lang.Exception

This is the exception class that the HardcopyWriter constructor
throws when the user clicks “Cancel” in the print dialog box.

See Also:
Serialized Form

Constructor Summary
HardcopyWriter.PrintCanceledException(java.lang.String msg)

           

 

Method Summary

 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

HardcopyWriter.PrintCanceledException

public HardcopyWriter.PrintCanceledException(java.lang.String msg)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

ExecutePane

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class ExecutePane

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JLayeredPane
javax.swing.JDesktopPane
mars.venus.ExecutePane

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible

public class ExecutePane
extends javax.swing.JDesktopPane

Container for the execution-related windows. Currently displayed as a tabbed pane.

Author:
Sanderson and Team JSpim
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JDesktopPane
javax.swing.JDesktopPane.AccessibleJDesktopPane

 

Nested classes/interfaces inherited from class javax.swing.JLayeredPane
javax.swing.JLayeredPane.AccessibleJLayeredPane

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JDesktopPane
LIVE_DRAG_MODE, OUTLINE_DRAG_MODE

 
Fields inherited from class javax.swing.JLayeredPane
DEFAULT_LAYER, DRAG_LAYER, FRAME_CONTENT_LAYER, LAYER_PROPERTY, MODAL_LAYER, PALETTE_LAYER, POPUP_LAYER

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
ExecutePane(VenusUI mainUI,
RegistersWindow regs,
Coprocessor1Window cop1Regs,
Coprocessor0Window cop0Regs)

          initialize the Execute pane with major components

 

Method Summary

 void clearPane()

          Clears out all components of the Execute tab: text segment
display, data segment display, label display and register display.

 int getAddressDisplayBase()

          Retrieve the number system base for displaying memory addresses

 NumberDisplayBaseChooser getAddressDisplayBaseChooser()

          Retrieve component used to set numerical base (10 or 16) of address display.

 Coprocessor0Window getCoprocessor0Window()

          Access the coprocessor0 values window.

 Coprocessor1Window getCoprocessor1Window()

          Access the coprocessor1 values window.

 DataSegmentWindow getDataSegmentWindow()

          Access the data segment window.

 LabelsWindow getLabelsWindow()

          Access the label values window.

 RegistersWindow getRegistersWindow()

          Access the register values window.

 TextSegmentWindow getTextSegmentWindow()

          Access the text segment window.

 int getValueDisplayBase()

          Retrieve the number system base for displaying values (mem/register contents)

 NumberDisplayBaseChooser getValueDisplayBaseChooser()

          Retrieve component used to set numerical base (10 or 16) of data value display.

 void numberDisplayBaseChanged(NumberDisplayBaseChooser chooser)

          Update display of columns based on state of given chooser.

 void setLabelWindowVisibility(boolean visibility)

          Show or hide the label window (symbol table).

 void setWindowBounds()

          This method will set the bounds of this JDesktopPane’s internal windows
relative to the current size of this JDesktopPane.

 
Methods inherited from class javax.swing.JDesktopPane
addImpl, getAccessibleContext, getAllFrames, getAllFramesInLayer, getDesktopManager, getDragMode, getSelectedFrame, getUI, getUIClassID, paramString, remove, removeAll, selectFrame, setComponentZOrder, setDesktopManager, setDragMode, setSelectedFrame, setUI, updateUI

 
Methods inherited from class javax.swing.JLayeredPane
getComponentCountInLayer, getComponentsInLayer, getComponentToLayer, getIndexOf, getLayer, getLayer, getLayeredPaneAbove, getObjectForLayer, getPosition, highestLayer, insertIndexForLayer, isOptimizedDrawingEnabled, lowestLayer, moveToBack, moveToFront, paint, putLayer, setLayer, setLayer, setPosition

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, removeContainerListener, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

ExecutePane

public ExecutePane(VenusUI mainUI,
RegistersWindow regs,
Coprocessor1Window cop1Regs,
Coprocessor0Window cop0Regs)

initialize the Execute pane with major components

Parameters:
mainUI – the parent GUI
regs – window containing integer register set
cop1Regs – window containing Coprocessor 1 register set
cop0Regs – window containing Coprocessor 0 register set

Method Detail

setWindowBounds

public void setWindowBounds()

This method will set the bounds of this JDesktopPane’s internal windows
relative to the current size of this JDesktopPane. Such an operation
cannot be adequately done at constructor time because the actual
size of the desktop pane window is not yet established. Layout manager
is not a good option here because JDesktopPane does not work well with
them (the whole idea of using JDesktopPane with internal frames is to
have mini-frames that you can resize, move around, minimize, etc). This
method should be invoked only once: the first time the Execute tab is
selected (a change listener invokes it). We do not want it invoked
on subsequent tab selections; otherwise, user manipulations of the
internal frames would be lost the next time execute tab is selected.

setLabelWindowVisibility

public void setLabelWindowVisibility(boolean visibility)

Show or hide the label window (symbol table). If visible, it is displayed
to the right of the text segment and the latter is shrunk accordingly.

Parameters:
visibility – set to true or false

clearPane

public void clearPane()

Clears out all components of the Execute tab: text segment
display, data segment display, label display and register display.
This will typically be done upon File->Close, Open, New.

getTextSegmentWindow

public TextSegmentWindow getTextSegmentWindow()

Access the text segment window.

getDataSegmentWindow

public DataSegmentWindow getDataSegmentWindow()

Access the data segment window.

getRegistersWindow

public RegistersWindow getRegistersWindow()

Access the register values window.

getCoprocessor1Window

public Coprocessor1Window getCoprocessor1Window()

Access the coprocessor1 values window.

getCoprocessor0Window

public Coprocessor0Window getCoprocessor0Window()

Access the coprocessor0 values window.

getLabelsWindow

public LabelsWindow getLabelsWindow()

Access the label values window.

getValueDisplayBase

public int getValueDisplayBase()

Retrieve the number system base for displaying values (mem/register contents)

getAddressDisplayBase

public int getAddressDisplayBase()

Retrieve the number system base for displaying memory addresses

getValueDisplayBaseChooser

public NumberDisplayBaseChooser getValueDisplayBaseChooser()

Retrieve component used to set numerical base (10 or 16) of data value display.

Returns:
the chooser

getAddressDisplayBaseChooser

public NumberDisplayBaseChooser getAddressDisplayBaseChooser()

Retrieve component used to set numerical base (10 or 16) of address display.

Returns:
the chooser

numberDisplayBaseChanged

public void numberDisplayBaseChanged(NumberDisplayBaseChooser chooser)

Update display of columns based on state of given chooser. Normally
called only by the chooser’s ItemListener.

Parameters:
chooser – the GUI object manipulated by the user to change number base

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RunClearBreakpointsAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RunClearBreakpointsAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.RunClearBreakpointsAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action, javax.swing.event.TableModelListener

public class RunClearBreakpointsAction
extends GuiAction
implements javax.swing.event.TableModelListener

Action class for the Run menu item to clear execution breakpoints that have been set.
It is a listener and is notified whenever a breakpoint is added or removed, thus will
set its enabled status true or false depending on whether breakpoints remain after that action.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
RunClearBreakpointsAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

          Create the object and register with text segment window as a listener on its table model.

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          When this option is selected, tell text segment window to clear breakpoints in its table model.

 void tableChanged(javax.swing.event.TableModelEvent e)

          Required TableModelListener method.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

RunClearBreakpointsAction

public RunClearBreakpointsAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Create the object and register with text segment window as a listener on its table model.
The table model has not been created yet, so text segment window will hang onto this
registration info and transfer it to the table model upon creation (which happens with
each successful assembly).

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

When this option is selected, tell text segment window to clear breakpoints in its table model.

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

tableChanged

public void tableChanged(javax.swing.event.TableModelEvent e)

Required TableModelListener method. This is response upon editing of text segment table
model. The only editable column is breakpoints so this method is called only when user
adds or removes a breakpoint. Gets new breakpoint count and sets enabled status
accordingly.

Specified by:
tableChanged in interface javax.swing.event.TableModelListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Coprocessor0Window

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class Coprocessor0Window

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
mars.venus.Coprocessor0Window

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible

public class Coprocessor0Window
extends javax.swing.JPanel
implements java.util.Observer

Sets up a window to display registers in the UI.

Author:
Sanderson, Bumgarner
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JPanel
javax.swing.JPanel.AccessibleJPanel

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
Coprocessor0Window()

          Constructor which sets up a fresh window with a table that contains the register values.

 

Method Summary

 void clearHighlighting()

          Clear highlight background color from any row currently highlighted.

 void clearWindow()

          Reset and redisplay registers

 void refresh()

          Refresh the table, triggering re-rendering.

 java.lang.Object[][] setupWindow()

          Sets up the data for the window.

 void update(java.util.Observable observable,
java.lang.Object obj)

          Required by Observer interface.

 void updateRegisters()

          Update register display using current display base (10 or 16)

 void updateRegisters(int base)

          Update register display using specified display base

 void updateRegisterValue(int number,
int val,
int base)

          This method handles the updating of the GUI.

 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

Coprocessor0Window

public Coprocessor0Window()

Constructor which sets up a fresh window with a table that contains the register values.

Method Detail

setupWindow

public java.lang.Object[][] setupWindow()

Sets up the data for the window.

Returns:
The array object with the data for the window.

clearWindow

public void clearWindow()

Reset and redisplay registers

clearHighlighting

public void clearHighlighting()

Clear highlight background color from any row currently highlighted.

refresh

public void refresh()

Refresh the table, triggering re-rendering.

updateRegisters

public void updateRegisters()

Update register display using current display base (10 or 16)

updateRegisters

public void updateRegisters(int base)

Update register display using specified display base

Parameters:
base – number base for display (10 or 16)

updateRegisterValue

public void updateRegisterValue(int number,
int val,
int base)

This method handles the updating of the GUI.

Parameters:
number – The number of the register to update.
val – New value.

update

public void update(java.util.Observable observable,
java.lang.Object obj)

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.

Specified by:
update in interface java.util.Observer

Parameters:
observable – The Observable object who is notifying us
obj – Auxiliary object with additional information.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RegistersPane

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RegistersPane

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JTabbedPane
mars.venus.RegistersPane

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.SwingConstants

public class RegistersPane
extends javax.swing.JTabbedPane

Contains tabbed areas in the UI to display register contents

Author:
Sanderson
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JTabbedPane
javax.swing.JTabbedPane.AccessibleJTabbedPane, javax.swing.JTabbedPane.ModelListener

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JTabbedPane
changeEvent, changeListener, model, SCROLL_TAB_LAYOUT, tabPlacement, WRAP_TAB_LAYOUT

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
RegistersPane(VenusUI appFrame,
RegistersWindow regs,
Coprocessor1Window cop1,
Coprocessor0Window cop0)

          Constructor for the RegistersPane class.

 

Method Summary

 Coprocessor0Window getCoprocessor0Window()

          Return component containing coprocessor 0 (exceptions) register set.

 Coprocessor1Window getCoprocessor1Window()

          Return component containing coprocessor 1 (floating point) register set.

 RegistersWindow getRegistersWindow()

          Return component containing integer register set.

 
Methods inherited from class javax.swing.JTabbedPane
add, add, add, add, add, addChangeListener, addTab, addTab, addTab, createChangeListener, fireStateChanged, getAccessibleContext, getBackgroundAt, getBoundsAt, getChangeListeners, getComponentAt, getDisabledIconAt, getDisplayedMnemonicIndexAt, getForegroundAt, getIconAt, getMnemonicAt, getModel, getSelectedComponent, getSelectedIndex, getTabComponentAt, getTabCount, getTabLayoutPolicy, getTabPlacement, getTabRunCount, getTitleAt, getToolTipText, getToolTipTextAt, getUI, getUIClassID, indexAtLocation, indexOfComponent, indexOfTab, indexOfTab, indexOfTabComponent, insertTab, isEnabledAt, paramString, remove, remove, removeAll, removeChangeListener, removeTabAt, setBackgroundAt, setComponentAt, setDisabledIconAt, setDisplayedMnemonicIndexAt, setEnabledAt, setForegroundAt, setIconAt, setMnemonicAt, setModel, setSelectedComponent, setSelectedIndex, setTabComponentAt, setTabLayoutPolicy, setTabPlacement, setTitleAt, setToolTipTextAt, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

RegistersPane

public RegistersPane(VenusUI appFrame,
RegistersWindow regs,
Coprocessor1Window cop1,
Coprocessor0Window cop0)

Constructor for the RegistersPane class.

Method Detail

getRegistersWindow

public RegistersWindow getRegistersWindow()

Return component containing integer register set.

Returns:
integer register window

getCoprocessor1Window

public Coprocessor1Window getCoprocessor1Window()

Return component containing coprocessor 1 (floating point) register set.

Returns:
floating point register window

getCoprocessor0Window

public Coprocessor0Window getCoprocessor0Window()

Return component containing coprocessor 0 (exceptions) register set.

Returns:
exceptions register window

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

mars.venus

Classes 

AbstractFontSettingDialog

Coprocessor0Window

Coprocessor1Window

DataSegmentWindow

EditCopyAction

EditCutAction

EditFindReplaceAction

Editor

EditPane

EditPasteAction

EditRedoAction

EditSelectAllAction

EditTabbedPane

EditUndoAction

ExecutePane

FileCloseAction

FileCloseAllAction

FileDumpMemoryAction

FileExitAction

FileNewAction

FileOpenAction

FilePrintAction

FileSaveAction

FileSaveAllAction

FileSaveAsAction

FileStatus

GuiAction

HardcopyWriter

HelpAboutAction

HelpHelpAction

LabelsWindow

MainPane

MessagesPane

NumberDisplayBaseChooser

PopupListener

RegistersPane

RegistersWindow

RepeatButton

RunAssembleAction

RunBackstepAction

RunClearBreakpointsAction

RunGoAction

RunPauseAction

RunResetAction

RunSpeedPanel

RunStepAction

RunStopAction

RunToggleBreakpointsAction

SettingsAddressDisplayBaseAction

SettingsAssembleAllAction

SettingsAssembleOnOpenAction

SettingsDelayedBranchingAction

SettingsEditorAction

SettingsExceptionHandlerAction

SettingsExtendedAction

SettingsHighlightingAction

SettingsLabelAction

SettingsMemoryConfigurationAction

SettingsPopupInputAction

SettingsProgramArgumentsAction

SettingsStartAtMainAction

SettingsValueDisplayBaseAction

SettingsWarningsAreErrorsAction

TextSegmentWindow

ToolAction

ToolLoader

VenusUI

Exceptions 

HardcopyWriter.PrintCanceledException

HelpHelpAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class HelpHelpAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.HelpHelpAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class HelpHelpAction
extends GuiAction

Action for the Help -> Help menu item

See Also:
Serialized Form

Field Summary

static java.lang.String descriptionDetailSeparator

          Separates Instruction name descriptor from detailed (operation) description
in help string.

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
HelpHelpAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          Displays tabs with categories of information

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

descriptionDetailSeparator

public static final java.lang.String descriptionDetailSeparator

Separates Instruction name descriptor from detailed (operation) description
in help string.

See Also:
Constant Field Values

Constructor Detail

HelpHelpAction

public HelpHelpAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Displays tabs with categories of information

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

EditCutAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class EditCutAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.EditCutAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class EditCutAction
extends GuiAction

Action for the Edit -> Cut menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
EditCutAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

EditCutAction

public EditCutAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FileDumpMemoryAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FileDumpMemoryAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.FileDumpMemoryAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class FileDumpMemoryAction
extends GuiAction

Action for the File -> Save For Dump Memory menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
FileDumpMemoryAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

FileDumpMemoryAction

public FileDumpMemoryAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.venus

Class Summary
AbstractFontSettingDialog Abstract class for a font selection dialog.
Coprocessor0Window Sets up a window to display registers in the UI.
Coprocessor1Window Sets up a window to display Coprocessor 1 registers in the Registers pane of the UI.
DataSegmentWindow Represents the Data Segment window, which is a type of JInternalFrame.
EditCopyAction Action for the Edit -> Copy menu item
EditCutAction Action for the Edit -> Cut menu item
EditFindReplaceAction Action for the Edit -> Find/Replace menu item
Editor Manage the file being edited.
EditPane Represents one file opened for editing.
EditPasteAction Action for the Edit -> Paste menu item
EditRedoAction Action for the Edit -> Redo menu item
EditSelectAllAction Action for the Edit -> Copy menu item
EditTabbedPane Tabbed pane for the editor.
EditUndoAction Action for the Edit -> Undo menu item
ExecutePane Container for the execution-related windows.
FileCloseAction Action for the File -> Close menu item
FileCloseAllAction Action for the File -> Close All menu item
FileDumpMemoryAction Action for the File -> Save For Dump Memory menu item
FileExitAction Action for the File -> Exit menu item
FileNewAction Action for the File -> New menu item
FileOpenAction Action for the File -> Open menu item
FilePrintAction Action for the File -> Print menu item
FileSaveAction Action for the File -> Save menu item
FileSaveAllAction Action for the File -> Close All menu item
FileSaveAsAction Action for the File -> Save As menu item
FileStatus Used to store and return information on the status of the current ASM file that
is being edited in the program.
GuiAction parent class for Action subclasses to be defined for every menu/toolbar
option.
HardcopyWriter  
HelpAboutAction Action for the Help -> About menu item
HelpHelpAction Action for the Help -> Help menu item
LabelsWindow Represents the Labels window, which is a type of JInternalFrame.
MainPane Creates the tabbed areas in the UI and also created the internal windows that
exist in them.
MessagesPane Creates the message window at the bottom of the UI.
NumberDisplayBaseChooser Use to select base for displaying numbers.
PopupListener  
RegistersPane Contains tabbed areas in the UI to display register contents
RegistersWindow Sets up a window to display registers in the UI.
RepeatButton RepeatButton is a JButton which contains a timer
for firing events while the button is held down.
RunAssembleAction Action class for the Run -> Assemble menu item (and toolbar icon)
RunBackstepAction Action for the Run -> Backstep menu item
RunClearBreakpointsAction Action class for the Run menu item to clear execution breakpoints that have been set.
RunGoAction Action class for the Run -> Go menu item (and toolbar icon)
RunPauseAction Action class for the Run -> Pause menu item (and toolbar icon)
RunResetAction Action for the Run -> Reset menu item
RunSpeedPanel Class for the Run speed slider control.
RunStepAction Action for the Run -> Step menu item
RunStopAction Action class for the Run -> Stop menu item (and toolbar icon)
RunToggleBreakpointsAction Action class for the Run menu item to clear execution breakpoints that have been set.
SettingsAddressDisplayBaseAction Action class for the Settings menu item to control number base (10 or 16) of memory addresses.
SettingsAssembleAllAction Action class for the Settings menu item to determine whether assemble operation applies
only to current file or to all files in its directory.
SettingsAssembleOnOpenAction Action class for the Settings menu item to control automatic assemble of file upon opening.
SettingsDelayedBranchingAction Action class for the Settings menu item to control delayed branching.
SettingsEditorAction Action class for the Settings menu item for text editor settings.
SettingsExceptionHandlerAction Action class for the Settings menu item for optionally loading a MIPS exception handler.
SettingsExtendedAction Action class for the Settings menu item to control use of extended (pseudo) instructions or formats.
SettingsHighlightingAction Action class for the Settings menu item for text editor settings.
SettingsLabelAction Action class for the Settings menu item to control display of Labels window (symbol table).
SettingsMemoryConfigurationAction Action class for the Settings menu item for text editor settings.
SettingsPopupInputAction Action class for the Settings menu item to control use of popup dialog for input syscalls.
SettingsProgramArgumentsAction Action class for the Settings menu item to control whether or not
program arguments can be entered and used.
SettingsStartAtMainAction Action class for the Settings menu item to control whether or not
assembler warnings are considered errors.
SettingsValueDisplayBaseAction Action class for the Settings menu item to control number base (10 or 16) of memory/register contents.
SettingsWarningsAreErrorsAction Action class for the Settings menu item to control whether or not
assembler warnings are considered errors.
TextSegmentWindow Creates the Text Segment window in the Execute tab of the UI
ToolAction Connects a MarsTool class (class that implements MarsTool interface) to
the Mars menu system by supplying the response to that tool’s menu item
selection.
ToolLoader This class provides functionality to bring external Mars tools into the Mars
system by adding them to its Tools menu.
VenusUI Top level container for Venus GUI.

 

Exception Summary
HardcopyWriter.PrintCanceledException This is the exception class that the HardcopyWriter constructor
throws when the user clicks “Cancel” in the print dialog box.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

RepeatButton

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RepeatButton

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.AbstractButton
javax.swing.JButton
mars.venus.RepeatButton

All Implemented Interfaces:
java.awt.event.ActionListener, java.awt.event.MouseListener, java.awt.image.ImageObserver, java.awt.ItemSelectable, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, javax.accessibility.Accessible, javax.swing.SwingConstants

public class RepeatButton
extends javax.swing.JButton
implements java.awt.event.ActionListener, java.awt.event.MouseListener

RepeatButton is a JButton which contains a timer
for firing events while the button is held down. There is a default
initial delay of 300ms before the first event is fired and a 60ms delay
between subsequent events. When the user holds the button down and moves
the mouse out from over the button, the timer stops, but if the user moves
the mouse back over the button without having released the mouse button,
the timer starts up again at the same delay rate. If the enabled state is
changed while the timer is active, it will be stopped.

NOTE: The normal button behavior is that the action event is fired after
the button is released. It may be important to konw then that this is
still the case. So in effect, listeners will get 1 more event then what
the internal timer fires. It’s not a “bug”, per se, just something to be
aware of. There seems to be no way to suppress the final event from
firing anyway, except to process all ActionListeners internally. But
realistically, it probably doesn’t matter.

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JButton
javax.swing.JButton.AccessibleJButton

 

Nested classes/interfaces inherited from class javax.swing.AbstractButton
javax.swing.AbstractButton.AccessibleAbstractButton, javax.swing.AbstractButton.ButtonChangeListener

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.AbstractButton
actionListener, BORDER_PAINTED_CHANGED_PROPERTY, changeEvent, changeListener, CONTENT_AREA_FILLED_CHANGED_PROPERTY, DISABLED_ICON_CHANGED_PROPERTY, DISABLED_SELECTED_ICON_CHANGED_PROPERTY, FOCUS_PAINTED_CHANGED_PROPERTY, HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY, HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY, ICON_CHANGED_PROPERTY, itemListener, MARGIN_CHANGED_PROPERTY, MNEMONIC_CHANGED_PROPERTY, model, MODEL_CHANGED_PROPERTY, PRESSED_ICON_CHANGED_PROPERTY, ROLLOVER_ENABLED_CHANGED_PROPERTY, ROLLOVER_ICON_CHANGED_PROPERTY, ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY, SELECTED_ICON_CHANGED_PROPERTY, TEXT_CHANGED_PROPERTY, VERTICAL_ALIGNMENT_CHANGED_PROPERTY, VERTICAL_TEXT_POSITION_CHANGED_PROPERTY

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
RepeatButton()

          Creates a button with no set text or icon.
RepeatButton(javax.swing.Action a)

          Creates a button where properties are taken from the Action supplied.
RepeatButton(javax.swing.Icon icon)

          Creates a button with an icon.
RepeatButton(java.lang.String text)

          Creates a button with text.
RepeatButton(java.lang.String text,
javax.swing.Icon icon)

          Creates a button with initial text and an icon.

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent ae)

          Handle action events.

 int getDelay()

          Gets the delay for the timer of this button.

 int getInitialDelay()

          Gets the initial delay for the timer of this button.

 boolean isRepeatEnabled()

          Checks if the button should fire events when held.

static void main(java.lang.String[] args)

          Main method, for testing.

 void mouseClicked(java.awt.event.MouseEvent me)

          Handle mouse clicked events.

 void mouseEntered(java.awt.event.MouseEvent me)

          Handle mouse entered events.

 void mouseExited(java.awt.event.MouseEvent me)

          Handle mouse exited events.

 void mousePressed(java.awt.event.MouseEvent me)

          Handle mouse pressed events.

 void mouseReleased(java.awt.event.MouseEvent me)

          Handle mouse released events.

 void setDelay(int d)

          Set the delay for the timer of this button.

 void setEnabled(boolean en)

          Sets the enabled state of this button.

 void setInitialDelay(int d)

          Sets the initial delay for the timer of this button.

 void setRepeatEnabled(boolean en)

          Sets if the button should fire events when held.

 
Methods inherited from class javax.swing.JButton
getAccessibleContext, getUIClassID, isDefaultButton, isDefaultCapable, paramString, removeNotify, setDefaultCapable, updateUI

 
Methods inherited from class javax.swing.AbstractButton
actionPropertyChanged, addActionListener, addChangeListener, addImpl, addItemListener, checkHorizontalKey, checkVerticalKey, configurePropertiesFromAction, createActionListener, createActionPropertyChangeListener, createChangeListener, createItemListener, doClick, doClick, fireActionPerformed, fireItemStateChanged, fireStateChanged, getAction, getActionCommand, getActionListeners, getChangeListeners, getDisabledIcon, getDisabledSelectedIcon, getDisplayedMnemonicIndex, getHideActionText, getHorizontalAlignment, getHorizontalTextPosition, getIcon, getIconTextGap, getItemListeners, getLabel, getMargin, getMnemonic, getModel, getMultiClickThreshhold, getPressedIcon, getRolloverIcon, getRolloverSelectedIcon, getSelectedIcon, getSelectedObjects, getText, getUI, getVerticalAlignment, getVerticalTextPosition, imageUpdate, init, isBorderPainted, isContentAreaFilled, isFocusPainted, isRolloverEnabled, isSelected, paintBorder, removeActionListener, removeChangeListener, removeItemListener, setAction, setActionCommand, setBorderPainted, setContentAreaFilled, setDisabledIcon, setDisabledSelectedIcon, setDisplayedMnemonicIndex, setFocusPainted, setHideActionText, setHorizontalAlignment, setHorizontalTextPosition, setIcon, setIconTextGap, setLabel, setLayout, setMargin, setMnemonic, setMnemonic, setModel, setMultiClickThreshhold, setPressedIcon, setRolloverEnabled, setRolloverIcon, setRolloverSelectedIcon, setSelected, setSelectedIcon, setText, setUI, setVerticalAlignment, setVerticalTextPosition

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

RepeatButton

public RepeatButton()

Creates a button with no set text or icon.

RepeatButton

public RepeatButton(javax.swing.Action a)

Creates a button where properties are taken from the Action supplied.

Parameters:
a – the button action

RepeatButton

public RepeatButton(javax.swing.Icon icon)

Creates a button with an icon.

Parameters:
icon – the button icon

RepeatButton

public RepeatButton(java.lang.String text)

Creates a button with text.

Parameters:
text – the button text

RepeatButton

public RepeatButton(java.lang.String text,
javax.swing.Icon icon)

Creates a button with initial text and an icon.

Parameters:
text – the button text
icon – the button icon

Method Detail

getDelay

public int getDelay()

Gets the delay for the timer of this button.

Returns:
the delay

setDelay

public void setDelay(int d)

Set the delay for the timer of this button.

Parameters:
d – the delay

getInitialDelay

public int getInitialDelay()

Gets the initial delay for the timer of this button.

Returns:
the initial delay

setInitialDelay

public void setInitialDelay(int d)

Sets the initial delay for the timer of this button.

Parameters:
d – the initial delay

isRepeatEnabled

public boolean isRepeatEnabled()

Checks if the button should fire events when held. If false, the
button is effectively a plain old JButton, but there may be times
when this feature might wish to be disabled.

Returns:
if true, the button should fire events when held

setRepeatEnabled

public void setRepeatEnabled(boolean en)

Sets if the button should fire events when held. If false, the
button is effectively a plain old JButton, but there may be times
when this feature might wish to be disabled. If false, it will
also stop the timer if it’s running.

Parameters:
en – if true, the button should fire events when held

setEnabled

public void setEnabled(boolean en)

Sets the enabled state of this button. Overridden to stop the timer
if it’s running.

Overrides:
setEnabled in class javax.swing.AbstractButton

Parameters:
en – if true, enables the button

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent ae)

Handle action events. OVERRIDE THIS IN SUBCLASS!

Specified by:
actionPerformed in interface java.awt.event.ActionListener

Parameters:
ae – the action event

mouseClicked

public void mouseClicked(java.awt.event.MouseEvent me)

Handle mouse clicked events.

Specified by:
mouseClicked in interface java.awt.event.MouseListener

Parameters:
me – the mouse event

mousePressed

public void mousePressed(java.awt.event.MouseEvent me)

Handle mouse pressed events.

Specified by:
mousePressed in interface java.awt.event.MouseListener

Parameters:
me – the mouse event

mouseReleased

public void mouseReleased(java.awt.event.MouseEvent me)

Handle mouse released events.

Specified by:
mouseReleased in interface java.awt.event.MouseListener

Parameters:
me – the mouse event

mouseEntered

public void mouseEntered(java.awt.event.MouseEvent me)

Handle mouse entered events.

Specified by:
mouseEntered in interface java.awt.event.MouseListener

Parameters:
me – the mouse event

mouseExited

public void mouseExited(java.awt.event.MouseEvent me)

Handle mouse exited events.

Specified by:
mouseExited in interface java.awt.event.MouseListener

Parameters:
me – the mouse event

main

public static void main(java.lang.String[] args)

Main method, for testing. Creates a frame with both styles of menu.

Parameters:
args – the command-line arguments

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

EditCopyAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class EditCopyAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.EditCopyAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class EditCopyAction
extends GuiAction

Action for the Edit -> Copy menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
EditCopyAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

EditCopyAction

public EditCopyAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FileSaveAllAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FileSaveAllAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.FileSaveAllAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class FileSaveAllAction
extends GuiAction

Action for the File -> Close All menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
FileSaveAllAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

FileSaveAllAction

public FileSaveAllAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MessagesPane

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class MessagesPane

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JTabbedPane
mars.venus.MessagesPane

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.SwingConstants

public class MessagesPane
extends javax.swing.JTabbedPane

Creates the message window at the bottom of the UI.

Author:
Team JSpim
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JTabbedPane
javax.swing.JTabbedPane.AccessibleJTabbedPane, javax.swing.JTabbedPane.ModelListener

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

static int MAXIMUM_SCROLLED_CHARACTERS

           

static int NUMBER_OF_CHARACTERS_TO_CUT

           

 
Fields inherited from class javax.swing.JTabbedPane
changeEvent, changeListener, model, SCROLL_TAB_LAYOUT, tabPlacement, WRAP_TAB_LAYOUT

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
MessagesPane()

          Constructor for the class, sets up two fresh tabbed text areas for program feedback.

 

Method Summary

 javax.swing.JTextArea getAssembleTextArea()

          Returns component used to display assembler messages

 java.lang.String getInputString(int maxLen)

          Method used by the SystemIO class to get interactive user input
requested by a running MIPS program (e.g.

 java.lang.String getInputString(java.lang.String prompt)

          Method used by the SystemIO class to get interactive user input
requested by a running MIPS program (e.g.

 javax.swing.JTextArea getRunTextArea()

          Returns component used to display runtime messages

 void postMarsMessage(java.lang.String message)

          Post a message to the assembler display

 void postRunMessage(java.lang.String message)

          Post a message to the runtime display

 void selectEditorTextLine(java.lang.String fileName,
int line,
int column)

          Will select the specified line in an editor tab.

 void selectErrorMessage(java.lang.String fileName,
int line,
int column)

          Will select the Mars Messages tab error message that matches the given
specifications, if it is found.

 void selectMarsMessageTab()

          Make the assembler message tab current (up front)

 void selectRunMessageTab()

          Make the runtime message tab current (up front)

 
Methods inherited from class javax.swing.JTabbedPane
add, add, add, add, add, addChangeListener, addTab, addTab, addTab, createChangeListener, fireStateChanged, getAccessibleContext, getBackgroundAt, getBoundsAt, getChangeListeners, getComponentAt, getDisabledIconAt, getDisplayedMnemonicIndexAt, getForegroundAt, getIconAt, getMnemonicAt, getModel, getSelectedComponent, getSelectedIndex, getTabComponentAt, getTabCount, getTabLayoutPolicy, getTabPlacement, getTabRunCount, getTitleAt, getToolTipText, getToolTipTextAt, getUI, getUIClassID, indexAtLocation, indexOfComponent, indexOfTab, indexOfTab, indexOfTabComponent, insertTab, isEnabledAt, paramString, remove, remove, removeAll, removeChangeListener, removeTabAt, setBackgroundAt, setComponentAt, setDisabledIconAt, setDisplayedMnemonicIndexAt, setEnabledAt, setForegroundAt, setIconAt, setMnemonicAt, setModel, setSelectedComponent, setSelectedIndex, setTabComponentAt, setTabLayoutPolicy, setTabPlacement, setTitleAt, setToolTipTextAt, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

MAXIMUM_SCROLLED_CHARACTERS

public static final int MAXIMUM_SCROLLED_CHARACTERS

NUMBER_OF_CHARACTERS_TO_CUT

public static final int NUMBER_OF_CHARACTERS_TO_CUT

Constructor Detail

MessagesPane

public MessagesPane()

Constructor for the class, sets up two fresh tabbed text areas for program feedback.

Method Detail

selectErrorMessage

public void selectErrorMessage(java.lang.String fileName,
int line,
int column)

Will select the Mars Messages tab error message that matches the given
specifications, if it is found. Matching is done by constructing
a string using the parameter values and searching the text area for the last
occurrance of that string.

Parameters:
fileName – A String containing the file path name.
line – Line number for error message
column – Column number for error message

selectEditorTextLine

public void selectEditorTextLine(java.lang.String fileName,
int line,
int column)

Will select the specified line in an editor tab. If the file is open
but not current, its tab will be made current. If the file is not open,
it will be opened in a new tab and made current, however the line will
not be selected (apparent apparent problem with JEditTextArea).

Parameters:
fileName – A String containing the file path name.
line – Line number for error message
column – Column number for error message

getAssembleTextArea

public javax.swing.JTextArea getAssembleTextArea()

Returns component used to display assembler messages

Returns:
assembler message text component

getRunTextArea

public javax.swing.JTextArea getRunTextArea()

Returns component used to display runtime messages

Returns:
runtime message text component

postMarsMessage

public void postMarsMessage(java.lang.String message)

Post a message to the assembler display

Parameters:
message – String to append to assembler display text

postRunMessage

public void postRunMessage(java.lang.String message)

Post a message to the runtime display

Parameters:
message – String to append to runtime display text

selectMarsMessageTab

public void selectMarsMessageTab()

Make the assembler message tab current (up front)

selectRunMessageTab

public void selectRunMessageTab()

Make the runtime message tab current (up front)

getInputString

public java.lang.String getInputString(java.lang.String prompt)

Method used by the SystemIO class to get interactive user input
requested by a running MIPS program (e.g. syscall #5 to read an
integer). SystemIO knows whether simulator is being run at
command line by the user, or by the GUI. If run at command line,
it gets input from System.in rather than here.

This is an overloaded method. This version, with the String parameter,
is used to get input from a popup dialog.

Parameters:
prompt – Prompt to display to the user.

Returns:
User input.

getInputString

public java.lang.String getInputString(int maxLen)

Method used by the SystemIO class to get interactive user input
requested by a running MIPS program (e.g. syscall #5 to read an
integer). SystemIO knows whether simulator is being run at
command line by the user, or by the GUI. If run at command line,
it gets input from System.in rather than here.

This is an overloaded method. This version, with the int parameter,
is used to get input from the MARS Run I/O window.

Parameters:
maxLen: – maximum length of input. This method returns when maxLen characters have been read. Use -1 for no length restrictions.

Returns:
User input.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsWarningsAreErrorsAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsWarningsAreErrorsAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsWarningsAreErrorsAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsWarningsAreErrorsAction
extends GuiAction

Action class for the Settings menu item to control whether or not
assembler warnings are considered errors. If so, a program generating
warnings but not errors will not assemble.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsWarningsAreErrorsAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsWarningsAreErrorsAction

public SettingsWarningsAreErrorsAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

NumberDisplayBaseChooser

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class NumberDisplayBaseChooser

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.AbstractButton
javax.swing.JToggleButton
javax.swing.JCheckBox
mars.venus.NumberDisplayBaseChooser

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.ItemSelectable, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.SwingConstants

public class NumberDisplayBaseChooser
extends javax.swing.JCheckBox

Use to select base for displaying numbers. Initially the
choices are only 10 (decimal) and 16 (hex), so I’m using
a check box where checked means hex. If base 8 (octal)
is added later, the Component will need to change.

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JCheckBox
javax.swing.JCheckBox.AccessibleJCheckBox

 

Nested classes/interfaces inherited from class javax.swing.JToggleButton
javax.swing.JToggleButton.AccessibleJToggleButton, javax.swing.JToggleButton.ToggleButtonModel

 

Nested classes/interfaces inherited from class javax.swing.AbstractButton
javax.swing.AbstractButton.AccessibleAbstractButton, javax.swing.AbstractButton.ButtonChangeListener

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

static int ASCII

           

static int DECIMAL

           

static int HEXADECIMAL

           

 
Fields inherited from class javax.swing.JCheckBox
BORDER_PAINTED_FLAT_CHANGED_PROPERTY

 
Fields inherited from class javax.swing.AbstractButton
actionListener, BORDER_PAINTED_CHANGED_PROPERTY, changeEvent, changeListener, CONTENT_AREA_FILLED_CHANGED_PROPERTY, DISABLED_ICON_CHANGED_PROPERTY, DISABLED_SELECTED_ICON_CHANGED_PROPERTY, FOCUS_PAINTED_CHANGED_PROPERTY, HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY, HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY, ICON_CHANGED_PROPERTY, itemListener, MARGIN_CHANGED_PROPERTY, MNEMONIC_CHANGED_PROPERTY, model, MODEL_CHANGED_PROPERTY, PRESSED_ICON_CHANGED_PROPERTY, ROLLOVER_ENABLED_CHANGED_PROPERTY, ROLLOVER_ICON_CHANGED_PROPERTY, ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY, SELECTED_ICON_CHANGED_PROPERTY, TEXT_CHANGED_PROPERTY, VERTICAL_ALIGNMENT_CHANGED_PROPERTY, VERTICAL_TEXT_POSITION_CHANGED_PROPERTY

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
NumberDisplayBaseChooser(java.lang.String text,
boolean displayInHex)

          constructor.

 

Method Summary

static java.lang.String formatDoubleNumber(long value,
int base)

          Produces a string form of a double given a long containing
the 64 bit pattern and the numerical base to use (10 or 16).

static java.lang.String formatFloatNumber(int value,
int base)

          Produces a string form of a float given an integer containing
the 32 bit pattern and the numerical base to use (10 or 16).

static java.lang.String formatNumber(double value,
int base)

          Produces a string form of a double given the value and the
numerical base to convert it to.

static java.lang.String formatNumber(float value,
int base)

          Produces a string form of a float given the value and the
numerical base to convert it to.

 java.lang.String formatNumber(int value)

          Produces a string form of a number given the value.

static java.lang.String formatNumber(int value,
int base)

          Produces a string form of an integer given the value and the
numerical base to convert it to.

 java.lang.String formatUnsignedInteger(int value)

          Produces a string form of an unsigned integer given the value.

static java.lang.String formatUnsignedInteger(int value,
int base)

          Produces a string form of an unsigned given the value and the
numerical base to convert it to.

 int getBase()

          Retrieve the current number base.

static int getBase(boolean setting)

          Return the number base corresponding to the specified setting.

 void setBase(int newBase)

          Set the current number base.

 void setSettingsMenuItem(javax.swing.JCheckBoxMenuItem setter)

          Set the menu item from Settings menu that corresponds to this chooser.

 
Methods inherited from class javax.swing.JCheckBox
getAccessibleContext, getUIClassID, isBorderPaintedFlat, paramString, setBorderPaintedFlat, updateUI

 
Methods inherited from class javax.swing.AbstractButton
actionPropertyChanged, addActionListener, addChangeListener, addImpl, addItemListener, checkHorizontalKey, checkVerticalKey, configurePropertiesFromAction, createActionListener, createActionPropertyChangeListener, createChangeListener, createItemListener, doClick, doClick, fireActionPerformed, fireItemStateChanged, fireStateChanged, getAction, getActionCommand, getActionListeners, getChangeListeners, getDisabledIcon, getDisabledSelectedIcon, getDisplayedMnemonicIndex, getHideActionText, getHorizontalAlignment, getHorizontalTextPosition, getIcon, getIconTextGap, getItemListeners, getLabel, getMargin, getMnemonic, getModel, getMultiClickThreshhold, getPressedIcon, getRolloverIcon, getRolloverSelectedIcon, getSelectedIcon, getSelectedObjects, getText, getUI, getVerticalAlignment, getVerticalTextPosition, imageUpdate, init, isBorderPainted, isContentAreaFilled, isFocusPainted, isRolloverEnabled, isSelected, paintBorder, removeActionListener, removeChangeListener, removeItemListener, removeNotify, setAction, setActionCommand, setBorderPainted, setContentAreaFilled, setDisabledIcon, setDisabledSelectedIcon, setDisplayedMnemonicIndex, setEnabled, setFocusPainted, setHideActionText, setHorizontalAlignment, setHorizontalTextPosition, setIcon, setIconTextGap, setLabel, setLayout, setMargin, setMnemonic, setMnemonic, setModel, setMultiClickThreshhold, setPressedIcon, setRolloverEnabled, setRolloverIcon, setRolloverSelectedIcon, setSelected, setSelectedIcon, setText, setUI, setVerticalAlignment, setVerticalTextPosition

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

DECIMAL

public static final int DECIMAL

See Also:
Constant Field Values

HEXADECIMAL

public static final int HEXADECIMAL

See Also:
Constant Field Values

ASCII

public static final int ASCII

See Also:
Constant Field Values

Constructor Detail

NumberDisplayBaseChooser

public NumberDisplayBaseChooser(java.lang.String text,
boolean displayInHex)

constructor. It assumes the text will be worded
so that a checked box means hexadecimal!

Parameters:
text – Text to accompany the check box.
defaultBase – Currently either DECIMAL or HEXADECIMAL

Method Detail

getBase

public int getBase()

Retrieve the current number base.

Returns:
current number base, currently DECIMAL or HEXADECIMAL

setBase

public void setBase(int newBase)

Set the current number base.

Parameters:
newBase – The new number base. Currently, if it is
neither DECIMAL nor HEXADECIMAL, the base will not be changed.

formatUnsignedInteger

public static java.lang.String formatUnsignedInteger(int value,
int base)

Produces a string form of an unsigned given the value and the
numerical base to convert it to. This class
method can be used by anyone anytime. If base is 16, result
is same as for formatNumber(). If base is 10, will produce
string version of unsigned value. E.g. 0xffffffff will produce
“4294967295” instead of “-1”.

Parameters:
value – the number to be converted
base – the numerical base to use (currently 10 or 16)

Returns:
a String equivalent of the value rendered appropriately.

formatNumber

public static java.lang.String formatNumber(int value,
int base)

Produces a string form of an integer given the value and the
numerical base to convert it to. There is an instance
method that uses the internally stored base. This class
method can be used by anyone anytime.

Parameters:
value – the number to be converted
base – the numerical base to use (currently 10 or 16)

Returns:
a String equivalent of the value rendered appropriately.

formatNumber

public static java.lang.String formatNumber(float value,
int base)

Produces a string form of a float given the value and the
numerical base to convert it to. There is an instance
method that uses the internally stored base. This class
method can be used by anyone anytime.

Parameters:
value – the number to be converted
base – the numerical base to use (currently 10 or 16)

Returns:
a String equivalent of the value rendered appropriately.

formatNumber

public static java.lang.String formatNumber(double value,
int base)

Produces a string form of a double given the value and the
numerical base to convert it to. There is an instance
method that uses the internally stored base. This class
method can be used by anyone anytime.

Parameters:
value – the number to be converted
base – the numerical base to use (currently 10 or 16)

Returns:
a String equivalent of the value rendered appropriately.

formatNumber

public java.lang.String formatNumber(int value)

Produces a string form of a number given the value. There
is also an class (static method) that uses a specified
base.

Parameters:
value – the number to be converted

Returns:
a String equivalent of the value rendered appropriately.

formatUnsignedInteger

public java.lang.String formatUnsignedInteger(int value)

Produces a string form of an unsigned integer given the value. There
is also an class (static method) that uses a specified base.
If the current base is 16, this produces the same result as formatNumber().

Parameters:
value – the number to be converted

Returns:
a String equivalent of the value rendered appropriately.

formatFloatNumber

public static java.lang.String formatFloatNumber(int value,
int base)

Produces a string form of a float given an integer containing
the 32 bit pattern and the numerical base to use (10 or 16). If the
base is 16, the string will be built from the 32 bits. If the
base is 10, the int bits will be converted to float and the
string constructed from that. Seems an odd distinction to make,
except that contents of floating point registers are stored
internally as int bits. If the int bits represent a NaN value
(of which there are many!), converting them to float then calling
formatNumber(float, int) above, causes the float value to become
the canonical NaN value 0x7fc00000. It does not preserve the bit
pattern! Then converting it to hex string yields the canonical NaN.
Not an issue if display base is 10 since result string will be NaN
no matter what the internal NaN value is.

Parameters:
value – the int bits to be converted to string of corresponding float.
base – the numerical base to use (currently 10 or 16)

Returns:
a String equivalent of the value rendered appropriately.

formatDoubleNumber

public static java.lang.String formatDoubleNumber(long value,
int base)

Produces a string form of a double given a long containing
the 64 bit pattern and the numerical base to use (10 or 16). If the
base is 16, the string will be built from the 64 bits. If the
base is 10, the long bits will be converted to double and the
string constructed from that. Seems an odd distinction to make,
except that contents of floating point registers are stored
internally as int bits. If the int bits represent a NaN value
(of which there are many!), converting them to double then calling
formatNumber(double, int) above, causes the double value to become
the canonical NaN value. It does not preserve the bit
pattern! Then converting it to hex string yields the canonical NaN.
Not an issue if display base is 10 since result string will be NaN
no matter what the internal NaN value is.

Parameters:
value – the long bits to be converted to string of corresponding double.
base – the numerical base to use (currently 10 or 16)

Returns:
a String equivalent of the value rendered appropriately.

setSettingsMenuItem

public void setSettingsMenuItem(javax.swing.JCheckBoxMenuItem setter)

Set the menu item from Settings menu that corresponds to this chooser.
It is the responsibility of that item to register here, because this
one is created first (before the menu item). They need to communicate
with each other so that whenever one changes, so does the other. They
cannot be the same object (one is JCheckBox, the other is JCheckBoxMenuItem).

getBase

public static int getBase(boolean setting)

Return the number base corresponding to the specified setting.

Returns:
HEXADECIMAL if setting is true, DECIMAL otherwise.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RunStepAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RunStepAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.RunStepAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class RunStepAction
extends GuiAction

Action for the Run -> Step menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
RunStepAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          perform next simulated instruction step.

 void stepped(boolean done,
int reason,
ProcessingException pe)

           

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

RunStepAction

public RunStepAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

perform next simulated instruction step.

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

stepped

public void stepped(boolean done,
int reason,
ProcessingException pe)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsHighlightingAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsHighlightingAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsHighlightingAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsHighlightingAction
extends GuiAction

Action class for the Settings menu item for text editor settings.

See Also:
Serialized Form

Field Summary

static java.lang.String APPLY_TOOL_TIP_TEXT

           

static java.lang.String CANCEL_TOOL_TIP_TEXT

           

static java.lang.String CLOSE_TOOL_TIP_TEXT

           

static java.lang.String RESET_TOOL_TIP_TEXT

           

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsHighlightingAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

          Create a new SettingsEditorAction.

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          When this action is triggered, launch a dialog to view and modify
editor settings.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

CLOSE_TOOL_TIP_TEXT

public static final java.lang.String CLOSE_TOOL_TIP_TEXT

See Also:
Constant Field Values

APPLY_TOOL_TIP_TEXT

public static final java.lang.String APPLY_TOOL_TIP_TEXT

See Also:
Constant Field Values

RESET_TOOL_TIP_TEXT

public static final java.lang.String RESET_TOOL_TIP_TEXT

See Also:
Constant Field Values

CANCEL_TOOL_TIP_TEXT

public static final java.lang.String CANCEL_TOOL_TIP_TEXT

See Also:
Constant Field Values

Constructor Detail

SettingsHighlightingAction

public SettingsHighlightingAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Create a new SettingsEditorAction. Has all the GuiAction parameters.

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

When this action is triggered, launch a dialog to view and modify
editor settings.

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

EditPane

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class EditPane

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
mars.venus.EditPane

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.Observer, javax.accessibility.Accessible

public class EditPane
extends javax.swing.JPanel
implements java.util.Observer

Represents one file opened for editing. Maintains required internal structures.
Before Mars 4.0, there was only one editor pane, a tab, and only one file could
be open at a time. With 4.0 came the multifile (pane, tab) editor, and existing
duties were split between EditPane and the new EditTabbedPane class.

Author:
Sanderson and Bumgarner
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JPanel
javax.swing.JPanel.AccessibleJPanel

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
EditPane(VenusUI appFrame)

          Constructor for the EditPane class.

 

Method Summary

 int convertLineColumnToStreamPosition(int line,
int column)

          Given line and column (position in the line) numbers, calculate
its byte stream position in text being edited.

 java.awt.Point convertStreamPositionToLineColumn(int position)

           

 void copyText()

          copy currently-selected text into clipboard

 void cutText()

          cut currently-selected text into clipboard

 void discardAllUndoableEdits()

          Get rid of any accumulated undoable edits.

 void displayCaretPosition(int pos)

          Update the caret position label on the editor’s border to
display the current line and column.

 void displayCaretPosition(java.awt.Point p)

          Display cursor coordinates

 int doFindText(java.lang.String find,
boolean caseSensitive)

          Finds next occurrence of text in a forward search of a string.

 int doReplace(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

          Finds and replaces next occurrence of text in a string in a forward search.

 int doReplaceAll(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

          Finds and replaces ALL occurrences of text in a string in a forward search.

 java.lang.String getFilename()

          Delegates to corresponding FileStatus method

 int getFileStatus()

          Get the editing status for this EditPane’s associated document.

 java.lang.String getLineNumbersList(javax.swing.text.Document doc)

           

 java.lang.String getPathname()

          Delegates to corresponding FileStatus method

 java.lang.String getSource()

          Get source code text

 int getSourceLineCount()

          Calculate and return number of lines in source code text.

 javax.swing.undo.UndoManager getUndoManager()

          get the manager in charge of Undo and Redo operations

 boolean hasUnsavedEdits()

          Delegates to corresponding FileStatus method

 boolean isNew()

          Delegates to corresponding FileStatus method

 void pasteText()

          paste clipboard contents at cursor position

 void redo()

          Redo previous edit

 void selectAllText()

          select all text

 void selectLine(int line)

          Select the specified editor text line.

 void selectLine(int line,
int column)

          Select the specified editor text line.

 void setFileStatus(int fileStatus)

          Set the editing status for this EditPane’s associated document.

 void setPathname(java.lang.String pathname)

          Delegates to corresponding FileStatus method

 void setShowLineNumbersEnabled(boolean enabled)

          enable or disable checkbox that controls display of line numbers

 void setSourceCode(java.lang.String s,
boolean editable)

          For initalizing the source code when opening an ASM file

 boolean showingLineNumbers()

          get editor’s line number display status

 void tellEditingComponentToRequestFocusInWindow()

          Delegates to text area’s requestFocusInWindow method.

 void undo()

          Undo previous edit

 void update(java.util.Observable fontChanger,
java.lang.Object arg)

          Update, if source code is visible, when Font setting changes.

 void updateRedoState()

          Update state of Edit menu’s Redo menu item.

 void updateStaticFileStatus()

          Delegates to corresponding FileStatus method

 void updateUndoState()

          Update state of Edit menu’s Undo menu item.

 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

EditPane

public EditPane(VenusUI appFrame)

Constructor for the EditPane class.

Method Detail

setSourceCode

public void setSourceCode(java.lang.String s,
boolean editable)

For initalizing the source code when opening an ASM file

Parameters:
s – String containing text
editable – set true if code is editable else false

discardAllUndoableEdits

public void discardAllUndoableEdits()

Get rid of any accumulated undoable edits. It is useful to call
this method after opening a file into the text area. The
act of setting its text content upon reading the file will generate
an undoable edit. Normally you don’t want a freshly-opened file
to appear with its Undo action enabled. But it will unless you
call this after setting the text.

getLineNumbersList

public java.lang.String getLineNumbersList(javax.swing.text.Document doc)

getSourceLineCount

public int getSourceLineCount()

Calculate and return number of lines in source code text.
Do this by counting newline characters then adding one if last line does
not end with newline character.

getSource

public java.lang.String getSource()

Get source code text

Returns:
Sting containing source code

setFileStatus

public void setFileStatus(int fileStatus)

Set the editing status for this EditPane’s associated document.
For the argument, use one of the constants from class FileStatus.

Parameters:
FileStatus – the status constant from class FileStatus

getFileStatus

public int getFileStatus()

Get the editing status for this EditPane’s associated document.
This will be one of the constants from class FileStatus.

getFilename

public java.lang.String getFilename()

Delegates to corresponding FileStatus method

getPathname

public java.lang.String getPathname()

Delegates to corresponding FileStatus method

setPathname

public void setPathname(java.lang.String pathname)

Delegates to corresponding FileStatus method

hasUnsavedEdits

public boolean hasUnsavedEdits()

Delegates to corresponding FileStatus method

isNew

public boolean isNew()

Delegates to corresponding FileStatus method

tellEditingComponentToRequestFocusInWindow

public void tellEditingComponentToRequestFocusInWindow()

Delegates to text area’s requestFocusInWindow method.

updateStaticFileStatus

public void updateStaticFileStatus()

Delegates to corresponding FileStatus method

getUndoManager

public javax.swing.undo.UndoManager getUndoManager()

get the manager in charge of Undo and Redo operations

Returns:
the UnDo manager

copyText

public void copyText()

copy currently-selected text into clipboard

cutText

public void cutText()

cut currently-selected text into clipboard

pasteText

public void pasteText()

paste clipboard contents at cursor position

selectAllText

public void selectAllText()

select all text

undo

public void undo()

Undo previous edit

redo

public void redo()

Redo previous edit

updateUndoState

public void updateUndoState()

Update state of Edit menu’s Undo menu item.

updateRedoState

public void updateRedoState()

Update state of Edit menu’s Redo menu item.

showingLineNumbers

public boolean showingLineNumbers()

get editor’s line number display status

Returns:
true if editor is current displaying line numbers, false otherwise.

setShowLineNumbersEnabled

public void setShowLineNumbersEnabled(boolean enabled)

enable or disable checkbox that controls display of line numbers

Parameters:
enable – True to enable box, false to disable.

displayCaretPosition

public void displayCaretPosition(int pos)

Update the caret position label on the editor’s border to
display the current line and column. The position is given
as text stream offset and will be converted into line and column.

Parameters:
pos – Offset into the text stream of caret.

displayCaretPosition

public void displayCaretPosition(java.awt.Point p)

Display cursor coordinates

Parameters:
p – Point object with x-y (column, line number) coordinates of cursor

convertStreamPositionToLineColumn

public java.awt.Point convertStreamPositionToLineColumn(int position)

convertLineColumnToStreamPosition

public int convertLineColumnToStreamPosition(int line,
int column)

Given line and column (position in the line) numbers, calculate
its byte stream position in text being edited.

Parameters:
line – Line number in file (starts with 1)
column – Position within that line (starts with 1)

Returns:
corresponding stream position. Returns -1 if there is no corresponding position.

selectLine

public void selectLine(int line)

Select the specified editor text line. Lines are numbered starting with 1, consistent
with line numbers displayed by the editor.

Parameters:
line – The desired line number of this TextPane’s text. Numbering starts at 1, and
nothing will happen if the parameter value is less than 1

selectLine

public void selectLine(int line,
int column)

Select the specified editor text line. Lines are numbered starting with 1, consistent
with line numbers displayed by the editor.

Parameters:
line – The desired line number of this TextPane’s text. Numbering starts at 1, and
nothing will happen if the parameter value is less than 1
column – Desired column at which to place the cursor.

doFindText

public int doFindText(java.lang.String find,
boolean caseSensitive)

Finds next occurrence of text in a forward search of a string. Search begins
at the current cursor location, and wraps around when the end of the string
is reached.

Parameters:
find – the text to locate in the string
caseSensitive – true if search is to be case-sensitive, false otherwise

Returns:
TEXT_FOUND or TEXT_NOT_FOUND, depending on the result.

doReplace

public int doReplace(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

Finds and replaces next occurrence of text in a string in a forward search.
If cursor is initially at end
of matching selection, will immediately replace then find and select the
next occurrence if any. Otherwise it performs a find operation. The replace
can be undone with one undo operation.

Parameters:
find – the text to locate in the string
replace – the text to replace the find text with – if the find text exists
caseSensitive – true for case sensitive. false to ignore case

Returns:
Returns TEXT_FOUND if not initially at end of selected match and matching
occurrence is found. Returns TEXT_NOT_FOUND if the text is not matched.
Returns TEXT_REPLACED_NOT_FOUND_NEXT if replacement is successful but there are
no additional matches. Returns TEXT_REPLACED_FOUND_NEXT if reaplacement is
successful and there is at least one additional match.

doReplaceAll

public int doReplaceAll(java.lang.String find,
java.lang.String replace,
boolean caseSensitive)

Finds and replaces ALL occurrences of text in a string in a forward search.
All replacements are bundled into one CompoundEdit, so one Undo operation will
undo all of them.

Parameters:
find – the text to locate in the string
replace – the text to replace the find text with – if the find text exists
caseSensitive – true for case sensitive. false to ignore case

Returns:
the number of occurrences that were matched and replaced.

update

public void update(java.util.Observable fontChanger,
java.lang.Object arg)

Update, if source code is visible, when Font setting changes.
This method is specified by the Observer interface.

Specified by:
update in interface java.util.Observer

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

ToolLoader

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class ToolLoader

java.lang.Object
mars.venus.ToolLoader

public class ToolLoader
extends java.lang.Object

This class provides functionality to bring external Mars tools into the Mars
system by adding them to its Tools menu. This permits anyone with knowledge
of the Mars public interfaces, in particular of the Memory and Register
classes, to write applications which can interact with a MIPS program
executing under Mars. The execution is of course simulated. The
private method for loading tool classes is adapted from Bret Barker’s
GameServer class from the book “Developing Games In Java”.

Author:
Pete Sanderson with help from Bret Barker

Constructor Summary
ToolLoader()

           

 

Method Summary

 javax.swing.JMenu buildToolsMenu()

          Called in VenusUI to build its Tools menu.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

ToolLoader

public ToolLoader()

Method Detail

buildToolsMenu

public javax.swing.JMenu buildToolsMenu()

Called in VenusUI to build its Tools menu. If there are no qualifying tools
or any problems accessing those tools, it returns null. A qualifying tool
must be a class in the Tools package that implements MarsTool, must be compiled
into a .class file, and its .class file must be in the same Tools folder as
MarsTool.class.

Returns:
a Tools JMenu if qualifying tool classes are found, otherwise null

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsProgramArgumentsAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsProgramArgumentsAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsProgramArgumentsAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsProgramArgumentsAction
extends GuiAction

Action class for the Settings menu item to control whether or not
program arguments can be entered and used. If so, a text field
will be displayed where they can be interactively entered.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsProgramArgumentsAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsProgramArgumentsAction

public SettingsProgramArgumentsAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.venus

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object javax.swing.AbstractAction (implements javax.swing.Action, java.lang.Cloneable, java.io.Serializable)
mars.venus.GuiAction mars.venus.EditCopyAction
mars.venus.EditCutAction
mars.venus.EditFindReplaceAction
mars.venus.EditPasteAction
mars.venus.EditRedoAction
mars.venus.EditSelectAllAction
mars.venus.EditUndoAction
mars.venus.FileCloseAction
mars.venus.FileCloseAllAction
mars.venus.FileDumpMemoryAction
mars.venus.FileExitAction
mars.venus.FileNewAction
mars.venus.FileOpenAction
mars.venus.FilePrintAction
mars.venus.FileSaveAction
mars.venus.FileSaveAllAction
mars.venus.FileSaveAsAction
mars.venus.HelpAboutAction
mars.venus.HelpHelpAction
mars.venus.RunAssembleAction
mars.venus.RunBackstepAction
mars.venus.RunClearBreakpointsAction (implements javax.swing.event.TableModelListener)

mars.venus.RunGoAction
mars.venus.RunPauseAction
mars.venus.RunResetAction
mars.venus.RunStepAction
mars.venus.RunStopAction
mars.venus.RunToggleBreakpointsAction
mars.venus.SettingsAddressDisplayBaseAction
mars.venus.SettingsAssembleAllAction
mars.venus.SettingsAssembleOnOpenAction
mars.venus.SettingsDelayedBranchingAction
mars.venus.SettingsEditorAction
mars.venus.SettingsExceptionHandlerAction
mars.venus.SettingsExtendedAction
mars.venus.SettingsHighlightingAction
mars.venus.SettingsLabelAction
mars.venus.SettingsMemoryConfigurationAction
mars.venus.SettingsPopupInputAction
mars.venus.SettingsProgramArgumentsAction
mars.venus.SettingsStartAtMainAction
mars.venus.SettingsValueDisplayBaseAction
mars.venus.SettingsWarningsAreErrorsAction

mars.venus.ToolAction

java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
java.awt.Container javax.swing.JComponent (implements java.io.Serializable)
javax.swing.AbstractButton (implements java.awt.ItemSelectable, javax.swing.SwingConstants)
javax.swing.JButton (implements javax.accessibility.Accessible)
mars.venus.RepeatButton (implements java.awt.event.ActionListener, java.awt.event.MouseListener)

javax.swing.JToggleButton (implements javax.accessibility.Accessible)
javax.swing.JCheckBox (implements javax.accessibility.Accessible)
mars.venus.NumberDisplayBaseChooser

javax.swing.JInternalFrame (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants)
mars.venus.DataSegmentWindow (implements java.util.Observer)

mars.venus.LabelsWindow
mars.venus.TextSegmentWindow

javax.swing.JLayeredPane (implements javax.accessibility.Accessible)
javax.swing.JDesktopPane (implements javax.accessibility.Accessible)
mars.venus.ExecutePane

javax.swing.JPanel (implements javax.accessibility.Accessible)
mars.venus.Coprocessor0Window (implements java.util.Observer)

mars.venus.Coprocessor1Window (implements java.awt.event.ActionListener, java.util.Observer)

mars.venus.EditPane (implements java.util.Observer)

mars.venus.RegistersWindow (implements java.util.Observer)

mars.venus.RunSpeedPanel

javax.swing.JTabbedPane (implements javax.accessibility.Accessible, java.io.Serializable, javax.swing.SwingConstants)
mars.venus.EditTabbedPane
mars.venus.MainPane
mars.venus.MessagesPane
mars.venus.RegistersPane

java.awt.Window (implements javax.accessibility.Accessible)
java.awt.Dialog javax.swing.JDialog (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants)
mars.venus.AbstractFontSettingDialog

java.awt.Frame (implements java.awt.MenuContainer)
javax.swing.JFrame (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants)
mars.venus.VenusUI

mars.venus.Editor
mars.venus.FileStatus
java.awt.event.MouseAdapter (implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.MouseWheelListener)
mars.venus.PopupListener

java.lang.Throwable (implements java.io.Serializable)
java.lang.Exception mars.venus.HardcopyWriter.PrintCanceledException

mars.venus.ToolLoader
java.io.Writer (implements java.lang.Appendable, java.io.Closeable, java.io.Flushable)
mars.venus.HardcopyWriter

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

RunSpeedPanel

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RunSpeedPanel

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
mars.venus.RunSpeedPanel

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible

public class RunSpeedPanel
extends javax.swing.JPanel

Class for the Run speed slider control. One is created and can be obtained using
getInstance().

Author:
Pete Sanderson
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JPanel
javax.swing.JPanel.AccessibleJPanel

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

static double UNLIMITED_SPEED

          Constant that represents unlimited run speed.

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Method Summary

static RunSpeedPanel getInstance()

          Retrieve the run speed panel object

 double getRunSpeed()

          returns current run speed setting, in instructions/second.

 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

UNLIMITED_SPEED

public static final double UNLIMITED_SPEED

Constant that represents unlimited run speed. Compare with return value of
getRunSpeed() to determine if set to unlimited. At the unlimited setting, the GUI
will not attempt to update register and memory contents as each instruction
is executed. This is the only possible value for command-line use of Mars.

See Also:
Constant Field Values

Method Detail

getInstance

public static RunSpeedPanel getInstance()

Retrieve the run speed panel object

Returns:
the run speed panel

getRunSpeed

public double getRunSpeed()

returns current run speed setting, in instructions/second. Unlimited speed
setting is equal to RunSpeedPanel.UNLIMITED_SPEED

Returns:
run speed setting in instructions/second.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class GuiAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

Direct Known Subclasses:
EditCopyAction, EditCutAction, EditFindReplaceAction, EditPasteAction, EditRedoAction, EditSelectAllAction, EditUndoAction, FileCloseAction, FileCloseAllAction, FileDumpMemoryAction, FileExitAction, FileNewAction, FileOpenAction, FilePrintAction, FileSaveAction, FileSaveAllAction, FileSaveAsAction, HelpAboutAction, HelpHelpAction, RunAssembleAction, RunBackstepAction, RunClearBreakpointsAction, RunGoAction, RunPauseAction, RunResetAction, RunStepAction, RunStopAction, RunToggleBreakpointsAction, SettingsAddressDisplayBaseAction, SettingsAssembleAllAction, SettingsAssembleOnOpenAction, SettingsDelayedBranchingAction, SettingsEditorAction, SettingsExceptionHandlerAction, SettingsExtendedAction, SettingsHighlightingAction, SettingsLabelAction, SettingsMemoryConfigurationAction, SettingsPopupInputAction, SettingsProgramArgumentsAction, SettingsStartAtMainAction, SettingsValueDisplayBaseAction, SettingsWarningsAreErrorsAction

public class GuiAction
extends javax.swing.AbstractAction

parent class for Action subclasses to be defined for every menu/toolbar
option.

See Also:
Serialized Form

Field Summary

protected  VenusUI mainUI

           

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary

protected GuiAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

mainUI

protected VenusUI mainUI

Constructor Detail

GuiAction

protected GuiAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

does nothing by default. Should be over-ridden by subclass

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FileSaveAsAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FileSaveAsAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.FileSaveAsAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class FileSaveAsAction
extends GuiAction

Action for the File -> Save As menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
FileSaveAsAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

FileSaveAsAction

public FileSaveAsAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

VenusUI

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class VenusUI

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
mars.venus.VenusUI

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants

public class VenusUI
extends javax.swing.JFrame

Top level container for Venus GUI.

Author:
Sanderson and Team JSpim
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame

 

Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 javax.swing.JMenuBar menu

           

 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
VenusUI(java.lang.String s)

          Constructor for the Class.

 

Method Summary

 void dispatchEventToMenu(java.awt.event.KeyEvent evt)

          Send keyboard event to menu for possible processing.

 javax.swing.JCheckBoxMenuItem getAddressDisplayBaseMenuItem()

          Get reference to settings menu item for display base of memory/register values.

 Editor getEditor()

          Get reference to Editor object associated with this GUI.

 MainPane getMainPane()

          Get reference to messages pane associated with this GUI.

static int getMenuState()

          Get current menu state.

 MessagesPane getMessagesPane()

          Get reference to messages pane associated with this GUI.

 RegistersPane getRegistersPane()

          Get reference to registers pane associated with this GUI.

static boolean getReset()

          To find out whether the register values are reset.

 javax.swing.Action getRunAssembleAction()

          Return reference tothe Run->Assemble item’s action.

static boolean getStarted()

          To find out whether MIPS program is currently executing.

 javax.swing.JCheckBoxMenuItem getValueDisplayBaseMenuItem()

          Get reference to settings menu item for display base of memory/register values.

 void haveMenuRequestFocus()

          Have the menu request keyboard focus.

static void setReset(boolean b)

          To set whether the register values are reset.

static void setStarted(boolean b)

          To set whether MIPS program execution has started.

 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent

 

Field Detail

menu

public javax.swing.JMenuBar menu

Constructor Detail

VenusUI

public VenusUI(java.lang.String s)

Constructor for the Class. Sets up a window object for the UI

Parameters:
s – Name of the window to be created.

Method Detail

getMenuState

public static int getMenuState()

Get current menu state. State values are constants in FileStatus class. DPS 23 July 2008

Returns:
current menu state.

setReset

public static void setReset(boolean b)

To set whether the register values are reset.

Parameters:
b – Boolean true if the register values have been reset.

setStarted

public static void setStarted(boolean b)

To set whether MIPS program execution has started.

Parameters:
b – true if the MIPS program execution has started.

getReset

public static boolean getReset()

To find out whether the register values are reset.

Returns:
Boolean true if the register values have been reset.

getStarted

public static boolean getStarted()

To find out whether MIPS program is currently executing.

Returns:
true if MIPS program is currently executing.

getEditor

public Editor getEditor()

Get reference to Editor object associated with this GUI.

Returns:
Editor for the GUI.

getMainPane

public MainPane getMainPane()

Get reference to messages pane associated with this GUI.

Returns:
MessagesPane object associated with the GUI.

getMessagesPane

public MessagesPane getMessagesPane()

Get reference to messages pane associated with this GUI.

Returns:
MessagesPane object associated with the GUI.

getRegistersPane

public RegistersPane getRegistersPane()

Get reference to registers pane associated with this GUI.

Returns:
RegistersPane object associated with the GUI.

getValueDisplayBaseMenuItem

public javax.swing.JCheckBoxMenuItem getValueDisplayBaseMenuItem()

Get reference to settings menu item for display base of memory/register values.

Returns:
the menu item

getAddressDisplayBaseMenuItem

public javax.swing.JCheckBoxMenuItem getAddressDisplayBaseMenuItem()

Get reference to settings menu item for display base of memory/register values.

Returns:
the menu item

getRunAssembleAction

public javax.swing.Action getRunAssembleAction()

Return reference tothe Run->Assemble item’s action. Needed by File->Open in case
assemble-upon-open flag is set.

Returns:
the Action object for the Run->Assemble operation.

haveMenuRequestFocus

public void haveMenuRequestFocus()

Have the menu request keyboard focus. DPS 5-4-10

dispatchEventToMenu

public void dispatchEventToMenu(java.awt.event.KeyEvent evt)

Send keyboard event to menu for possible processing. DPS 5-4-10

Parameters:
evt – KeyEvent for menu component to consider for processing.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MainPane

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class MainPane

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JTabbedPane
mars.venus.MainPane

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.SwingConstants

public class MainPane
extends javax.swing.JTabbedPane

Creates the tabbed areas in the UI and also created the internal windows that
exist in them.

Author:
Sanderson and Bumgarner
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JTabbedPane
javax.swing.JTabbedPane.AccessibleJTabbedPane, javax.swing.JTabbedPane.ModelListener

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JTabbedPane
changeEvent, changeListener, model, SCROLL_TAB_LAYOUT, tabPlacement, WRAP_TAB_LAYOUT

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
MainPane(VenusUI appFrame,
Editor editor,
RegistersWindow regs,
Coprocessor1Window cop1Regs,
Coprocessor0Window cop0Regs)

          Constructor for the MainPane class.

 

Method Summary

 EditPane getEditPane()

          Returns current edit pane.

 javax.swing.JComponent getEditTabbedPane()

          Returns component containing editor display

 ExecutePane getExecutePane()

          returns component containing execution-time display

 ExecutePane getExecuteTab()

          returns component containing execution-time display.

 
Methods inherited from class javax.swing.JTabbedPane
add, add, add, add, add, addChangeListener, addTab, addTab, addTab, createChangeListener, fireStateChanged, getAccessibleContext, getBackgroundAt, getBoundsAt, getChangeListeners, getComponentAt, getDisabledIconAt, getDisplayedMnemonicIndexAt, getForegroundAt, getIconAt, getMnemonicAt, getModel, getSelectedComponent, getSelectedIndex, getTabComponentAt, getTabCount, getTabLayoutPolicy, getTabPlacement, getTabRunCount, getTitleAt, getToolTipText, getToolTipTextAt, getUI, getUIClassID, indexAtLocation, indexOfComponent, indexOfTab, indexOfTab, indexOfTabComponent, insertTab, isEnabledAt, paramString, remove, remove, removeAll, removeChangeListener, removeTabAt, setBackgroundAt, setComponentAt, setDisabledIconAt, setDisplayedMnemonicIndexAt, setEnabledAt, setForegroundAt, setIconAt, setMnemonicAt, setModel, setSelectedComponent, setSelectedIndex, setTabComponentAt, setTabLayoutPolicy, setTabPlacement, setTitleAt, setToolTipTextAt, setUI, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

MainPane

public MainPane(VenusUI appFrame,
Editor editor,
RegistersWindow regs,
Coprocessor1Window cop1Regs,
Coprocessor0Window cop0Regs)

Constructor for the MainPane class.

Method Detail

getEditPane

public EditPane getEditPane()

Returns current edit pane. Implementation changed for MARS 4.0 support
for multiple panes, but specification is same.

Returns:
the editor pane

getEditTabbedPane

public javax.swing.JComponent getEditTabbedPane()

Returns component containing editor display

Returns:
the editor tabbed pane

getExecutePane

public ExecutePane getExecutePane()

returns component containing execution-time display

Returns:
the execute pane

getExecuteTab

public ExecutePane getExecuteTab()

returns component containing execution-time display.
Same as getExecutePane().

Returns:
the execute pane

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RunBackstepAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RunBackstepAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.RunBackstepAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class RunBackstepAction
extends GuiAction

Action for the Run -> Backstep menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
RunBackstepAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          perform next simulated instruction step.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

RunBackstepAction

public RunBackstepAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

perform next simulated instruction step.

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

FileCloseAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class FileCloseAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.FileCloseAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class FileCloseAction
extends GuiAction

Action for the File -> Close menu item

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
FileCloseAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

FileCloseAction

public FileCloseAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsPopupInputAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsPopupInputAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsPopupInputAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsPopupInputAction
extends GuiAction

Action class for the Settings menu item to control use of popup dialog for input syscalls.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsPopupInputAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsPopupInputAction

public SettingsPopupInputAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RunStopAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class RunStopAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.RunStopAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class RunStopAction
extends GuiAction

Action class for the Run -> Stop menu item (and toolbar icon)

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
RunStopAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

RunStopAction

public RunStopAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsAssembleOnOpenAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsAssembleOnOpenAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsAssembleOnOpenAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsAssembleOnOpenAction
extends GuiAction

Action class for the Settings menu item to control automatic assemble of file upon opening.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsAssembleOnOpenAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsAssembleOnOpenAction

public SettingsAssembleOnOpenAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsExceptionHandlerAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsExceptionHandlerAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsExceptionHandlerAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsExceptionHandlerAction
extends GuiAction

Action class for the Settings menu item for optionally loading a MIPS exception handler.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsExceptionHandlerAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsExceptionHandlerAction

public SettingsExceptionHandlerAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SettingsValueDisplayBaseAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class SettingsValueDisplayBaseAction

java.lang.Object
javax.swing.AbstractAction
mars.venus.GuiAction
mars.venus.SettingsValueDisplayBaseAction

All Implemented Interfaces:
java.awt.event.ActionListener, java.io.Serializable, java.lang.Cloneable, java.util.EventListener, javax.swing.Action

public class SettingsValueDisplayBaseAction
extends GuiAction

Action class for the Settings menu item to control number base (10 or 16) of memory/register contents.

See Also:
Serialized Form

Field Summary

 
Fields inherited from class mars.venus.GuiAction
mainUI

 
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled

 
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, DISPLAYED_MNEMONIC_INDEX_KEY, LARGE_ICON_KEY, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SELECTED_KEY, SHORT_DESCRIPTION, SMALL_ICON

 

Constructor Summary
SettingsValueDisplayBaseAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

           

 

Method Summary

 void actionPerformed(java.awt.event.ActionEvent e)

          does nothing by default.

 
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled

 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SettingsValueDisplayBaseAction

public SettingsValueDisplayBaseAction(java.lang.String name,
javax.swing.Icon icon,
java.lang.String descrip,
java.lang.Integer mnemonic,
javax.swing.KeyStroke accel,
VenusUI gui)

Method Detail

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)

Description copied from class: GuiAction
does nothing by default. Should be over-ridden by subclass

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Overrides:
actionPerformed in class GuiAction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

AbstractFontSettingDialog

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class AbstractFontSettingDialog

java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Dialog
javax.swing.JDialog
mars.venus.AbstractFontSettingDialog

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants

public abstract class AbstractFontSettingDialog
extends javax.swing.JDialog

Abstract class for a font selection dialog.

See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JDialog
javax.swing.JDialog.AccessibleJDialog

 

Nested classes/interfaces inherited from class java.awt.Dialog
java.awt.Dialog.AccessibleAWTDialog, java.awt.Dialog.ModalExclusionType, java.awt.Dialog.ModalityType

 

Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

protected  java.awt.Font currentFont

           

 
Fields inherited from class javax.swing.JDialog
accessibleContext, rootPane, rootPaneCheckingEnabled

 
Fields inherited from class java.awt.Dialog
DEFAULT_MODALITY_TYPE

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, EXIT_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
AbstractFontSettingDialog(java.awt.Frame owner,
java.lang.String title,
boolean modality,
java.awt.Font currentFont)

          Create a new font chooser.

 

Method Summary

protected abstract  void apply(java.awt.Font font)

          Apply the given font.

protected abstract  java.awt.Component buildControlPanel()

           

protected  javax.swing.JPanel buildDialogPanel()

           

protected  void closeDialog()

           

 java.awt.Font getFont()

           

protected  void performApply()

           

protected  void reset()

           

 
Methods inherited from class javax.swing.JDialog
addImpl, createRootPane, dialogInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update

 
Methods inherited from class java.awt.Dialog
addNotify, getModalityType, getTitle, hide, isModal, isResizable, isUndecorated, setModal, setModalityType, setResizable, setTitle, setUndecorated, setVisible, show, toBack

 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeNotify, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImage, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, toFront

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

currentFont

protected java.awt.Font currentFont

Constructor Detail

AbstractFontSettingDialog

public AbstractFontSettingDialog(java.awt.Frame owner,
java.lang.String title,
boolean modality,
java.awt.Font currentFont)

Create a new font chooser. Has pertinent JDialog parameters.
Will do everything except make it visible.

Method Detail

buildDialogPanel

protected javax.swing.JPanel buildDialogPanel()

buildControlPanel

protected abstract java.awt.Component buildControlPanel()

getFont

public java.awt.Font getFont()

Specified by:
getFont in interface java.awt.MenuContainer
Overrides:
getFont in class java.awt.Component

performApply

protected void performApply()

closeDialog

protected void closeDialog()

reset

protected void reset()

apply

protected abstract void apply(java.awt.Font font)

Apply the given font. Left for the client to define.

Parameters:
font – a font to be applied by the client.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

LabelsWindow

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.venus

Class LabelsWindow

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JInternalFrame
mars.venus.LabelsWindow

All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants

public class LabelsWindow
extends javax.swing.JInternalFrame

Represents the Labels window, which is a type of JInternalFrame. Venus user
can view MIPS program labels.

Author:
Sanderson and Team JSpim
See Also:
Serialized Form

Nested Class Summary

 
Nested classes/interfaces inherited from class javax.swing.JInternalFrame
javax.swing.JInternalFrame.AccessibleJInternalFrame, javax.swing.JInternalFrame.JDesktopIcon

 

Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent

 

Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer

 

Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy

 

Field Summary

 
Fields inherited from class javax.swing.JInternalFrame
closable, CONTENT_PANE_PROPERTY, desktopIcon, FRAME_ICON_PROPERTY, frameIcon, GLASS_PANE_PROPERTY, iconable, IS_CLOSED_PROPERTY, IS_ICON_PROPERTY, IS_MAXIMUM_PROPERTY, IS_SELECTED_PROPERTY, isClosed, isIcon, isMaximum, isSelected, LAYERED_PANE_PROPERTY, maximizable, MENU_BAR_PROPERTY, resizable, ROOT_PANE_PROPERTY, rootPane, rootPaneCheckingEnabled, title, TITLE_PROPERTY

 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW

 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, EXIT_ON_CLOSE, HIDE_ON_CLOSE

 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

 

Constructor Summary
LabelsWindow()

          Constructor for the Labels (symbol table) window.

 

Method Summary

 void clearWindow()

          Clear the window

 void setupTable()

          Initialize table of labels (symbol table)

 void updateLabelAddresses()

          Method to update display of label addresses.

 
Methods inherited from class javax.swing.JInternalFrame
addImpl, addInternalFrameListener, createRootPane, dispose, doDefaultCloseAction, fireInternalFrameEvent, getAccessibleContext, getContentPane, getDefaultCloseOperation, getDesktopIcon, getDesktopPane, getFocusCycleRootAncestor, getFocusOwner, getFrameIcon, getGlassPane, getInternalFrameListeners, getJMenuBar, getLastCursor, getLayer, getLayeredPane, getMenuBar, getMostRecentFocusOwner, getNormalBounds, getRootPane, getTitle, getUI, getUIClassID, getWarningString, hide, isClosable, isClosed, isFocusCycleRoot, isIcon, isIconifiable, isMaximizable, isMaximum, isResizable, isRootPaneCheckingEnabled, isSelected, moveToBack, moveToFront, pack, paintComponent, paramString, remove, removeInternalFrameListener, reshape, restoreSubcomponentFocus, setClosable, setClosed, setContentPane, setCursor, setDefaultCloseOperation, setDesktopIcon, setFocusCycleRoot, setFrameIcon, setGlassPane, setIcon, setIconifiable, setJMenuBar, setLayer, setLayer, setLayeredPane, setLayout, setMaximizable, setMaximum, setMenuBar, setNormalBounds, setResizable, setRootPane, setRootPaneCheckingEnabled, setSelected, setTitle, setUI, show, toBack, toFront, updateUI

 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update

 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, transferFocusBackward, transferFocusDownCycle, validate, validateTree

 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, size, toString, transferFocus, transferFocusUpCycle

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

LabelsWindow

public LabelsWindow()

Constructor for the Labels (symbol table) window.

Method Detail

setupTable

public void setupTable()

Initialize table of labels (symbol table)

clearWindow

public void clearWindow()

Clear the window

updateLabelAddresses

public void updateLabelAddresses()

Method to update display of label addresses. Since label information doesn’t change,
this should only be done when address base is changed.
(e.g. between base 16 hex and base 10 dec).

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

Class ProcessingException

java.lang.Object
java.lang.Throwable
java.lang.Exception
mars.ProcessingException

All Implemented Interfaces:
java.io.Serializable

public class ProcessingException
extends java.lang.Exception

Class to represent error that occurs while assembling or running a MIPS program.

Author:
Pete Sanderson
See Also:
Serialized Form

Constructor Summary
ProcessingException()

          Constructor for ProcessingException.
ProcessingException(ErrorList e)

          Constructor for ProcessingException.
ProcessingException(ProgramStatement ps,
AddressErrorException aee)

          Constructor for ProcessingException to handle address runtime exceptions
ProcessingException(ProgramStatement ps,
java.lang.String m)

          Constructor for ProcessingException to handle runtime exceptions
ProcessingException(ProgramStatement ps,
java.lang.String m,
int cause)

          Constructor for ProcessingException to handle runtime exceptions

 

Method Summary

 ErrorList errors()

          Produce the list of error messages.

 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

ProcessingException

public ProcessingException(ErrorList e)

Constructor for ProcessingException.

Parameters:
e – An ErrorList which is an ArrayList of ErrorMessage objects. Each ErrorMessage
represents one processing error.

ProcessingException

public ProcessingException(ProgramStatement ps,
java.lang.String m)

Constructor for ProcessingException to handle runtime exceptions

Parameters:
ps – a ProgramStatement of statement causing runtime exception
m – a String containing specialized error message

ProcessingException

public ProcessingException(ProgramStatement ps,
java.lang.String m,
int cause)

Constructor for ProcessingException to handle runtime exceptions

Parameters:
ps – a ProgramStatement of statement causing runtime exception
m – a String containing specialized error message
cause – exception cause (see Exceptions class for list)

ProcessingException

public ProcessingException(ProgramStatement ps,
AddressErrorException aee)

Constructor for ProcessingException to handle address runtime exceptions

Parameters:
ps – a ProgramStatement of statement causing runtime exception
aee – AddressErrorException object containing specialized error message, cause, address

ProcessingException

public ProcessingException()

Constructor for ProcessingException.

No parameter and thus no error list. Use this for normal MIPS
program termination (e.g. syscall 10 for exit).

Method Detail

errors

public ErrorList errors()

Produce the list of error messages.

Returns:
Returns ErrorList of error messages.
See Also:
ErrorList,
ErrorMessage

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

ErrorList

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

Class ErrorList

java.lang.Object
mars.ErrorList

public class ErrorList
extends java.lang.Object

Maintains list of generated error messages, regardless of source (tokenizing, parsing,
assembly, execution).

Author:
Pete Sanderson

Field Summary

static java.lang.String ERROR_MESSAGE_PREFIX

           

static java.lang.String FILENAME_PREFIX

           

static java.lang.String LINE_PREFIX

           

static java.lang.String MESSAGE_SEPARATOR

           

static java.lang.String POSITION_PREFIX

           

static java.lang.String WARNING_MESSAGE_PREFIX

           

 

Constructor Summary
ErrorList()

          Constructor for ErrorList

 

Method Summary

 void add(ErrorMessage mess)

          Add new error message to end of list.

 void add(ErrorMessage mess,
int index)

          Add new error message at specified index position.

 int errorCount()

          Count of number of error messages in list.

 boolean errorLimitExceeded()

          Check to see if error limit has been exceeded.

 boolean errorsOccurred()

          Determine whether error has occured or not.

 java.lang.String generateErrorAndWarningReport()

          Produce report containing both warnings and errors, warnings first.

 java.lang.String generateErrorReport()

          Produce error report.

 java.lang.String generateWarningReport()

          Produce warning report.

 int getErrorLimit()

          Get limit on number of error messages to be generated
by one assemble operation.

 java.util.ArrayList getErrorMessages()

          Get ArrayList of error messages.

 int warningCount()

          Count of number of warning messages in list.

 boolean warningsOccurred()

          Determine whether warning has occured or not.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

ERROR_MESSAGE_PREFIX

public static final java.lang.String ERROR_MESSAGE_PREFIX

See Also:
Constant Field Values

WARNING_MESSAGE_PREFIX

public static final java.lang.String WARNING_MESSAGE_PREFIX

See Also:
Constant Field Values

FILENAME_PREFIX

public static final java.lang.String FILENAME_PREFIX

See Also:
Constant Field Values

LINE_PREFIX

public static final java.lang.String LINE_PREFIX

See Also:
Constant Field Values

POSITION_PREFIX

public static final java.lang.String POSITION_PREFIX

See Also:
Constant Field Values

MESSAGE_SEPARATOR

public static final java.lang.String MESSAGE_SEPARATOR

See Also:
Constant Field Values

Constructor Detail

ErrorList

public ErrorList()

Constructor for ErrorList

Method Detail

getErrorMessages

public java.util.ArrayList getErrorMessages()

Get ArrayList of error messages.

Returns:
ArrayList of ErrorMessage objects

errorsOccurred

public boolean errorsOccurred()

Determine whether error has occured or not.

Returns:
true if an error has occurred (does not include warnings), false otherwise.

warningsOccurred

public boolean warningsOccurred()

Determine whether warning has occured or not.

Returns:
true if an warning has occurred, false otherwise.

add

public void add(ErrorMessage mess)

Add new error message to end of list.

Parameters:
mess – ErrorMessage object to be added to end of error list.

add

public void add(ErrorMessage mess,
int index)

Add new error message at specified index position.

Parameters:
mess – ErrorMessage object to be added to end of error list.
index – position in error list

errorCount

public int errorCount()

Count of number of error messages in list.

Returns:
Number of error messages in list.

warningCount

public int warningCount()

Count of number of warning messages in list.

Returns:
Number of warning messages in list.

errorLimitExceeded

public boolean errorLimitExceeded()

Check to see if error limit has been exceeded.

Returns:
True if error limit exceeded, false otherwise.

getErrorLimit

public int getErrorLimit()

Get limit on number of error messages to be generated
by one assemble operation.

Returns:
error limit.

generateErrorReport

public java.lang.String generateErrorReport()

Produce error report.

Returns:
String containing report.

generateWarningReport

public java.lang.String generateWarningReport()

Produce warning report.

Returns:
String containing report.

generateErrorAndWarningReport

public java.lang.String generateErrorAndWarningReport()

Produce report containing both warnings and errors, warnings first.

Returns:
String containing report.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SimulationCode

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions

Interface SimulationCode

public interface SimulationCode

Interface to represent the method for simulating the execution of a specific MIPS basic
instruction. It will be implemented by the anonymous class created in the last
argument to the BasicInstruction constructor.

Author:
Pete Sanderson

Method Summary

 void simulate(ProgramStatement statement)

          Method to simulate the execution of a specific MIPS basic instruction.

 

Method Detail

simulate

void simulate(ProgramStatement statement)
throws ProcessingException

Method to simulate the execution of a specific MIPS basic instruction.

Parameters:
statement – A ProgramStatement representing the MIPS instruction to simulate.

Throws:

ProcessingException – This is a run-time exception generated during simulation.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

ExtendedInstruction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions

Class ExtendedInstruction

java.lang.Object
mars.mips.instructions.Instruction
mars.mips.instructions.ExtendedInstruction

public class ExtendedInstruction
extends Instruction

ExtendedInstruction represents a MIPS extended (a.k.a pseudo) instruction. This
assembly language instruction does not have a corresponding machine instruction. Instead
it is translated by the extended assembler into one or more basic instructions (operations
that have a corresponding machine instruction). The TranslationCode object is
responsible for performing the translation.

Author:
Pete Sanderson

Field Summary

 
Fields inherited from class mars.mips.instructions.Instruction
description, exampleFormat, INSTRUCTION_LENGTH, INSTRUCTION_LENGTH_BITS, mnemonic, operandMask, tokenList

 

Constructor Summary
ExtendedInstruction(java.lang.String example,
java.lang.String translation)

          Constructor for ExtendedInstruction, where no instruction description or
compact translation is provided.
ExtendedInstruction(java.lang.String example,
java.lang.String translation,
java.lang.String description)

          Constructor for ExtendedInstruction.
ExtendedInstruction(java.lang.String example,
java.lang.String translation,
java.lang.String compactTranslation,
java.lang.String description)

          Constructor for ExtendedInstruction.

 

Method Summary

 java.util.ArrayList getBasicIntructionTemplateList()

          Get ArrayList of Strings that represent list of templates for
basic instructions generated by this extended instruction.

 java.util.ArrayList getCompactBasicIntructionTemplateList()

          Get ArrayList of Strings that represent list of templates for
basic instructions generated by the “compact” or 16-bit version
of this extended instruction.

 int getCompactInstructionLength()

          Get length in bytes that this extended instruction requires in its
binary form if it includes an alternative expansion for compact
memory (16 bit addressing) configuration.

 int getInstructionLength()

          Get length in bytes that this extended instruction requires in its
binary form.

 boolean hasCompactTranslation()

          Determine whether or not this pseudo-instruction has a second
translation optimized for 16 bit address space: a compact version.

static java.lang.String makeTemplateSubstitutions(MIPSprogram program,
java.lang.String template,
TokenList theTokenList)

          Given a basic instruction template and the list of tokens from an extended
instruction statement, substitute operands from the token list appropriately into the
template to generate the basic statement.

 
Methods inherited from class mars.mips.instructions.Instruction
createExampleTokenList, extractOperator, getDescription, getExampleFormat, getName, getTokenList

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

ExtendedInstruction

public ExtendedInstruction(java.lang.String example,
java.lang.String translation,
java.lang.String compactTranslation,
java.lang.String description)

Constructor for ExtendedInstruction.

Parameters:
example – A String containing example use of the MIPS extended instruction.
translation – Specifications for translating this instruction into a sequence
of one or more MIPS basic instructions.
compactTranslation – Alternative translation that can be used if running under
a compact (16 bit) memory configuration.
description – a helpful description to be included on help requests

The presence of an alternative “compact translation” can optimize code generation
by assuming that data label addresses are 16 bits instead of 32

ExtendedInstruction

public ExtendedInstruction(java.lang.String example,
java.lang.String translation,
java.lang.String description)

Constructor for ExtendedInstruction. No compact translation is provided.

Parameters:
example – A String containing example use of the MIPS extended instruction.
translation – Specifications for translating this instruction into a sequence
of one or more MIPS basic instructions.
description – a helpful description to be included on help requests

ExtendedInstruction

public ExtendedInstruction(java.lang.String example,
java.lang.String translation)

Constructor for ExtendedInstruction, where no instruction description or
compact translation is provided.

Parameters:
example – A String containing example use of the MIPS extended instruction.
translation – Specifications for translating this instruction into a sequence
of one or more MIPS basic instructions.

Method Detail

getInstructionLength

public int getInstructionLength()

Get length in bytes that this extended instruction requires in its
binary form. The answer depends on how many basic instructions it
expands to. This may vary, if expansion includes a nop, depending on
whether or not delayed branches are enabled. Each requires 4 bytes.

Overrides:
getInstructionLength in class Instruction

Returns:
int length in bytes of corresponding binary instruction(s).

getBasicIntructionTemplateList

public java.util.ArrayList getBasicIntructionTemplateList()

Get ArrayList of Strings that represent list of templates for
basic instructions generated by this extended instruction.

Returns:
ArrayList of Strings.

getCompactInstructionLength

public int getCompactInstructionLength()

Get length in bytes that this extended instruction requires in its
binary form if it includes an alternative expansion for compact
memory (16 bit addressing) configuration. The answer depends on
how many basic instructions it expands to. This may vary, if
expansion includes a nop, depending on whether or not delayed
branches are enabled. Each requires 4 bytes.

Returns:
int length in bytes of corresponding binary instruction(s).
Returns 0 if an alternative expansion is not defined for this
instruction.

hasCompactTranslation

public boolean hasCompactTranslation()

Determine whether or not this pseudo-instruction has a second
translation optimized for 16 bit address space: a compact version.

getCompactBasicIntructionTemplateList

public java.util.ArrayList getCompactBasicIntructionTemplateList()

Get ArrayList of Strings that represent list of templates for
basic instructions generated by the “compact” or 16-bit version
of this extended instruction.

Returns:
ArrayList of Strings. Returns null if the instruction does not
have a compact alternative.

makeTemplateSubstitutions

public static java.lang.String makeTemplateSubstitutions(MIPSprogram program,
java.lang.String template,
TokenList theTokenList)

Given a basic instruction template and the list of tokens from an extended
instruction statement, substitute operands from the token list appropriately into the
template to generate the basic statement. Assumes the extended instruction statement has
been translated from source form to basic assembly form (e.g. register mnemonics
translated to corresponding register numbers).
Operand format of source statement is already verified correct.
Assume the template has correct number and positions of operands.
Template is String with special markers. In the list below, n represents token position (1,2,3,etc)
in source statement (operator is token 0, parentheses count but commas don’t):
RGn means substitute register found in n’th token of source statement

NRn means substitute next higher register than the one in n’th token of source code

OPn means substitute n’th token of source code as is

LLn means substitute low order 16 bits from label address in source token n.

LLnU means substitute low order 16 bits (unsigned) from label address in source token n.

LLnPm (m=1,2,3,4) means substitute low order 16 bits from label address in source token n, after adding m.

LHn means substitute high order 16 bits from label address in source token n. Must add 1 if address bit 15 is 1.

LHnPm (m=1,2,3,4) means substitute high order 16 bits from label address in source token n, after adding m. Must then add 1 if bit 15 is 1.

VLn means substitute low order 16 bits from 32 bit value in source token n.

VLnU means substitute low order 16 bits (unsigned) from 32 bit value in source token n.

VLnPm (m=1,2,3,4) means substitute low order 16 bits from 32 bit value in source token n, after adding m to value.

VLnPmU (m=1,2,3,4) means substitute low order 16 bits (unsigned) from 32 bit value in source token n, after adding m to value.

VHLn means substitute high order 16 bits from 32 bit value in source token n. Use this if later combined with low order 16 bits using “ori $1,$1,VLn”. See logical and branch operations.

VHn means substitute high order 16 bits from 32 bit value in source token n, then add 1 if value’s bit 15 is 1. Use this only if later instruction uses VLn($1) to calculate 32 bit address. See loads and stores.

VHLnPm (m=1,2,3,4) means substitute high order 16 bits from 32 bit value in source token n, after adding m. See VHLn.

VHnPm (m=1,2,3,4) means substitute high order 16 bits from 32 bit value in source token n, after adding m. Must then add 1 if bit 15 is 1. See VHn.

LLP is similar to LLn, but is needed for “label+100000” address offset. Immediate is added before taking low order 16.

LLPU is similar to LLnU, but is needed for “label+100000” address offset. Immediate is added before taking low order 16 (unsigned).

LLPPm (m=1,2,3,4) is similar to LLP except m is added along with mmediate before taking low order 16.

LHPA is similar to LHn, but is needed for “label+100000” address offset. Immediate is added before taking high order 16.

LHPN is similar to LHPA, used only by “la” instruction. Address resolved by “ori” so do not add 1 if bit 15 is 1.

LHPAPm (m=1,2,3,4) is similar to LHPA except value m is added along with immediate before taking high order 16.

LHL means substitute high order 16 bits from label address in token 2 of “la” (load address) source statement.

LAB means substitute textual label from last token of source statement. Used for various branches.

S32 means substitute the result of subtracting the constant value in last token from 32. Used by “ror”, “rol”.

DBNOP means Delayed Branching NOP – generate a “nop” instruction but only if delayed branching is enabled. Added in 3.4.1 release.

BROFFnm means substitute n if delayed branching is NOT enabled otherwise substitute m. n and m are single digit numbers indicating constant branch offset (in words). Added in 3.4.1 release.

Parameters:
template – a String containing template for basic statement.
tokenList – a TokenList containing tokens from extended instruction.

Returns:
String representing basic assembler statement.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions

mars.mips.instructions

Interfaces 

SimulationCode

Classes 

BasicInstruction

BasicInstructionFormat

ExtendedInstruction

Instruction

InstructionSet

BasicInstructionFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions

Class BasicInstructionFormat

java.lang.Object
mars.mips.instructions.BasicInstructionFormat

public class BasicInstructionFormat
extends java.lang.Object

These are the MIPS-defined formats of basic machine instructions. The R-format indicates
the instruction works only with registers. The I-format indicates the instruction
works with an immediate value (e.g. constant). The J-format indicates this is a Jump
instruction. The I-branch-format is defined by me, not MIPS, to to indicate this is
a Branch instruction, specifically to distinguish immediate
values used as target addresses.

Author:
Pete Sanderson

Field Summary

static BasicInstructionFormat I_BRANCH_FORMAT

           

static BasicInstructionFormat I_FORMAT

           

static BasicInstructionFormat J_FORMAT

           

static BasicInstructionFormat R_FORMAT

           

 

Method Summary

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

R_FORMAT

public static final BasicInstructionFormat R_FORMAT

I_FORMAT

public static final BasicInstructionFormat I_FORMAT

I_BRANCH_FORMAT

public static final BasicInstructionFormat I_BRANCH_FORMAT

J_FORMAT

public static final BasicInstructionFormat J_FORMAT

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.mips.instructions

Interface Summary
SimulationCode Interface to represent the method for simulating the execution of a specific MIPS basic
instruction.

 

Class Summary
BasicInstruction Class to represent a basic instruction in the MIPS instruction set.
BasicInstructionFormat These are the MIPS-defined formats of basic machine instructions.
ExtendedInstruction ExtendedInstruction represents a MIPS extended (a.k.a pseudo) instruction.
Instruction Base class to represent member of MIPS instruction set.
InstructionSet The list of Instruction objects, each of which represents a MIPS instruction.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

mars.mips.instructions Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.mips.instructions

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object mars.mips.instructions.BasicInstructionFormat
mars.mips.instructions.Instruction mars.mips.instructions.BasicInstruction
mars.mips.instructions.ExtendedInstruction

mars.mips.instructions.InstructionSet

Interface Hierarchy

mars.mips.instructions.SimulationCode

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Instruction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions

Class Instruction

java.lang.Object
mars.mips.instructions.Instruction

Direct Known Subclasses:
BasicInstruction, ExtendedInstruction

public abstract class Instruction
extends java.lang.Object

Base class to represent member of MIPS instruction set.

Author:
Pete Sanderson and Ken Vollmar

Field Summary

protected  java.lang.String description

          Description of instruction for display to user

protected  java.lang.String exampleFormat

          Example usage of this instruction.

static int INSTRUCTION_LENGTH

          Length in bytes of a machine instruction.

static int INSTRUCTION_LENGTH_BITS

           

protected  java.lang.String mnemonic

          The instruction name.

static char[] operandMask

          Characters used in instruction mask to indicate bit positions
for ‘f’irst, ‘s’econd, and ‘t’hird operands.

protected  TokenList tokenList

          List of tokens generated by tokenizing example usage (see exampleFormat).

 

Constructor Summary
Instruction()

           

 

Method Summary

protected  void createExampleTokenList()

          Used to build a token list from the example instruction
provided as constructor argument.

protected  java.lang.String extractOperator(java.lang.String example)

          Used by subclass constructors to extract operator mnemonic from the
instruction example.

 java.lang.String getDescription()

          Get string describing the instruction.

 java.lang.String getExampleFormat()

          Get string descriptor of instruction’s format.

 int getInstructionLength()

          Get length in bytes that this instruction requires in its binary form.

 java.lang.String getName()

          Get operation mnemonic

 TokenList getTokenList()

          Get TokenList corresponding to correct instruction syntax.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

INSTRUCTION_LENGTH

public static final int INSTRUCTION_LENGTH

Length in bytes of a machine instruction. MIPS is a RISC architecture
so all instructions are the same length. Currently set to 4.

See Also:
Constant Field Values

INSTRUCTION_LENGTH_BITS

public static final int INSTRUCTION_LENGTH_BITS

See Also:
Constant Field Values

operandMask

public static char[] operandMask

Characters used in instruction mask to indicate bit positions
for ‘f’irst, ‘s’econd, and ‘t’hird operands.

mnemonic

protected java.lang.String mnemonic

The instruction name.

exampleFormat

protected java.lang.String exampleFormat

Example usage of this instruction. Is provided as subclass constructor argument.

description

protected java.lang.String description

Description of instruction for display to user

tokenList

protected TokenList tokenList

List of tokens generated by tokenizing example usage (see exampleFormat).

Constructor Detail

Instruction

public Instruction()

Method Detail

getName

public java.lang.String getName()

Get operation mnemonic

Returns:
operation mnemonic (e.g. addi, sw)

getExampleFormat

public java.lang.String getExampleFormat()

Get string descriptor of instruction’s format. This is an example MIPS
assembler instruction usage which contains the operator and all operands.
Operands are separated by commas, an operand that begins with a ‘$’
represents a register, and an integer operand represents an immediate value
or address. Here are two examples: “nor $1,$2,$3” and “sw $1,100($2)”

Returns:
String representing example instruction format.

getDescription

public java.lang.String getDescription()

Get string describing the instruction. This is not used internally by
MARS, but is for display to the user.

Returns:
String describing the instruction.

getTokenList

public TokenList getTokenList()

Get TokenList corresponding to correct instruction syntax.
For example, the instruction with format “sw $1,100($2)” yields token list

Returns:
TokenList object representing correct instruction usage.

getInstructionLength

public int getInstructionLength()

Get length in bytes that this instruction requires in its binary form.
Default is 4 (holds for all basic instructions), but can be overridden
in subclass.

Returns:
int length in bytes of corresponding binary instruction(s).

extractOperator

protected java.lang.String extractOperator(java.lang.String example)

Used by subclass constructors to extract operator mnemonic from the
instruction example.

createExampleTokenList

protected void createExampleTokenList()

Used to build a token list from the example instruction
provided as constructor argument. Parser uses this for syntax checking.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

InstructionSet

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions

Class InstructionSet

java.lang.Object
mars.mips.instructions.InstructionSet

public class InstructionSet
extends java.lang.Object

The list of Instruction objects, each of which represents a MIPS instruction.
The instruction may either be basic (translates into binary machine code) or
extended (translates into sequence of one or more basic instructions).

Author:
Pete Sanderson and Ken Vollmar

Constructor Summary
InstructionSet()

          Creates a new InstructionSet object.

 

Method Summary

 java.util.ArrayList getInstructionList()

          Retrieve the current instruction set.

 java.util.ArrayList matchOperator(java.lang.String name)

          Given an operator mnemonic, will return the corresponding Instruction object(s)
from the instruction set.

 void populate()

          Adds all instructions to the set.

 java.util.ArrayList prefixMatchOperator(java.lang.String name)

          Given a string, will return the Instruction object(s) from the instruction
set whose operator mnemonic prefix matches it.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

InstructionSet

public InstructionSet()

Creates a new InstructionSet object.

Method Detail

getInstructionList

public java.util.ArrayList getInstructionList()

Retrieve the current instruction set.

populate

public void populate()

Adds all instructions to the set. A given extended instruction may have
more than one Instruction object, depending on how many formats it can have.

See Also:
Instruction,
BasicInstruction,
ExtendedInstruction

matchOperator

public java.util.ArrayList matchOperator(java.lang.String name)

Given an operator mnemonic, will return the corresponding Instruction object(s)
from the instruction set. Uses straight linear search technique.

Parameters:
name – operator mnemonic (e.g. addi, sw,…)

Returns:
list of corresponding Instruction object(s), or null if not found.

prefixMatchOperator

public java.util.ArrayList prefixMatchOperator(java.lang.String name)

Given a string, will return the Instruction object(s) from the instruction
set whose operator mnemonic prefix matches it. Case-insensitive. For example
“s” will match “sw”, “sh”, “sb”, etc. Uses straight linear search technique.

Parameters:
name – a string

Returns:
list of matching Instruction object(s), or null if none match.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallPrintString

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallPrintString

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallPrintString

All Implemented Interfaces:
Syscall

public class SyscallPrintString
extends AbstractSyscall

Service to display string stored starting at address in $a0 onto the console.

Constructor Summary
SyscallPrintString()

          Build an instance of the Print String syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to print string stored starting at address in $a0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallPrintString

public SyscallPrintString()

Build an instance of the Print String syscall. Default service number
is 4 and name is “PrintString”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to print string stored starting at address in $a0.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallPrintIntBinary

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallPrintIntBinary

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallPrintIntBinary

All Implemented Interfaces:
Syscall

public class SyscallPrintIntBinary
extends AbstractSyscall

Service to display integer stored in $a0 on the console.

Constructor Summary
SyscallPrintIntBinary()

          Build an instance of the Print Integer syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to print on the console the integer stored in $a0, in hexadecimal format.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallPrintIntBinary

public SyscallPrintIntBinary()

Build an instance of the Print Integer syscall. Default service number
is 1 and name is “PrintInt”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to print on the console the integer stored in $a0, in hexadecimal format.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallMidiOut

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallMidiOut

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallMidiOut

All Implemented Interfaces:
Syscall

public class SyscallMidiOut
extends AbstractSyscall

Service to output simulated MIDI tone to sound card. The call returns
immediately upon generating the tone. By contrast, syscall 33
(MidiOutSync) does not return until tone duration has elapsed.

Constructor Summary
SyscallMidiOut()

          Build an instance of the MIDI (simulated) out syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to send MIDI output to sound card.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallMidiOut

public SyscallMidiOut()

Build an instance of the MIDI (simulated) out syscall. Default service number
is 31 and name is “MidiOut”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to send MIDI output to sound card. This requires
four arguments in registers $a0 through $a3.

$a0 – pitch (note). Integer value from 0 to 127, with 60 being middle-C on a piano.

$a1 – duration. Integer value in milliseconds.

$a2 – instrument. Integer value from 0 to 127, with 0 being acoustic grand piano.

$a3 – volume. Integer value from 0 to 127.

Default values, in case any parameters are outside the above ranges, are $a0=60, $a1=1000,
$a2=0, $a3=100.

See MARS documentation elsewhere or www.midi.org for more information. Note that the pitch,
instrument and volume value ranges 0-127 are from javax.sound.midi; actual MIDI instruments
use the range 1-128.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallMessageDialogInt

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallMessageDialogInt

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallMessageDialogInt

All Implemented Interfaces:
Syscall

public class SyscallMessageDialogInt
extends AbstractSyscall

Service to display a message to user.

Constructor Summary
SyscallMessageDialogInt()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to display a message to user.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallMessageDialogInt

public SyscallMessageDialogInt()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to display a message to user.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallExit

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallExit

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallExit

All Implemented Interfaces:
Syscall

public class SyscallExit
extends AbstractSyscall

Service to exit the MIPS program.

Constructor Summary
SyscallExit()

          Build an instance of the Exit syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to exit the MIPS program.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallExit

public SyscallExit()

Build an instance of the Exit syscall. Default service number
is 10 and name is “Exit”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to exit the MIPS program.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallInputDialogInt

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallInputDialogInt

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallInputDialogInt

All Implemented Interfaces:
Syscall

public class SyscallInputDialogInt
extends AbstractSyscall

Service to input data.

Constructor Summary
SyscallInputDialogInt()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to input data.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallInputDialogInt

public SyscallInputDialogInt()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to input data.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallReadFloat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallReadFloat

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallReadFloat

All Implemented Interfaces:
Syscall

public class SyscallReadFloat
extends AbstractSyscall

Service to read the bits of input float into $f0

Constructor Summary
SyscallReadFloat()

          Build an instance of the Read Float syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to read the bits of input float into $f0

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallReadFloat

public SyscallReadFloat()

Build an instance of the Read Float syscall. Default service number
is 6 and name is “ReadFloat”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to read the bits of input float into $f0

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallOpen

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallOpen

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallOpen

All Implemented Interfaces:
Syscall

public class SyscallOpen
extends AbstractSyscall

Service to open file name specified by $a0. File descriptor returned in $v0.
(this was changed from $a0 in MARS 3.7 for SPIM compatibility. The table
in COD erroneously shows $a0).

Constructor Summary
SyscallOpen()

          Build an instance of the Open file syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to open file name specified by $a0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallOpen

public SyscallOpen()

Build an instance of the Open file syscall. Default service number
is 13 and name is “Open”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to open file name specified by $a0. File descriptor returned
in $v0. Only supported flags ($a1) are read-only (0), write-only (1) and
write-append (9). write-only flag creates file if it does not exist, so it is technically
write-create. write-append will start writing at end of existing file.
Mode ($a2) is ignored.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallReadChar

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallReadChar

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallReadChar

All Implemented Interfaces:
Syscall

public class SyscallReadChar
extends AbstractSyscall

Service to read a character from input console into $a0.

Constructor Summary
SyscallReadChar()

          Build an instance of the Read Char syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to read a character from input console into $a0

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallReadChar

public SyscallReadChar()

Build an instance of the Read Char syscall. Default service number
is 12 and name is “ReadChar”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to read a character from input console into $a0

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallMessageDialog

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallMessageDialog

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallMessageDialog

All Implemented Interfaces:
Syscall

public class SyscallMessageDialog
extends AbstractSyscall

Service to display a message to user.

Constructor Summary
SyscallMessageDialog()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to display a message to user.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallMessageDialog

public SyscallMessageDialog()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to display a message to user.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallPrintFloat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallPrintFloat

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallPrintFloat

All Implemented Interfaces:
Syscall

public class SyscallPrintFloat
extends AbstractSyscall

Service to display on the console float whose bits are stored in $f12

Constructor Summary
SyscallPrintFloat()

          Build an instance of the Print Float syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to display float whose bits are stored in $f12

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallPrintFloat

public SyscallPrintFloat()

Build an instance of the Print Float syscall. Default service number
is 2 and name is “PrintFloat”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to display float whose bits are stored in $f12

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallSbrk

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallSbrk

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallSbrk

All Implemented Interfaces:
Syscall

public class SyscallSbrk
extends AbstractSyscall

Service to allocate amount of heap memory specified in $a0, putting address into $v0.

Constructor Summary
SyscallSbrk()

          Build an instance of the Sbrk syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to allocate amount of heap memory specified in $a0, putting address into $v0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallSbrk

public SyscallSbrk()

Build an instance of the Sbrk syscall. Default service number
is 9 and name is “Sbrk”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to allocate amount of heap memory specified in $a0, putting address into $v0.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallRandDouble

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallRandDouble

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallRandDouble

All Implemented Interfaces:
Syscall

public class SyscallRandDouble
extends AbstractSyscall

Service to return a random floating point value.

Constructor Summary
SyscallRandDouble()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to the random number generator.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallRandDouble

public SyscallRandDouble()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to the random number generator.
Return in $f0 the next pseudorandom, uniformly distributed double value between 0.0 and 1.0
from this random number generator’s sequence.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallPrintIntUnsigned

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallPrintIntUnsigned

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallPrintIntUnsigned

All Implemented Interfaces:
Syscall

public class SyscallPrintIntUnsigned
extends AbstractSyscall

Service to display integer stored in $a0 on the console as unsigned decimal.

Constructor Summary
SyscallPrintIntUnsigned()

          Build an instance of the Print Integer Unsigned syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to print on the console the integer stored in $a0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallPrintIntUnsigned

public SyscallPrintIntUnsigned()

Build an instance of the Print Integer Unsigned syscall. Default service number
is 36 and name is “PrintIntUnsigned”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to print on the console the integer stored in $a0.
The value is treated as unsigned.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallMessageDialogString

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallMessageDialogString

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallMessageDialogString

All Implemented Interfaces:
Syscall

public class SyscallMessageDialogString
extends AbstractSyscall

Service to display a message to user.

Constructor Summary
SyscallMessageDialogString()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to display a message to user.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallMessageDialogString

public SyscallMessageDialogString()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to display a message to user.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

AbstractSyscall

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class AbstractSyscall

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall

All Implemented Interfaces:
Syscall

Direct Known Subclasses:
SyscallClose, SyscallConfirmDialog, SyscallExit, SyscallExit2, SyscallInputDialogDouble, SyscallInputDialogFloat, SyscallInputDialogInt, SyscallInputDialogString, SyscallMessageDialog, SyscallMessageDialogDouble, SyscallMessageDialogFloat, SyscallMessageDialogInt, SyscallMessageDialogString, SyscallMidiOut, SyscallMidiOutSync, SyscallOpen, SyscallPrintChar, SyscallPrintDouble, SyscallPrintFloat, SyscallPrintInt, SyscallPrintIntBinary, SyscallPrintIntHex, SyscallPrintIntUnsigned, SyscallPrintString, SyscallRandDouble, SyscallRandFloat, SyscallRandInt, SyscallRandIntRange, SyscallRandSeed, SyscallRead, SyscallReadChar, SyscallReadDouble, SyscallReadFloat, SyscallReadInt, SyscallReadString, SyscallSbrk, SyscallSleep, SyscallTime, SyscallWrite

public abstract class AbstractSyscall
extends java.lang.Object
implements Syscall

Abstract class that a MIPS syscall system service may extend. A qualifying service
must be a class in the mars.mips.instructions.syscalls package that
implements the Syscall interface, must be compiled into a .class file,
and its .class file must be in the same folder as Syscall.class.
Mars will detect a qualifying syscall upon startup, create an instance
using its no-argument constructor and add it to its syscall list.
When its service is invoked at runtime (“syscall” instruction
with its service number stored in register $v0), its simulate()
method will be invoked.

Constructor Summary
AbstractSyscall(int number,
java.lang.String name)

          Constructor is provided so subclass may initialize instance variables.

 

Method Summary

 java.lang.String getName()

          Return the name you have chosen for this syscall.

 int getNumber()

          Return the assigned service number.

 void setNumber(int num)

          Set the service number.

abstract  void simulate(ProgramStatement statement)

          Performs syscall function.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

AbstractSyscall

public AbstractSyscall(int number,
java.lang.String name)

Constructor is provided so subclass may initialize instance variables.

Parameters:
number – default assigned service number
name – service name which may be used for reference independent of number

Method Detail

getName

public java.lang.String getName()

Return the name you have chosen for this syscall. This can be used by a MARS
user to refer to the service when choosing to override its default service
number in the configuration file.

Specified by:
getName in interface Syscall

Returns:
service name as a string

setNumber

public void setNumber(int num)

Set the service number. This is provided to allow MARS implementer or user
to override the default service number.

Specified by:
setNumber in interface Syscall

Parameters:
num – specified service number to override the default.

getNumber

public int getNumber()

Return the assigned service number. This is the number the MIPS programmer
must store into $v0 before issuing the SYSCALL instruction.

Specified by:
getNumber in interface Syscall

Returns:
assigned service number

simulate

public abstract void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function. It will be invoked when the service is invoked
at simulation time. Service is identified by value stored in $v0.

Specified by:
simulate in interface Syscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallInputDialogFloat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallInputDialogFloat

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallInputDialogFloat

All Implemented Interfaces:
Syscall

public class SyscallInputDialogFloat
extends AbstractSyscall

Service to input data.

Constructor Summary
SyscallInputDialogFloat()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to input data.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallInputDialogFloat

public SyscallInputDialogFloat()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to input data.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RandomStreams

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class RandomStreams

java.lang.Object
mars.mips.instructions.syscalls.RandomStreams

public class RandomStreams
extends java.lang.Object

This small class serves only to hold a static HashMap for storing
random number generators for use by all the random number generator
syscalls.

Constructor Summary
RandomStreams()

           

 

Method Summary

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

RandomStreams

public RandomStreams()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallInputDialogString

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallInputDialogString

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallInputDialogString

All Implemented Interfaces:
Syscall

public class SyscallInputDialogString
extends AbstractSyscall

Service to input data.

Constructor Summary
SyscallInputDialogString()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to input data.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallInputDialogString

public SyscallInputDialogString()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to input data.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallReadString

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallReadString

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallReadString

All Implemented Interfaces:
Syscall

public class SyscallReadString
extends AbstractSyscall

Service to read console input string into buffer starting at address in $a0.

Constructor Summary
SyscallReadString()

          Build an instance of the Read String syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to read console input string into buffer starting at address in $a0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallReadString

public SyscallReadString()

Build an instance of the Read String syscall. Default service number
is 8 and name is “ReadString”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to read console input string into buffer starting at address in $a0.
Follows semantics of UNIX ‘fgets’. For specified length n,
string can be no longer than n-1. If less than that, add
newline to end. In either case, then pad with null byte.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallPrintChar

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallPrintChar

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallPrintChar

All Implemented Interfaces:
Syscall

public class SyscallPrintChar
extends AbstractSyscall

Service to display character stored in $a0 on the console.

Constructor Summary
SyscallPrintChar()

          Build an instance of the Print Char syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to print on the console the character stored in $a0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallPrintChar

public SyscallPrintChar()

Build an instance of the Print Char syscall. Default service number
is 11 and name is “PrintChar”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to print on the console the character stored in $a0.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallRandIntRange

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallRandIntRange

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallRandIntRange

All Implemented Interfaces:
Syscall

public class SyscallRandIntRange
extends AbstractSyscall

Service to return a random integer in a specified range.

Constructor Summary
SyscallRandIntRange()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to the random number generator, with an upper range specified.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallRandIntRange

public SyscallRandIntRange()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to the random number generator, with an upper range specified.
Return in $a0 the next pseudorandom, uniformly distributed int value between 0 (inclusive)
and the specified value (exclusive), drawn from this random number generator’s sequence.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Syscall

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Interface Syscall

All Known Implementing Classes:
AbstractSyscall, SyscallClose, SyscallConfirmDialog, SyscallExit, SyscallExit2, SyscallInputDialogDouble, SyscallInputDialogFloat, SyscallInputDialogInt, SyscallInputDialogString, SyscallMessageDialog, SyscallMessageDialogDouble, SyscallMessageDialogFloat, SyscallMessageDialogInt, SyscallMessageDialogString, SyscallMidiOut, SyscallMidiOutSync, SyscallOpen, SyscallPrintChar, SyscallPrintDouble, SyscallPrintFloat, SyscallPrintInt, SyscallPrintIntBinary, SyscallPrintIntHex, SyscallPrintIntUnsigned, SyscallPrintString, SyscallRandDouble, SyscallRandFloat, SyscallRandInt, SyscallRandIntRange, SyscallRandSeed, SyscallRead, SyscallReadChar, SyscallReadDouble, SyscallReadFloat, SyscallReadInt, SyscallReadString, SyscallSbrk, SyscallSleep, SyscallTime, SyscallWrite

public interface Syscall

Interface for any MIPS syscall system service. A qualifying service
must be a class in the mars.mips.instructions.syscalls package that
implements the Syscall interface, must be compiled into a .class file,
and its .class file must be in the same folder as Syscall.class.
Mars will detect a qualifying syscall upon startup, create an instance
using its no-argument constructor and add it to its syscall list.
When its service is invoked at runtime (“syscall” instruction
with its service number stored in register $v0), its simulate()
method will be invoked.

Method Summary

 java.lang.String getName()

          Return a name you have chosen for this syscall.

 int getNumber()

          Return the assigned service number.

 void setNumber(int num)

          Set the service number.

 void simulate(ProgramStatement statement)

          Performs syscall function.

 

Method Detail

getName

java.lang.String getName()

Return a name you have chosen for this syscall. This can be used by a MARS
user to refer to the service when choosing to override its default service
number in the configuration file.

Returns:
service name as a string

setNumber

void setNumber(int num)

Set the service number. This is provided to allow MARS implementer or user
to override the default service number.

Parameters:
num – specified service number to override the default.

getNumber

int getNumber()

Return the assigned service number. This is the number the MIPS programmer
must store into $v0 before issuing the SYSCALL instruction.

Returns:
assigned service number

simulate

void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function. It will be invoked when the service is invoked
at simulation time. Service is identified by value stored in $v0.

Parameters:
statement – ProgramStatement for this syscall statement.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallTime

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallTime

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallTime

All Implemented Interfaces:
Syscall

public class SyscallTime
extends AbstractSyscall

Service to read a character from input console into $a0.

Constructor Summary
SyscallTime()

          Build an instance of the Read Char syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to place current system time into $a0 (low order 32 bits)
and $a1 (high order 32 bits).

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallTime

public SyscallTime()

Build an instance of the Read Char syscall. Default service number
is 12 and name is “ReadChar”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to place current system time into $a0 (low order 32 bits)
and $a1 (high order 32 bits).

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallRandSeed

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallRandSeed

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallRandSeed

All Implemented Interfaces:
Syscall

public class SyscallRandSeed
extends AbstractSyscall

Service to set seed for the underlying Java pseudorandom number generator. No values are returned.

Constructor Summary
SyscallRandSeed()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          Set the seed of the underlying Java pseudorandom number generator.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallRandSeed

public SyscallRandSeed()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Set the seed of the underlying Java pseudorandom number generator.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallPrintIntHex

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallPrintIntHex

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallPrintIntHex

All Implemented Interfaces:
Syscall

public class SyscallPrintIntHex
extends AbstractSyscall

Service to display integer stored in $a0 on the console.

Constructor Summary
SyscallPrintIntHex()

          Build an instance of the Print Integer syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to print on the console the integer stored in $a0, in hexadecimal format.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallPrintIntHex

public SyscallPrintIntHex()

Build an instance of the Print Integer syscall. Default service number
is 1 and name is “PrintInt”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to print on the console the integer stored in $a0, in hexadecimal format.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

mars.mips.instructions.syscalls

Interfaces 

Syscall

Classes 

AbstractSyscall

RandomStreams

SyscallClose

SyscallConfirmDialog

SyscallExit

SyscallExit2

SyscallInputDialogDouble

SyscallInputDialogFloat

SyscallInputDialogInt

SyscallInputDialogString

SyscallMessageDialog

SyscallMessageDialogDouble

SyscallMessageDialogFloat

SyscallMessageDialogInt

SyscallMessageDialogString

SyscallMidiOut

SyscallMidiOutSync

SyscallNumberOverride

SyscallOpen

SyscallPrintChar

SyscallPrintDouble

SyscallPrintFloat

SyscallPrintInt

SyscallPrintIntBinary

SyscallPrintIntHex

SyscallPrintIntUnsigned

SyscallPrintString

SyscallRandDouble

SyscallRandFloat

SyscallRandInt

SyscallRandIntRange

SyscallRandSeed

SyscallRead

SyscallReadChar

SyscallReadDouble

SyscallReadFloat

SyscallReadInt

SyscallReadString

SyscallSbrk

SyscallSleep

SyscallTime

SyscallWrite

SyscallPrintInt

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallPrintInt

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallPrintInt

All Implemented Interfaces:
Syscall

public class SyscallPrintInt
extends AbstractSyscall

Service to display integer stored in $a0 on the console.

Constructor Summary
SyscallPrintInt()

          Build an instance of the Print Integer syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to print on the console the integer stored in $a0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallPrintInt

public SyscallPrintInt()

Build an instance of the Print Integer syscall. Default service number
is 1 and name is “PrintInt”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to print on the console the integer stored in $a0.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallMessageDialogDouble

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallMessageDialogDouble

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallMessageDialogDouble

All Implemented Interfaces:
Syscall

public class SyscallMessageDialogDouble
extends AbstractSyscall

Service to display a message to user.

Constructor Summary
SyscallMessageDialogDouble()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to display a message to user.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallMessageDialogDouble

public SyscallMessageDialogDouble()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to display a message to user.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallConfirmDialog

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallConfirmDialog

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallConfirmDialog

All Implemented Interfaces:
Syscall

public class SyscallConfirmDialog
extends AbstractSyscall

Service to display a message to user.

Constructor Summary
SyscallConfirmDialog()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to display a message to user.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallConfirmDialog

public SyscallConfirmDialog()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to display a message to user.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.mips.instructions.syscalls

Interface Summary
Syscall Interface for any MIPS syscall system service.

 

Class Summary
AbstractSyscall Abstract class that a MIPS syscall system service may extend.
RandomStreams This small class serves only to hold a static HashMap for storing
random number generators for use by all the random number generator
syscalls.
SyscallClose Service to close file descriptor given in $a0.
SyscallConfirmDialog Service to display a message to user.
SyscallExit Service to exit the MIPS program.
SyscallExit2 Service to exit the MIPS program with return value given in $a0.
SyscallInputDialogDouble Service to input data.
SyscallInputDialogFloat Service to input data.
SyscallInputDialogInt Service to input data.
SyscallInputDialogString Service to input data.
SyscallMessageDialog Service to display a message to user.
SyscallMessageDialogDouble Service to display a message to user.
SyscallMessageDialogFloat Service to display a message to user.
SyscallMessageDialogInt Service to display a message to user.
SyscallMessageDialogString Service to display a message to user.
SyscallMidiOut Service to output simulated MIDI tone to sound card.
SyscallMidiOutSync Service to output simulated MIDI tone to sound card.
SyscallNumberOverride Represents User override of default syscall number assignment.
SyscallOpen Service to open file name specified by $a0.
SyscallPrintChar Service to display character stored in $a0 on the console.
SyscallPrintDouble Service to display double whose bits are stored in $f12 & $f13 onto the console.
SyscallPrintFloat Service to display on the console float whose bits are stored in $f12
SyscallPrintInt Service to display integer stored in $a0 on the console.
SyscallPrintIntBinary Service to display integer stored in $a0 on the console.
SyscallPrintIntHex Service to display integer stored in $a0 on the console.
SyscallPrintIntUnsigned Service to display integer stored in $a0 on the console as unsigned decimal.
SyscallPrintString Service to display string stored starting at address in $a0 onto the console.
SyscallRandDouble Service to return a random floating point value.
SyscallRandFloat Service to return a random floating point value.
SyscallRandInt Service to return a random integer.
SyscallRandIntRange Service to return a random integer in a specified range.
SyscallRandSeed Service to set seed for the underlying Java pseudorandom number generator.
SyscallRead Service to read from file descriptor given in $a0.
SyscallReadChar Service to read a character from input console into $a0.
SyscallReadDouble Service to read the bits of console input double into $f0 and $f1.
SyscallReadFloat Service to read the bits of input float into $f0
SyscallReadInt Service to read an integer from input console into $v0.
SyscallReadString Service to read console input string into buffer starting at address in $a0.
SyscallSbrk Service to allocate amount of heap memory specified in $a0, putting address into $v0.
SyscallSleep Service to cause the MARS Java thread to sleep for (at least) the specified number of milliseconds.
SyscallTime Service to read a character from input console into $a0.
SyscallWrite Service to write to file descriptor given in $a0.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

SyscallReadInt

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallReadInt

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallReadInt

All Implemented Interfaces:
Syscall

public class SyscallReadInt
extends AbstractSyscall

Service to read an integer from input console into $v0.

Constructor Summary
SyscallReadInt()

          Build an instance of the Read Integer syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to read an integer from input console into $v0

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallReadInt

public SyscallReadInt()

Build an instance of the Read Integer syscall. Default service number
is 5 and name is “ReadInt”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to read an integer from input console into $v0

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallExit2

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallExit2

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallExit2

All Implemented Interfaces:
Syscall

public class SyscallExit2
extends AbstractSyscall

Service to exit the MIPS program with return value given in $a0. Ignored if running from GUI.

Constructor Summary
SyscallExit2()

          Build an instance of the Exit2 syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to exit the MIPS program with return value given in $a0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallExit2

public SyscallExit2()

Build an instance of the Exit2 syscall. Default service number
is 17 and name is “Exit2”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to exit the MIPS program with return value given in $a0.
If running in command mode, MARS will exit with that value. If running under GUI,
return value is ignored.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallReadDouble

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallReadDouble

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallReadDouble

All Implemented Interfaces:
Syscall

public class SyscallReadDouble
extends AbstractSyscall

Service to read the bits of console input double into $f0 and $f1.
$f1 contains high order word of the double.

Constructor Summary
SyscallReadDouble()

          Build an instance of the Read Double syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to read the bits of input double into $f0 and $f1.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallReadDouble

public SyscallReadDouble()

Build an instance of the Read Double syscall. Default service number
is 7 and name is “ReadDouble”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to read the bits of input double into $f0 and $f1.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallInputDialogDouble

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallInputDialogDouble

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallInputDialogDouble

All Implemented Interfaces:
Syscall

public class SyscallInputDialogDouble
extends AbstractSyscall

Service to input data.

Constructor Summary
SyscallInputDialogDouble()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to input data.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallInputDialogDouble

public SyscallInputDialogDouble()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to input data.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallMessageDialogFloat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallMessageDialogFloat

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallMessageDialogFloat

All Implemented Interfaces:
Syscall

public class SyscallMessageDialogFloat
extends AbstractSyscall

Service to display a message to user.

Constructor Summary
SyscallMessageDialogFloat()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to display a message to user.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallMessageDialogFloat

public SyscallMessageDialogFloat()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to display a message to user.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallWrite

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallWrite

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallWrite

All Implemented Interfaces:
Syscall

public class SyscallWrite
extends AbstractSyscall

Service to write to file descriptor given in $a0. $a1 specifies buffer
and $a2 specifies length. Number of characters written is returned in $v0
(this was changed from $a0 in MARS 3.7 for SPIM compatibility. The table
in COD erroneously shows $a0).

Constructor Summary
SyscallWrite()

          Build an instance of the Write file syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to write to file descriptor given in $a0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallWrite

public SyscallWrite()

Build an instance of the Write file syscall. Default service number
is 15 and name is “Write”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to write to file descriptor given in $a0. $a1 specifies buffer
and $a2 specifies length. Number of characters written is returned in $v0, starting in MARS 3.7.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.mips.instructions.syscalls

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object mars.mips.instructions.syscalls.AbstractSyscall (implements mars.mips.instructions.syscalls.Syscall)
mars.mips.instructions.syscalls.SyscallClose
mars.mips.instructions.syscalls.SyscallConfirmDialog
mars.mips.instructions.syscalls.SyscallExit
mars.mips.instructions.syscalls.SyscallExit2
mars.mips.instructions.syscalls.SyscallInputDialogDouble
mars.mips.instructions.syscalls.SyscallInputDialogFloat
mars.mips.instructions.syscalls.SyscallInputDialogInt
mars.mips.instructions.syscalls.SyscallInputDialogString
mars.mips.instructions.syscalls.SyscallMessageDialog
mars.mips.instructions.syscalls.SyscallMessageDialogDouble
mars.mips.instructions.syscalls.SyscallMessageDialogFloat
mars.mips.instructions.syscalls.SyscallMessageDialogInt
mars.mips.instructions.syscalls.SyscallMessageDialogString
mars.mips.instructions.syscalls.SyscallMidiOut
mars.mips.instructions.syscalls.SyscallMidiOutSync
mars.mips.instructions.syscalls.SyscallOpen
mars.mips.instructions.syscalls.SyscallPrintChar
mars.mips.instructions.syscalls.SyscallPrintDouble
mars.mips.instructions.syscalls.SyscallPrintFloat
mars.mips.instructions.syscalls.SyscallPrintInt
mars.mips.instructions.syscalls.SyscallPrintIntBinary
mars.mips.instructions.syscalls.SyscallPrintIntHex
mars.mips.instructions.syscalls.SyscallPrintIntUnsigned
mars.mips.instructions.syscalls.SyscallPrintString
mars.mips.instructions.syscalls.SyscallRandDouble
mars.mips.instructions.syscalls.SyscallRandFloat
mars.mips.instructions.syscalls.SyscallRandInt
mars.mips.instructions.syscalls.SyscallRandIntRange
mars.mips.instructions.syscalls.SyscallRandSeed
mars.mips.instructions.syscalls.SyscallRead
mars.mips.instructions.syscalls.SyscallReadChar
mars.mips.instructions.syscalls.SyscallReadDouble
mars.mips.instructions.syscalls.SyscallReadFloat
mars.mips.instructions.syscalls.SyscallReadInt
mars.mips.instructions.syscalls.SyscallReadString
mars.mips.instructions.syscalls.SyscallSbrk
mars.mips.instructions.syscalls.SyscallSleep
mars.mips.instructions.syscalls.SyscallTime
mars.mips.instructions.syscalls.SyscallWrite

mars.mips.instructions.syscalls.RandomStreams
mars.mips.instructions.syscalls.SyscallNumberOverride

Interface Hierarchy

mars.mips.instructions.syscalls.Syscall

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

SyscallSleep

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallSleep

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallSleep

All Implemented Interfaces:
Syscall

public class SyscallSleep
extends AbstractSyscall

Service to cause the MARS Java thread to sleep for (at least) the specified number of milliseconds.
This timing will not be precise as the Java implementation will add some overhead.

Constructor Summary
SyscallSleep()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to cause the MARS Java thread to sleep for (at least) the specified number of milliseconds.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallSleep

public SyscallSleep()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to cause the MARS Java thread to sleep for (at least) the specified number of milliseconds.
This timing will not be precise as the Java implementation will add some overhead.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallClose

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallClose

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallClose

All Implemented Interfaces:
Syscall

public class SyscallClose
extends AbstractSyscall

Service to close file descriptor given in $a0.

Constructor Summary
SyscallClose()

          Build an instance of the Close syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to close file descriptor given in $a0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallClose

public SyscallClose()

Build an instance of the Close syscall. Default service number
is 16 and name is “Close”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to close file descriptor given in $a0.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallRandInt

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallRandInt

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallRandInt

All Implemented Interfaces:
Syscall

public class SyscallRandInt
extends AbstractSyscall

Service to return a random integer.

Constructor Summary
SyscallRandInt()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to the random number generator.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallRandInt

public SyscallRandInt()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to the random number generator.
Return in $a0 the next pseudorandom, uniformly distributed int value from this random number generator’s sequence.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallPrintDouble

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallPrintDouble

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallPrintDouble

All Implemented Interfaces:
Syscall

public class SyscallPrintDouble
extends AbstractSyscall

Service to display double whose bits are stored in $f12 & $f13 onto the console.
$f13 contains high order word of the double.

Constructor Summary
SyscallPrintDouble()

          Build an instance of the Print Double syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to print double whose bits are stored in $f12 & $f13.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallPrintDouble

public SyscallPrintDouble()

Build an instance of the Print Double syscall. Default service number
is 3 and name is “PrintDouble”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to print double whose bits are stored in $f12 & $f13.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallRead

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallRead

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallRead

All Implemented Interfaces:
Syscall

public class SyscallRead
extends AbstractSyscall

Service to read from file descriptor given in $a0. $a1 specifies buffer
and $a2 specifies length. Number of characters read is returned in $v0.
(this was changed from $a0 in MARS 3.7 for SPIM compatibility. The table
in COD erroneously shows $a0). *

Constructor Summary
SyscallRead()

          Build an instance of the Read file syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to read from file descriptor given in $a0.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallRead

public SyscallRead()

Build an instance of the Read file syscall. Default service number
is 14 and name is “Read”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to read from file descriptor given in $a0. $a1 specifies buffer
and $a2 specifies length. Number of characters read is returned in $v0 (starting MARS 3.7).

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallRandFloat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallRandFloat

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallRandFloat

All Implemented Interfaces:
Syscall

public class SyscallRandFloat
extends AbstractSyscall

Service to return a random floating point value.

Constructor Summary
SyscallRandFloat()

          Build an instance of the syscall with its default service number and name.

 

Method Summary

 void simulate(ProgramStatement statement)

          System call to the random number generator.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallRandFloat

public SyscallRandFloat()

Build an instance of the syscall with its default service number and name.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

System call to the random number generator.
Return in $f0 the next pseudorandom, uniformly distributed float value between 0.0 and 1.0
from this random number generator’s sequence.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallNumberOverride

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallNumberOverride

java.lang.Object
mars.mips.instructions.syscalls.SyscallNumberOverride

public class SyscallNumberOverride
extends java.lang.Object

Represents User override of default syscall number assignment.
Such overrides are specified in the config.txt file read when
MARS starts up.

Constructor Summary
SyscallNumberOverride(java.lang.String serviceName,
java.lang.String value)

          Constructor is called with two strings: service name and desired
number.

 

Method Summary

 java.lang.String getName()

          Get the service name as a String.

 int getNumber()

          Get the new service number as an int.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallNumberOverride

public SyscallNumberOverride(java.lang.String serviceName,
java.lang.String value)

Constructor is called with two strings: service name and desired
number. Will throw an exception is number is malformed, but does
not check validity of the service name or number.

Parameters:
serviceName – a String containing syscall service mnemonic.
value – a String containing its reassigned syscall service number.
If this number is previously assigned to a different syscall which does not
also receive a new number, then an error for duplicate numbers will
be issued at MARS launch.

Method Detail

getName

public java.lang.String getName()

Get the service name as a String.

Returns:
the service name

getNumber

public int getNumber()

Get the new service number as an int.

Returns:
the service number

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SyscallMidiOutSync

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions.syscalls

Class SyscallMidiOutSync

java.lang.Object
mars.mips.instructions.syscalls.AbstractSyscall
mars.mips.instructions.syscalls.SyscallMidiOutSync

All Implemented Interfaces:
Syscall

public class SyscallMidiOutSync
extends AbstractSyscall

Service to output simulated MIDI tone to sound card. The call does
not return until the tone duration has elapsed. By contrast, syscall 31
(MidiOut) returns immediately upon generating the tone.

Constructor Summary
SyscallMidiOutSync()

          Build an instance of the MIDI (simulated) out syscall.

 

Method Summary

 void simulate(ProgramStatement statement)

          Performs syscall function to send MIDI output to sound card.

 
Methods inherited from class mars.mips.instructions.syscalls.AbstractSyscall
getName, getNumber, setNumber

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SyscallMidiOutSync

public SyscallMidiOutSync()

Build an instance of the MIDI (simulated) out syscall. Default service number
is 33 and name is “MidiOutSync”.

Method Detail

simulate

public void simulate(ProgramStatement statement)
throws ProcessingException

Performs syscall function to send MIDI output to sound card. The syscall does not
return until after the duration period ($a1) has elapsed. This requires
four arguments in registers $a0 through $a3.

$a0 – pitch (note). Integer value from 0 to 127, with 60 being middle-C on a piano.

$a1 – duration. Integer value in milliseconds.

$a2 – instrument. Integer value from 0 to 127, with 0 being acoustic grand piano.

$a3 – volume. Integer value from 0 to 127.

Default values, in case any parameters are outside the above ranges, are $a0=60, $a1=1000,
$a2=0, $a3=100.

See MARS documentation elsewhere or www.midi.org for more information. Note that the pitch,
instrument and volume value ranges 0-127 are from javax.sound.midi; actual MIDI instruments
use the range 1-128.

Specified by:
simulate in interface Syscall
Specified by:
simulate in class AbstractSyscall

Parameters:
statement – ProgramStatement object for this syscall instruction.

Throws:

ProcessingException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

BasicInstruction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.instructions

Class BasicInstruction

java.lang.Object
mars.mips.instructions.Instruction
mars.mips.instructions.BasicInstruction

public class BasicInstruction
extends Instruction

Class to represent a basic instruction in the MIPS instruction set.
Basic instruction means it translates directly to a 32-bit binary machine
instruction.

Author:
Pete Sanderson and Ken Vollmar

Field Summary

 
Fields inherited from class mars.mips.instructions.Instruction
description, exampleFormat, INSTRUCTION_LENGTH, INSTRUCTION_LENGTH_BITS, mnemonic, operandMask, tokenList

 

Constructor Summary
BasicInstruction(java.lang.String example,
BasicInstructionFormat instrFormat,
java.lang.String operMask,
SimulationCode simCode)

           
BasicInstruction(java.lang.String example,
java.lang.String description,
BasicInstructionFormat instrFormat,
java.lang.String operMask,
SimulationCode simCode)

          BasicInstruction constructor.

 

Method Summary

 BasicInstructionFormat getInstructionFormat()

          Gets the operand format of the instruction.

 java.lang.String getOperationMask()

          Gets the 32-character operation mask.

 SimulationCode getSimulationCode()

          Gets the SimulationCode object.

 
Methods inherited from class mars.mips.instructions.Instruction
createExampleTokenList, extractOperator, getDescription, getExampleFormat, getInstructionLength, getName, getTokenList

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

BasicInstruction

public BasicInstruction(java.lang.String example,
java.lang.String description,
BasicInstructionFormat instrFormat,
java.lang.String operMask,
SimulationCode simCode)

BasicInstruction constructor.

Parameters:
example – An example usage of the instruction, as a String.
instrFormat – The format is R, I, I-branch or J.
operMask – The opcode mask is a 32 character string that contains the opcode in binary in the appropriate bit positions and codes for operand positions (‘f’, ‘s’, ‘t’) in the remainding positions.
simCode – The inline definition of an object and class which anonymously implements the SimulationCode interface.
See Also:
SimulationCode

BasicInstruction

public BasicInstruction(java.lang.String example,
BasicInstructionFormat instrFormat,
java.lang.String operMask,
SimulationCode simCode)

Method Detail

getOperationMask

public java.lang.String getOperationMask()

Gets the 32-character operation mask. Each mask position represents a
bit position in the 32-bit machine instruction. Operation codes and
unused bits are represented in the mask by 1’s and 0’s. Operand codes
are represented by ‘f’, ‘s’, and ‘t’ for bits occupied by first, secon
and third operand, respectively.

Returns:
The 32 bit mask, as a String

getInstructionFormat

public BasicInstructionFormat getInstructionFormat()

Gets the operand format of the instruction. MIPS defines 3 of these
R-format, I-format, and J-format. R-format is all registers. I-format
is address formed from register base with immediate offset. J-format
is for jump destination addresses. I have added one more:
I-branch-format, for branch destination addresses. These are a variation
of the I-format in that the computed value is address relative to the
Program Counter. All four formats are represented by static objects.

Returns:
The machine instruction format, R, I, J or I-branch.

getSimulationCode

public SimulationCode getSimulationCode()

Gets the SimulationCode object. It is really an object of an anonymous
class that implements the SimulationCode interface. Such an object has but one
method: Simulate().

Returns:
the SimulationCode object for this instruction.
See Also:
SimulationCode

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Coprocessor0

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class Coprocessor0

java.lang.Object
mars.mips.hardware.Coprocessor0

public class Coprocessor0
extends java.lang.Object

Represents Coprocessor 0. We will use only its interrupt/exception registers.

Author:
Pete Sanderson

Field Summary

static int CAUSE

           

static int DEFAULT_STATUS_VALUE

           

static int EPC

           

static int EXCEPTION_LEVEL

           

static int STATUS

           

static int VADDR

          Coprocessor register names

 

Constructor Summary
Coprocessor0()

           

 

Method Summary

static void addRegistersObserver(java.util.Observer observer)

          Each individual register is a separate object and Observable.

static void deleteRegistersObserver(java.util.Observer observer)

          Each individual register is a separate object and Observable.

static int getNumber(java.lang.String n)

          For getting the number representation of the register.

static Register getRegister(java.lang.String rname)

          Get register object corresponding to given name.

static int getRegisterPosition(Register r)

          Coprocessor0 implements only selected registers, so the register number
(8, 12, 13, 14) does not correspond to its position in the list of registers
(0, 1, 2, 3).

static Register[] getRegisters()

          For returning the set of registers.

static int getValue(int num)

          Returns the value of the register who’s number is num.

static void resetRegisters()

          Method to reinitialize the values of the registers.

static void showRegisters()

          Method for displaying the register values for debugging.

static int updateRegister(int num,
int val)

          This method updates the register value who’s number is num.

static int updateRegister(java.lang.String n,
int val)

          Sets the value of the register given to the value given.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

VADDR

public static final int VADDR

Coprocessor register names

See Also:
Constant Field Values

STATUS

public static final int STATUS

See Also:
Constant Field Values

CAUSE

public static final int CAUSE

See Also:
Constant Field Values

EPC

public static final int EPC

See Also:
Constant Field Values

EXCEPTION_LEVEL

public static final int EXCEPTION_LEVEL

See Also:
Constant Field Values

DEFAULT_STATUS_VALUE

public static final int DEFAULT_STATUS_VALUE

See Also:
Constant Field Values

Constructor Detail

Coprocessor0

public Coprocessor0()

Method Detail

showRegisters

public static void showRegisters()

Method for displaying the register values for debugging.

updateRegister

public static int updateRegister(java.lang.String n,
int val)

Sets the value of the register given to the value given.

Parameters:
n – name of register to set the value of ($n, where n is reg number).
val – The desired value for the register.

Returns:
old value in register prior to update

updateRegister

public static int updateRegister(int num,
int val)

This method updates the register value who’s number is num.

Parameters:
num – Number of register to set the value of.
val – The desired value for the register.

Returns:
old value in register prior to update

getValue

public static int getValue(int num)

Returns the value of the register who’s number is num.

Parameters:
num – The register number.

Returns:
The value of the given register. 0 for non-implemented registers

getNumber

public static int getNumber(java.lang.String n)

For getting the number representation of the register.

Parameters:
n – The string formatted register name to look for.

Returns:
The number of the register represented by the string. -1 if no match.

getRegisters

public static Register[] getRegisters()

For returning the set of registers.

Returns:
The set of registers.

getRegisterPosition

public static int getRegisterPosition(Register r)

Coprocessor0 implements only selected registers, so the register number
(8, 12, 13, 14) does not correspond to its position in the list of registers
(0, 1, 2, 3).

Parameters:
r – A coprocessor0 Register

Returns:
the list position of given register, -1 if not found.

getRegister

public static Register getRegister(java.lang.String rname)

Get register object corresponding to given name. If no match, return null.

Parameters:
rname – The register name, in $0 format.

Returns:
The register object,or null if not found.

resetRegisters

public static void resetRegisters()

Method to reinitialize the values of the registers.

addRegistersObserver

public static void addRegistersObserver(java.util.Observer observer)

Each individual register is a separate object and Observable. This handy method
will add the given Observer to each one.

deleteRegistersObserver

public static void deleteRegistersObserver(java.util.Observer observer)

Each individual register is a separate object and Observable. This handy method
will delete the given Observer from each one.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Coprocessor1

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class Coprocessor1

java.lang.Object
mars.mips.hardware.Coprocessor1

public class Coprocessor1
extends java.lang.Object

Represents Coprocessor 1, the Floating Point Unit (FPU)

Author:
Pete Sanderson

Constructor Summary
Coprocessor1()

           

 

Method Summary

static void addRegistersObserver(java.util.Observer observer)

          Each individual register is a separate object and Observable.

static int clearConditionFlag(int flag)

          Set condition flag to 0 (false).

static void clearConditionFlags()

          Clear all condition flags (0-7).

static void deleteRegistersObserver(java.util.Observer observer)

          Each individual register is a separate object and Observable.

static int getConditionFlag(int flag)

          Get value of specified condition flag (0-7).

static int getConditionFlagCount()

          Get count of condition flags.

static int getConditionFlags()

          Get array of condition flags (0-7).

static double getDoubleFromRegisterPair(int reg)

          Gets the double value stored in the given FPU register.

static double getDoubleFromRegisterPair(java.lang.String reg)

          Gets the double value stored in the given FPU register.

static float getFloatFromRegister(int reg)

          Gets the float value stored in the given FPU register.

static float getFloatFromRegister(java.lang.String reg)

          Gets the float value stored in the given FPU register.

static int getIntFromRegister(int reg)

          Gets the 32-bit int bit pattern stored in the given FPU register.

static int getIntFromRegister(java.lang.String reg)

          Gets the 32-bit int bit pattern stored in the given FPU register.

static long getLongFromRegisterPair(int reg)

          Gets a long representing the double value stored in the given double
precision FPU register.

static long getLongFromRegisterPair(java.lang.String reg)

          Gets the double value stored in the given FPU register.

static Register getRegister(java.lang.String rName)

          Get register object corresponding to given name.

static int getRegisterNumber(java.lang.String n)

          For getting the number representation of the FPU register.

static Register[] getRegisters()

          For returning the set of registers.

static int getValue(int num)

          Returns the value of the FPU register who’s number is num.

static void resetRegisters()

          Method to reinitialize the values of the registers.

static int setConditionFlag(int flag)

          Set condition flag to 1 (true).

static void setConditionFlags()

          Set all condition flags (0-7).

static void setRegisterPairToDouble(int reg,
double val)

          Sets the value of the FPU register given to the double value given.

static void setRegisterPairToDouble(java.lang.String reg,
double val)

          Sets the value of the FPU register given to the double value given.

static void setRegisterPairToLong(int reg,
long val)

          Sets the value of the FPU register pair given to the long value containing 64 bit pattern
given.

static void setRegisterPairToLong(java.lang.String reg,
long val)

          Sets the value of the FPU register pair given to the long value containing 64 bit pattern
given.

static void setRegisterToFloat(int reg,
float val)

          Sets the value of the FPU register given to the value given.

static void setRegisterToFloat(java.lang.String reg,
float val)

          Sets the value of the FPU register given to the value given.

static void setRegisterToInt(int reg,
int val)

          Sets the value of the FPU register given to the 32-bit
pattern given by the int parameter.

static void setRegisterToInt(java.lang.String reg,
int val)

          Sets the value of the FPU register given to the 32-bit
pattern given by the int parameter.

static void showRegisters()

          Method for displaying the register values for debugging.

static int updateRegister(int num,
int val)

          This method updates the FPU register value who’s number is num.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

Coprocessor1

public Coprocessor1()

Method Detail

showRegisters

public static void showRegisters()

Method for displaying the register values for debugging.

setRegisterToFloat

public static void setRegisterToFloat(java.lang.String reg,
float val)

Sets the value of the FPU register given to the value given.

Parameters:
reg – Register to set the value of.
val – The desired float value for the register.

setRegisterToFloat

public static void setRegisterToFloat(int reg,
float val)

Sets the value of the FPU register given to the value given.

Parameters:
reg – Register to set the value of.
val – The desired float value for the register.

setRegisterToInt

public static void setRegisterToInt(java.lang.String reg,
int val)

Sets the value of the FPU register given to the 32-bit
pattern given by the int parameter.

Parameters:
reg – Register to set the value of.
val – The desired int bit pattern for the register.

setRegisterToInt

public static void setRegisterToInt(int reg,
int val)

Sets the value of the FPU register given to the 32-bit
pattern given by the int parameter.

Parameters:
reg – Register to set the value of.
val – The desired int bit pattern for the register.

setRegisterPairToDouble

public static void setRegisterPairToDouble(int reg,
double val)
throws InvalidRegisterAccessException

Sets the value of the FPU register given to the double value given. The register
must be even-numbered, and the low order 32 bits are placed in it. The high order
32 bits are placed in the (odd numbered) register that follows it.

Parameters:
reg – Register to set the value of.
val – The desired double value for the register.

Throws:

InvalidRegisterAccessException – if register ID is invalid or odd-numbered.

setRegisterPairToDouble

public static void setRegisterPairToDouble(java.lang.String reg,
double val)
throws InvalidRegisterAccessException

Sets the value of the FPU register given to the double value given. The register
must be even-numbered, and the low order 32 bits are placed in it. The high order
32 bits are placed in the (odd numbered) register that follows it.

Parameters:
reg – Register to set the value of.
val – The desired double value for the register.

Throws:

InvalidRegisterAccessException – if register ID is invalid or odd-numbered.

setRegisterPairToLong

public static void setRegisterPairToLong(int reg,
long val)
throws InvalidRegisterAccessException

Sets the value of the FPU register pair given to the long value containing 64 bit pattern
given. The register
must be even-numbered, and the low order 32 bits from the long are placed in it. The high order
32 bits from the long are placed in the (odd numbered) register that follows it.

Parameters:
reg – Register to set the value of. Must be even register of even/odd pair.
val – The desired double value for the register.

Throws:

InvalidRegisterAccessException – if register ID is invalid or odd-numbered.

setRegisterPairToLong

public static void setRegisterPairToLong(java.lang.String reg,
long val)
throws InvalidRegisterAccessException

Sets the value of the FPU register pair given to the long value containing 64 bit pattern
given. The register
must be even-numbered, and the low order 32 bits from the long are placed in it. The high order
32 bits from the long are placed in the (odd numbered) register that follows it.

Parameters:
reg – Register to set the value of. Must be even register of even/odd pair.
val – The desired long value containing the 64 bits for the register pair.

Throws:

InvalidRegisterAccessException – if register ID is invalid or odd-numbered.

getFloatFromRegister

public static float getFloatFromRegister(int reg)

Gets the float value stored in the given FPU register.

Parameters:
reg – Register to get the value of.

Returns:
The float value stored by that register.

getFloatFromRegister

public static float getFloatFromRegister(java.lang.String reg)

Gets the float value stored in the given FPU register.

Parameters:
reg – Register to get the value of.

Returns:
The float value stored by that register.

getIntFromRegister

public static int getIntFromRegister(int reg)

Gets the 32-bit int bit pattern stored in the given FPU register.

Parameters:
reg – Register to get the value of.

Returns:
The int bit pattern stored by that register.

getIntFromRegister

public static int getIntFromRegister(java.lang.String reg)

Gets the 32-bit int bit pattern stored in the given FPU register.

Parameters:
reg – Register to get the value of.

Returns:
The int bit pattern stored by that register.

getDoubleFromRegisterPair

public static double getDoubleFromRegisterPair(int reg)
throws InvalidRegisterAccessException

Gets the double value stored in the given FPU register. The register
must be even-numbered.

Parameters:
reg – Register to get the value of. Must be even number of even/odd pair.

Throws:

InvalidRegisterAccessException – if register ID is invalid or odd-numbered.

getDoubleFromRegisterPair

public static double getDoubleFromRegisterPair(java.lang.String reg)
throws InvalidRegisterAccessException

Gets the double value stored in the given FPU register. The register
must be even-numbered.

Parameters:
reg – Register to get the value of. Must be even number of even/odd pair.

Throws:

InvalidRegisterAccessException – if register ID is invalid or odd-numbered.

getLongFromRegisterPair

public static long getLongFromRegisterPair(int reg)
throws InvalidRegisterAccessException

Gets a long representing the double value stored in the given double
precision FPU register.
The register must be even-numbered.

Parameters:
reg – Register to get the value of. Must be even number of even/odd pair.

Throws:

InvalidRegisterAccessException – if register ID is invalid or odd-numbered.

getLongFromRegisterPair

public static long getLongFromRegisterPair(java.lang.String reg)
throws InvalidRegisterAccessException

Gets the double value stored in the given FPU register. The register
must be even-numbered.

Parameters:
reg – Register to get the value of. Must be even number of even/odd pair.

Throws:

InvalidRegisterAccessException – if register ID is invalid or odd-numbered.

updateRegister

public static int updateRegister(int num,
int val)

This method updates the FPU register value who’s number is num. Note the
registers themselves hold an int value. There are helper methods available
to which you can give a float or double to store.

Parameters:
num – FPU register to set the value of.
val – The desired int value for the register.

getValue

public static int getValue(int num)

Returns the value of the FPU register who’s number is num. Returns the
raw int value actually stored there. If you need a float, use
Float.intBitsToFloat() to get the equivent float.

Parameters:
num – The FPU register number.

Returns:
The int value of the given register.

getRegisterNumber

public static int getRegisterNumber(java.lang.String n)

For getting the number representation of the FPU register.

Parameters:
n – The string formatted register name to look for.

Returns:
The number of the register represented by the string.

getRegisters

public static Register[] getRegisters()

For returning the set of registers.

Returns:
The set of registers.

getRegister

public static Register getRegister(java.lang.String rName)

Get register object corresponding to given name. If no match, return null.

Parameters:
rName – The FPU register name, must be “$f0” through “$f31”.

Returns:
The register object,or null if not found.

resetRegisters

public static void resetRegisters()

Method to reinitialize the values of the registers.

addRegistersObserver

public static void addRegistersObserver(java.util.Observer observer)

Each individual register is a separate object and Observable. This handy method
will add the given Observer to each one.

deleteRegistersObserver

public static void deleteRegistersObserver(java.util.Observer observer)

Each individual register is a separate object and Observable. This handy method
will delete the given Observer from each one.

setConditionFlag

public static int setConditionFlag(int flag)

Set condition flag to 1 (true).

Parameters:
flag – condition flag number (0-7)

Returns:
previous flag setting (0 or 1)

clearConditionFlag

public static int clearConditionFlag(int flag)

Set condition flag to 0 (false).

Parameters:
flag – condition flag number (0-7)

Returns:
previous flag setting (0 or 1)

getConditionFlag

public static int getConditionFlag(int flag)

Get value of specified condition flag (0-7).

Parameters:
flag – condition flag number (0-7)

Returns:
0 if condition is false, 1 if condition is true

getConditionFlags

public static int getConditionFlags()

Get array of condition flags (0-7).

Returns:
array of int condition flags

clearConditionFlags

public static void clearConditionFlags()

Clear all condition flags (0-7).

setConditionFlags

public static void setConditionFlags()

Set all condition flags (0-7).

getConditionFlagCount

public static int getConditionFlagCount()

Get count of condition flags.

Returns:
number of condition flags

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

AccessNotice

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class AccessNotice

java.lang.Object
mars.mips.hardware.AccessNotice

Direct Known Subclasses:
MemoryAccessNotice, RegisterAccessNotice

public abstract class AccessNotice
extends java.lang.Object

Object provided to Observers of runtime access to MIPS memory or registers.
The access types READ and WRITE defined here; use subclasses defined for
MemoryAccessNotice and RegisterAccessNotice. This is abstract class.

Author:
Pete Sanderson

Field Summary

static int READ

          Indicates the purpose of access was to read.

static int WRITE

          Indicates the purpose of access was to write.

 

Constructor Summary

protected AccessNotice(int type)

           

 

Method Summary

 boolean accessIsFromGUI()

          Query whether the access originated from MARS GUI (AWT event queue)

 boolean accessIsFromMIPS()

          Query whether the access originated from executing MIPS program

 int getAccessType()

          Get the access type: READ or WRITE.

 java.lang.Thread getThread()

          Get reference to thread that created this notice

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

READ

public static final int READ

Indicates the purpose of access was to read.

See Also:
Constant Field Values

WRITE

public static final int WRITE

Indicates the purpose of access was to write.

See Also:
Constant Field Values

Constructor Detail

AccessNotice

protected AccessNotice(int type)

Method Detail

getAccessType

public int getAccessType()

Get the access type: READ or WRITE.

Returns:
Access type, either AccessNotice.READ or AccessNotice.WRITE

getThread

public java.lang.Thread getThread()

Get reference to thread that created this notice

Returns:
Return reference to the thread that created this notice.

accessIsFromGUI

public boolean accessIsFromGUI()

Query whether the access originated from MARS GUI (AWT event queue)

Returns:
true if this access originated from MARS GUI, false otherwise

accessIsFromMIPS

public boolean accessIsFromMIPS()

Query whether the access originated from executing MIPS program

Returns:
true if this access originated from executing MIPS program, false otherwise

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MemoryConfiguration

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class MemoryConfiguration

java.lang.Object
mars.mips.hardware.MemoryConfiguration

public class MemoryConfiguration
extends java.lang.Object

Models the memory configuration for the simulated MIPS machine.
“configuration” refers to the starting memory addresses for
the various memory segments.
The default configuration is based on SPIM. Starting with MARS 3.7,
the configuration can be changed.

Author:
Pete Sanderson

Constructor Summary
MemoryConfiguration(java.lang.String ident,
java.lang.String name,
java.lang.String[] items,
int[] values)

           

 

Method Summary

 java.lang.String getConfigurationIdentifier()

           

 java.lang.String[] getConfigurationItemNames()

           

 int[] getConfigurationItemValues()

           

 java.lang.String getConfigurationName()

           

 int getDataBaseAddress()

           

 int getDataSegmentBaseAddress()

           

 int getDataSegmentLimitAddress()

           

 int getExceptionHandlerAddress()

           

 int getExternBaseAddress()

           

 int getGlobalPointer()

           

 int getHeapBaseAddress()

           

 int getKernelBaseAddress()

           

 int getKernelDataBaseAddress()

           

 int getKernelDataSegmentLimitAddress()

           

 int getKernelHighAddress()

           

 int getKernelTextBaseAddress()

           

 int getKernelTextLimitAddress()

           

 int getMemoryMapBaseAddress()

           

 int getMemoryMapLimitAddress()

           

 int getStackBaseAddress()

           

 int getStackLimitAddress()

           

 int getStackPointer()

           

 int getTextBaseAddress()

           

 int getTextLimitAddress()

           

 int getUserHighAddress()

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

MemoryConfiguration

public MemoryConfiguration(java.lang.String ident,
java.lang.String name,
java.lang.String[] items,
int[] values)

Method Detail

getConfigurationIdentifier

public java.lang.String getConfigurationIdentifier()

getConfigurationName

public java.lang.String getConfigurationName()

getConfigurationItemValues

public int[] getConfigurationItemValues()

getConfigurationItemNames

public java.lang.String[] getConfigurationItemNames()

getTextBaseAddress

public int getTextBaseAddress()

getDataSegmentBaseAddress

public int getDataSegmentBaseAddress()

getExternBaseAddress

public int getExternBaseAddress()

getGlobalPointer

public int getGlobalPointer()

getDataBaseAddress

public int getDataBaseAddress()

getHeapBaseAddress

public int getHeapBaseAddress()

getStackPointer

public int getStackPointer()

getStackBaseAddress

public int getStackBaseAddress()

getUserHighAddress

public int getUserHighAddress()

getKernelBaseAddress

public int getKernelBaseAddress()

getKernelTextBaseAddress

public int getKernelTextBaseAddress()

getExceptionHandlerAddress

public int getExceptionHandlerAddress()

getKernelDataBaseAddress

public int getKernelDataBaseAddress()

getMemoryMapBaseAddress

public int getMemoryMapBaseAddress()

getKernelHighAddress

public int getKernelHighAddress()

getDataSegmentLimitAddress

public int getDataSegmentLimitAddress()

getTextLimitAddress

public int getTextLimitAddress()

getKernelDataSegmentLimitAddress

public int getKernelDataSegmentLimitAddress()

getKernelTextLimitAddress

public int getKernelTextLimitAddress()

getStackLimitAddress

public int getStackLimitAddress()

getMemoryMapLimitAddress

public int getMemoryMapLimitAddress()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Register

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class Register

java.lang.Object
java.util.Observable
mars.mips.hardware.Register

public class Register
extends java.util.Observable

Abstraction to represent a register of a MIPS Assembler.

Author:
Jason Bumgarner, Jason Shrewsbury, Ben Sherman

Constructor Summary
Register(java.lang.String n,
int num,
int val)

          Creates a new register with specified name, number, and value.

 

Method Summary

 void changeResetValue(int reset)

          Change the register’s reset value; the value to which it will be
set when resetValue() is called.

 java.lang.String getName()

          Returns the name of the Register.

 int getNumber()

          Returns the number of the Register.

 int getResetValue()

          Returns the reset value of the Register.

 int getValue()

          Returns the value of the Register.

 int getValueNoNotify()

          Returns the value of the Register.

 void resetValue()

          Resets the value of the register to the value it was constructed with.

 int setValue(int val)

          Sets the value of the register to the val passed to it.

 
Methods inherited from class java.util.Observable
addObserver, clearChanged, countObservers, deleteObserver, deleteObservers, hasChanged, notifyObservers, notifyObservers, setChanged

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

Register

public Register(java.lang.String n,
int num,
int val)

Creates a new register with specified name, number, and value.

Parameters:
n – The name of the register.
num – The number of the register.
val – The inital (and reset) value of the register.

Method Detail

getName

public java.lang.String getName()

Returns the name of the Register.

Returns:
name The name of the Register.

getValue

public int getValue()

Returns the value of the Register. Observers are notified
of the READ operation.

Returns:
value The value of the Register.

getValueNoNotify

public int getValueNoNotify()

Returns the value of the Register. Observers are not notified.
Added for release 3.8.

Returns:
value The value of the Register.

getResetValue

public int getResetValue()

Returns the reset value of the Register.

Returns:
The reset (initial) value of the Register.

getNumber

public int getNumber()

Returns the number of the Register.

Returns:
number The number of the Register.

setValue

public int setValue(int val)

Sets the value of the register to the val passed to it.
Observers are notified of the WRITE operation.

Parameters:
val – Value to set the Register to.

Returns:
previous value of register

resetValue

public void resetValue()

Resets the value of the register to the value it was constructed with.
Observers are not notified.

changeResetValue

public void changeResetValue(int reset)

Change the register’s reset value; the value to which it will be
set when resetValue() is called.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MemoryAccessNotice

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class MemoryAccessNotice

java.lang.Object
mars.mips.hardware.AccessNotice
mars.mips.hardware.MemoryAccessNotice

public class MemoryAccessNotice
extends AccessNotice

Object provided to Observers of runtime access to MIPS memory.
Observer can get the access type (R/W), address and length in bytes (4,2,1).

Author:
Pete Sanderson

Field Summary

 
Fields inherited from class mars.mips.hardware.AccessNotice
READ, WRITE

 

Method Summary

 int getAddress()

          Fetch the memory address that was accessed.

 int getLength()

          Fetch the length in bytes of the access operation (4,2,1).

 int getValue()

          Fetch the value of the access operation (the value read or written).

 java.lang.String toString()

          String representation indicates access type, address and length in bytes

 
Methods inherited from class mars.mips.hardware.AccessNotice
accessIsFromGUI, accessIsFromMIPS, getAccessType, getThread

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Method Detail

getAddress

public int getAddress()

Fetch the memory address that was accessed.

getLength

public int getLength()

Fetch the length in bytes of the access operation (4,2,1).

getValue

public int getValue()

Fetch the value of the access operation (the value read or written).

toString

public java.lang.String toString()

String representation indicates access type, address and length in bytes

Overrides:
toString in class java.lang.Object

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MemoryConfigurations

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class MemoryConfigurations

java.lang.Object
mars.mips.hardware.MemoryConfigurations

public class MemoryConfigurations
extends java.lang.Object

Models the collection of MIPS memory configurations.
The default configuration is based on SPIM. Starting with MARS 3.7,
the configuration can be changed.

Author:
Pete Sanderson

Constructor Summary
MemoryConfigurations()

           

 

Method Summary

static void buildConfigurationCollection()

           

static MemoryConfiguration getConfigurationByName(java.lang.String name)

           

static java.util.Iterator getConfigurationsIterator()

           

static MemoryConfiguration getCurrentConfiguration()

           

static MemoryConfiguration getDefaultConfiguration()

           

static int getDefaultDataBaseAddress()

           

static int getDefaultDataSegmentBaseAddress()

           

 int getDefaultDataSegmentLimitAddress()

           

static int getDefaultExceptionHandlerAddress()

           

static int getDefaultExternBaseAddress()

           

static int getDefaultGlobalPointer()

           

static int getDefaultHeapBaseAddress()

           

static int getDefaultKernelBaseAddress()

           

static int getDefaultKernelDataBaseAddress()

           

 int getDefaultKernelDataSegmentLimitAddress()

           

static int getDefaultKernelHighAddress()

           

static int getDefaultKernelTextBaseAddress()

           

 int getDefaultKernelTextLimitAddress()

           

static int getDefaultMemoryMapBaseAddress()

           

static int getDefaultStackBaseAddress()

           

 int getDefaultStackLimitAddress()

           

static int getDefaultStackPointer()

           

static int getDefaultTextBaseAddress()

           

 int getDefaultTextLimitAddress()

           

static int getDefaultUserHighAddress()

           

 int getMemoryMapLimitAddress()

           

static boolean setCurrentConfiguration(MemoryConfiguration config)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

MemoryConfigurations

public MemoryConfigurations()

Method Detail

buildConfigurationCollection

public static void buildConfigurationCollection()

getConfigurationsIterator

public static java.util.Iterator getConfigurationsIterator()

getConfigurationByName

public static MemoryConfiguration getConfigurationByName(java.lang.String name)

getDefaultConfiguration

public static MemoryConfiguration getDefaultConfiguration()

getCurrentConfiguration

public static MemoryConfiguration getCurrentConfiguration()

setCurrentConfiguration

public static boolean setCurrentConfiguration(MemoryConfiguration config)

getDefaultTextBaseAddress

public static int getDefaultTextBaseAddress()

getDefaultDataSegmentBaseAddress

public static int getDefaultDataSegmentBaseAddress()

getDefaultExternBaseAddress

public static int getDefaultExternBaseAddress()

getDefaultGlobalPointer

public static int getDefaultGlobalPointer()

getDefaultDataBaseAddress

public static int getDefaultDataBaseAddress()

getDefaultHeapBaseAddress

public static int getDefaultHeapBaseAddress()

getDefaultStackPointer

public static int getDefaultStackPointer()

getDefaultStackBaseAddress

public static int getDefaultStackBaseAddress()

getDefaultUserHighAddress

public static int getDefaultUserHighAddress()

getDefaultKernelBaseAddress

public static int getDefaultKernelBaseAddress()

getDefaultKernelTextBaseAddress

public static int getDefaultKernelTextBaseAddress()

getDefaultExceptionHandlerAddress

public static int getDefaultExceptionHandlerAddress()

getDefaultKernelDataBaseAddress

public static int getDefaultKernelDataBaseAddress()

getDefaultMemoryMapBaseAddress

public static int getDefaultMemoryMapBaseAddress()

getDefaultKernelHighAddress

public static int getDefaultKernelHighAddress()

getDefaultDataSegmentLimitAddress

public int getDefaultDataSegmentLimitAddress()

getDefaultTextLimitAddress

public int getDefaultTextLimitAddress()

getDefaultKernelDataSegmentLimitAddress

public int getDefaultKernelDataSegmentLimitAddress()

getDefaultKernelTextLimitAddress

public int getDefaultKernelTextLimitAddress()

getDefaultStackLimitAddress

public int getDefaultStackLimitAddress()

getMemoryMapLimitAddress

public int getMemoryMapLimitAddress()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

AddressErrorException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class AddressErrorException

java.lang.Object
java.lang.Throwable
java.lang.Exception
mars.mips.hardware.AddressErrorException

All Implemented Interfaces:
java.io.Serializable

public class AddressErrorException
extends java.lang.Exception

Represents MIPS AddressErrorException. This is generated by the assembler when the
source code references a memory address not valid for the context.

Author:
Pete Sanderson
See Also:
Serialized Form

Constructor Summary
AddressErrorException(java.lang.String message,
int exceptType,
int addr)

          Constructor for the AddressErrorException class

 

Method Summary

 int getAddress()

          Get the erroneous memory address.

 int getType()

          Get the exception type (load or store).

 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

AddressErrorException

public AddressErrorException(java.lang.String message,
int exceptType,
int addr)

Constructor for the AddressErrorException class

Parameters:
addr – The erroneous memory address.

Method Detail

getAddress

public int getAddress()

Get the erroneous memory address.

Returns:
The erroneous memory address.

getType

public int getType()

Get the exception type (load or store).

Returns:
Exception type: Exceptions.ADDRESS_EXCEPTION_LOAD, Exceptions.ADDRESS_EXCEPTION_STORE

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

mars.mips.hardware

Classes 

AccessNotice

Coprocessor0

Coprocessor1

Memory

MemoryAccessNotice

MemoryConfiguration

MemoryConfigurations

Register

RegisterAccessNotice

RegisterFile

Exceptions 

AddressErrorException

InvalidRegisterAccessException

InvalidRegisterAccessException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class InvalidRegisterAccessException

java.lang.Object
java.lang.Throwable
java.lang.Exception
mars.mips.hardware.InvalidRegisterAccessException

All Implemented Interfaces:
java.io.Serializable

public class InvalidRegisterAccessException
extends java.lang.Exception

Represents attempt to access double precision register using an odd
(e.g. $f1, $f23) register name.

Author:
Pete Sanderson
See Also:
Serialized Form

Constructor Summary
InvalidRegisterAccessException()

          Constructor for IllegalRegisterException.

 

Method Summary

 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

InvalidRegisterAccessException

public InvalidRegisterAccessException()

Constructor for IllegalRegisterException.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.mips.hardware

Class Summary
AccessNotice Object provided to Observers of runtime access to MIPS memory or registers.
Coprocessor0 Represents Coprocessor 0.
Coprocessor1 Represents Coprocessor 1, the Floating Point Unit (FPU)
Memory Represents MIPS memory.
MemoryAccessNotice Object provided to Observers of runtime access to MIPS memory.
MemoryConfiguration Models the memory configuration for the simulated MIPS machine.
MemoryConfigurations Models the collection of MIPS memory configurations.
Register Abstraction to represent a register of a MIPS Assembler.
RegisterAccessNotice Object provided to Observers of runtime access to MIPS register.
RegisterFile Represents the collection of MIPS registers.

 

Exception Summary
AddressErrorException Represents MIPS AddressErrorException.
InvalidRegisterAccessException Represents attempt to access double precision register using an odd
(e.g.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Memory

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class Memory

java.lang.Object
java.util.Observable
mars.mips.hardware.Memory

public class Memory
extends java.util.Observable

Represents MIPS memory. Different segments are represented by different data structs.

Author:
Pete Sanderson

Field Summary

static boolean BIG_ENDIAN

          Constant representing byte order of each memory word.

static int dataBaseAddress

          base address for storage of non-global static data in data segment: 0x10010000 (from SPIM)

static int dataSegmentBaseAddress

          base address for (user) data segment: 0x10000000

static int dataSegmentLimitAddress

           

static int exceptionHandlerAddress

          starting address for exception handlers: 0x80000180

static int externBaseAddress

          base address for .extern directive: 0x10000000

static int globalPointer

          base address for storing globals

static int heapAddress

           

static int heapBaseAddress

          base address for heap: 0x10040000 (I think from SPIM not MIPS)

static int kernelBaseAddress

          kernel boundary.

static int kernelDataBaseAddress

          base address for kernel data segment: 0x90000000

static int kernelDataSegmentLimitAddress

           

static int kernelHighAddress

          highest address acessible in kernel mode.

static int kernelTextBaseAddress

          base address for kernel text segment: 0x80000000

static int kernelTextLimitAddress

           

static boolean LITTLE_ENDIAN

          Constant representing byte order of each memory word.

static int memoryMapBaseAddress

          starting address for memory mapped I/O: 0xffff0000 (-65536)

static int memoryMapLimitAddress

           

static int stackBaseAddress

          base address for stack: 0x7ffffffc (this is mine – start of highest word below kernel space)

static int stackLimitAddress

           

static int stackPointer

          starting address for stack: 0x7fffeffc (this is from SPIM not MIPS)

static int textBaseAddress

          base address for (user) text segment: 0x00400000

static int textLimitAddress

           

static int userHighAddress

          highest address accessible in user (not kernel) mode.

static int WORD_LENGTH_BYTES

          MIPS word length in bytes.

 

Method Summary

 void addObserver(java.util.Observer obs)

          Method to accept registration from observer for any memory address.

 void addObserver(java.util.Observer obs,
int addr)

          Method to accept registration from observer for specific address.

 void addObserver(java.util.Observer obs,
int startAddr,
int endAddr)

          Method to accept registration from observer for specific address range.

static int alignToWordBoundary(int address)

          Utility method to align given address to next full word boundary, if not already
aligned.

 int allocateBytesFromHeap(int numBytes)

          Returns the next available word-aligned heap address.

 void clear()

          Explicitly clear the contents of memory.

 int countObservers()

          Return number of observers

 void deleteObserver(java.util.Observer obs)

          Remove specified memory observers

 void deleteObservers()

          Remove all memory observers

static boolean doublewordAligned(int address)

          Utility to determine if given address is doubleword-aligned.

 int get(int address,
int length)

          Starting at the given word address, read the given number of bytes (max 4).

 int getAddressOfFirstNull(int baseAddress,
int limitAddress)

          Look for first “null” memory value in an address range.

 int getByte(int address)

          Reads specified Memory byte into low order 8 bits of int.

 boolean getByteOrder()

          Retrieve memory byte order.

 int getHalf(int address)

          Starting at the given word address, read a 2 byte word into lower 16 bits of int.

static Memory getInstance()

          Returns the unique Memory instance, which becomes in essence global.

 int getRawWord(int address)

          Starting at the given word address, read a 4 byte word as an int.

 java.lang.Integer getRawWordOrNull(int address)

          Starting at the given word address, read a 4 byte word as an int and return Integer.

 ProgramStatement getStatement(int address)

          Gets ProgramStatement from Text Segment.

 ProgramStatement getStatementNoNotify(int address)

          Gets ProgramStatement from Text Segment without notifying observers.

 int getWord(int address)

          Starting at the given word address, read a 4 byte word as an int.

 int getWordNoNotify(int address)

          Starting at the given word address, read a 4 byte word as an int.

static boolean inDataSegment(int address)

          Handy little utility to find out if given address is in MARS data
segment (starts at Memory.dataSegmentBaseAddress).

static boolean inKernelDataSegment(int address)

          Handy little utility to find out if given address is in MARS kernel data
segment (starts at Memory.kernelDataSegmentBaseAddress).

static boolean inKernelTextSegment(int address)

          Handy little utility to find out if given address is in MARS kernel
text segment (starts at Memory.kernelTextBaseAddress).

static boolean inMemoryMapSegment(int address)

          Handy little utility to find out if given address is in the Memory Map area
starts at Memory.memoryMapBaseAddress, range 0xffff0000 to 0xffffffff.

static boolean inTextSegment(int address)

          Handy little utility to find out if given address is in MARS text
segment (starts at Memory.textBaseAddress).

 void notifyObservers()

          Overridden to be unavailable.

 void notifyObservers(java.lang.Object obj)

          Overridden to be unavailable.

 int set(int address,
int value,
int length)

          Starting at the given address, write the given value over the given number of bytes.

 int setByte(int address,
int value)

          Writes low order 8 bits of given value into specified Memory byte.

 void setByteOrder(boolean order)

          Set byte order to either LITTLE_ENDIAN or BIG_ENDIAN.

static void setConfiguration()

          Sets current memory configuration for simulated MIPS.

 double setDouble(int address,
double value)

          Writes 64 bit double value starting at specified Memory address.

 int setHalf(int address,
int value)

          Starting at the given halfword address, write the lower 16 bits of given value
into 2 bytes (a halfword).

 int setRawWord(int address,
int value)

          Starting at the given word address, write the given value over 4 bytes (a word).

 void setStatement(int address,
ProgramStatement statement)

          Stores ProgramStatement in Text Segment.

 int setWord(int address,
int value)

          Starting at the given word address, write the given value over 4 bytes (a word).

 boolean usingCompactMemoryConfiguration()

          Determine whether the current memory configuration has a maximum address that can be stored
in 16 bits.

static boolean wordAligned(int address)

          Utility to determine if given address is word-aligned.

 
Methods inherited from class java.util.Observable
clearChanged, hasChanged, setChanged

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

textBaseAddress

public static int textBaseAddress

base address for (user) text segment: 0x00400000

dataSegmentBaseAddress

public static int dataSegmentBaseAddress

base address for (user) data segment: 0x10000000

externBaseAddress

public static int externBaseAddress

base address for .extern directive: 0x10000000

globalPointer

public static int globalPointer

base address for storing globals

dataBaseAddress

public static int dataBaseAddress

base address for storage of non-global static data in data segment: 0x10010000 (from SPIM)

heapBaseAddress

public static int heapBaseAddress

base address for heap: 0x10040000 (I think from SPIM not MIPS)

stackPointer

public static int stackPointer

starting address for stack: 0x7fffeffc (this is from SPIM not MIPS)

stackBaseAddress

public static int stackBaseAddress

base address for stack: 0x7ffffffc (this is mine – start of highest word below kernel space)

userHighAddress

public static int userHighAddress

highest address accessible in user (not kernel) mode.

kernelBaseAddress

public static int kernelBaseAddress

kernel boundary. Only OS can access this or higher address

kernelTextBaseAddress

public static int kernelTextBaseAddress

base address for kernel text segment: 0x80000000

exceptionHandlerAddress

public static int exceptionHandlerAddress

starting address for exception handlers: 0x80000180

kernelDataBaseAddress

public static int kernelDataBaseAddress

base address for kernel data segment: 0x90000000

memoryMapBaseAddress

public static int memoryMapBaseAddress

starting address for memory mapped I/O: 0xffff0000 (-65536)

kernelHighAddress

public static int kernelHighAddress

highest address acessible in kernel mode.

WORD_LENGTH_BYTES

public static final int WORD_LENGTH_BYTES

MIPS word length in bytes.

See Also:
Constant Field Values

LITTLE_ENDIAN

public static final boolean LITTLE_ENDIAN

Constant representing byte order of each memory word. Little-endian means lowest
numbered byte is right most [3][2][1][0].

See Also:
Constant Field Values

BIG_ENDIAN

public static final boolean BIG_ENDIAN

Constant representing byte order of each memory word. Big-endian means lowest
numbered byte is left most [0][1][2][3].

See Also:
Constant Field Values

heapAddress

public static int heapAddress

dataSegmentLimitAddress

public static int dataSegmentLimitAddress

textLimitAddress

public static int textLimitAddress

kernelDataSegmentLimitAddress

public static int kernelDataSegmentLimitAddress

kernelTextLimitAddress

public static int kernelTextLimitAddress

stackLimitAddress

public static int stackLimitAddress

memoryMapLimitAddress

public static int memoryMapLimitAddress

Method Detail

getInstance

public static Memory getInstance()

Returns the unique Memory instance, which becomes in essence global.

clear

public void clear()

Explicitly clear the contents of memory. Typically done at start of assembly.

setConfiguration

public static void setConfiguration()

Sets current memory configuration for simulated MIPS. Configuration is
collection of memory segment addresses. e.g. text segment starting at
address 0x00400000. Configuration can be modified starting with MARS 3.7.

usingCompactMemoryConfiguration

public boolean usingCompactMemoryConfiguration()

Determine whether the current memory configuration has a maximum address that can be stored
in 16 bits.

Returns:
true if maximum address can be stored in 16 bits or less, false otherwise

allocateBytesFromHeap

public int allocateBytesFromHeap(int numBytes)
throws java.lang.IllegalArgumentException

Returns the next available word-aligned heap address. There is no recycling and
no heap management! There is however nearly 4MB of heap space available in Mars.

Parameters:
numBytes – Number of bytes requested. Should be multiple of 4, otherwise next higher multiple of 4 allocated.

Returns:
address of allocated heap storage.

Throws:

java.lang.IllegalArgumentException – if number of requested bytes is negative or exceeds available heap storage

setByteOrder

public void setByteOrder(boolean order)

Set byte order to either LITTLE_ENDIAN or BIG_ENDIAN. Default is LITTLE_ENDIAN.

Parameters:
order – either LITTLE_ENDIAN or BIG_ENDIAN

getByteOrder

public boolean getByteOrder()

Retrieve memory byte order. Default is LITTLE_ENDIAN (like PCs).

Returns:
either LITTLE_ENDIAN or BIG_ENDIAN

set

public int set(int address,
int value,
int length)
throws AddressErrorException

Starting at the given address, write the given value over the given number of bytes.
This one does not check for word boundaries, and copies one byte at a time.
If length == 1, takes value from low order byte. If 2, takes from low order half-word.

Parameters:
address – Starting address of Memory address to be set.
value – Value to be stored starting at that address.
length – Number of bytes to be written.

Returns:
old value that was replaced by the set operation

Throws:

AddressErrorException

setRawWord

public int setRawWord(int address,
int value)
throws AddressErrorException

Starting at the given word address, write the given value over 4 bytes (a word).
It must be written as is, without adjusting for byte order (little vs big endian).
Address must be word-aligned.

Parameters:
address – Starting address of Memory address to be set.
value – Value to be stored starting at that address.

Returns:
old value that was replaced by the set operation.

Throws:

AddressErrorException – If address is not on word boundary.

setWord

public int setWord(int address,
int value)
throws AddressErrorException

Starting at the given word address, write the given value over 4 bytes (a word).
The address must be word-aligned.

Parameters:
address – Starting address of Memory address to be set.
value – Value to be stored starting at that address.

Returns:
old value that was replaced by setWord operation.

Throws:

AddressErrorException – If address is not on word boundary.

setHalf

public int setHalf(int address,
int value)
throws AddressErrorException

Starting at the given halfword address, write the lower 16 bits of given value
into 2 bytes (a halfword).

Parameters:
address – Starting address of Memory address to be set.
value – Value to be stored starting at that address. Only low order 16 bits used.

Returns:
old value that was replaced by setHalf operation.

Throws:

AddressErrorException – If address is not on halfword boundary.

setByte

public int setByte(int address,
int value)
throws AddressErrorException

Writes low order 8 bits of given value into specified Memory byte.

Parameters:
address – Address of Memory byte to be set.
value – Value to be stored at that address. Only low order 8 bits used.

Returns:
old value that was replaced by setByte operation.

Throws:

AddressErrorException

setDouble

public double setDouble(int address,
double value)
throws AddressErrorException

Writes 64 bit double value starting at specified Memory address. Note that
high-order 32 bits are stored in higher (second) memory word regardless
of “endianness”.

Parameters:
address – Starting address of Memory address to be set.
value – Value to be stored at that address.

Returns:
old value that was replaced by setDouble operation.

Throws:

AddressErrorException

setStatement

public void setStatement(int address,
ProgramStatement statement)
throws AddressErrorException

Stores ProgramStatement in Text Segment.

Parameters:
address – Starting address of Memory address to be set. Must be word boundary.
statement – Machine code to be stored starting at that address — for simulation
purposes, actually stores reference to ProgramStatement instead of 32-bit machine code.

Throws:

AddressErrorException – If address is not on word boundary or is outside Text Segment.
See Also:
ProgramStatement

get

public int get(int address,
int length)
throws AddressErrorException

Starting at the given word address, read the given number of bytes (max 4).
This one does not check for word boundaries, and copies one byte at a time.
If length == 1, puts value in low order byte. If 2, puts into low order half-word.

Parameters:
address – Starting address of Memory address to be read.
length – Number of bytes to be read.

Returns:
Value stored starting at that address.

Throws:

AddressErrorException

getRawWord

public int getRawWord(int address)
throws AddressErrorException

Starting at the given word address, read a 4 byte word as an int.
It transfers the 32 bit value “raw” as stored in memory, and does not adjust
for byte order (big or little endian). Address must be word-aligned.

Parameters:
address – Starting address of word to be read.

Returns:
Word (4-byte value) stored starting at that address.

Throws:

AddressErrorException – If address is not on word boundary.

getRawWordOrNull

public java.lang.Integer getRawWordOrNull(int address)
throws AddressErrorException

Starting at the given word address, read a 4 byte word as an int and return Integer.
It transfers the 32 bit value “raw” as stored in memory, and does not adjust
for byte order (big or little endian). Address must be word-aligned.

Returns null if reading from text segment and there is no instruction at the
requested address. Returns null if reading from data segment and this is the
first reference to the MARS 4K memory allocation block (i.e., an array to
hold the memory has not been allocated).

This method was developed by Greg Giberling of UC Berkeley to support the memory
dump feature that he implemented in Fall 2007.

Parameters:
address – Starting address of word to be read.

Returns:
Word (4-byte value) stored starting at that address as an Integer. Conditions
that cause return value null are described above.

Throws:

AddressErrorException – If address is not on word boundary.

getAddressOfFirstNull

public int getAddressOfFirstNull(int baseAddress,
int limitAddress)
throws AddressErrorException

Look for first “null” memory value in an address range. For text segment (binary code), this
represents a word that does not contain an instruction. Normally use this to find the end of
the program. For data segment, this represents the first block of simulated memory (block length
currently 4K words) that has not been referenced by an assembled/executing program.

Parameters:
baseAddress – lowest MIPS address to be searched; the starting point
limitAddress – highest MIPS address to be searched

Returns:
lowest address within specified range that contains “null” value as described above.

Throws:

AddressErrorException – if the base address is not on a word boundary

getWord

public int getWord(int address)
throws AddressErrorException

Starting at the given word address, read a 4 byte word as an int.
Does not use “get()”; we can do it faster here knowing we’re working only
with full words.

Parameters:
address – Starting address of word to be read.

Returns:
Word (4-byte value) stored starting at that address.

Throws:

AddressErrorException – If address is not on word boundary.

getWordNoNotify

public int getWordNoNotify(int address)
throws AddressErrorException

Starting at the given word address, read a 4 byte word as an int.
Does not use “get()”; we can do it faster here knowing we’re working only
with full words. Observers are NOT notified.

Parameters:
address – Starting address of word to be read.

Returns:
Word (4-byte value) stored starting at that address.

Throws:

AddressErrorException – If address is not on word boundary.

getHalf

public int getHalf(int address)
throws AddressErrorException

Starting at the given word address, read a 2 byte word into lower 16 bits of int.

Parameters:
address – Starting address of word to be read.

Returns:
Halfword (2-byte value) stored starting at that address, stored in lower 16 bits.

Throws:

AddressErrorException – If address is not on halfword boundary.

getByte

public int getByte(int address)
throws AddressErrorException

Reads specified Memory byte into low order 8 bits of int.

Parameters:
address – Address of Memory byte to be read.

Returns:
Value stored at that address. Only low order 8 bits used.

Throws:

AddressErrorException

getStatement

public ProgramStatement getStatement(int address)
throws AddressErrorException

Gets ProgramStatement from Text Segment.

Parameters:
address – Starting address of Memory address to be read. Must be word boundary.

Returns:
reference to ProgramStatement object associated with that address, or null if none.

Throws:

AddressErrorException – If address is not on word boundary or is outside Text Segment.
See Also:
ProgramStatement

getStatementNoNotify

public ProgramStatement getStatementNoNotify(int address)
throws AddressErrorException

Gets ProgramStatement from Text Segment without notifying observers.

Parameters:
address – Starting address of Memory address to be read. Must be word boundary.

Returns:
reference to ProgramStatement object associated with that address, or null if none.

Throws:

AddressErrorException – If address is not on word boundary or is outside Text Segment.
See Also:
ProgramStatement

wordAligned

public static boolean wordAligned(int address)

Utility to determine if given address is word-aligned.

Parameters:
address – the address to check

Returns:
true if address is word-aligned, false otherwise

doublewordAligned

public static boolean doublewordAligned(int address)

Utility to determine if given address is doubleword-aligned.

Parameters:
address – the address to check

Returns:
true if address is doubleword-aligned, false otherwise

alignToWordBoundary

public static int alignToWordBoundary(int address)

Utility method to align given address to next full word boundary, if not already
aligned.

Parameters:
address – a memory address (any int value is potentially valid)

Returns:
address aligned to next word boundary (divisible by 4)

inTextSegment

public static boolean inTextSegment(int address)

Handy little utility to find out if given address is in MARS text
segment (starts at Memory.textBaseAddress).
Note that MARS does not implement the entire MIPS text segment space,
but it does implement enough for hundreds of thousands of lines
of code.

Parameters:
address – integer memory address

Returns:
true if that address is within MARS-defined text segment,
false otherwise.

inKernelTextSegment

public static boolean inKernelTextSegment(int address)

Handy little utility to find out if given address is in MARS kernel
text segment (starts at Memory.kernelTextBaseAddress).

Parameters:
address – integer memory address

Returns:
true if that address is within MARS-defined kernel text segment,
false otherwise.

inDataSegment

public static boolean inDataSegment(int address)

Handy little utility to find out if given address is in MARS data
segment (starts at Memory.dataSegmentBaseAddress).
Note that MARS does not implement the entire MIPS data segment space,
but it does support at least 4MB.

Parameters:
address – integer memory address

Returns:
true if that address is within MARS-defined data segment,
false otherwise.

inKernelDataSegment

public static boolean inKernelDataSegment(int address)

Handy little utility to find out if given address is in MARS kernel data
segment (starts at Memory.kernelDataSegmentBaseAddress).

Parameters:
address – integer memory address

Returns:
true if that address is within MARS-defined kernel data segment,
false otherwise.

inMemoryMapSegment

public static boolean inMemoryMapSegment(int address)

Handy little utility to find out if given address is in the Memory Map area
starts at Memory.memoryMapBaseAddress, range 0xffff0000 to 0xffffffff.

Parameters:
address – integer memory address

Returns:
true if that address is within MARS-defined memory map (MMIO) area,
false otherwise.

addObserver

public void addObserver(java.util.Observer obs)

Method to accept registration from observer for any memory address. Overrides
inherited method. Note to observers: this class delegates Observable operations
so notices will come from the delegate, not the memory object.

Overrides:
addObserver in class java.util.Observable

Parameters:
obs – the observer

addObserver

public void addObserver(java.util.Observer obs,
int addr)
throws AddressErrorException

Method to accept registration from observer for specific address. This includes
the memory word starting at the given address. Note to observers: this class delegates Observable operations
so notices will come from the delegate, not the memory object.

Parameters:
obs – the observer
addr – the memory address which must be on word boundary

Throws:

AddressErrorException

addObserver

public void addObserver(java.util.Observer obs,
int startAddr,
int endAddr)
throws AddressErrorException

Method to accept registration from observer for specific address range. The
last byte included in the address range is the last byte of the word specified
by the ending address. Note to observers: this class delegates Observable operations
so notices will come from the delegate, not the memory object.

Parameters:
obs – the observer
startAddr – the low end of memory address range, must be on word boundary
endAddr – the high end of memory address range, must be on word boundary

Throws:

AddressErrorException

countObservers

public int countObservers()

Return number of observers

Overrides:
countObservers in class java.util.Observable

deleteObserver

public void deleteObserver(java.util.Observer obs)

Remove specified memory observers

Overrides:
deleteObserver in class java.util.Observable

Parameters:
obs – Observer to be removed

deleteObservers

public void deleteObservers()

Remove all memory observers

Overrides:
deleteObservers in class java.util.Observable

notifyObservers

public void notifyObservers()

Overridden to be unavailable. The notice that an Observer
receives does not come from the memory object itself, but
instead from a delegate.

Overrides:
notifyObservers in class java.util.Observable

Throws:

java.lang.UnsupportedOperationException

notifyObservers

public void notifyObservers(java.lang.Object obj)

Overridden to be unavailable. The notice that an Observer
receives does not come from the memory object itself, but
instead from a delegate.

Overrides:
notifyObservers in class java.util.Observable

Throws:

java.lang.UnsupportedOperationException

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

RegisterAccessNotice

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class RegisterAccessNotice

java.lang.Object
mars.mips.hardware.AccessNotice
mars.mips.hardware.RegisterAccessNotice

public class RegisterAccessNotice
extends AccessNotice

Object provided to Observers of runtime access to MIPS register.
Observer can get the access type (R/W) and register number.

Author:
Pete Sanderson

Field Summary

 
Fields inherited from class mars.mips.hardware.AccessNotice
READ, WRITE

 

Method Summary

 java.lang.String getRegisterName()

          Fetch the register number of register accessed.

 java.lang.String toString()

          String representation indicates access type and which register

 
Methods inherited from class mars.mips.hardware.AccessNotice
accessIsFromGUI, accessIsFromMIPS, getAccessType, getThread

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Method Detail

getRegisterName

public java.lang.String getRegisterName()

Fetch the register number of register accessed.

toString

public java.lang.String toString()

String representation indicates access type and which register

Overrides:
toString in class java.lang.Object

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.mips.hardware

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object mars.mips.hardware.AccessNotice mars.mips.hardware.MemoryAccessNotice
mars.mips.hardware.RegisterAccessNotice

mars.mips.hardware.Coprocessor0
mars.mips.hardware.Coprocessor1
mars.mips.hardware.MemoryConfiguration
mars.mips.hardware.MemoryConfigurations
java.util.Observable mars.mips.hardware.Memory
mars.mips.hardware.Register

mars.mips.hardware.RegisterFile
java.lang.Throwable (implements java.io.Serializable)
java.lang.Exception mars.mips.hardware.AddressErrorException
mars.mips.hardware.InvalidRegisterAccessException

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

RegisterFile

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.hardware

Class RegisterFile

java.lang.Object
mars.mips.hardware.RegisterFile

public class RegisterFile
extends java.lang.Object

Represents the collection of MIPS registers.

Author:
Jason Bumgarner, Jason Shrewsbury

Field Summary

static int GLOBAL_POINTER_REGISTER

           

static int STACK_POINTER_REGISTER

           

 

Constructor Summary
RegisterFile()

           

 

Method Summary

static void addRegistersObserver(java.util.Observer observer)

          Each individual register is a separate object and Observable.

static void deleteRegistersObserver(java.util.Observer observer)

          Each individual register is a separate object and Observable.

static int getInitialProgramCounter()

          For returning the program counter’s initial (reset) value.

static int getNumber(java.lang.String n)

          For getting the number representation of the register.

static int getProgramCounter()

          For returning the program counters value.

static Register getProgramCounterRegister()

          Returns Register object for program counter.

static Register[] getRegisters()

          For returning the set of registers.

static Register getUserRegister(java.lang.String Rname)

          Get register object corresponding to given name.

static int getValue(int num)

          Returns the value of the register who’s number is num.

static void incrementPC()

          Method to increment the Program counter in the general case (not a jump or branch).

static void initializeProgramCounter(boolean startAtMain)

          Will initialize the Program Counter to either the default reset value, or the address
associated with source program global label “main”, if it exists as a text segment label
and the global setting is set.

static void initializeProgramCounter(int value)

          For initializing the Program Counter.

static void resetRegisters()

          Method to reinitialize the values of the registers.

static int setProgramCounter(int value)

          For setting the Program Counter.

static void showRegisters()

          Method for displaying the register values for debugging.

static int updateRegister(int num,
int val)

          This method updates the register value who’s number is num.

static void updateRegister(java.lang.String reg,
int val)

          Sets the value of the register given to the value given.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

GLOBAL_POINTER_REGISTER

public static final int GLOBAL_POINTER_REGISTER

See Also:
Constant Field Values

STACK_POINTER_REGISTER

public static final int STACK_POINTER_REGISTER

See Also:
Constant Field Values

Constructor Detail

RegisterFile

public RegisterFile()

Method Detail

showRegisters

public static void showRegisters()

Method for displaying the register values for debugging.

updateRegister

public static int updateRegister(int num,
int val)

This method updates the register value who’s number is num. Also handles the lo and hi registers

Parameters:
num – Register to set the value of.
val – The desired value for the register.

updateRegister

public static void updateRegister(java.lang.String reg,
int val)

Sets the value of the register given to the value given.

Parameters:
reg – Name of register to set the value of.
val – The desired value for the register.

getValue

public static int getValue(int num)

Returns the value of the register who’s number is num.

Parameters:
num – The register number.

Returns:
The value of the given register.

getNumber

public static int getNumber(java.lang.String n)

For getting the number representation of the register.

Parameters:
n – The string formatted register name to look for.

Returns:
The number of the register represented by the string
or -1 if no match.

getRegisters

public static Register[] getRegisters()

For returning the set of registers.

Returns:
The set of registers.

getUserRegister

public static Register getUserRegister(java.lang.String Rname)

Get register object corresponding to given name. If no match, return null.

Parameters:
Rname – The register name, either in $0 or $zero format.

Returns:
The register object,or null if not found.

initializeProgramCounter

public static void initializeProgramCounter(int value)

For initializing the Program Counter. Do not use this to implement jumps and
branches, as it will NOT record a backstep entry with the restore value.
If you need backstepping capability, use setProgramCounter instead.

Parameters:
value – The value to set the Program Counter to.

initializeProgramCounter

public static void initializeProgramCounter(boolean startAtMain)

Will initialize the Program Counter to either the default reset value, or the address
associated with source program global label “main”, if it exists as a text segment label
and the global setting is set.

Parameters:
startAtMain – If true, will set program counter to address of statement labeled
‘main’ (or other defined start label) if defined. If not defined, or if parameter false,
will set program counter to default reset value.

setProgramCounter

public static int setProgramCounter(int value)

For setting the Program Counter. Note that ordinary PC update should be done using
incrementPC() method. Use this only when processing jumps and branches.

Parameters:
value – The value to set the Program Counter to.

Returns:
previous PC value

getProgramCounter

public static int getProgramCounter()

For returning the program counters value.

Returns:
The program counters value as an int.

getProgramCounterRegister

public static Register getProgramCounterRegister()

Returns Register object for program counter. Use with caution.

Returns:
program counter’s Register object.

getInitialProgramCounter

public static int getInitialProgramCounter()

For returning the program counter’s initial (reset) value.

Returns:
The program counter’s initial value

resetRegisters

public static void resetRegisters()

Method to reinitialize the values of the registers.
NOTE: Should not be called from command-mode MARS because this
this method uses global settings from the registry. Command-mode must operate
using only the command switches, not registry settings. It can be called
from tools running stand-alone, and this is done in
AbstractMarsToolAndApplication.

incrementPC

public static void incrementPC()

Method to increment the Program counter in the general case (not a jump or branch).

addRegistersObserver

public static void addRegistersObserver(java.util.Observer observer)

Each individual register is a separate object and Observable. This handy method
will add the given Observer to each one. Currently does not apply to Program
Counter.

deleteRegistersObserver

public static void deleteRegistersObserver(java.util.Observer observer)

Each individual register is a separate object and Observable. This handy method
will delete the given Observer from each one. Currently does not apply to Program
Counter.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

AsciiTextDumpFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Class AsciiTextDumpFormat

java.lang.Object
mars.mips.dump.AbstractDumpFormat
mars.mips.dump.AsciiTextDumpFormat

All Implemented Interfaces:
DumpFormat

public class AsciiTextDumpFormat
extends AbstractDumpFormat

Class that represents the “ASCII text” memory dump format. Memory contents
are interpreted as ASCII codes. The output
is a text file with one word of MIPS memory per line. The word is formatted
to leave three spaces for each character. Non-printing characters
rendered as period (.) as placeholder. Common escaped characters
rendered using backslash and single-character descriptor, e.g. \t for tab.

Author:
Pete Sanderson

Constructor Summary
AsciiTextDumpFormat()

          Constructor.

 

Method Summary

 void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)

          Interpret MIPS memory contents as ASCII characters.

 
Methods inherited from class mars.mips.dump.AbstractDumpFormat
getCommandDescriptor, getDescription, getFileExtension, toString

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

AsciiTextDumpFormat

public AsciiTextDumpFormat()

Constructor. There is no standard file extension for this format.

Method Detail

dumpMemoryRange

public void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)
throws AddressErrorException,
java.io.IOException

Interpret MIPS memory contents as ASCII characters. Each line of
text contains one memory word written in ASCII characters. Those
corresponding to tab, newline, null, etc are rendered as backslash
followed by single-character code, e.g. \t for tab, \0 for null.
Non-printing character (control code,
values above 127) is rendered as a period (.). Written
using PrintStream’s println() method.
Adapted by Pete Sanderson from code written by Greg Gibeling.

Specified by:
dumpMemoryRange in interface DumpFormat
Specified by:
dumpMemoryRange in class AbstractDumpFormat

Parameters:
file – File in which to store MIPS memory contents.
firstAddress – first (lowest) memory address to dump. In bytes but
must be on word boundary.
lastAddress – last (highest) memory address to dump. In bytes but
must be on word boundary. Will dump the word that starts at this address.

Throws:

AddressErrorException – if firstAddress is invalid or not on a word boundary.

java.io.IOException – if error occurs during file output.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

BinaryTextDumpFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Class BinaryTextDumpFormat

java.lang.Object
mars.mips.dump.AbstractDumpFormat
mars.mips.dump.BinaryTextDumpFormat

All Implemented Interfaces:
DumpFormat

public class BinaryTextDumpFormat
extends AbstractDumpFormat

Class that represents the “binary text” memory dump format. The output
is a text file with one word of MIPS memory per line. The word is formatted
using ‘0’ and ‘1’ characters, e.g. 01110101110000011111110101010011.

Author:
Pete Sanderson

Constructor Summary
BinaryTextDumpFormat()

          Constructor.

 

Method Summary

 void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)

          Write MIPS memory contents in binary text format.

 
Methods inherited from class mars.mips.dump.AbstractDumpFormat
getCommandDescriptor, getDescription, getFileExtension, toString

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

BinaryTextDumpFormat

public BinaryTextDumpFormat()

Constructor. There is no standard file extension for this format.

Method Detail

dumpMemoryRange

public void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)
throws AddressErrorException,
java.io.IOException

Write MIPS memory contents in binary text format. Each line of
text contains one memory word written as 32 ‘0’ and ‘1’ characters. Written
using PrintStream’s println() method.
Adapted by Pete Sanderson from code written by Greg Gibeling.

Specified by:
dumpMemoryRange in interface DumpFormat
Specified by:
dumpMemoryRange in class AbstractDumpFormat

Parameters:
file – File in which to store MIPS memory contents.
firstAddress – first (lowest) memory address to dump. In bytes but
must be on word boundary.
lastAddress – last (highest) memory address to dump. In bytes but
must be on word boundary. Will dump the word that starts at this address.

Throws:

AddressErrorException – if firstAddress is invalid or not on a word boundary.

java.io.IOException – if error occurs during file output.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MIFDumpFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Class MIFDumpFormat

java.lang.Object
mars.mips.dump.MIFDumpFormat

public class MIFDumpFormat
extends java.lang.Object

The Memory Initialization File (.mif) VHDL-supported file format
This is documented for the Altera platform at
www.altera.com/support/software/nativelink/quartus2/glossary/def_mif.html.

Author:
Pete Sanderson

Constructor Summary
MIFDumpFormat()

          Constructor.

 

Method Summary

 void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)

          Write MIPS memory contents according to the Memory Initialization File
(MIF) specification.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

MIFDumpFormat

public MIFDumpFormat()

Constructor. File extention is “mif”.

Method Detail

dumpMemoryRange

public void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)
throws AddressErrorException,
java.io.IOException

Write MIPS memory contents according to the Memory Initialization File
(MIF) specification.

Parameters:
file – File in which to store MIPS memory contents.
firstAddress – first (lowest) memory address to dump. In bytes but
must be on word boundary.
lastAddress – last (highest) memory address to dump. In bytes but
must be on word boundary. Will dump the word that starts at this address.

Throws:

AddressErrorException – if firstAddress is invalid or not on a word boundary.

java.io.IOException – if error occurs during file output.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DumpFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Interface DumpFormat

All Known Implementing Classes:
AbstractDumpFormat, AsciiTextDumpFormat, BinaryDumpFormat, BinaryTextDumpFormat, HexTextDumpFormat, IntelHexDumpFormat, SegmentWindowDumpFormat

public interface DumpFormat

Interface for memory dump file formats. All MARS needs to be able
to do is save an assembled program or data in the specified manner for
a given format. Formats are specified through classes
that implement this interface.

Author:
Pete Sanderson

Method Summary

 void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)

          Write MIPS memory contents according to the
specification for this format.

 java.lang.String getCommandDescriptor()

          A short one-word descriptor that will be used by the MARS
command line parser (and the MARS command line user) to specify
that this format is to be used.

 java.lang.String getDescription()

          Get a short description of the format, suitable
for displaying along with the extension, if any, in the file
save dialog and also for displaying as a tool tip.

 java.lang.String getFileExtension()

          Get the file extension associated with this format.

 java.lang.String toString()

          Descriptive name for the format.

 

Method Detail

getFileExtension

java.lang.String getFileExtension()

Get the file extension associated with this format.

Returns:
String containing file extension — without the leading “.” — or
null if there is no standard extension.

getDescription

java.lang.String getDescription()

Get a short description of the format, suitable
for displaying along with the extension, if any, in the file
save dialog and also for displaying as a tool tip.

Returns:
String containing short description to go with the extension
or as tool tip when mouse hovers over GUI component representing
this format.

getCommandDescriptor

java.lang.String getCommandDescriptor()

A short one-word descriptor that will be used by the MARS
command line parser (and the MARS command line user) to specify
that this format is to be used.

toString

java.lang.String toString()

Descriptive name for the format.

Overrides:
toString in class java.lang.Object

Returns:
Format name.

dumpMemoryRange

void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)
throws AddressErrorException,
java.io.IOException

Write MIPS memory contents according to the
specification for this format.

Parameters:
file – File in which to store MIPS memory contents.
firstAddress – first (lowest) memory address to dump. In bytes but
must be on word boundary.
lastAddress – last (highest) memory address to dump. In bytes but
must be on word boundary. Will dump the word that starts at this address.

Throws:

AddressErrorException – if firstAddress is invalid or not on a word boundary.

java.io.IOException – if error occurs during file output.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

mars.mips.dump

Interfaces 

DumpFormat

Classes 

AbstractDumpFormat

AsciiTextDumpFormat

BinaryDumpFormat

BinaryTextDumpFormat

DumpFormatLoader

HexTextDumpFormat

IntelHexDumpFormat

MIFDumpFormat

SegmentWindowDumpFormat

SegmentWindowDumpFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Class SegmentWindowDumpFormat

java.lang.Object
mars.mips.dump.AbstractDumpFormat
mars.mips.dump.SegmentWindowDumpFormat

All Implemented Interfaces:
DumpFormat

public class SegmentWindowDumpFormat
extends AbstractDumpFormat

Dump MIPS memory contents in Segment Window format. Each line of
text output resembles the Text Segment Window or Data Segment Window
depending on which segment is selected for the dump. Written
using PrintStream’s println() method. Each line of Text Segment
Window represents one word of text segment memory. The line
includes (1) address, (2) machine code in hex, (3) basic instruction,
(4) source line. Each line of Data Segment Window represents 8
words of data segment memory. The line includes address of first
word for that line followed by 8 32-bit values.

In either case, addresses and values are displayed in decimal or
hexadecimal representation according to the corresponding settings.

Author:
Pete Sanderson

Constructor Summary
SegmentWindowDumpFormat()

          Constructor.

 

Method Summary

 void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)

          Write MIPS memory contents in Segment Window format.

 
Methods inherited from class mars.mips.dump.AbstractDumpFormat
getCommandDescriptor, getDescription, getFileExtension, toString

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

SegmentWindowDumpFormat

public SegmentWindowDumpFormat()

Constructor. There is no standard file extension for this format.

Method Detail

dumpMemoryRange

public void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)
throws AddressErrorException,
java.io.IOException

Write MIPS memory contents in Segment Window format. Each line of
text output resembles the Text Segment Window or Data Segment Window
depending on which segment is selected for the dump. Written
using PrintStream’s println() method.

Specified by:
dumpMemoryRange in interface DumpFormat
Specified by:
dumpMemoryRange in class AbstractDumpFormat

Parameters:
file – File in which to store MIPS memory contents.
firstAddress – first (lowest) memory address to dump. In bytes but
must be on word boundary.
lastAddress – last (highest) memory address to dump. In bytes but
must be on word boundary. Will dump the word that starts at this address.

Throws:

AddressErrorException – if firstAddress is invalid or not on a word boundary.

java.io.IOException – if error occurs during file output.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

DumpFormatLoader

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Class DumpFormatLoader

java.lang.Object
mars.mips.dump.DumpFormatLoader

public class DumpFormatLoader
extends java.lang.Object

Constructor Summary
DumpFormatLoader()

           

 

Method Summary

static DumpFormat findDumpFormatGivenCommandDescriptor(java.util.ArrayList formatList,
java.lang.String formatCommandDescriptor)

           

 java.util.ArrayList loadDumpFormats()

          Dynamically loads dump formats into an ArrayList.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

DumpFormatLoader

public DumpFormatLoader()

Method Detail

loadDumpFormats

public java.util.ArrayList loadDumpFormats()

Dynamically loads dump formats into an ArrayList. This method is adapted from
the loadGameControllers() method in Bret Barker’s GameServer class.
Barker ( ) is co-author of the book “Developing Games
in Java”. Also see the ToolLoader and SyscallLoader classes elsewhere in MARS.

findDumpFormatGivenCommandDescriptor

public static DumpFormat findDumpFormatGivenCommandDescriptor(java.util.ArrayList formatList,
java.lang.String formatCommandDescriptor)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.mips.dump

Interface Summary
DumpFormat Interface for memory dump file formats.

 

Class Summary
AbstractDumpFormat Abstract class for memory dump file formats.
AsciiTextDumpFormat Class that represents the “ASCII text” memory dump format.
BinaryDumpFormat Class that represents the “binary” memory dump format.
BinaryTextDumpFormat Class that represents the “binary text” memory dump format.
DumpFormatLoader  
HexTextDumpFormat Class that represents the “hexadecimal text” memory dump format.
IntelHexDumpFormat Intel’s Hex memory initialization format
MIFDumpFormat The Memory Initialization File (.mif) VHDL-supported file format
This is documented for the Altera platform at
www.altera.com/support/software/nativelink/quartus2/glossary/def_mif.html.
SegmentWindowDumpFormat Dump MIPS memory contents in Segment Window format.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

mars.mips.dump Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.mips.dump

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object mars.mips.dump.AbstractDumpFormat (implements mars.mips.dump.DumpFormat)
mars.mips.dump.AsciiTextDumpFormat
mars.mips.dump.BinaryDumpFormat
mars.mips.dump.BinaryTextDumpFormat
mars.mips.dump.HexTextDumpFormat
mars.mips.dump.IntelHexDumpFormat
mars.mips.dump.SegmentWindowDumpFormat

mars.mips.dump.DumpFormatLoader
mars.mips.dump.MIFDumpFormat

Interface Hierarchy

mars.mips.dump.DumpFormat

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

AbstractDumpFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Class AbstractDumpFormat

java.lang.Object
mars.mips.dump.AbstractDumpFormat

All Implemented Interfaces:
DumpFormat

Direct Known Subclasses:
AsciiTextDumpFormat, BinaryDumpFormat, BinaryTextDumpFormat, HexTextDumpFormat, IntelHexDumpFormat, SegmentWindowDumpFormat

public abstract class AbstractDumpFormat
extends java.lang.Object
implements DumpFormat

Abstract class for memory dump file formats. Provides constructors and
defaults for everything except the dumpMemoryRange method itself.

Author:
Pete Sanderson

Constructor Summary
AbstractDumpFormat(java.lang.String name,
java.lang.String commandDescriptor,
java.lang.String description,
java.lang.String extension)

          Typical constructor.

 

Method Summary

abstract  void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)

          Write MIPS memory contents according to the
specification for this format.

 java.lang.String getCommandDescriptor()

          One-word description of format to be used by MARS command mode parser
and user in conjunction with the “dump” option.

 java.lang.String getDescription()

          Get a short description of the format, suitable for displaying along with
the extension, in the file save dialog, or as a tool tip.

 java.lang.String getFileExtension()

          Get the file extension associated with this format.

 java.lang.String toString()

          String representing this object.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

AbstractDumpFormat

public AbstractDumpFormat(java.lang.String name,
java.lang.String commandDescriptor,
java.lang.String description,
java.lang.String extension)

Typical constructor. Note you cannot creates objects from this
class but subclass constructor can call this one.

Parameters:
name – Brief descriptive name to be displayed in selection list.
commandDescriptor – One-word descriptive name to be used by MARS command mode parser and user.
Any spaces in this string will be removed.
description – Description to go with standard file extension for
display in file save dialog or to be used as tool tip.
extension – Standard file extension for this format. Null if none.

Method Detail

getFileExtension

public java.lang.String getFileExtension()

Get the file extension associated with this format.

Specified by:
getFileExtension in interface DumpFormat

Returns:
String containing file extension — without the leading “.” — or
null if there is no standard extension.

getDescription

public java.lang.String getDescription()

Get a short description of the format, suitable for displaying along with
the extension, in the file save dialog, or as a tool tip.

Specified by:
getDescription in interface DumpFormat

Returns:
String containing short description to go with the extension
or for use as tool tip. Possibly null.

toString

public java.lang.String toString()

String representing this object.

Specified by:
toString in interface DumpFormat
Overrides:
toString in class java.lang.Object

Returns:
Name given for this object.

getCommandDescriptor

public java.lang.String getCommandDescriptor()

One-word description of format to be used by MARS command mode parser
and user in conjunction with the “dump” option.

Specified by:
getCommandDescriptor in interface DumpFormat

Returns:
One-word String describing the format.

dumpMemoryRange

public abstract void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)
throws AddressErrorException,
java.io.IOException

Write MIPS memory contents according to the
specification for this format.

Specified by:
dumpMemoryRange in interface DumpFormat

Parameters:
file – File in which to store MIPS memory contents.
firstAddress – first (lowest) memory address to dump. In bytes but
must be on word boundary.
lastAddress – last (highest) memory address to dump. In bytes but
must be on word boundary. Will dump the word that starts at this address.

Throws:

AddressErrorException – if firstAddress is invalid or not on a word boundary.

java.io.IOException – if error occurs during file output.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

BinaryDumpFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Class BinaryDumpFormat

java.lang.Object
mars.mips.dump.AbstractDumpFormat
mars.mips.dump.BinaryDumpFormat

All Implemented Interfaces:
DumpFormat

public class BinaryDumpFormat
extends AbstractDumpFormat

Class that represents the “binary” memory dump format. The output
is a binary file containing the memory words as a byte stream. Output
is produced using PrintStream’s write() method.

Author:
Pete Sanderson

Constructor Summary
BinaryDumpFormat()

          Constructor.

 

Method Summary

 void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)

          Write MIPS memory contents in pure binary format.

 
Methods inherited from class mars.mips.dump.AbstractDumpFormat
getCommandDescriptor, getDescription, getFileExtension, toString

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

BinaryDumpFormat

public BinaryDumpFormat()

Constructor. There is no standard file extension for this format.

Method Detail

dumpMemoryRange

public void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)
throws AddressErrorException,
java.io.IOException

Write MIPS memory contents in pure binary format. One byte at a time
using PrintStream’s write() method. Adapted by Pete Sanderson from
code written by Greg Gibeling.

Specified by:
dumpMemoryRange in interface DumpFormat
Specified by:
dumpMemoryRange in class AbstractDumpFormat

Parameters:
file – File in which to store MIPS memory contents.
firstAddress – first (lowest) memory address to dump. In bytes but
must be on word boundary.
lastAddress – last (highest) memory address to dump. In bytes but
must be on word boundary. Will dump the word that starts at this address.

Throws:

AddressErrorException – if firstAddress is invalid or not on a word boundary.

java.io.IOException – if error occurs during file output.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

HexTextDumpFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Class HexTextDumpFormat

java.lang.Object
mars.mips.dump.AbstractDumpFormat
mars.mips.dump.HexTextDumpFormat

All Implemented Interfaces:
DumpFormat

public class HexTextDumpFormat
extends AbstractDumpFormat

Class that represents the “hexadecimal text” memory dump format. The output
is a text file with one word of MIPS memory per line. The word is formatted
using hexadecimal characters, e.g. 3F205A39.

Author:
Pete Sanderson

Constructor Summary
HexTextDumpFormat()

          Constructor.

 

Method Summary

 void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)

          Write MIPS memory contents in hexadecimal text format.

 
Methods inherited from class mars.mips.dump.AbstractDumpFormat
getCommandDescriptor, getDescription, getFileExtension, toString

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

HexTextDumpFormat

public HexTextDumpFormat()

Constructor. There is no standard file extension for this format.

Method Detail

dumpMemoryRange

public void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)
throws AddressErrorException,
java.io.IOException

Write MIPS memory contents in hexadecimal text format. Each line of
text contains one memory word written in hexadecimal characters. Written
using PrintStream’s println() method.
Adapted by Pete Sanderson from code written by Greg Gibeling.

Specified by:
dumpMemoryRange in interface DumpFormat
Specified by:
dumpMemoryRange in class AbstractDumpFormat

Parameters:
file – File in which to store MIPS memory contents.
firstAddress – first (lowest) memory address to dump. In bytes but
must be on word boundary.
lastAddress – last (highest) memory address to dump. In bytes but
must be on word boundary. Will dump the word that starts at this address.

Throws:

AddressErrorException – if firstAddress is invalid or not on a word boundary.

java.io.IOException – if error occurs during file output.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

IntelHexDumpFormat

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.mips.dump

Class IntelHexDumpFormat

java.lang.Object
mars.mips.dump.AbstractDumpFormat
mars.mips.dump.IntelHexDumpFormat

All Implemented Interfaces:
DumpFormat

public class IntelHexDumpFormat
extends AbstractDumpFormat

Intel’s Hex memory initialization format

Author:
Leo Alterman

Constructor Summary
IntelHexDumpFormat()

          Constructor.

 

Method Summary

 void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)

          Write MIPS memory contents according to the Memory Initialization File
(MIF) specification.

 
Methods inherited from class mars.mips.dump.AbstractDumpFormat
getCommandDescriptor, getDescription, getFileExtension, toString

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

IntelHexDumpFormat

public IntelHexDumpFormat()

Constructor. File extention is “hex”.

Method Detail

dumpMemoryRange

public void dumpMemoryRange(java.io.File file,
int firstAddress,
int lastAddress)
throws AddressErrorException,
java.io.IOException

Write MIPS memory contents according to the Memory Initialization File
(MIF) specification.

Specified by:
dumpMemoryRange in interface DumpFormat
Specified by:
dumpMemoryRange in class AbstractDumpFormat

Parameters:
file – File in which to store MIPS memory contents.
firstAddress – first (lowest) memory address to dump. In bytes but
must be on word boundary.
lastAddress – last (highest) memory address to dump. In bytes but
must be on word boundary. Will dump the word that starts at this address.

Throws:

AddressErrorException – if firstAddress is invalid or not on a word boundary.

java.io.IOException – if error occurs during file output.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

mars

Classes 

ErrorList

ErrorMessage

Globals

MarsLaunch

MarsSplashScreen

MIPSprogram

ProgramStatement

Settings

Exceptions 

ProcessingException

ErrorMessage

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

Class ErrorMessage

java.lang.Object
mars.ErrorMessage

public class ErrorMessage
extends java.lang.Object

Represents occurrance of an error detected during tokenizing, assembly or simulation.

Author:
Pete Sanderson

Field Summary

static boolean ERROR

          Constant to indicate this message is error not warning

static boolean WARNING

          Constant to indicate this message is warning not error

 

Constructor Summary
ErrorMessage(boolean isWarning,
MIPSprogram sourceMIPSprogram,
int line,
int position,
java.lang.String message)

          Constructor for ErrorMessage.
ErrorMessage(boolean isWarning,
java.lang.String filename,
int line,
int position,
java.lang.String message,
java.lang.String macroExpansionHistory)

          Deprecated. Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.
ErrorMessage(MIPSprogram sourceMIPSprogram,
int line,
int position,
java.lang.String message)

          Constructor for ErrorMessage.
ErrorMessage(java.lang.String filename,
int line,
int position,
java.lang.String message)

          Deprecated. Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.
ErrorMessage(java.lang.String filename,
int line,
int position,
java.lang.String message,
java.lang.String macroExpansionHistory)

          Deprecated. Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.

 

Method Summary

 java.lang.String getFilename()

          Produce name of file containing error.

 int getLine()

          Produce line number of error.

 java.lang.String getMacroExpansionHistory()

          Returns string describing macro expansion.

 java.lang.String getMessage()

          Produce error message.

 int getPosition()

          Produce position within erroneous line.

 boolean isWarning()

          Determine whether this message represents error or warning.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

WARNING

public static final boolean WARNING

Constant to indicate this message is warning not error

See Also:
Constant Field Values

ERROR

public static final boolean ERROR

Constant to indicate this message is error not warning

See Also:
Constant Field Values

Constructor Detail

ErrorMessage

@Deprecated
public ErrorMessage(java.lang.String filename,
int line,
int position,
java.lang.String message)

Deprecated. Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.

Constructor for ErrorMessage.

Parameters:
filename – String containing name of source file in which this error appears.
line – Line number in source program being processed when error occurred.
position – Position within line being processed when error occurred. Normally is starting
position of source token.
message – String containing appropriate error message.

ErrorMessage

@Deprecated
public ErrorMessage(java.lang.String filename,
int line,
int position,
java.lang.String message,
java.lang.String macroExpansionHistory)

Deprecated. Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.

Constructor for ErrorMessage.

Parameters:
filename – String containing name of source file in which this error appears.
line – Line number in source program being processed when error occurred.
position – Position within line being processed when error occurred. Normally is starting
position of source token.
message – String containing appropriate error message.
macroExpansionHistory –

ErrorMessage

@Deprecated
public ErrorMessage(boolean isWarning,
java.lang.String filename,
int line,
int position,
java.lang.String message,
java.lang.String macroExpansionHistory)

Deprecated. Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.

Constructor for ErrorMessage.

Parameters:
isWarning – set to WARNING if message is a warning not error, else set to ERROR or omit.
filename – String containing name of source file in which this error appears.
line – Line number in source program being processed when error occurred.
position – Position within line being processed when error occurred. Normally is starting
position of source token.
message – String containing appropriate error message.
macroExpansionHistory – provided so message for macro can include both definition and usage line numbers

ErrorMessage

public ErrorMessage(MIPSprogram sourceMIPSprogram,
int line,
int position,
java.lang.String message)

Constructor for ErrorMessage. Assumes line number is calculated after any .include files expanded, and
if there were, it will adjust filename and line number so message reflects original file and line number.

Parameters:
sourceMIPSprogram – MIPSprogram object of source file in which this error appears.
line – Line number in source program being processed when error occurred.
position – Position within line being processed when error occurred. Normally is starting
position of source token.
message – String containing appropriate error message.

ErrorMessage

public ErrorMessage(boolean isWarning,
MIPSprogram sourceMIPSprogram,
int line,
int position,
java.lang.String message)

Constructor for ErrorMessage. Assumes line number is calculated after any .include files expanded, and
if there were, it will adjust filename and line number so message reflects original file and line number.

Parameters:
isWarning – set to WARNING if message is a warning not error, else set to ERROR or omit.
sourceMIPSprogram – MIPSprogram object of source file in which this error appears.
line – Line number in source program being processed when error occurred.
position – Position within line being processed when error occurred. Normally is starting
position of source token.
message – String containing appropriate error message.

Method Detail

getFilename

public java.lang.String getFilename()

Produce name of file containing error.

Returns:
Returns String containing name of source file containing the error.

getLine

public int getLine()

Produce line number of error.

Returns:
Returns line number in source program where error occurred.

getPosition

public int getPosition()

Produce position within erroneous line.

Returns:
Returns position within line of source program where error occurred.

getMessage

public java.lang.String getMessage()

Produce error message.

Returns:
Returns String containing textual error message.

isWarning

public boolean isWarning()

Determine whether this message represents error or warning.

Returns:
Returns true if this message reflects warning, false if error.

getMacroExpansionHistory

public java.lang.String getMacroExpansionHistory()

Returns string describing macro expansion. Empty string if none.

Returns:
string describing macro expansion

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

BackStepper

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator

Class BackStepper

java.lang.Object
mars.simulator.BackStepper

public class BackStepper
extends java.lang.Object

Used to “step backward” through execution, undoing each instruction.

Author:
Pete Sanderson

Constructor Summary
BackStepper()

          Create a fresh BackStepper.

 

Method Summary

 int addConditionFlagClear(int flag)

          Add a new “back step” (the undo action) to the stack.

 int addConditionFlagSet(int flag)

          Add a new “back step” (the undo action) to the stack.

 int addCoprocessor0Restore(int register,
int value)

          Add a new “back step” (the undo action) to the stack.

 int addCoprocessor1Restore(int register,
int value)

          Add a new “back step” (the undo action) to the stack.

 int addDoNothing(int pc)

          Add a new “back step” (the undo action) to the stack.

 int addMemoryRestoreByte(int address,
int value)

          Add a new “back step” (the undo action) to the stack.

 int addMemoryRestoreHalf(int address,
int value)

          Add a new “back step” (the undo action) to the stack.

 int addMemoryRestoreRawWord(int address,
int value)

          Add a new “back step” (the undo action) to the stack.

 int addMemoryRestoreWord(int address,
int value)

          Add a new “back step” (the undo action) to the stack.

 int addPCRestore(int value)

          Add a new “back step” (the undo action) to the stack.

 int addRegisterFileRestore(int register,
int value)

          Add a new “back step” (the undo action) to the stack.

 void backStep()

          Carry out a “back step”, which will undo the latest execution step.

 boolean empty()

          Test whether there are steps that can be undone.

 boolean enabled()

          Determine whether execution “undo” steps are currently being recorded.

 boolean inDelaySlot()

          Determine whether the next back-step action occurred as the result of
an instruction that executed in the “delay slot” of a delayed branch.

 void setEnabled(boolean state)

          Set enable status.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

BackStepper

public BackStepper()

Create a fresh BackStepper. It is enabled, which means all
subsequent instruction executions will have their “undo” action
recorded here.

Method Detail

enabled

public boolean enabled()

Determine whether execution “undo” steps are currently being recorded.

Returns:
true if undo steps being recorded, false if not.

setEnabled

public void setEnabled(boolean state)

Set enable status.

Parameters:
state – If true, will begin (or continue) recoding “undo” steps. If false, will stop.

empty

public boolean empty()

Test whether there are steps that can be undone.

Returns:
true if there are no steps to be undone, false otherwise.

inDelaySlot

public boolean inDelaySlot()

Determine whether the next back-step action occurred as the result of
an instruction that executed in the “delay slot” of a delayed branch.

Returns:
true if next backstep is instruction that executed in delay slot,
false otherwise.

backStep

public void backStep()

Carry out a “back step”, which will undo the latest execution step.
Does nothing if backstepping not enabled or if there are no steps to undo.

addMemoryRestoreRawWord

public int addMemoryRestoreRawWord(int address,
int value)

Add a new “back step” (the undo action) to the stack. The action here
is to restore a raw memory word value (setRawWord).

Parameters:
address – The affected memory address.
value – The “restore” value to be stored there.

Returns:
the argument value

addMemoryRestoreWord

public int addMemoryRestoreWord(int address,
int value)

Add a new “back step” (the undo action) to the stack. The action here
is to restore a memory word value.

Parameters:
address – The affected memory address.
value – The “restore” value to be stored there.

Returns:
the argument value

addMemoryRestoreHalf

public int addMemoryRestoreHalf(int address,
int value)

Add a new “back step” (the undo action) to the stack. The action here
is to restore a memory half-word value.

Parameters:
address – The affected memory address.
value – The “restore” value to be stored there, in low order half.

Returns:
the argument value

addMemoryRestoreByte

public int addMemoryRestoreByte(int address,
int value)

Add a new “back step” (the undo action) to the stack. The action here
is to restore a memory byte value.

Parameters:
address – The affected memory address.
value – The “restore” value to be stored there, in low order byte.

Returns:
the argument value

addRegisterFileRestore

public int addRegisterFileRestore(int register,
int value)

Add a new “back step” (the undo action) to the stack. The action here
is to restore a register file register value.

Parameters:
register – The affected register number.
value – The “restore” value to be stored there.

Returns:
the argument value

addPCRestore

public int addPCRestore(int value)

Add a new “back step” (the undo action) to the stack. The action here
is to restore the program counter.

Parameters:
value – The “restore” value to be stored there.

Returns:
the argument value

addCoprocessor0Restore

public int addCoprocessor0Restore(int register,
int value)

Add a new “back step” (the undo action) to the stack. The action here
is to restore a coprocessor 0 register value.

Parameters:
register – The affected register number.
value – The “restore” value to be stored there.

Returns:
the argument value

addCoprocessor1Restore

public int addCoprocessor1Restore(int register,
int value)

Add a new “back step” (the undo action) to the stack. The action here
is to restore a coprocessor 1 register value.

Parameters:
register – The affected register number.
value – The “restore” value to be stored there.

Returns:
the argument value

addConditionFlagSet

public int addConditionFlagSet(int flag)

Add a new “back step” (the undo action) to the stack. The action here
is to set the given coprocessor 1 condition flag (to 1).

Parameters:
flag – The condition flag number.

Returns:
the argument value

addConditionFlagClear

public int addConditionFlagClear(int flag)

Add a new “back step” (the undo action) to the stack. The action here
is to clear the given coprocessor 1 condition flag (to 0).

Parameters:
flag – The condition flag number.

Returns:
the argument value

addDoNothing

public int addDoNothing(int pc)

Add a new “back step” (the undo action) to the stack. The action here
is to do nothing! This is just a place holder so when user is backstepping
through the program no instructions will be skipped. Cosmetic. If the top of the
stack has the same PC counter, the do-nothing action will not be added.

Returns:
0

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Exceptions

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator

Class Exceptions

java.lang.Object
mars.simulator.Exceptions

public class Exceptions
extends java.lang.Object

Represents an error/interrupt that occurs during execution (simulation).

Author:
Pete Sanderson

Field Summary

static int ADDRESS_EXCEPTION_LOAD

           

static int ADDRESS_EXCEPTION_STORE

           

static int ARITHMETIC_OVERFLOW_EXCEPTION

           

static int BREAKPOINT_EXCEPTION

           

static int DIVIDE_BY_ZERO_EXCEPTION

           

static int EXTERNAL_INTERRUPT_DISPLAY

           

static int EXTERNAL_INTERRUPT_KEYBOARD

          The exception number is stored in coprocessor 0 cause register ($13)
Note: the codes for External Interrupts have been modified from MIPS
specs in order to encode two pieces of information.

static int FLOATING_POINT_OVERFLOW

           

static int FLOATING_POINT_UNDERFLOW

           

static int RESERVED_INSTRUCTION_EXCEPTION

           

static int SYSCALL_EXCEPTION

           

static int TRAP_EXCEPTION

           

 

Constructor Summary
Exceptions()

           

 

Method Summary

static void setRegisters(int cause)

          Given MIPS exception cause code, will place that code into
coprocessor 0 CAUSE register ($13), set the EPC register to
“current” program counter, and set Exception Level bit in STATUS register.

static void setRegisters(int cause,
int addr)

          Given MIPS exception cause code and bad address, place the bad address into VADDR
register ($8) then call overloaded setRegisters with the cause code to do the rest.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

EXTERNAL_INTERRUPT_KEYBOARD

public static final int EXTERNAL_INTERRUPT_KEYBOARD

The exception number is stored in coprocessor 0 cause register ($13)
Note: the codes for External Interrupts have been modified from MIPS
specs in order to encode two pieces of information. According
to spec, there is one External Interrupt code, 0. But then
how to distinguish keyboard interrupt from display interrupt?
The Cause register has Interupt Pending bits that can be set.
Bit 8 represents keyboard, bit 9 represents display. Those
bits are included into this code, but shifted right two positions
since the interrupt code will be shifted left two positions
for inserting cause code into bit positions 2-6 in Cause register.
DPS 23 July 2008.

See Also:
Constant Field Values

EXTERNAL_INTERRUPT_DISPLAY

public static final int EXTERNAL_INTERRUPT_DISPLAY

See Also:
Constant Field Values

ADDRESS_EXCEPTION_LOAD

public static final int ADDRESS_EXCEPTION_LOAD

See Also:
Constant Field Values

ADDRESS_EXCEPTION_STORE

public static final int ADDRESS_EXCEPTION_STORE

See Also:
Constant Field Values

SYSCALL_EXCEPTION

public static final int SYSCALL_EXCEPTION

See Also:
Constant Field Values

BREAKPOINT_EXCEPTION

public static final int BREAKPOINT_EXCEPTION

See Also:
Constant Field Values

RESERVED_INSTRUCTION_EXCEPTION

public static final int RESERVED_INSTRUCTION_EXCEPTION

See Also:
Constant Field Values

ARITHMETIC_OVERFLOW_EXCEPTION

public static final int ARITHMETIC_OVERFLOW_EXCEPTION

See Also:
Constant Field Values

TRAP_EXCEPTION

public static final int TRAP_EXCEPTION

See Also:
Constant Field Values

DIVIDE_BY_ZERO_EXCEPTION

public static final int DIVIDE_BY_ZERO_EXCEPTION

See Also:
Constant Field Values

FLOATING_POINT_OVERFLOW

public static final int FLOATING_POINT_OVERFLOW

See Also:
Constant Field Values

FLOATING_POINT_UNDERFLOW

public static final int FLOATING_POINT_UNDERFLOW

See Also:
Constant Field Values

Constructor Detail

Exceptions

public Exceptions()

Method Detail

setRegisters

public static void setRegisters(int cause)

Given MIPS exception cause code, will place that code into
coprocessor 0 CAUSE register ($13), set the EPC register to
“current” program counter, and set Exception Level bit in STATUS register.

Parameters:
cause – The cause code (see Exceptions for a list)

setRegisters

public static void setRegisters(int cause,
int addr)

Given MIPS exception cause code and bad address, place the bad address into VADDR
register ($8) then call overloaded setRegisters with the cause code to do the rest.

Parameters:
cause – The cause code (see Exceptions for a list). Should be address exception.
addr – The address that caused the exception.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator

mars.simulator

Interfaces 

Simulator.StopListener

Classes 

BackStepper

DelayedBranch

Exceptions

ProgramArgumentList

Simulator

SimulatorNotice

SwingWorker

Simulator.StopListener

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator

Interface Simulator.StopListener

Enclosing class:
Simulator

public static interface Simulator.StopListener

Method Summary

 void stopped(Simulator s)

           

 

Method Detail

stopped

void stopped(Simulator s)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Simulator

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator

Class Simulator

java.lang.Object
java.util.Observable
mars.simulator.Simulator

public class Simulator
extends java.util.Observable

Used to simulate the execution of an assembled MIPS program.

Author:
Pete Sanderson

Nested Class Summary

static interface Simulator.StopListener

           

 

Field Summary

static int BREAKPOINT

          various reasons for simulate to end…

static int CLIFF_TERMINATION

           

static int EXCEPTION

           

static int externalInterruptingDevice

           

static int MAX_STEPS

           

static int NO_DEVICE

           

static int NORMAL_TERMINATION

           

static int PAUSE_OR_STOP

           

 

Method Summary

 void addStopListener(Simulator.StopListener l)

           

static Simulator getInstance()

          Returns the Simulator object

static boolean inDelaySlot()

          Determine whether or not the next instruction to be executed is in a
“delay slot”.

 void removeStopListener(Simulator.StopListener l)

           

 boolean simulate(MIPSprogram p,
int pc,
int maxSteps,
int[] breakPoints,
javax.swing.AbstractAction actor)

          Simulate execution of given MIPS program.

 void stopExecution(javax.swing.AbstractAction actor)

          Set the volatile stop boolean variable checked by the execution
thread at the end of each MIPS instruction execution.

 
Methods inherited from class java.util.Observable
addObserver, clearChanged, countObservers, deleteObserver, deleteObservers, hasChanged, notifyObservers, notifyObservers, setChanged

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

NO_DEVICE

public static final int NO_DEVICE

See Also:
Constant Field Values

externalInterruptingDevice

public static volatile int externalInterruptingDevice

BREAKPOINT

public static final int BREAKPOINT

various reasons for simulate to end…

See Also:
Constant Field Values

EXCEPTION

public static final int EXCEPTION

See Also:
Constant Field Values

MAX_STEPS

public static final int MAX_STEPS

See Also:
Constant Field Values

NORMAL_TERMINATION

public static final int NORMAL_TERMINATION

See Also:
Constant Field Values

CLIFF_TERMINATION

public static final int CLIFF_TERMINATION

See Also:
Constant Field Values

PAUSE_OR_STOP

public static final int PAUSE_OR_STOP

See Also:
Constant Field Values

Method Detail

getInstance

public static Simulator getInstance()

Returns the Simulator object

Returns:
the Simulator object in use

inDelaySlot

public static boolean inDelaySlot()

Determine whether or not the next instruction to be executed is in a
“delay slot”. This means delayed branching is enabled, the branch
condition has evaluated true, and the next instruction executed will
be the one following the branch. It is said to occupy the “delay slot.”
Normally programmers put a nop instruction here but it can be anything.

Returns:
true if next instruction is in delay slot, false otherwise.

simulate

public boolean simulate(MIPSprogram p,
int pc,
int maxSteps,
int[] breakPoints,
javax.swing.AbstractAction actor)
throws ProcessingException

Simulate execution of given MIPS program. It must have already been assembled.

Parameters:
p – The MIPSprogram to be simulated.
pc – address of first instruction to simulate; this goes into program counter
maxSteps – maximum number of steps to perform before returning false (0 or less means no max)
breakPoints – array of breakpoint program counter values, use null if none
actor – the GUI component responsible for this call, usually GO or STEP. null if none.

Returns:
true if execution completed, false otherwise

Throws:

ProcessingException – Throws exception if run-time exception occurs.

stopExecution

public void stopExecution(javax.swing.AbstractAction actor)

Set the volatile stop boolean variable checked by the execution
thread at the end of each MIPS instruction execution. If variable
is found to be true, the execution thread will depart
gracefully so the main thread handling the GUI can take over.
This is used by both STOP and PAUSE features.

addStopListener

public void addStopListener(Simulator.StopListener l)

removeStopListener

public void removeStopListener(Simulator.StopListener l)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

SimulatorNotice

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator

Class SimulatorNotice

java.lang.Object
mars.simulator.SimulatorNotice

public class SimulatorNotice
extends java.lang.Object

Object provided to Observers of the Simulator.
They are notified at important phases of the runtime simulator,
such as start and stop of simulation.

Author:
Pete Sanderson

Field Summary

static int SIMULATOR_START

           

static int SIMULATOR_STOP

           

 

Constructor Summary
SimulatorNotice(int action,
int maxSteps,
double runSpeed,
int programCounter)

          Constructor will be called only within this package, so assume
address and length are in valid ranges.

 

Method Summary

 int getAction()

          Fetch the memory address that was accessed.

 int getMaxSteps()

          Fetch the length in bytes of the access operation (4,2,1).

 int getProgramCounter()

          Fetch the value of the access operation (the value read or written).

 double getRunSpeed()

          Fetch the value of the access operation (the value read or written).

 java.lang.String toString()

          String representation indicates access type, address and length in bytes

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

SIMULATOR_START

public static final int SIMULATOR_START

See Also:
Constant Field Values

SIMULATOR_STOP

public static final int SIMULATOR_STOP

See Also:
Constant Field Values

Constructor Detail

SimulatorNotice

public SimulatorNotice(int action,
int maxSteps,
double runSpeed,
int programCounter)

Constructor will be called only within this package, so assume
address and length are in valid ranges.

Method Detail

getAction

public int getAction()

Fetch the memory address that was accessed.

getMaxSteps

public int getMaxSteps()

Fetch the length in bytes of the access operation (4,2,1).

getRunSpeed

public double getRunSpeed()

Fetch the value of the access operation (the value read or written).

getProgramCounter

public int getProgramCounter()

Fetch the value of the access operation (the value read or written).

toString

public java.lang.String toString()

String representation indicates access type, address and length in bytes

Overrides:
toString in class java.lang.Object

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars.simulator

Interface Summary
Simulator.StopListener  

 

Class Summary
BackStepper Used to “step backward” through execution, undoing each instruction.
DelayedBranch Represents a (potential) delayed branch.
Exceptions Represents an error/interrupt that occurs during execution (simulation).
ProgramArgumentList Models Program Arguments, one or more strings provided to the MIPS
program at runtime.
Simulator Used to simulate the execution of an assembled MIPS program.
SimulatorNotice Object provided to Observers of the Simulator.
SwingWorker This is the 3rd version of SwingWorker (also known as
SwingWorker 3), an abstract class that you subclass to
perform GUI-related work in a dedicated thread.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

SwingWorker

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator

Class SwingWorker

java.lang.Object
mars.simulator.SwingWorker

public abstract class SwingWorker
extends java.lang.Object

This is the 3rd version of SwingWorker (also known as
SwingWorker 3), an abstract class that you subclass to
perform GUI-related work in a dedicated thread. For
instructions on and examples of using this class, see:

http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html

Note that the API changed slightly in the 3rd version:
You must now invoke start() on the SwingWorker after
creating it.

Constructor Summary
SwingWorker(boolean useSwing)

          Start a thread that will call the construct method
and then exit.

 

Method Summary

abstract  java.lang.Object construct()

          Compute the value to be returned by the get method.

 void finished()

          Called on the event dispatching thread (not on the worker thread)
after the construct method has returned.

 java.lang.Object get()

          Return the value created by the construct method.

protected  java.lang.Object getValue()

          Get the value produced by the worker thread, or null if it
hasn’t been constructed yet.

 void interrupt()

          A new method that interrupts the worker thread.

 void start()

          Start the worker thread.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

SwingWorker

public SwingWorker(boolean useSwing)

Start a thread that will call the construct method
and then exit.

Parameters:
useSwing – Set true if MARS is running from GUI, false otherwise.

Method Detail

getValue

protected java.lang.Object getValue()

Get the value produced by the worker thread, or null if it
hasn’t been constructed yet.

construct

public abstract java.lang.Object construct()

Compute the value to be returned by the get method.

finished

public void finished()

Called on the event dispatching thread (not on the worker thread)
after the construct method has returned.

interrupt

public void interrupt()

A new method that interrupts the worker thread. Call this method
to force the worker to stop what it’s doing.

get

public java.lang.Object get()

Return the value created by the construct method.
Returns null if either the constructing thread or the current
thread was interrupted before a value was produced.

Returns:
the value created by the construct method

start

public void start()

Start the worker thread.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

ProgramArgumentList

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator

Class ProgramArgumentList

java.lang.Object
mars.simulator.ProgramArgumentList

public class ProgramArgumentList
extends java.lang.Object

Models Program Arguments, one or more strings provided to the MIPS
program at runtime. Equivalent to C’s main(int argc, char **argv) or
Java’s main(String[] args).

Author:
Pete Sanderson

Constructor Summary
ProgramArgumentList(java.util.ArrayList list)

          Constructor that gets list from ArrayList of String, one argument per element.
ProgramArgumentList(java.util.ArrayList list,
int startPosition)

          Constructor that gets list from section of String ArrayList, one
argument per element.
ProgramArgumentList(java.lang.String args)

          Constructor that parses string to produce list.
ProgramArgumentList(java.lang.String[] list)

          Constructor that gets list from String array, one argument per element.
ProgramArgumentList(java.lang.String[] list,
int startPosition)

          Constructor that gets list from section of String array, one
argument per element.

 

Method Summary

 void storeProgramArguments()

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

ProgramArgumentList

public ProgramArgumentList(java.lang.String args)

Constructor that parses string to produce list. Delimiters
are the default Java StringTokenizer delimiters (space, tab,
newline, return, formfeed)

Parameters:
args – String containing delimiter-separated arguments

ProgramArgumentList

public ProgramArgumentList(java.lang.String[] list)

Constructor that gets list from String array, one argument per element.

Parameters:
list – Array of String, each element containing one argument

ProgramArgumentList

public ProgramArgumentList(java.lang.String[] list,
int startPosition)

Constructor that gets list from section of String array, one
argument per element.

Parameters:
args – Array of String, each element containing one argument
startPosition – Index of array element containing the first argument; all remaining
elements are assumed to contain an argument.

ProgramArgumentList

public ProgramArgumentList(java.util.ArrayList list)

Constructor that gets list from ArrayList of String, one argument per element.

Parameters:
list – ArrayList of String, each element containing one argument

ProgramArgumentList

public ProgramArgumentList(java.util.ArrayList list,
int startPosition)

Constructor that gets list from section of String ArrayList, one
argument per element.

Parameters:
args – ArrayList of String, each element containing one argument
startPosition – Index of array element containing the first argument; all remaining
elements are assumed to contain an argument.

Method Detail

storeProgramArguments

public void storeProgramArguments()

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars.simulator

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object mars.simulator.BackStepper
mars.simulator.DelayedBranch
mars.simulator.Exceptions
java.util.Observable mars.simulator.Simulator

mars.simulator.ProgramArgumentList
mars.simulator.SimulatorNotice
mars.simulator.SwingWorker

Interface Hierarchy

mars.simulator.Simulator.StopListener

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

DelayedBranch

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars.simulator

Class DelayedBranch

java.lang.Object
mars.simulator.DelayedBranch

public class DelayedBranch
extends java.lang.Object

Represents a (potential) delayed branch. Note it is necessary only when
delayed branching is enabled. Here’s the protocol for using it:

(1) When a runtime decision to branch is made (by either a branch or jump
instruction’s simulate() method in InstructionSet), then if delayed branching
is enabled, the register() method is called with the branch target address but
the program counter is NOT set to the branch target address.

(2) At the end of that instruction cycle, the simulate() method in Simulator
will detect the registered branch, and set its trigger. Don’t do anything yet
because the next instruction cycle is the delay slot and needs to complete.

(3) At the end of the next (delay slot) instruction cycle, the simulate()
method in Simulator will detect the triggered branch, set the program
counter to its target value and clear the delayed branch.

The only interesting situation is when the delay slot itself contains a
successful branch! I tried this with SPIM (e.g. beq followed by b)
and it treats it as if nothing was there and continues the delay slot
into the next cycle. The eventual branch taken is the original one (as one
would hope) but in the meantime the first statement following the sequence
of successful branches will constitute the delay slot and will be executed!

Since only one pending delayed branch can be taken at a time, everything
here is done with statics. The class itself represents the potential branch.

Author:
Pete Sanderson

Constructor Summary
DelayedBranch()

           

 

Method Summary

static void register(int targetAddress)

          Register the fact that a successful branch is to occur.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

DelayedBranch

public DelayedBranch()

Method Detail

register

public static void register(int targetAddress)

Register the fact that a successful branch is to occur. This is called in
the instruction’s simulated execution (its simulate() method in InstructionSet).
If a branch is registered but not triggered, this registration will be ignored
(cannot happen if class usage protocol is followed). If a branch is currently
registered and triggered, reset the state back to registered (but not triggered)
in order to carry over the delay slot for another execution cycle. This is the
only public member of the class.

Parameters:
targetAddress – The address to branch to after executing the next instruction

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

Package mars

Class Summary
ErrorList Maintains list of generated error messages, regardless of source (tokenizing, parsing,
assembly, execution).
ErrorMessage Represents occurrance of an error detected during tokenizing, assembly or simulation.
Globals Collection of globally-available data structures.
MarsLaunch Launch the Mars application
MarsSplashScreen Produces MARS splash screen.

Adapted from http://www.java-tips.org/content/view/1267/2/

MIPSprogram Internal representations of MIPS program.
ProgramStatement Represents one assembly/machine statement.
Settings Contains various IDE settings.

 

Exception Summary
ProcessingException Class to represent error that occurs while assembling or running a MIPS program.

 

Overview   Package  Class  Tree  Deprecated  Index  Help 

 PREV PACKAGE 
 NEXT PACKAGE
FRAMES  
 NO FRAMES  
 

All Classes

ProgramStatement

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

Class ProgramStatement

java.lang.Object
mars.ProgramStatement

public class ProgramStatement
extends java.lang.Object

Represents one assembly/machine statement. This represents the “bare machine” level.
Pseudo-instructions have already been processed at this point and each assembly
statement generated by them is one of these.

Author:
Pete Sanderson and Jason Bumgarner

Constructor Summary
ProgramStatement(int binaryStatement,
int textAddress)

          Constructor for ProgramStatement used only for writing a binary machine
instruction with no source code to refer back to.
ProgramStatement(MIPSprogram sourceMIPSprogram,
java.lang.String source,
TokenList origTokenList,
TokenList strippedTokenList,
Instruction inst,
int textAddress,
int sourceLine)

          Constructor for ProgramStatement when there are links back to all source and token
information.

 

Method Summary

 void buildBasicStatementFromBasicInstruction(ErrorList errors)

          Given specification of BasicInstruction for this operator, build the
corresponding assembly statement in basic assembly format (e.g.

 void buildMachineStatementFromBasicStatement(ErrorList errors)

          Given the current statement in Basic Assembly format (see above), build the
32-bit binary machine code statement.

 int getAddress()

          Produces Text Segment address where the binary machine statement is stored.

 java.lang.String getBasicAssemblyStatement()

          Produces Basic Assembly statement for this MIPS source statement.

 int getBinaryStatement()

          Produces 32-bit binary machine statement as int.

 Instruction getInstruction()

          Produces Instruction object corresponding to this statement’s operator.

 java.lang.String getMachineStatement()

          Produces binary machine statement as 32 character string, all ‘0’ and ‘1’ chars.

 int getOperand(int i)

          Produces operand value from given array position (first operand is position 0).

 int[] getOperands()

          Produces int array of operand values for this statement.

 TokenList getOriginalTokenList()

          Produces token list generated from original source statement.

 java.lang.String getPrintableBasicAssemblyStatement()

          Produces printable Basic Assembly statement for this MIPS source
statement.

 java.lang.String getSource()

          Produces MIPS source statement.

 java.lang.String getSourceFile()

          Produces String name of the source file containing this statement.

 int getSourceLine()

          Produces line number of MIPS source statement.

 MIPSprogram getSourceMIPSprogram()

          Produces MIPSprogram object representing the source file containing this statement.

 TokenList getStrippedTokenList()

          Produces token list stripped of all but operator and operand tokens.

 void setBasicAssemblyStatement(java.lang.String statement)

          Assigns given String to be Basic Assembly statement equivalent to this source line.

 void setBinaryStatement(int binaryCode)

          Assigns given int to be binary machine code equivalent to this source line.

 void setMachineStatement(java.lang.String statement)

          Assigns given String to be binary machine code (32 characters, all of them 0 or 1)
equivalent to this source line.

 void setSource(java.lang.String src)

          associates MIPS source statement.

 java.lang.String toString()

          Crude attempt at building String representation of this complex structure.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Constructor Detail

ProgramStatement

public ProgramStatement(MIPSprogram sourceMIPSprogram,
java.lang.String source,
TokenList origTokenList,
TokenList strippedTokenList,
Instruction inst,
int textAddress,
int sourceLine)

Constructor for ProgramStatement when there are links back to all source and token
information. These can be used by a debugger later on.

Parameters:
sourceMIPSprogram – The MIPSprogram object that contains this statement
source – The corresponding MIPS source statement.
origTokenList – Complete list of Token objects (includes labels, comments, parentheses, etc)
strippedTokenList – List of Token objects with all but operators and operands removed.
inst – The Instruction object for this statement’s operator.
textAddress – The Text Segment address in memory where the binary machine code for this statement
is stored.

ProgramStatement

public ProgramStatement(int binaryStatement,
int textAddress)

Constructor for ProgramStatement used only for writing a binary machine
instruction with no source code to refer back to. It could be extended to support
self-modifying code but currently supports only NOP which is all zeroes.

Parameters:
binaryStatement – The 32-bit machine code.
textAddress – The Text Segment address in memory where the binary machine code for this statement
is stored.

Method Detail

buildBasicStatementFromBasicInstruction

public void buildBasicStatementFromBasicInstruction(ErrorList errors)

Given specification of BasicInstruction for this operator, build the
corresponding assembly statement in basic assembly format (e.g. substituting
register numbers for register names, replacing labels by values).

Parameters:
errors – The list of assembly errors encountered so far. May add to it here.

buildMachineStatementFromBasicStatement

public void buildMachineStatementFromBasicStatement(ErrorList errors)

Given the current statement in Basic Assembly format (see above), build the
32-bit binary machine code statement.

Parameters:
errors – The list of assembly errors encountered so far. May add to it here.

toString

public java.lang.String toString()

Crude attempt at building String representation of this complex structure.

Overrides:
toString in class java.lang.Object

Returns:
A String representing the ProgramStatement.

setBasicAssemblyStatement

public void setBasicAssemblyStatement(java.lang.String statement)

Assigns given String to be Basic Assembly statement equivalent to this source line.

Parameters:
statement – A String containing equivalent Basic Assembly statement.

setMachineStatement

public void setMachineStatement(java.lang.String statement)

Assigns given String to be binary machine code (32 characters, all of them 0 or 1)
equivalent to this source line.

Parameters:
statement – A String containing equivalent machine code.

setBinaryStatement

public void setBinaryStatement(int binaryCode)

Assigns given int to be binary machine code equivalent to this source line.

Parameters:
binaryCode – An int containing equivalent binary machine code.

setSource

public void setSource(java.lang.String src)

associates MIPS source statement. Used by assembler when generating basic
statements during macro expansion of extended statement.

Parameters:
src – a MIPS source statement.

getSourceMIPSprogram

public MIPSprogram getSourceMIPSprogram()

Produces MIPSprogram object representing the source file containing this statement.

Returns:
The MIPSprogram object. May be null…

getSourceFile

public java.lang.String getSourceFile()

Produces String name of the source file containing this statement.

Returns:
The file name.

getSource

public java.lang.String getSource()

Produces MIPS source statement.

Returns:
The MIPS source statement.

getSourceLine

public int getSourceLine()

Produces line number of MIPS source statement.

Returns:
The MIPS source statement line number.

getBasicAssemblyStatement

public java.lang.String getBasicAssemblyStatement()

Produces Basic Assembly statement for this MIPS source statement.
All numeric values are in decimal.

Returns:
The Basic Assembly statement.

getPrintableBasicAssemblyStatement

public java.lang.String getPrintableBasicAssemblyStatement()

Produces printable Basic Assembly statement for this MIPS source
statement. This is generated dynamically and any addresses and
values will be rendered in hex or decimal depending on the current
setting.

Returns:
The Basic Assembly statement.

getMachineStatement

public java.lang.String getMachineStatement()

Produces binary machine statement as 32 character string, all ‘0’ and ‘1’ chars.

Returns:
The String version of 32-bit binary machine code.

getBinaryStatement

public int getBinaryStatement()

Produces 32-bit binary machine statement as int.

Returns:
The int version of 32-bit binary machine code.

getOriginalTokenList

public TokenList getOriginalTokenList()

Produces token list generated from original source statement.

Returns:
The TokenList of Token objects generated from original source.

getStrippedTokenList

public TokenList getStrippedTokenList()

Produces token list stripped of all but operator and operand tokens.

Returns:
The TokenList of Token objects generated by stripping original list of all
except operator and operand tokens.

getInstruction

public Instruction getInstruction()

Produces Instruction object corresponding to this statement’s operator.

Returns:
The Instruction that matches the operator used in this statement.

getAddress

public int getAddress()

Produces Text Segment address where the binary machine statement is stored.

Returns:
address in Text Segment of this binary machine statement.

getOperands

public int[] getOperands()

Produces int array of operand values for this statement.

Returns:
int array of operand values (if any) required by this statement’s operator.

getOperand

public int getOperand(int i)

Produces operand value from given array position (first operand is position 0).

Parameters:
i – Operand position in array (first operand is position 0).

Returns:
Operand value at given operand array position. If < 0 or >= numOperands, it returns -1.

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

MarsLaunch

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

Class MarsLaunch

java.lang.Object
mars.MarsLaunch

public class MarsLaunch
extends java.lang.Object

Launch the Mars application

Author:
Pete Sanderson

Constructor Summary
MarsLaunch(java.lang.String[] args)

           

 

Method Summary

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

MarsLaunch

public MarsLaunch(java.lang.String[] args)

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars Class Hierarchy

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

Hierarchy For Package mars

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
java.awt.Container java.awt.Window (implements javax.accessibility.Accessible)
javax.swing.JWindow (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer)
mars.MarsSplashScreen

mars.ErrorList
mars.ErrorMessage
mars.Globals
mars.MarsLaunch
mars.MIPSprogram
java.util.Observable mars.Settings

mars.ProgramStatement
java.lang.Throwable (implements java.io.Serializable)
java.lang.Exception mars.ProcessingException

Overview  Package  Class   Tree  Deprecated  Index  Help 

 PREV 
 NEXT
FRAMES  
 NO FRAMES  
 

All Classes

MIPSprogram

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

Class MIPSprogram

java.lang.Object
mars.MIPSprogram

public class MIPSprogram
extends java.lang.Object

Internal representations of MIPS program. Connects source, tokens and machine code. Having
all these structures available facilitates construction of good messages,
debugging, and easy simulation.

Author:
Pete Sanderson

Constructor Summary
MIPSprogram()

           

 

Method Summary

 ErrorList assemble(java.util.ArrayList MIPSprogramsToAssemble,
boolean extendedAssemblerEnabled)

          Assembles the MIPS source program.

 ErrorList assemble(java.util.ArrayList MIPSprogramsToAssemble,
boolean extendedAssemblerEnabled,
boolean warningsAreErrors)

          Assembles the MIPS source program.

 boolean backSteppingEnabled()

          Returns status of BackStepper associated with this program.

 MacroPool createMacroPool()

          Instantiates a new MacroPool and sends reference of this
MIPSprogram to it

 java.util.ArrayList createParsedList()

          Produces new empty list to hold parsed source code statements.

 BackStepper getBackStepper()

          Returns BackStepper associated with this program.

 java.lang.String getFilename()

          Produces name of associated source code file.

 MacroPool getLocalMacroPool()

          Gets local macro pool MacroPool for this program

 SymbolTable getLocalSymbolTable()

          Returns SymbolTable associated with this program.

 java.util.ArrayList getMachineList()

          Produces list of machine statements that are assembled from the program.

 java.util.ArrayList getParsedList()

          Produces existing list of parsed source code statements.

 java.lang.String getSourceLine(int i)

          Produces specified line of MIPS source program.

 java.util.ArrayList getSourceLineList()

          Retrieve list of source statements that comprise the program.

 java.util.ArrayList getSourceList()

          Produces list of source statements that comprise the program.

 java.util.ArrayList getTokenList()

          Produces list of tokens that comprise the program.

 boolean inSteppedExecution()

          Will be true only while in process of simulating a program statement
in step mode (e.g.

 java.util.ArrayList prepareFilesForAssembly(java.util.ArrayList filenames,
java.lang.String leadFilename,
java.lang.String exceptionHandler)

          Prepares the given list of files for assembly.

 void readSource(java.lang.String file)

          Reads MIPS source code from file into structure.

 void setLocalMacroPool(MacroPool macroPool)

          Sets local macro pool MacroPool for this program

 void setSourceLineList(java.util.ArrayList sourceLineList)

          Set list of source statements that comprise the program.

 boolean simulate(int maxSteps)

          Simulates execution of the MIPS program.

 boolean simulate(int[] breakPoints)

          Simulates execution of the MIPS program.

 boolean simulateFromPC(int[] breakPoints,
int maxSteps,
javax.swing.AbstractAction a)

          Simulates execution of the MIPS program.

 boolean simulateStepAtPC(javax.swing.AbstractAction a)

          Simulates execution of the MIPS program.

 void tokenize()

          Tokenizes the MIPS source program.

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Constructor Detail

MIPSprogram

public MIPSprogram()

Method Detail

getSourceList

public java.util.ArrayList getSourceList()

Produces list of source statements that comprise the program.

Returns:
ArrayList of String. Each String is one line of MIPS source code.

setSourceLineList

public void setSourceLineList(java.util.ArrayList sourceLineList)

Set list of source statements that comprise the program.

Parameters:
sourceLineList – ArrayList of SourceLine.
Each SourceLine represents one line of MIPS source code.

getSourceLineList

public java.util.ArrayList getSourceLineList()

Retrieve list of source statements that comprise the program.

Returns:
ArrayList of SourceLine.
Each SourceLine represents one line of MIPS source cod

getFilename

public java.lang.String getFilename()

Produces name of associated source code file.

Returns:
File name as String.

getTokenList

public java.util.ArrayList getTokenList()

Produces list of tokens that comprise the program.

Returns:
ArrayList of TokenList. Each TokenList is list of tokens generated by
corresponding line of MIPS source code.
See Also:
TokenList

createParsedList

public java.util.ArrayList createParsedList()

Produces new empty list to hold parsed source code statements.

Returns:
ArrayList of ProgramStatement. Each ProgramStatement represents a parsed
MIPS statement.
See Also:
ProgramStatement

getParsedList

public java.util.ArrayList getParsedList()

Produces existing list of parsed source code statements.

Returns:
ArrayList of ProgramStatement. Each ProgramStatement represents a parsed
MIPS statement.
See Also:
ProgramStatement

getMachineList

public java.util.ArrayList getMachineList()

Produces list of machine statements that are assembled from the program.

Returns:
ArrayList of ProgramStatement. Each ProgramStatement represents an assembled
basic MIPS instruction.
See Also:
ProgramStatement

getBackStepper

public BackStepper getBackStepper()

Returns BackStepper associated with this program. It is created upon successful assembly.

Returns:
BackStepper object, null if there is none.

getLocalSymbolTable

public SymbolTable getLocalSymbolTable()

Returns SymbolTable associated with this program. It is created at assembly time,
and stores local labels (those not declared using .globl directive).

backSteppingEnabled

public boolean backSteppingEnabled()

Returns status of BackStepper associated with this program.

Returns:
true if enabled, false if disabled or non-existant.

getSourceLine

public java.lang.String getSourceLine(int i)

Produces specified line of MIPS source program.

Parameters:
i – Line number of MIPS source program to get. Line 1 is first line.

Returns:
Returns specified line of MIPS source. If outside the line range,
it returns null. Line 1 is first line.

readSource

public void readSource(java.lang.String file)
throws ProcessingException

Reads MIPS source code from file into structure. Will always read from file.
It is GUI responsibility to assure that source edits are written to file
when user selects compile or run/step options.

Parameters:
file – String containing name of MIPS source code file.

Throws:

ProcessingException – Will throw exception if there is any problem reading the file.

tokenize

public void tokenize()
throws ProcessingException

Tokenizes the MIPS source program. Program must have already been read from file.

Throws:

ProcessingException – Will throw exception if errors occured while tokenizing.

prepareFilesForAssembly

public java.util.ArrayList prepareFilesForAssembly(java.util.ArrayList filenames,
java.lang.String leadFilename,
java.lang.String exceptionHandler)
throws ProcessingException

Prepares the given list of files for assembly. This involves
reading and tokenizing all the source files. There may be only one.

Parameters:
filenames – ArrayList containing the source file name(s) in no particular order
leadFilename – String containing name of source file that needs to go first and
will be represented by “this” MIPSprogram object.
exceptionHandler – String containing name of source file containing exception
handler. This will be assembled first, even ahead of leadFilename, to allow it to
include “startup” instructions loaded beginning at 0x00400000. Specify null or
empty String to indicate there is no such designated exception handler.

Returns:
ArrayList containing one MIPSprogram object for each file to assemble.
objects for any additional files (send ArrayList to assembler)

Throws:

ProcessingException – Will throw exception if errors occured while reading or tokenizing.

assemble

public ErrorList assemble(java.util.ArrayList MIPSprogramsToAssemble,
boolean extendedAssemblerEnabled)
throws ProcessingException

Assembles the MIPS source program. All files comprising the program must have
already been tokenized. Assembler warnings are not considered errors.

Parameters:
MIPSprogramsToAssemble – ArrayList of MIPSprogram objects, each representing a tokenized source file.
extendedAssemblerEnabled – A boolean value – true means extended (pseudo) instructions
are permitted in source code and false means they are to be flagged as errors.

Returns:
ErrorList containing nothing or only warnings (otherwise would have thrown exception).

Throws:

ProcessingException – Will throw exception if errors occured while assembling.

assemble

public ErrorList assemble(java.util.ArrayList MIPSprogramsToAssemble,
boolean extendedAssemblerEnabled,
boolean warningsAreErrors)
throws ProcessingException

Assembles the MIPS source program. All files comprising the program must have
already been tokenized.

Parameters:
MIPSprogramsToAssemble – ArrayList of MIPSprogram objects, each representing a tokenized source file.
extendedAssemblerEnabled – A boolean value – true means extended (pseudo) instructions
are permitted in source code and false means they are to be flagged as errors
warningsAreErrors – A boolean value – true means assembler warnings will be considered errors and terminate
the assemble; false means the assembler will produce warning message but otherwise ignore warnings.

Returns:
ErrorList containing nothing or only warnings (otherwise would have thrown exception).

Throws:

ProcessingException – Will throw exception if errors occured while assembling.

simulate

public boolean simulate(int[] breakPoints)
throws ProcessingException

Simulates execution of the MIPS program. Program must have already been assembled.
Begins simulation at beginning of text segment and continues to completion.

Parameters:
breakPoints – int array of breakpoints (PC addresses). Can be null.

Returns:
true if execution completed and false otherwise

Throws:

ProcessingException – Will throw exception if errors occured while simulating.

simulate

public boolean simulate(int maxSteps)
throws ProcessingException

Simulates execution of the MIPS program. Program must have already been assembled.
Begins simulation at beginning of text segment and continues to completion or
until the specified maximum number of steps are simulated.

Parameters:
maxSteps – maximum number of steps to simulate.

Returns:
true if execution completed and false otherwise

Throws:

ProcessingException – Will throw exception if errors occured while simulating.

simulateFromPC

public boolean simulateFromPC(int[] breakPoints,
int maxSteps,
javax.swing.AbstractAction a)
throws ProcessingException

Simulates execution of the MIPS program. Program must have already been assembled.
Begins simulation at current program counter address and continues until stopped,
paused, maximum steps exceeded, or exception occurs.

Parameters:
breakPoints – int array of breakpoints (PC addresses). Can be null.
maxSteps – maximum number of instruction executions. Default -1 means no maximum.
a – the GUI component responsible for this call (GO normally). set to null if none.

Returns:
true if execution completed and false otherwise

Throws:

ProcessingException – Will throw exception if errors occured while simulating.

simulateStepAtPC

public boolean simulateStepAtPC(javax.swing.AbstractAction a)
throws ProcessingException

Simulates execution of the MIPS program. Program must have already been assembled.
Begins simulation at current program counter address and executes one step.

Parameters:
a – the GUI component responsible for this call (STEP normally). Set to null if none.

Returns:
true if execution completed and false otherwise

Throws:

ProcessingException – Will throw exception if errors occured while simulating.

inSteppedExecution

public boolean inSteppedExecution()

Will be true only while in process of simulating a program statement
in step mode (e.g. returning to GUI after each step). This is used to
prevent spurious AccessNotices from being sent from Memory and Register
to observers at other times (e.g. while updating the data and register
displays, while assembling program’s data segment, etc).

createMacroPool

public MacroPool createMacroPool()

Instantiates a new MacroPool and sends reference of this
MIPSprogram to it

Returns:
instatiated MacroPool

getLocalMacroPool

public MacroPool getLocalMacroPool()

Gets local macro pool MacroPool for this program

Returns:
MacroPool

setLocalMacroPool

public void setLocalMacroPool(MacroPool macroPool)

Sets local macro pool MacroPool for this program

Parameters:
macroPool – reference to MacroPool

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Settings

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

Class Settings

java.lang.Object
java.util.Observable
mars.Settings

public class Settings
extends java.util.Observable

Contains various IDE settings. Persistent settings are maintained for the
current user and on the current machine using
Java’s Preference objects. Failing that, default setting values come from
Settings.properties file. If both of those fail, default values come from
static arrays defined in this class. The latter can can be modified prior to
instantiating Settings object.

NOTE: If the Preference objects fail due to security exceptions, changes to
settings will not carry over from one MARS session to the next.

Actual implementation of the Preference objects is platform-dependent.
For Windows, they are stored in Registry. To see, run regedit and browse to:
HKEY_CURRENT_USER\Software\JavaSoft\Prefs\mars

Author:
Pete Sanderson

Field Summary

static int ASSEMBLE_ALL_ENABLED

          Flag to determine whether only the current editor source file (enabled false) or
all files in its directory (enabled true) will be assembled when assembly is selected.

static int ASSEMBLE_ON_OPEN_ENABLED

          Flag to determine whether or not a file is immediately and automatically assembled
upon opening.

static int AUTO_INDENT

          Flag to control whether or not language-aware editor will use auto-indent feature

static int BARE_MACHINE_ENABLED

          Flag to determine whether or not program being assembled is limited to
using register numbers instead of names.

static int CARET_BLINK_RATE

          Caret blink rate in milliseconds, 0 means don’t blink.

static int DATA_SEGMENT_HIGHLIGHTING

          Flag to control whether or not highlighting is applied to data segment window

static int DATASEGMENT_HIGHLIGHT_BACKGROUND

          RGB color for text segment highlighted background

static int DATASEGMENT_HIGHLIGHT_FONT

          Font for text segment highlighted background

static int DATASEGMENT_HIGHLIGHT_FOREGROUND

          RGB color for text segment highlighted foreground

static boolean[] defaultBooleanSettingsValues

          Last resort default values for boolean settings; will use only if neither
the Preferences nor the properties file work.

static int DELAYED_BRANCHING_ENABLED

          Flag to determine whether or not delayed branching is in effect at MIPS execution.

static int DISPLAY_ADDRESSES_IN_HEX

          Default setting for displaying addresses and values in hexidecimal in the Execute
pane.

static int DISPLAY_VALUES_IN_HEX

           

static int EDITOR_CURRENT_LINE_HIGHLIGHTING

          Flag to control whether or not editor will highlight the line currently being edited

static int EDITOR_FONT

          Font for the text editor

static int EDITOR_LINE_NUMBERS_DISPLAYED

          Flag to determine whether or not the editor will display line numbers.

static int EDITOR_POPUP_PREFIX_LENGTH

          Number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled)

static int EDITOR_TAB_SIZE

          Editor tab size in characters.

static int EVEN_ROW_BACKGROUND

          RGB color for table even row background (text, data, register displays)

static int EVEN_ROW_FONT

          Font for table even row background (text, data, register displays)

static int EVEN_ROW_FOREGROUND

          RGB color for table even row foreground (text, data, register displays)

static int EXCEPTION_HANDLER

          Current specified exception handler file (a MIPS assembly source file)

static int EXCEPTION_HANDLER_ENABLED

          Flag to determine whether the currently selected exception handler source file will
be included in each assembly operation.

static int EXTENDED_ASSEMBLER_ENABLED

          Flag to determine whether or not program being assembled is limited to
basic MIPS instructions and formats.

static int GENERIC_TEXT_EDITOR

          Flag to control whether or not to use generic text editor instead of language-aware styled editor

static int LABEL_SORT_STATE

          State for sorting label window display

static int LABEL_WINDOW_VISIBILITY

          Default visibilty of label window (symbol table).

static int MEMORY_CONFIGURATION

          Identifier of current memory configuration

static int ODD_ROW_BACKGROUND

          RGB color for table odd row background (text, data, register displays)

static int ODD_ROW_FONT

          Font for table odd row background (text, data, register displays)

static int ODD_ROW_FOREGROUND

          RGB color for table odd row foreground (text, data, register displays)

static int POPUP_INSTRUCTION_GUIDANCE

          Flag to control whether or not editor will provide popup instruction guidance while typing

static int POPUP_SYSCALL_INPUT

          Flag to control whether or not simulator will use popup dialog for input syscalls

static int PROGRAM_ARGUMENTS

          Flag to determine whether or not to display and use program arguments

static int REGISTER_HIGHLIGHT_BACKGROUND

          RGB color for register highlighted background

static int REGISTER_HIGHLIGHT_FONT

          Font for register highlighted background

static int REGISTER_HIGHLIGHT_FOREGROUND

          RGB color for register highlighted foreground

static int REGISTERS_HIGHLIGHTING

          Flag to control whether or not highlighting is applied to register windows

static int START_AT_MAIN

          Flag to control whether or not assembler automatically initializes program counter to ‘main’s address

static int TEXT_COLUMN_ORDER

          Order of text segment table columns

static int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_BACKGROUND

          RGB color for text segment delay slot highlighted background

static int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FONT

          Font for text segment delay slot highlighted background

static int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FOREGROUND

          RGB color for text segment delay slot highlighted foreground

static int TEXTSEGMENT_HIGHLIGHT_BACKGROUND

          RGB color for text segment highlighted background

static int TEXTSEGMENT_HIGHLIGHT_FONT

          Font for table odd row foreground (text, data, register displays)

static int TEXTSEGMENT_HIGHLIGHT_FOREGROUND

          RGB color for text segment highlighted foreground

static int WARNINGS_ARE_ERRORS

          Flag to determine whether or not assembler warnings are considered errors.

 

Constructor Summary
Settings()

          Create Settings object and set to saved values.
Settings(boolean gui)

          Create Settings object and set to saved values.

 

Method Summary

 boolean getAssembleAllEnabled()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ALL_ENABLED)

 boolean getAssembleOnOpenEnabled()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ON_OPEN_ENABLED)

 boolean getBackSteppingEnabled()

          Return whether backstepping is permitted at this time.

 boolean getBareMachineEnabled()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.BARE_MACHINE_ENABLED)

 boolean getBooleanSetting(int id)

          Fetch value of a boolean setting given its identifier.

 int getCaretBlinkRate()

          Retrieve the caret blink rate in milliseconds.

 java.awt.Color getColorSettingByKey(java.lang.String key)

          Get Color object for specified settings key.

 java.awt.Color getColorSettingByPosition(int position)

          Get Color object for specified settings name (a static constant).

 boolean getDataSegmentHighlighting()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DATA_SEGMENT_HIGHLIGHTING)

 java.awt.Color getDefaultColorSettingByKey(java.lang.String key)

          Get default Color value for specified settings key.

 java.awt.Color getDefaultColorSettingByPosition(int position)

          Get default Color object for specified settings name (a static constant).

 SyntaxStyle getDefaultEditorSyntaxStyleByPosition(int index)

           

 int getDefaultEditorTabSize()

          Get the text editor default tab size in characters

 java.awt.Font getDefaultFontByPosition(int fontSettingPosition)

          Retrieve a default Font setting

 boolean getDelayedBranchingEnabled()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED)

 boolean getDisplayAddressesInHex()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_ADDRESSES_IN_HEX)

 boolean getDisplayValuesInHex()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_VALUES_IN_HEX)

 java.awt.Font getEditorFont()

          Current editor font.

 boolean getEditorLineNumbersDisplayed()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EDITOR_LINE_NUMBERS_DISPLAYED)

 int getEditorPopupPrefixLength()

          Get number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled).

 SyntaxStyle getEditorSyntaxStyleByPosition(int index)

           

 int getEditorTabSize()

          Get the tab size in characters.

 java.lang.String getExceptionHandler()

          Name of currently selected exception handler file.

 boolean getExceptionHandlerEnabled()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EXCEPTION_HANDLER_ENABLED)

 boolean getExtendedAssemblerEnabled()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EXTENDED_ASSEMBLER_ENABLED)

 java.awt.Font getFontByPosition(int fontSettingPosition)

          Retrieve a Font setting

 java.lang.String getLabelSortState()

          Get the saved state of the Labels Window sorting (can sort by either
label or address and either ascending or descending order).

 boolean getLabelWindowVisibility()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.LABEL_WINDOW_VISIBILITY)

 java.lang.String getMemoryConfiguration()

          Returns identifier of current built-in memory configuration.

 boolean getProgramArguments()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.PROGRAM_ARGUMENTS)

 boolean getRegistersHighlighting()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.REGISTERS_HIGHLIGHTING)

 boolean getStartAtMain()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.START_AT_MAIN)

 int[] getTextColumnOrder()

          Order of text segment display columns (there are 5, numbered 0 to 4).

 boolean getWarningsAreErrors()

          Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.WARNINGS_ARE_ERRORS)

 void reset(boolean gui)

          Reset settings to default values, as described in the constructor comments.

 void setAssembleAllEnabled(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ALL_ENABLED)

 void setAssembleOnOpenEnabled(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ON_OPEN_ENABLED)

 void setBooleanSetting(int id,
boolean value)

          Set value of a boolean setting given its id and the value.

 void setCaretBlinkRate(int rate)

          Set the caret blinking rate in milliseconds.

 void setColorSettingByKey(java.lang.String key,
java.awt.Color color)

          Set Color object for specified settings key.

 void setColorSettingByPosition(int position,
java.awt.Color color)

          Set Color object for specified settings name (a static constant).

 void setDataSegmentHighlighting(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DATA_SEGMENT_HIGHLIGHTING)

 void setDelayedBranchingEnabled(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED)

 void setDelayedBranchingEnabledNonPersistent(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED)

 void setDisplayAddressesInHex(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_ADDRESSES_IN_HEX)

 void setDisplayValuesInHex(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_VALUES_IN_HEX)

 void setEditorFont(java.awt.Font font)

          Set editor font to the specified Font object and write it to persistent storage.

 void setEditorLineNumbersDisplayed(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EDITOR_LINE_NUMBERS_DISPLAYED)

 void setEditorPopupPrefixLength(int length)

          Set number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled).

 void setEditorSyntaxStyleByPosition(int index,
SyntaxStyle syntaxStyle)

           

 void setEditorTabSize(int size)

          Set the tab size in characters.

 void setExceptionHandler(java.lang.String newFilename)

          Set name of exception handler file and write it to persistent storage.

 void setExceptionHandlerEnabled(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EXCEPTION_HANDLER_ENABLED)

 void setExtendedAssemblerEnabled(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EXTENDED_ASSEMBLER_ENABLED)

 void setFontByPosition(int fontSettingPosition,
java.awt.Font font)

          Store a Font setting

 void setLabelSortState(java.lang.String state)

          Store the current state of the Labels Window sorter.

 void setLabelWindowVisibility(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.LABEL_WINDOW_VISIBILITY)

 void setMemoryConfiguration(java.lang.String config)

          Store the identifier of the memory configuration.

 void setProgramArguments(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.PROGRAM_ARGUMENTS)

 void setRegistersHighlighting(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.REGISTERS_HIGHLIGHTING)

 void setStartAtMain(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.START_AT_MAIN)

 void setTextColumnOrder(int[] columnOrder)

          Store the current order of Text Segment window table columns, so the ordering
can be preserved and restored.

 void setWarningsAreErrors(boolean value)

          Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.WARNINGS_ARE_ERRORS)

 
Methods inherited from class java.util.Observable
addObserver, clearChanged, countObservers, deleteObserver, deleteObservers, hasChanged, notifyObservers, notifyObservers, setChanged

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

EXTENDED_ASSEMBLER_ENABLED

public static final int EXTENDED_ASSEMBLER_ENABLED

Flag to determine whether or not program being assembled is limited to
basic MIPS instructions and formats.

See Also:
Constant Field Values

BARE_MACHINE_ENABLED

public static final int BARE_MACHINE_ENABLED

Flag to determine whether or not program being assembled is limited to
using register numbers instead of names. NOTE: Its default value is
false and the IDE provides no means to change it!

See Also:
Constant Field Values

ASSEMBLE_ON_OPEN_ENABLED

public static final int ASSEMBLE_ON_OPEN_ENABLED

Flag to determine whether or not a file is immediately and automatically assembled
upon opening. Handy when using externa editor like mipster.

See Also:
Constant Field Values

ASSEMBLE_ALL_ENABLED

public static final int ASSEMBLE_ALL_ENABLED

Flag to determine whether only the current editor source file (enabled false) or
all files in its directory (enabled true) will be assembled when assembly is selected.

See Also:
Constant Field Values

LABEL_WINDOW_VISIBILITY

public static final int LABEL_WINDOW_VISIBILITY

Default visibilty of label window (symbol table). Default only, dynamic status
maintained by ExecutePane

See Also:
Constant Field Values

DISPLAY_ADDRESSES_IN_HEX

public static final int DISPLAY_ADDRESSES_IN_HEX

Default setting for displaying addresses and values in hexidecimal in the Execute
pane.

See Also:
Constant Field Values

DISPLAY_VALUES_IN_HEX

public static final int DISPLAY_VALUES_IN_HEX

See Also:
Constant Field Values

EXCEPTION_HANDLER_ENABLED

public static final int EXCEPTION_HANDLER_ENABLED

Flag to determine whether the currently selected exception handler source file will
be included in each assembly operation.

See Also:
Constant Field Values

DELAYED_BRANCHING_ENABLED

public static final int DELAYED_BRANCHING_ENABLED

Flag to determine whether or not delayed branching is in effect at MIPS execution.
This means we simulate the pipeline and statement FOLLOWING a successful branch
is executed before branch is taken. DPS 14 June 2007.

See Also:
Constant Field Values

EDITOR_LINE_NUMBERS_DISPLAYED

public static final int EDITOR_LINE_NUMBERS_DISPLAYED

Flag to determine whether or not the editor will display line numbers.

See Also:
Constant Field Values

WARNINGS_ARE_ERRORS

public static final int WARNINGS_ARE_ERRORS

Flag to determine whether or not assembler warnings are considered errors.

See Also:
Constant Field Values

PROGRAM_ARGUMENTS

public static final int PROGRAM_ARGUMENTS

Flag to determine whether or not to display and use program arguments

See Also:
Constant Field Values

DATA_SEGMENT_HIGHLIGHTING

public static final int DATA_SEGMENT_HIGHLIGHTING

Flag to control whether or not highlighting is applied to data segment window

See Also:
Constant Field Values

REGISTERS_HIGHLIGHTING

public static final int REGISTERS_HIGHLIGHTING

Flag to control whether or not highlighting is applied to register windows

See Also:
Constant Field Values

START_AT_MAIN

public static final int START_AT_MAIN

Flag to control whether or not assembler automatically initializes program counter to ‘main’s address

See Also:
Constant Field Values

EDITOR_CURRENT_LINE_HIGHLIGHTING

public static final int EDITOR_CURRENT_LINE_HIGHLIGHTING

Flag to control whether or not editor will highlight the line currently being edited

See Also:
Constant Field Values

POPUP_INSTRUCTION_GUIDANCE

public static final int POPUP_INSTRUCTION_GUIDANCE

Flag to control whether or not editor will provide popup instruction guidance while typing

See Also:
Constant Field Values

POPUP_SYSCALL_INPUT

public static final int POPUP_SYSCALL_INPUT

Flag to control whether or not simulator will use popup dialog for input syscalls

See Also:
Constant Field Values

GENERIC_TEXT_EDITOR

public static final int GENERIC_TEXT_EDITOR

Flag to control whether or not to use generic text editor instead of language-aware styled editor

See Also:
Constant Field Values

AUTO_INDENT

public static final int AUTO_INDENT

Flag to control whether or not language-aware editor will use auto-indent feature

See Also:
Constant Field Values

defaultBooleanSettingsValues

public static boolean[] defaultBooleanSettingsValues

Last resort default values for boolean settings; will use only if neither
the Preferences nor the properties file work. If you wish to change them,
do so before instantiating the Settings object.
Values are matched to keys by list position.

EXCEPTION_HANDLER

public static final int EXCEPTION_HANDLER

Current specified exception handler file (a MIPS assembly source file)

See Also:
Constant Field Values

TEXT_COLUMN_ORDER

public static final int TEXT_COLUMN_ORDER

Order of text segment table columns

See Also:
Constant Field Values

LABEL_SORT_STATE

public static final int LABEL_SORT_STATE

State for sorting label window display

See Also:
Constant Field Values

MEMORY_CONFIGURATION

public static final int MEMORY_CONFIGURATION

Identifier of current memory configuration

See Also:
Constant Field Values

CARET_BLINK_RATE

public static final int CARET_BLINK_RATE

Caret blink rate in milliseconds, 0 means don’t blink.

See Also:
Constant Field Values

EDITOR_TAB_SIZE

public static final int EDITOR_TAB_SIZE

Editor tab size in characters.

See Also:
Constant Field Values

EDITOR_POPUP_PREFIX_LENGTH

public static final int EDITOR_POPUP_PREFIX_LENGTH

Number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled)

See Also:
Constant Field Values

EDITOR_FONT

public static final int EDITOR_FONT

Font for the text editor

See Also:
Constant Field Values

EVEN_ROW_FONT

public static final int EVEN_ROW_FONT

Font for table even row background (text, data, register displays)

See Also:
Constant Field Values

ODD_ROW_FONT

public static final int ODD_ROW_FONT

Font for table odd row background (text, data, register displays)

See Also:
Constant Field Values

TEXTSEGMENT_HIGHLIGHT_FONT

public static final int TEXTSEGMENT_HIGHLIGHT_FONT

Font for table odd row foreground (text, data, register displays)

See Also:
Constant Field Values

TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FONT

public static final int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FONT

Font for text segment delay slot highlighted background

See Also:
Constant Field Values

DATASEGMENT_HIGHLIGHT_FONT

public static final int DATASEGMENT_HIGHLIGHT_FONT

Font for text segment highlighted background

See Also:
Constant Field Values

REGISTER_HIGHLIGHT_FONT

public static final int REGISTER_HIGHLIGHT_FONT

Font for register highlighted background

See Also:
Constant Field Values

EVEN_ROW_BACKGROUND

public static final int EVEN_ROW_BACKGROUND

RGB color for table even row background (text, data, register displays)

See Also:
Constant Field Values

EVEN_ROW_FOREGROUND

public static final int EVEN_ROW_FOREGROUND

RGB color for table even row foreground (text, data, register displays)

See Also:
Constant Field Values

ODD_ROW_BACKGROUND

public static final int ODD_ROW_BACKGROUND

RGB color for table odd row background (text, data, register displays)

See Also:
Constant Field Values

ODD_ROW_FOREGROUND

public static final int ODD_ROW_FOREGROUND

RGB color for table odd row foreground (text, data, register displays)

See Also:
Constant Field Values

TEXTSEGMENT_HIGHLIGHT_BACKGROUND

public static final int TEXTSEGMENT_HIGHLIGHT_BACKGROUND

RGB color for text segment highlighted background

See Also:
Constant Field Values

TEXTSEGMENT_HIGHLIGHT_FOREGROUND

public static final int TEXTSEGMENT_HIGHLIGHT_FOREGROUND

RGB color for text segment highlighted foreground

See Also:
Constant Field Values

TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_BACKGROUND

public static final int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_BACKGROUND

RGB color for text segment delay slot highlighted background

See Also:
Constant Field Values

TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FOREGROUND

public static final int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FOREGROUND

RGB color for text segment delay slot highlighted foreground

See Also:
Constant Field Values

DATASEGMENT_HIGHLIGHT_BACKGROUND

public static final int DATASEGMENT_HIGHLIGHT_BACKGROUND

RGB color for text segment highlighted background

See Also:
Constant Field Values

DATASEGMENT_HIGHLIGHT_FOREGROUND

public static final int DATASEGMENT_HIGHLIGHT_FOREGROUND

RGB color for text segment highlighted foreground

See Also:
Constant Field Values

REGISTER_HIGHLIGHT_BACKGROUND

public static final int REGISTER_HIGHLIGHT_BACKGROUND

RGB color for register highlighted background

See Also:
Constant Field Values

REGISTER_HIGHLIGHT_FOREGROUND

public static final int REGISTER_HIGHLIGHT_FOREGROUND

RGB color for register highlighted foreground

See Also:
Constant Field Values

Constructor Detail

Settings

public Settings()

Create Settings object and set to saved values. If saved values not found, will set
based on defaults stored in Settings.properties file. If file problems, will set based
on defaults stored in this class.

Settings

public Settings(boolean gui)

Create Settings object and set to saved values. If saved values not found, will set
based on defaults stored in Settings.properties file. If file problems, will set based
on defaults stored in this class.

Parameters:
gui – true if running the graphical IDE, false if running from command line.
Ignored as of release 3.6 but retained for compatability.

Method Detail

getBackSteppingEnabled

public boolean getBackSteppingEnabled()

Return whether backstepping is permitted at this time. Backstepping is ability to undo execution
steps one at a time. Available only in the IDE. This is not a persistent setting and is not under
MARS user control.

Returns:
true if backstepping is permitted, false otherwise.

reset

public void reset(boolean gui)

Reset settings to default values, as described in the constructor comments.

Parameters:
gui – true if running from GUI IDE and false if running from command mode.
Ignored as of release 3.6 but retained for compatibility.

setEditorSyntaxStyleByPosition

public void setEditorSyntaxStyleByPosition(int index,
SyntaxStyle syntaxStyle)

getEditorSyntaxStyleByPosition

public SyntaxStyle getEditorSyntaxStyleByPosition(int index)

getDefaultEditorSyntaxStyleByPosition

public SyntaxStyle getDefaultEditorSyntaxStyleByPosition(int index)

getBooleanSetting

public boolean getBooleanSetting(int id)

Fetch value of a boolean setting given its identifier.

Parameters:
id – int containing the setting’s identifier (constants listed above)

Returns:
corresponding boolean setting.

Throws:

java.lang.IllegalArgumentException – if identifier is invalid.

getBareMachineEnabled

public boolean getBareMachineEnabled()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.BARE_MACHINE_ENABLED)

Setting for whether user programs limited to “bare machine” formatted basic instructions.
This was added 8 Aug 2006 but is fixed at false for now, due to uncertainty as to what
exactly constitutes “bare machine”.

Returns:
true if only bare machine instructions allowed, false otherwise.

getExtendedAssemblerEnabled

public boolean getExtendedAssemblerEnabled()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EXTENDED_ASSEMBLER_ENABLED)

Setting for whether user programs can use pseudo-instructions or extended addressing modes
or alternative instruction formats (all are implemented as pseudo-instructions).

Returns:
true if pseudo-instructions and formats permitted, false otherwise.

getAssembleOnOpenEnabled

public boolean getAssembleOnOpenEnabled()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ON_OPEN_ENABLED)

Setting for whether selected program will be automatically assembled upon opening. This
can be useful if user employs an external editor such as MIPSter.

Returns:
true if file is to be automatically assembled upon opening and false otherwise.

getDisplayAddressesInHex

public boolean getDisplayAddressesInHex()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_ADDRESSES_IN_HEX)

Setting for whether Addresses in the Execute pane will be displayed in hexadecimal.

Returns:
true if addresses are displayed in hexadecimal and false otherwise (decimal).

getDisplayValuesInHex

public boolean getDisplayValuesInHex()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_VALUES_IN_HEX)

Setting for whether values in the Execute pane will be displayed in hexadecimal.

Returns:
true if values are displayed in hexadecimal and false otherwise (decimal).

getAssembleAllEnabled

public boolean getAssembleAllEnabled()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ALL_ENABLED)

Setting for whether the assemble operation applies only to the file currently open in
the editor or whether it applies to all files in that file’s directory (primitive project
capability). If the “assemble on open” setting is set, this “assemble all” setting will
be applied as soon as the file is opened.

Returns:
true if all files are to be assembled, false if only the file open in editor.

getExceptionHandlerEnabled

public boolean getExceptionHandlerEnabled()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EXCEPTION_HANDLER_ENABLED)

Setting for whether the currently selected exception handler
(a MIPS source file) will be automatically included in each
assemble operation.

Returns:
true if exception handler is to be included in assemble, false otherwise.

getDelayedBranchingEnabled

public boolean getDelayedBranchingEnabled()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED)

Setting for whether delayed branching will be applied during MIPS
program execution. If enabled, the statement following a successful
branch will be executed and then the branch is taken! This simulates
pipelining and all MIPS processors do it. However it is confusing to
assembly language students so is disabled by default. SPIM does same thing.

Returns:
true if delayed branching is enabled, false otherwise.

getLabelWindowVisibility

public boolean getLabelWindowVisibility()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.LABEL_WINDOW_VISIBILITY)

Setting concerning whether or not to display the Labels Window — symbol table.

Returns:
true if label window is to be displayed, false otherwise.

getEditorLineNumbersDisplayed

public boolean getEditorLineNumbersDisplayed()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.EDITOR_LINE_NUMBERS_DISPLAYED)

Setting concerning whether or not the editor will display line numbers.

Returns:
true if line numbers are to be displayed, false otherwise.

getWarningsAreErrors

public boolean getWarningsAreErrors()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.WARNINGS_ARE_ERRORS)

Setting concerning whether or not assembler will consider warnings to be errors.

Returns:
true if warnings are considered errors, false otherwise.

getProgramArguments

public boolean getProgramArguments()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.PROGRAM_ARGUMENTS)

Setting concerning whether or not program arguments can be entered and used.

Returns:
true if program arguments can be entered/used, false otherwise.

getDataSegmentHighlighting

public boolean getDataSegmentHighlighting()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.DATA_SEGMENT_HIGHLIGHTING)

Setting concerning whether or not highlighting is applied to Data Segment window.

Returns:
true if highlighting is to be applied, false otherwise.

getRegistersHighlighting

public boolean getRegistersHighlighting()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.REGISTERS_HIGHLIGHTING)

Setting concerning whether or not highlighting is applied to Registers,
Coprocessor0, and Coprocessor1 windows.

Returns:
true if highlighting is to be applied, false otherwise.

getStartAtMain

public boolean getStartAtMain()

Deprecated. Use getBooleanSetting(int id) with the appropriate boolean setting ID
(e.g. Settings.START_AT_MAIN)

Setting concerning whether or not assembler will automatically initialize
the program counter to address of statement labeled ‘main’ if defined.

Returns:
true if it initializes to ‘main’, false otherwise.

getExceptionHandler

public java.lang.String getExceptionHandler()

Name of currently selected exception handler file.

Returns:
String pathname of current exception handler file, empty if none.

getMemoryConfiguration

public java.lang.String getMemoryConfiguration()

Returns identifier of current built-in memory configuration.

Returns:
String identifier of current built-in memory configuration, empty if none.

getEditorFont

public java.awt.Font getEditorFont()

Current editor font. Retained for compatibility but replaced
by: getFontByPosition(Settings.EDITOR_FONT)

Returns:
Font object for current editor font.

getFontByPosition

public java.awt.Font getFontByPosition(int fontSettingPosition)

Retrieve a Font setting

Parameters:
fontSettingPosition – constant that identifies which item

Returns:
Font object for given item

getDefaultFontByPosition

public java.awt.Font getDefaultFontByPosition(int fontSettingPosition)

Retrieve a default Font setting

Parameters:
fontSettingPosition – constant that identifies which item

Returns:
Font object for given item

getTextColumnOrder

public int[] getTextColumnOrder()

Order of text segment display columns (there are 5, numbered 0 to 4).

Returns:
Array of int indicating the order. Original order is 0 1 2 3 4.

getCaretBlinkRate

public int getCaretBlinkRate()

Retrieve the caret blink rate in milliseconds. Blink rate of 0 means
do not blink.

Returns:
int blink rate in milliseconds

getEditorTabSize

public int getEditorTabSize()

Get the tab size in characters.

Returns:
tab size in characters.

getEditorPopupPrefixLength

public int getEditorPopupPrefixLength()

Get number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled).
Should be 1 or 2. If 1, the popup will be generated after first letter typed, based on all matches; if 2,
the popup will be generated after second letter typed.

Returns:
number of letters (should be 1 or 2).

getDefaultEditorTabSize

public int getDefaultEditorTabSize()

Get the text editor default tab size in characters

Returns:
tab size in characters

getLabelSortState

public java.lang.String getLabelSortState()

Get the saved state of the Labels Window sorting (can sort by either
label or address and either ascending or descending order).
Default state is 0, by ascending addresses.

Returns:
State value 0-7, as a String.

getColorSettingByKey

public java.awt.Color getColorSettingByKey(java.lang.String key)

Get Color object for specified settings key.
Returns null if key is not found or its value is not a valid color encoding.

Parameters:
key – the Setting key

Returns:
corresponding Color, or null if key not found or value not valid color

getDefaultColorSettingByKey

public java.awt.Color getDefaultColorSettingByKey(java.lang.String key)

Get default Color value for specified settings key.
Returns null if key is not found or its value is not a valid color encoding.

Parameters:
key – the Setting key

Returns:
corresponding default Color, or null if key not found or value not valid color

getColorSettingByPosition

public java.awt.Color getColorSettingByPosition(int position)

Get Color object for specified settings name (a static constant).
Returns null if argument invalid or its value is not a valid color encoding.

Parameters:
position – the Setting name (see list of static constants)

Returns:
corresponding Color, or null if argument invalid or value not valid color

getDefaultColorSettingByPosition

public java.awt.Color getDefaultColorSettingByPosition(int position)

Get default Color object for specified settings name (a static constant).
Returns null if argument invalid or its value is not a valid color encoding.

Parameters:
position – the Setting name (see list of static constants)

Returns:
corresponding default Color, or null if argument invalid or value not valid color

setBooleanSetting

public void setBooleanSetting(int id,
boolean value)

Set value of a boolean setting given its id and the value.

Parameters:
id – int containing the setting’s identifier (constants listed above)
value – boolean value to store

Throws:

java.lang.IllegalArgumentException – if identifier is not valid.

setExtendedAssemblerEnabled

public void setExtendedAssemblerEnabled(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EXTENDED_ASSEMBLER_ENABLED)

Establish setting for whether or not pseudo-instructions and formats are permitted
in user programs. User can change this setting via the IDE. If setting changes,
new setting will be written to properties file.

Parameters:
value – True to permit, false otherwise.

setAssembleOnOpenEnabled

public void setAssembleOnOpenEnabled(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ON_OPEN_ENABLED)

Establish setting for whether a file will be automatically assembled as soon as it
is opened. This is handy for those using an external text editor such as Mipster.
If setting changes, new setting will be written to properties file.

Parameters:
value – True to automatically assemble, false otherwise.

setAssembleAllEnabled

public void setAssembleAllEnabled(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.ASSEMBLE_ALL_ENABLED)

Establish setting for whether a file will be assembled by itself (false) or along
with all other files in its directory (true). This permits multi-file programs
and a primitive “project” capability. If setting changes,
new setting will be written to properties file.

Parameters:
value – True to assemble all, false otherwise.

setDisplayAddressesInHex

public void setDisplayAddressesInHex(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_ADDRESSES_IN_HEX)

Establish setting for whether addresses in the Execute pane will be displayed
in hexadecimal format.

Parameters:
value – True to display addresses in hexadecimal, false for decimal.

setDisplayValuesInHex

public void setDisplayValuesInHex(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DISPLAY_VALUES_IN_HEX)

Establish setting for whether values in the Execute pane will be displayed
in hexadecimal format.

Parameters:
value – True to display values in hexadecimal, false for decimal.

setLabelWindowVisibility

public void setLabelWindowVisibility(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.LABEL_WINDOW_VISIBILITY)

Establish setting for whether the labels window (i.e. symbol table) will
be displayed as part of the Text Segment display. If setting changes,
new setting will be written to properties file.

Parameters:
value – True to dispay labels window, false otherwise.

setExceptionHandlerEnabled

public void setExceptionHandlerEnabled(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EXCEPTION_HANDLER_ENABLED)

Establish setting for whether the currently selected exception handler
(a MIPS source file) will be automatically included in each
assemble operation. If setting changes, new setting will be written
to properties file.

Parameters:
value – True to assemble exception handler, false otherwise.

setDelayedBranchingEnabled

public void setDelayedBranchingEnabled(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED)

Establish setting for whether delayed branching will be applied during
MIPS program execution. If enabled, the statement following a successful
branch will be executed and then the branch is taken! This simulates
pipelining and all MIPS processors do it. However it is confusing to
assembly language students so is disabled by default. SPIM does same thing.

Parameters:
value – True to enable delayed branching, false otherwise.

setEditorLineNumbersDisplayed

public void setEditorLineNumbersDisplayed(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.EDITOR_LINE_NUMBERS_DISPLAYED)

Establish setting for whether line numbers will be displayed by the
text editor.

Parameters:
value – True to display line numbers, false otherwise.

setWarningsAreErrors

public void setWarningsAreErrors(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.WARNINGS_ARE_ERRORS)

Establish setting for whether assembler warnings will be considered errors.

Parameters:
value – True to consider warnings to be errors, false otherwise.

setProgramArguments

public void setProgramArguments(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.PROGRAM_ARGUMENTS)

Establish setting for whether program arguments can be ented/used.

Parameters:
value – True if program arguments can be entered/used, false otherwise.

setDataSegmentHighlighting

public void setDataSegmentHighlighting(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DATA_SEGMENT_HIGHLIGHTING)

Establish setting for whether highlighting is to be applied to
Data Segment window.

Parameters:
value – True if highlighting is to be applied, false otherwise.

setRegistersHighlighting

public void setRegistersHighlighting(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.REGISTERS_HIGHLIGHTING)

Establish setting for whether highlighting is to be applied to
Registers, Coprocessor0 and Coprocessor1 windows.

Parameters:
value – True if highlighting is to be applied, false otherwise.

setStartAtMain

public void setStartAtMain(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.START_AT_MAIN)

Establish setting for whether assembler will automatically initialize
program counter to address of statement labeled ‘main’ if defined.

Parameters:
value – True if PC set to address of ‘main’, false otherwise.

setDelayedBranchingEnabledNonPersistent

public void setDelayedBranchingEnabledNonPersistent(boolean value)

Deprecated. Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
(e.g. Settings.DELAYED_BRANCHING_ENABLED)

Establish setting for whether delayed branching will be applied during
MIPS program execution. This setting will NOT be written to persisent
store! This method should be called only to temporarily set this
setting — currently this is needed only when running MARS from the
command line (MarsLaunch.java).

Parameters:
value – True to enabled delayed branching, false otherwise.

setExceptionHandler

public void setExceptionHandler(java.lang.String newFilename)

Set name of exception handler file and write it to persistent storage.

Parameters:
newFilename – name of exception handler file

setMemoryConfiguration

public void setMemoryConfiguration(java.lang.String config)

Store the identifier of the memory configuration.

Parameters:
config – A string that identifies the current built-in memory configuration

setCaretBlinkRate

public void setCaretBlinkRate(int rate)

Set the caret blinking rate in milliseconds. Rate of 0 means no blinking.

Parameters:
rate – blink rate in milliseconds

setEditorTabSize

public void setEditorTabSize(int size)

Set the tab size in characters.

Parameters:
size – tab size in characters.

setEditorPopupPrefixLength

public void setEditorPopupPrefixLength(int length)

Set number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled).
Should be 1 or 2. If 1, the popup will be generated after first letter typed, based on all matches; if 2,
the popup will be generated after second letter typed.

Parameters:
number – of letters (should be 1 or 2).

setEditorFont

public void setEditorFont(java.awt.Font font)

Set editor font to the specified Font object and write it to persistent storage.
This method retained for compatibility but replaced by:
setFontByPosition(Settings.EDITOR_FONT, font)

Parameters:
font – Font object to be used by text editor.

setFontByPosition

public void setFontByPosition(int fontSettingPosition,
java.awt.Font font)

Store a Font setting

Parameters:
fontSettingPosition – Constant that identifies the item the font goes with

setTextColumnOrder

public void setTextColumnOrder(int[] columnOrder)

Store the current order of Text Segment window table columns, so the ordering
can be preserved and restored.

Parameters:
columnOrder – An array of int indicating column order.

setLabelSortState

public void setLabelSortState(java.lang.String state)

Store the current state of the Labels Window sorter. There are 8 possible states
as described in LabelsWindow.java

Parameters:
state – The current labels window sorting state, as a String.

setColorSettingByKey

public void setColorSettingByKey(java.lang.String key,
java.awt.Color color)

Set Color object for specified settings key. Has no effect if key is invalid.

Parameters:
key – the Setting key
color – the Color to save

setColorSettingByPosition

public void setColorSettingByPosition(int position,
java.awt.Color color)

Set Color object for specified settings name (a static constant). Has no effect if invalid.

Parameters:
position – the Setting name (see list of static constants)
color – the Color to save

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Globals

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

mars

Class Globals

java.lang.Object
mars.Globals

public class Globals
extends java.lang.Object

Collection of globally-available data structures.

Author:
Pete Sanderson

Field Summary

static java.lang.String ASCII_NON_PRINT

          Placeholder for non-printable ASCII codes

static java.lang.String[] ASCII_TABLE

          Array of strings to display for ASCII codes in ASCII display of data segment.

static java.lang.String copyrightHolders

          MARS copyright holders

static java.lang.String copyrightYears

          MARS copyright years

static boolean debug

          Flag to determine whether or not to produce internal debugging information.

static int exitCode

          MARS exit code — useful with SYSCALL 17 when running from command line (not GUI)

static java.util.ArrayList fileExtensions

          List of accepted file extensions for MIPS assembly source files.

static java.lang.String helpPath

          Path to folder that contains help text

static java.lang.String imagesPath

          Path to folder that contains images

static InstructionSet instructionSet

          The set of implemented MIPS instructions.

static int maximumBacksteps

          Maximum number of back-step operations to buffer

static int maximumErrorMessages

          Maximum number of assembler errors produced by one assemble operation

static int maximumMessageCharacters

          Maximum length of scrolled message window (MARS Messages and Run I/O)

static Memory memory

          Simulated MIPS memory component.

static java.lang.Object memoryAndRegistersLock

          Lock variable used at head of synchronized block to guard MIPS memory and registers

static MIPSprogram program

          the program currently being worked with.

static boolean runSpeedPanelExists

           

static SymbolTable symbolTable

          Symbol table for file currently being assembled.

static java.lang.String userInputAlert

          String to GUI’s RunI/O text area when echoing user input from pop-up dialog.

static java.lang.String version

          The current MARS version number.

 

Constructor Summary
Globals()

           

 

Method Summary

static java.lang.String getAsciiNonPrint()

           

static java.lang.String[] getAsciiStrings()

           

static java.util.ArrayList getExternalTools()

          Get list of MarsTools that reside outside the MARS distribution.

static VenusUI getGui()

           

static java.lang.String getPropertyEntry(java.lang.String propertiesFile,
java.lang.String propertyName)

          Read and return property file value (if any) for requested property.

static Settings getSettings()

           

 java.util.ArrayList getSyscallOverrides()

          Read any syscall number assignment overrides from config file.

static void initialize(boolean gui)

          Method called once upon system initialization to create the global data structures.

static void setGui(VenusUI g)

           

 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

 

Field Detail

instructionSet

public static InstructionSet instructionSet

The set of implemented MIPS instructions.

program

public static MIPSprogram program

the program currently being worked with. Used by GUI only, not command line.

symbolTable

public static SymbolTable symbolTable

Symbol table for file currently being assembled.

memory

public static Memory memory

Simulated MIPS memory component.

memoryAndRegistersLock

public static java.lang.Object memoryAndRegistersLock

Lock variable used at head of synchronized block to guard MIPS memory and registers

debug

public static boolean debug

Flag to determine whether or not to produce internal debugging information.

userInputAlert

public static java.lang.String userInputAlert

String to GUI’s RunI/O text area when echoing user input from pop-up dialog.

imagesPath

public static final java.lang.String imagesPath

Path to folder that contains images

See Also:
Constant Field Values

helpPath

public static final java.lang.String helpPath

Path to folder that contains help text

See Also:
Constant Field Values

version

public static final java.lang.String version

The current MARS version number. Can’t wait for “initialize()” call to get it.

See Also:
Constant Field Values

fileExtensions

public static final java.util.ArrayList fileExtensions

List of accepted file extensions for MIPS assembly source files.

maximumMessageCharacters

public static final int maximumMessageCharacters

Maximum length of scrolled message window (MARS Messages and Run I/O)

maximumErrorMessages

public static final int maximumErrorMessages

Maximum number of assembler errors produced by one assemble operation

maximumBacksteps

public static final int maximumBacksteps

Maximum number of back-step operations to buffer

copyrightYears

public static final java.lang.String copyrightYears

MARS copyright years

copyrightHolders

public static final java.lang.String copyrightHolders

MARS copyright holders

ASCII_NON_PRINT

public static final java.lang.String ASCII_NON_PRINT

Placeholder for non-printable ASCII codes

ASCII_TABLE

public static final java.lang.String[] ASCII_TABLE

Array of strings to display for ASCII codes in ASCII display of data segment. ASCII code 0-255 is array index.

exitCode

public static int exitCode

MARS exit code — useful with SYSCALL 17 when running from command line (not GUI)

runSpeedPanelExists

public static boolean runSpeedPanelExists

Constructor Detail

Globals

public Globals()

Method Detail

setGui

public static void setGui(VenusUI g)

getGui

public static VenusUI getGui()

getSettings

public static Settings getSettings()

initialize

public static void initialize(boolean gui)

Method called once upon system initialization to create the global data structures.

getAsciiNonPrint

public static java.lang.String getAsciiNonPrint()

getAsciiStrings

public static java.lang.String[] getAsciiStrings()

getExternalTools

public static java.util.ArrayList getExternalTools()

Get list of MarsTools that reside outside the MARS distribution.
Currently this is done by adding the tool’s path name to the list
of values for the external_tools property. Use “;” as delimiter!

Returns:
ArrayList. Each item is file path to .class file
of a class that implements MarsTool. If none, returns empty list.

getPropertyEntry

public static java.lang.String getPropertyEntry(java.lang.String propertiesFile,
java.lang.String propertyName)

Read and return property file value (if any) for requested property.

Parameters:
propertiesFile – name of properties file (do NOT include filename extension,
which is assumed to be “.properties”)
propertyName – String containing desired property name

Returns:
String containing associated value; null if property not found

getSyscallOverrides

public java.util.ArrayList getSyscallOverrides()

Read any syscall number assignment overrides from config file.

Returns:
ArrayList of SyscallNumberOverride objects

Overview  Package   Class  Tree  Deprecated  Index  Help 

 PREV CLASS 
 NEXT CLASS
FRAMES  
 NO FRAMES  
 

All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

Macros in MARS

Writing and Using Macros

.macro, .end_macro,.eqv and .include directives are new in MARS 4.3

Introduction to macros

Patterson and Hennessy define a macro as a pattern-matching and replacement facility
that provides a simple mechanism to name a frequently used sequence of instructions [1].
This permits the programmer to specify the instruction sequence by invoking the macro. This requires
only one line of code for each use instead of repeatedly typing
in the instruction sequence each time. It follows the axiom “define once, use many times,” which
not only reduces the chance for error but also facilitates program maintenance.

Macros are like procedures (subroutines) in this sense but operate differently than procedures.
Procedures in MIPS assembly language follow particular protocols for procedure definition, call and return.
Macros operate by substituting the macro body for each use at the time of assembly. This substitution
is called macro expansion.. They do not require the protocols and execution overhead of procedures.

As a simple example, you may want to terminate your program from a number of locations. If you are running
from the MARS IDE, you will use system call 10, exit. The instruction sequence is pretty easy

li $v0,10
syscall

but still tedious. You can define a macro, let’s call it done, to represent this sequence

.macro done
li $v0,10
syscall
.end_macro

then invoke it whenever you wish with the statement

done

At assembly time, the assembler will replace each occurrence of the statement done with the two-statement
sequence

li $v0,10
syscall

This is the macro expansion. The runtime simulator is unaware of macros or macro expansion.

If running MARS from the command line, perhaps you want to return a termination value. This can be done
with syscall 17, exit2, which takes the termination value as an argument. An equivalent macro,
let’s call it terminate would be

.macro terminate (%termination_value)
li $a0, %termination_value
li $v0, 17
syscall
.end_macro

This macro defines a formal parameter to represent the termination value. You would invoke it
with the statement

terminate (1)

to terminate with value 1. Upon assembly,
the statement terminate (1) would be replaced by the three-statement sequence

li $a0, 1
li $v0, 17
syscall

The argument value, 1, is substituted wherever the formal parameter %termination_value appears
in the macro body.
This is a textual substitution. Note that in this example the argument value must be an integer, not a
register name or a label, because the parameter is used as the second operand in the Load Immediate operation.

In MARS, a macro is similar to an extended (pseudo) instruction. They are distinguished in that the expansion of
extended instructions is supported by an internally-defined specification language and mechanism which can manipulate argument values.
The macro facility can only substitute argument values as given, and it uses a separate mechanism from extended instructions.

Additional examples and details follow.

How to define macros

The first line begins with a .macro directive followed by an optional list of formal parameters.
Placing commas between parameters and parentheses around the list is optional.

Each formal parameter is an identifier that begins with a % character. For compatibility with
the SPIM preprocessor APP, it may alternatively begin with $.

The lines that follow define the body of the macro. Use the formal parameters as appropriate. The body
may contain data segments as well as text segments.

The macro definition finishes with a .end_macro directive.

See the Notes below for additional information.

How to use macros

To invoke a macro, form a statement consisting of the macro name and then one token for each argument
to be substituted for its corresponding formal parameter by the assembler.
The argument list may optionally be surrounded by parentheses.
Arguments may be separated either by spaces or commas.

Macro expansion is a pre-processing task for assemblers.

Notes

A macro definition must appear before its use. No forward references.

All macro definitions are local in each file and they cannot be global.

Nested macro definitions are not supported. No .macro directive should appear inside body of a macro definition.

A macro definition can contain a call to a previously-defined macro. Only backward references are allowed.

Labels placed in the body of a macro definition will not have same name after macro expansion.
During expansion, their name will be followed by “_M#” where # will be a unique number for each macro expansion.

Two macros with the same name but different number of parameters are considered different and both can be used.

A macro defined with the same name and same number of parameters as another macro defined before it will be ignored.

Each argument in a macro call can only be a single language element (token). For instance “4($t0)” cannot be an argument.

Macros are a part of the assembler, not the ISA. So the syntax might be different with other assemblers.
For compatibility with the SPIM simulator, SPIM-style macros are also supported in MARS. SPIM-style macros are same as MARS but formal parameters begin with “$” instead of “%”.

Examples

Printing an integer (argument may be either an immediate value or register name):
.macro print_int (%x)
li $v0, 1
add $a0, $zero, %x
syscall
.end_macro

print_int ($s0)
print_int (10)

Printing a string (macro will first assign a label to its parameter in data segment then print it):
.macro print_str (%str)
.data
myLabel: .asciiz %str
.text
li $v0, 4
la $a0, myLabel
syscall
.end_macro

print_str (“test1″) #”test1” will be labeled with name “myLabel_M0”
print_str (“test2″) #”test2” will be labeled with name “myLabel_M1”

Implementing a simple for-loop:
# generic looping mechanism
.macro for (%regIterator, %from, %to, %bodyMacroName)
add %regIterator, $zero, %from
Loop:
%bodyMacroName ()
add %regIterator, %regIterator, 1
ble %regIterator, %to, Loop
.end_macro

#print an integer
.macro body()
print_int $t0
print_str “\n”
.end_macro

#printing 1 to 10:
for ($t0, 1, 10, body)

The for macro has 4 parameters. %regIterator should be the name of a register which iterates from %from to %to and in each iteration %bodyMacroName will be expanded and run.
Arguments for
%from and %to can be either a register name or an immediate value, and %bodyMacroName should be name of a macro that has no parameters.

Macro source line numbers

For purpose of error messaging and Text Segment display, MARS attempts to display line numbers for both the definition and use of the pertinent
macro statement. If an error message shows the line number in the form “X->Y” (e.g. “20->4”), then X is the line number in the expansion
(use) where the error was detected and Y is the line number in the macro definition. In the Text Segment display
of source code, the macro definition
line number will be displayed within brackets, e.g. “<4>“, at the point of expansion. Line numbers should correspond to the
numbers you would see in the text editor.

The .eqv directive

The .eqv directive (short for “equivalence”) is also new in MARS 4.3. It is similar to #define in C or C++. It
is used to substitute an arbitrary string for an identifier. It is useful but much less powerful than macros.
It was developed independently of the macro facility.

Using .eqv, you can specify simple substitutions that provide “define once, use many times” capability at assembly
pre-processing time. For example, once you define

.eqv LIMIT 20
.eqv CTR $t2
.eqv CLEAR_CTR add CTR, $zero, 0

then you can refer to them in subsequent code:

li $v0,1
CLEAR_CTR
loop: move $a0, CTR
syscall
add CTR, CTR, 1
blt CTR, LIMIT, loop
CLEAR_CTR

During assembly pre-processing, the .eqv substitutions will be applied. The resulting code is

li $v0,1
add $t2, $zero, 0
loop: move $a0, $t2
syscall
add $t2, $t2, 1
blt $t2, 20, loop
add $t2, $zero, 0

which when run will display the values 0 through 19 on one line with no intervening spaces.

Note that the substitution string is not limited to a single token. Like .macro, .eqv is local to the file
in which it is defined, and must be defined prior to use. Macro bodies can contain references to .eqv directives.

The .include directive

The .include directive is also new in MARS 4.3. It has one operand, a quoted filename. When the
directive is carried out, the contents of the specified file are substituted for the directive. This occurs
during assembly preprocessing. It is like #include in C or C++.

.include is designed to make macro and equivalence (.eqv directive) use
more convenient. Both macro definitions and equivalence definitions are local, which means they can be used only
in the same file where defined. Without .include, you would have to repeat their definitions in every
file where you want to use them. Besides being tedious, this is poor programming practice; remember
“define once, use many times.” Now you can define macros and equivalences in a separate file, then include it
in any file where you want to use them.

The .include preprocessor will detect and flag any circular includes (file that includes itself, directly or
indirectly).

The use of .include presents some challenges for error messaging and for source code numbering in the Text
Segment display. If a file being included has any assembly errors, the filename and line number in the error
message should refer to the file being included, not the file it was substituted into. Similarly, the line number
given in the Text Segment source code display refers to the line in the file being included. Thus the displayed line numbers do not
monotonically increase – this is also the case when using the “assemble all” setting. Line numbers should correspond to the numbers
you would see in the text editor.

As a simple example, you could define the done macro (and others) in a separate file
then include it wherever you need it. Suppose “macros.asm” contains the following:

.macro done
li $v0,10
syscall
.end_macro

You could then include it in a different source file something like this:

.include “macros.asm”
.data
value: .word 13
.text
li $v0, 1
lw $a0, value
syscall
done

During assembly preprocessing, this would be expanded to

.macro done
li $v0,10
syscall
.end_macro
.data
value: .word 13
.text
li $v0, 1
lw $a0, value
syscall
done

The assembler will then perform the appropriate macro expansion.

Acknowledgements

The MARS macro facility was developed in 2012 by Mohammad Hossein Sekhavat, , while an engineering student at
Sharif University in Tehran. MARS creators Pete and Ken are incredibly grateful for his contribution! Pete developed .eqv
and .include at about the same time.

References

[1] Computer Organization and Design: The Hardware/Software Interface, Fourth Edition, Patterson and Hennessy,
Morgan Kauffman Publishers, 2009.

MARS 4.3 help contents

MARS – Mips Assembly and Runtime Simulator

Release 4.3

January 2013

Operating Requirements

MARS is written in Java and
requires at least Release 1.5 of the J2SE Java Runtime Environment (JRE) to work.
The graphical IDE is implemented using Swing. It has been
tested on Windows XP and Vista, Mac OS X, and is also being used under Linux.

Some MARS Assembler and Simulator Limitations

Releases 3.0 and later assemble and simulate nearly all the MIPS32 instructions documented in the
textbook Computer Organization and Design, Fourth Edition by Patterson and Hennessy,
Elsevier – Morgan Kaufmann, 2009. All basic and pseudo instructions, directives,
and system services described in Appendix B are implemented.

Limitations of MARS as of Release 4.3 include:

Memory segments (text, data, stack, kernel text, kernel data) are limited to 4MB each starting at their
respective base addresses.
There is no pipelined mode (but delayed branching is supported).
Self-modifying code is not supported. This is a program that during
execution modifies the contents of its own text segment (binary instructions).
If you open a file which is a link or shortcut to another file, MARS will not
open the target file. The file open dialog is implemented using Java Swing’s JFileChooser,
which does not support links.
Very few configuration changes, besides those in the Settings menu, are saved from one session to the next.
The editor settings, which include font settings and display of line numbers, are saved.
The IDE will work only with the MARS assembler. It cannot be used
with any other compiler, assembler, or simulator. The MARS assembler and simulator
can be used either through the IDE or from a command prompt.
Bug:A couple of critical Alt-key combinations do not work with some European Mac keyboard layouts.
For instance, the Italian Mac keyboard requires an Alt-key combination for the # symbol
and Swedish keyboards require an Alt-key combination for the $ symbol. We do not have the equipment to
work on this bug, but would appreciate any of our European friends doing so.
Start by checking mars.venus.editors.jeditsyntax.DefaultInputHandler.keyTyped().
We’ve been told that workarounds include using the generic non-highlighting editor (checkbox in editor settings dialog)
or switching to Windows/Linux. Or paste from the outside world, use alternate character then replace-all, etc.
Bug:The error message highlighter does not automatically select the code for the first assembly
error if the file containing the error is not open at the time of assembly (assemble-on-open, assemble-all).
Bug: The Screen Magnifier screen capture feature does not appear to work properly under Windows Vista.
Bug: There appears to be a memory leak in the Editor. Several different people have independently
reported the same behavior: severe slowdown in editor response during an extended interactive session.
If MARS is exited and restarted, this behavior disappears and the editor responds instantly to actions.
Not a bug, but documented here anyway: MIPS Branch instruction target addresses are represented by
the relative number of words to branch. With Release 3.4, this value reflects delayed branching,
regardless of whether the Delayed Branching setting is enabled or not.
The generated binary code for branches will now match that of examples in the Computer Organization
and Design textbook. This is a change from the past, and was made after extensive discussions
with several faculty adopters of MARS. Previously, the branch offset was 1 lower if the Delayed Branching setting
was enabled — the instruction label: beq $0,$0,label would generate 0x1000FFFF if
Delayed Branching was enabled and 0x10000000 if it was disabled. Now it will generate 0x1000FFFF in
either case. The simulator will always branch to the correct location; MARS does not allow assembly under one
setting and simulation under the other to occur.

This document is available for printing on the MARS home page
http://www.cs.missouristate.edu/MARS/.

MARS 4.3 help contents

MARS – Mips Assembly and Runtime Simulator

Release 4.3

January 2013

Configuration Settings

Releases 3.0 and later include a Settings menu. The Editor and Exception Handler items launch a dialog but the rest are each
controlled by a checkbox for selecting or deselecting it (checked means true, unchecked means false). Settings and their default
values are:
Display the Labels window in the Execute tab. Default value is false. If selected, the Labels window,
which shows the name and associated address for each label defined in the program, will be
displayed to the right of the Text Segment.
Provide program arguments to the MIPS program. Default value is false. New in Release 3.5.
If selected, a text field will appear at the top of the Text Segment Display. Any argument values in this
text field at the time of program execution will be stored in MIPS memory prior to execution. The argument
count (argc) will be placed in register $a0, and the address of an array of null-terminated strings containing
the arguments (argv) will be placed in register $a1. These values are also available on the runtime stack ($sp).

Popup Dialog for input syscalls (5,6,7,8,12). New in Release 4.0. Default value is false. If selected, runtime console
input will be entered using popup dialogs (this was the only option prior to Release 4.0). Otherwise, input is entered
directly into the Run I/O tab at the bottom of the screen.
Display memory addresses in hexadecimal. Default value is true. If deselected, addresses will be displayed in decimal.
This setting can also be toggled in a checkbox on the lower border of the Data Segment Window.
Display memory and register contents in hexadecimal. Default value is true. If deselected, vlaues will be displayed in decimal.
This setting can also be toggled in a checkbox on the lower border of the Data Segment Window.
Assemble a file automatically as soon as it is opened, and initialize the File Open dialog with the most-recently opened file.
Default value is false. This is convenient if you use an external editor for composing your programs.
Assemble applies to all files in directory. Default value is false.
If selected, the file currently open in the
editor will become the “main” program in a multi-file assemble-and-link operation involving all
assembly files (*.asm; *.s) in its directory. If successful, execution will begin with the currently open file.
Assembler warnings are considered errors. Default value is false. New in Release 3.5.
If selected, the assemble operation will fail if any warnings are produced. At this time, all assembler warnings
relate to unrecognized or ignored directives. MARS may be able to assemble code produced by compilers for other MIPS
assemblers if this setting is deselected.

Initialize Program Counter to global ‘main’ if defined. Default value is false. New in Release 3.8.
If selected, the Program Counter will be initialized to the address of the text segment statement with the global label ‘main’ if it
exists. If it does not exist or if the setting is not selected, the Program Counter will be initialized to the default text segment
starting address.

Permit programs to use extended (pseudo) instructions and formats. Default value is true. This includes all memory addressing
modes other than the MIPS native mode (16 bit constant offset added to register content).
Assemble and execute programs using delayed branching. Default value is false. MIPS processors use delayed branches
as part of the pipelined design, but it can be confusing to programmers. With delayed branching, the instruction
following a branch or jump instruction will always be executed even if the branch condition is true! Assemblers
and, failing that, programmers, often deal with this by following branches and jumps with a “nop” instruction. The MARS
assembler does not insert a nop. When delayed branching was introduced in Release 3.3, the machine code generated
for a branch instruction depended on this setting since
its target value is relative to the Program Counter (PC-relative addressing). Although technically correct, this led to
confusion in the MARS community because the generated code did not match textbook examples. Starting with Release 3.4, the relative branching
offset is always calculated as if delayed branching is enabled even when it is not. The runtime simulation adjusts accordingly.
The Editor dialog. Use it to view and modify editor font settings. New with Release 3.3.
The Highlighting dialog. Use it to modify color and font settings for the highlighting of table items in the
Text Segment window, Data Segment window, Registers window, Coprocessor0 window and Coprocessor1 window.
Highlighting occurs during timed, stepped, and backstepped simulation. Color and font for normal (non-highlighted)
display can also be set separately for even-numbered and odd-numbered display rows but not individually by windows.
New with Release 3.6.
The Exception Handler dialog. It has the setting: Include this
exception handler in all assemble operations. Default value is false. If selected, a button to browse to the desired
file is enabled. New with Release 3.2
The Memory Configuration dialog. Use it to select from among available MIPS address space configurations.
The default configuration is derived from SPIM; it was only one available from MARS 1.0 through MARS 3.6.
New with Release 3.7.

Beginning with Release 3.2, settings are retained from one interactive session to the next. Settings are stored in a system-dependent
way as specified by java.util.prefs.Preferences. Windows systems use the Registry.
These settings are independent of command options given when using MARS from a command line;
neither affects the other. We anticipate future releases will include additional settings and preferences.

This document is available for printing on the MARS home page
http://www.cs.missouristate.edu/MARS/.

Writing and Using MIPS exception handlers in MARS

Writing and Using MIPS exception handlers in MARS

Introduction

Exception handlers, also known as trap handlers or
interrupt handlers, can easily be incorporated into a MIPS program.
This guide is not intended to be comprehensive but provides the essential
information for writing and using exception handlers.

Although the same mechanism services all three, exceptions, traps
and interrupts are all distinct from each other.
Exceptions are caused by exceptional conditions that occur at runtime
such as invalid memory address references. Traps are caused by instructions
constructed especially for this purpose, listed below. Interrupts are
caused by external devices.

MARS partially but not completely implements the exception and interrupt
mechanism of SPIM.

Essential Facts

Some essential facts about writing and using exception handlers include:
MARS simulates basic elements of the MIPS32 exception mechanism.
The MIPS instruction set includes a number of instructions that
conditionally trigger a trap exception based on the relative values of two
registers or of a constant and a register:
teq, teqi (trap if equal),
tne, tnei (trap if not equal),
tge, tgeu,
tgei, tgeiu (trap if greater than or equal),
tlt, tltu,
tlti, tltiu (trap if less than)

When an exception occurs,
Coprocessor 0 register $12 (status) bit 1 is set
Coprocessor 0 register $13 (cause) bits 2-6 are set to the exception type (codes below)
Coprocessor 0 register $14 (epc) is set to the
address of the instruction that triggered the exception
If the exception was caused by an invalid memory address,
Coprocessor 0 register $8 (vaddr) is set to the invalid address.
Execution flow jumps to the MIPS
instruction at memory location 0x800000180. This address
in the kernel text segment (.ktext directive) is the
standard MIPS32 exception handler location. The only way to change
it in MARS is to change the MIPS memory configuration through
the Settings menu item Memory Configuration.

There are three ways to include an exception handler in a MIPS program
Write the exception handler in the same file as the regular
program. An example of this is presented below.

Write the exception handler in a separate file, store that file
in the same directory as the regular program, and select
the Settings menu item “Assemble all files in directory”

Write the exception handler in a separate file, store that file
in any directory, then open the “Exception Handler…” dialog
in the Settings menu, check the check box and browse to
that file.

If there is no instruction at location 0x800000180,
MARS will terminate the MIPS program with an appropriate error message.

The exception handler can return control to the program using
the eret instruction. This will place the EPC register $14 value into the
Program Counter, so be sure to increment $14 by 4 before returning
to skip over the instruction that caused the exception. The mfc0
and mtc0 instructions are used to read from and write to Coprocessor 0
registers.
Bits 8-15 of the Cause register $13 can also be used to indicate
pending interrupts. Currently this is used only by the Keyboard and
Display Simulator Tool, where bit 8 represents a keyboard interrupt
and bit 9 represents a display interrupt. For more details, see the
Help panel for that Tool.

Exception types declared in mars.simulator.Exceptions, but
not necessarily implemented, are ADDRESS_EXCEPTION_LOAD (4), ADDRESS_EXCEPTION_STORE (5),
SYSCALL_EXCEPTION (8),
BREAKPOINT_EXCEPTION (9),
RESERVED_INSTRUCTION_EXCEPTION (10),
ARITHMETIC_OVERFLOW_EXCEPTION (12),
TRAP_EXCEPTION(13),
DIVIDE_BY_ZERO_EXCEPTION (15),
FLOATING_POINT_OVERFLOW (16), and
FLOATING_POINT_UNDERFLOW (17).

When writing a non-trivial exception handler, your handler must first save
general purpose register contents, then restore them before returning.

Example of Trap Handler

The sample MIPS program below will immediately generate a trap exception because
the trap condition evaluates true, control jumps to the exception handler,
the exception handler returns control to the instruction following
the one that triggered the exception, then the program terminates normally.

.text
main:
teqi $t0,0 # immediately trap because $t0 contains 0
li $v0, 10 # After return from exception handler, specify exit service
syscall # terminate normally

# Trap handler in the standard MIPS32 kernel text segment

.ktext 0x80000180
move $k0,$v0 # Save $v0 value
move $k1,$a0 # Save $a0 value
la $a0, msg # address of string to print
li $v0, 4 # Print String service
syscall
move $v0,$k0 # Restore $v0
move $a0,$k1 # Restore $a0
mfc0 $k0,$14 # Coprocessor 0 register $14 has address of trapping instruction
addi $k0,$k0,4 # Add 4 to point to next instruction
mtc0 $k0,$14 # Store new address back into $14
eret # Error return; set PC to value in $14
.kdata
msg:
.asciiz “Trap generated”

Widely Used Exception Handler

The exception handler exceptions.s provided with
the SPIM simulator will assemble and run under MARS. The MARS
assembler will generate warnings because this program
contains directives that it does not
recognize, but as long as the setting “Assembler warnings are
considered errors” is not set this will not cause any
problems.

MARS 4.3 help contents

MARS – Mips Assembly and Runtime Simulator

Release 4.3

January 2013

Using MARS through its Integrated Development Environment (IDE)

The IDE is invoked when MARS is run with no command arguments, e.g. java -jar mars.jar.
It may also be launched from a graphical interface by double-clicking the mars.jar icon
that represents this executable JAR file.
The IDE provides basic editing, assembling and execution capabilities. Hopefully it
is intuitive to use. Here are comments on some features.
Menus and Toolbar: Most menu items have equivalent toolbar icons.
If the function of a toolbar icon is not obvious, just hover the mouse over it and
a tool tip will soon appear. Nearly all menu items also have keyboard shortcuts.
Any menu item not appropriate in a given situation is disabled.
Editor: MARS includes two integrated text editors. The default editor, new
in Release 4.0, features syntax-aware color highlighting of most MIPS language elements
and popup instruction guides. The original, generic, text editor without these features
is still available and can be selected in the Editor Settings dialog. It supports a single
font which can be modified in the Editor Settings dialog.
The bottom border of either editor includes the cursor line
and column position and there is a checkbox to display line numbers.
They are displayed outside the editing area. If you use an external editor, MARS provides
a convenience setting that will automatically assemble a file as soon as it is opened. See
the Settings menu.

Message Areas: There are two tabbed message areas at the
bottom of the screen. The Run I/O tab is used at runtime for
displaying console output and entering console input as program execution progresses.
You have the option of entering console input into a pop-up dialog then echoes to the message area.
The MARS Messages tab is used for other messages such as assembly or
runtime errors and informational messages. You can click on assembly error messages to
select the corresponding line of code in the editor.

MIPS Registers: MIPS registers are displayed at all times, even
when you are editing and not running a program. While writing your program,
this serves as a useful reference for register names and their conventional
uses (hover mouse over the register name to see tool tips). There are three
register tabs: the Register File (integer registers $0 through $31 plus LO,
HI and the Program Counter), selected Coprocesor 0 registers (exceptions and
interrupts), and Coprocessor 1 floating point registers.

Assembly: Select Assemble from the Run menu or the
corresponding toolbar icon to assemble the file currently in the Edit tab.
Prior to Release 3.1, only one file could be assembled and run at a time.
Releases 3.1 and later provide a primitive Project capability. To use it, go to the
Settings menu and check Assemble operation applies to all
files in current directory. Subsequently, the assembler will assemble
the current file as the “main” program and also assemble all other assembly
files (*.asm; *.s)
in the same directory. The results are linked and if all these
operations were successful the program can be executed. Labels that are
declared global with the “.globl” directive may be referenced in any of the
other files in the project. There is also a setting that permits
automatic loading and assembly of a selected exception handler file. MARS uses
the MIPS32 starting address for exception handlers: 0x80000180.

Execution: Once a MIPS program successfully assembles, the
registers are initialized and three windows
in the Execute tab are filled: Text Segment, Data Segment,
and Program Labels. The major execution-time features are described below.

Labels Window: Display of the Labels window (symbol table) is
controlled through the Settings menu. When displayed, you can click on any label
or its associated address to center and highlight the contents of that address
in the Text Segment window or Data Segment window as appropriate.

The assembler and simulator are invoked from the IDE
when you select the Assemble, Go,
or Step operations from the Run menu or their corresponding
toolbar icons or keyboard shortcuts. MARS messages are displayed on the
MARS Messages tab of the message area at the bottom of the screen.
Runtime console input and output is handled in the Run I/O tab.

This document is available for printing on the MARS home page
http://www.cs.missouristate.edu/MARS/.

MARS 4.3 help contents

MARS – Mips Assembly and Runtime Simulator

Release 4.3

January 2013

Introduction

MARS, the Mips Assembly and Runtime Simulator,
will assemble and simulate the execution of MIPS assembly language programs.
It can be used either from a command line or through its
integrated development environment (IDE). MARS is written in Java and
requires at least Release 1.5 of the J2SE Java Runtime Environment (JRE) to work.
It is distributed as an executable JAR file.
The MARS home page
is
http://www.cs.missouristate.edu/MARS/. This document is available for printing there.

As of Release 4.0, MARS assembles and simulates 155 basic instructions of the MIPS-32
instruction set, approximately 370 pseudo-instructions or instruction variations, the 17 syscall functions
mainly for console and file I/O defined by SPIM, and an additional 22 syscalls for other uses such as MIDI
output, random number generation and more. These are listed in separate help tabs. It supports seven
different memory addressing modes for load and store instructions: label, immed,
label+immed, ($reg), label($reg), immed($reg), and label+immed($reg), where immed
is an integer up to 32 bits. A setting is available to disallow use of pseudo-instructions
and extended instruction formats and memory addressing modes.

Our guiding reference in implementing the instruction set has been
Computer Organization and Design, Fourth Edition by Patterson and Hennessy,
Elsevier – Morgan Kaufmann, 2009. It summarizes the MIPS-32 instruction set
and pseudo-instructions in Figures 3.24 and 3.25 on pages 279-281, with details
provided in the text and in Appendix B. MARS Releases 3.2 and above implement all the instructions
in Appendix B and those figures except the delay branches from the left column of Figure 3.25.
It also implements all the system services (syscalls) and assembler directives
documented in Appendix B.

The MARS IDE provides program editing and assembling but its real
strength is its support for interactive debugging. The programmer can easily set and
remove execution breakpoints or step through execution forward or backward (undo) while
viewing and directly editing register and memory contents.

Questions and Comments

Send MARS questions and comments to
Dr. Pete Sanderson at or
Dr. Ken Vollmar at .
We will respond as quickly as we can but as teaching professors do not have as much time to work on
this project as we would like during the school year. We presented papers
on MARS at the 2005 CCSC:MW conference and the 2006 SIGCSE Technical Symposium. We presented
a tutorial session on MARS at the 2007 CCSC:CP conference and the Tutorial handout is available
from the MARS homepage.

This document is available for printing on the MARS home page
http://www.cs.missouristate.edu/MARS/.

MARS 4.3 help contents

MARS – Mips Assembly and Runtime Simulator

Release 4.3

January 2013

Interactive Debugging Features

MARS provides many features for interactive debugging through its Execute pane.
Features include:

In Step mode, the next instruction to be simulated is highlighted and
memory content displays are updated at each step.
Select the Go option if you want to simulate continually.
It can also be used to continue simulation
from a paused (step, breakpoint, pause) state.
Breakpoints are easily set and reset using the check boxes next to each instruction displayed
in the Text Segment window. New in Release 3.8: You can temporarily suspend breakpoints
using Toggle Breakpoints in the Run menu or by clicking the “Bkpt” column header in the Text Segment
window. Repeat, to re-activate.
When running in the Go mode, you can select the simulation
speed using the Run Speed slider. Available speeds range
from .05 instructions per second (20 seconds between steps) up to 30
instructions per second, then above this offers an “unlimited” speed.
When using “unlimited” speed, code highlighting and memory display updating
are turned off while simulating (but it executes really fast!).
When a breakpoint is reached, highlighting and updating occur.
Run speed can be adjusted while the program is running.
When running in the Go mode, you can pause or stop
simulation at any time using the Pause or Stop features.
The former will pause execution and update the display, as if you
were stepping or at a breakpoint. The latter will terminate execution
and display final memory and register values. If running at “unlimited”
speed, the system may not respond immediately but it will respond.
You have the ability to interactively step “backward” through program execution
one instruction at a time to “undo” execution steps. It will buffer up to 2000 of the most
recent execution steps (this limit is stored in a properties file and can be changed).
It will undo changes made to MIPS memory, registers or condition flags,
but not console or file I/O. This should be a great debugging aid.
It is available anytime execution is paused and at termination (even if terminated due to
exception).

When program execution is paused or terminated, select Reset
to reset all memory cells and registers to their initial post-assembly values.
In fact, Reset is implemented by re-assembling the program.
Memory addresses and values, and register values, can be viewed in either decimal
or hexadecimal format. All data are stored in little-endian byte order (each
word consists of byte 3 followed by byte 2 then 1 then 0). Note that each word
can hold 4 characters of a string and those 4 characters will appear in the
reverse order from that of the string literal.
Data segment contents are displayed 512 bytes
at a time (with scrolling) starting with the data segment base address (0x10010000).
Navigation buttons are provided to change the display to the next
section of memory, the previous, or back to the initial (home) range. A combo box is
also provided to view memory contents in the vicinity of the stack pointer
(contents of MIPS $sp register), global pointer (contents of MIPS $gp register),
the heap base address (0x10040000), .extern globals (0x10000000),
the kernel data segment (0x90000000), or memory-mapped IO (MMIO, 0xFFFF0000).
Contents of any data segment memory word and almost any MIPS register can be modified by
editing its displayed table cell. Double-click on a cell to edit it and press the Enter key
when finished typing the new value. If you
enter an invalid 32-bit integer, the word INVALID appears in the cell
and memory/register contents are not affected. Values can be entered
in either decimal or hexadecimal (leading “0x”). Negative hexadecimal
values can be entered in either two’s complement or signed format. Note
that three of the integer registers (zero, program counter, return address)
cannot be edited.
Contents of cells representing floating point registers can be edited
as described above and will accept valid hexadecimal or decimal floating point
values. Since each double-precision register overlays two single-precision
registers, any changes to a double-precision register will affect one or both
of the displayed contents of its corresponding single-precision registers.
Changes to a single-precision register will affect the display of its
corresponding double-precision register. Values entered in hexadecimal
need to conform to IEEE-754 format. Values entered in decimal are entered
using decimal points and E-notation (e.g. 12.5e3 is 12.5 times 10 cubed).
Cell contents can be edited during program execution and once accepted
will apply starting with the next instruction to be executed.
Clicking on a Labels window entry will cause the location associated with
that label to be centered and highlighted in the Text Segment or Data Segment
window as appropriate. Note the Labels window is not displayed by default but
can be by selecting it from the Settings menu.

This document is available for printing on the MARS home page
http://www.cs.missouristate.edu/MARS/.

Bug Reporting help contents

Bug Reporting and General Comments

The MARS web page is maintained at
http://www.cs.missouristate.edu/MARS/

and will contain updated releases, bug lists, etc.

For bug reporting and general comments, please send email to
Dr. Pete Sanderson at

with “MARS” in the
subject line. Please include sufficient information to recreate
the problem, and assembly programs if appropriate.

MARS 4.3 help contents

MARS – Mips Assembly and Runtime Simulator

Release 4.3

January 2013

Using MARS from a command line.

MARS can be run from a command interpreter to assemble and execute a MIPS program in
a batch fashion.
The format for running MARS from a command line is:

java -jar mars.jar [options] program.asm [more files…] [ pa arg1 [more args…]]

Items in [ ] are optional. Valid options (not case sensitive, separated by spaces) are:

Option Description Since
a assemble only, do not simulate 1.0
aen terminate MARS with integer exit code n if assembly error occurs 4.1
ascii display memory or register contents interpreted as ASCII codes. (alternatives are dec and hex) 4.1
b brief – do not display register/memory address along with contents 2.2
d display MARS debugging statements (of interest mainly to MARS developer) 1.0
db MIPS delayed branching is enabled. 3.3
dec display memory or register contents in decimal. (alternatives are ascii and hex) 2.2
dump dump memory contents to file.
Option has 3 arguments, e.g. dump . Current supported segments are .text
and .data. Also supports an address range (see m-n below). Current supported dump formats are Binary, HexText, BinaryText, AsciiText. See examples below. 3.4
hex display memory or register contents in hexadecimal – this is the default. (alternatives are ascii and dec) 2.2
h display this help. Use this option by itself and with no filename. 1.0
ic display instruction count; the number of MIPS basic instructions ‘executed’ 4.3
mc set memory configuration.
Option has 1 argument, e.g. mc . Argument is case-sensitive and its
possible values are Default for the default 32-bit address space, CompactDataAtZero for
a 32KB address space with data segment at address 0, or CompactTextAtZero
for a 32KB address space with text segment at address 0. 3.7
me display MARS messages to standard err instead of standard out. Allows you to separate MARS messages from MIPS program output using redirection. 4.3
nc copyright notice will not be displayed. Useful if redirecting or piping program output. 3.5
np pseudo-instructions or extended instruction formats are not permitted. 3.0
p project option – will assemble the specified file and all other assembly files (*.asm; *.s) in its directory. 3.1
sen terminate MARS with exit code n if simulate (run) error occurs 4.1
sm start execution at statement having global label ‘main’ if defined 3.8
we assembler warnings will be considered errors. 3.5
n where n is an integer maximum count of execution steps to simulate.
If 0, negative or not specified, there is no maximum. 1.0
$reg where reg is number or name (e.g. 5, t3, f10) of register whose
content to display at end of run. Even-numbered float register displays both float and double. Option may be repeated.
NOTE: Depending on your command shell, you may need to escape the $, e.g. \$t3 2.2
reg_name where reg_name is the name (e.g. t3, f10) of register whose
content to display at end of run. Even-numbered float register displays both float and double. Option may be repeated. $ not required. 2.2
m-n memory address range from m to n whose contents to
display at end of run. m and n may be decimal or hexadecimal (starts with 0x),
m <= n, both must be on word boundary. Option may be repeated. 2.2 pa program arguments - all remaining space-separated items are argument values provided to the MIPS program via $a0 (argc - argument count) and $a1 (argv - address of array containing pointers to null-terminated argument strings). The count is also at the top of the runtime stack ($sp), followed by the array.This option and its arguments must be the last items in the command! 3.5 Example: java -jar mars.jar h Displays command options and explanations. Example: java -jar mars.jar $s0 $s1 0x10010000-0x10010010 fibonacci.asm Assemble and run fibonacci.asm. At the end of the run, display the contents of registers $s0 and $s1, and the contents of memory locations 0x10010000 through 0x10010010. The contents are displayed in hexadecimal format. Example: java -jar mars.jar a fibonacci.asm Assemble fibonacci.asm. Does not attempt to run the program, and the assembled code is not saved. Example: java -jar mars.jar 100000 infinite.asm Assemble and run infinite.asm for a maximum of 100,000 execution steps. Example: java -jar mars.jar p major.asm Assemble major.asm and all other files in the same directory, link the assembled code, and run starting with the first instruction in major.asm. Example: java -jar mars.jar major.asm minor.asm sub.asm Assemble and link major.asm, minor.asm and sub.asm. If successful, execution will begin with the first instruction in major.asm. Example: java -jar mars.jar a dump .text HexText hexcode.txt fibonacci.asm Assemble fibonacci.asm without simulating (note use of 'a' option). At end of assembly, dump the text segment (machine code) to file hexcode.txt in hexadecimal text format with one instruction per line. Example: java -jar mars.jar dump 0x10010000-0x10010020 HexText hexcode.txt fibonacci.asm Assemble and simulate fibonacci.asm. At end of simulation, dump the contents of addresses 0x1001000 to 0x10010020 to file hexdata.txt in hexadecimal text format with one word per line. Example: java -jar mars.jar t0 process.asm pa counter 10 Assemble and run process.asm with two program argument values, "counter" and "10". It may retrieve the argument count (2) from $a0, and the address of an array containing pointers to the strings "count" and "10", from $a1. At the end of the run, display the contents of register $t0. The ability to run MARS from the command line is useful if you want to develop scripts (macros) to exercise a given MIPS program under multiple scenarios or if you want to run a number of different MIPS programs such as for grading purposes. This document is available for printing on the MARS home page http://www.cs.missouristate.edu/MARS/. MARS 4.3 help contents MARS - Mips Assembly and Runtime Simulator Release 4.3 January 2013 Cool Capability: Plug-in Tools Beginning with Release 2.0, MARS is capable of running externally-developed software that interacts with an executing MIPS program and MIPS system resources. The requirements for such a program are: It implements the mars.tools.MarsTool interface. It is part of the mars.tools package. It compiles cleanly into a ".class" file, stored in the mars/tools directory. MARS will detect all qualifying tools upon startup and include them in its Tools menu. When a tool's menu item is selected, an instance of it will be created using its no-argument constructor and its action() method will be invoked. If no qualifying tools are found at MARS startup, the Tools menu will not appear. To use such a tool, load and assemble a MIPS program of interest then select the desired tool from the Tools menu. The tool's window will open and depending on how it is written it will either need to be "connected" to the MIPS program by clicking a button or will already be connected. Run the MIPS program as you normally would, to initiate tool interaction with the executing program. Beginning with Release 3.2, the abstract class mars.tools.AbstractMarsToolAndApplication is included in the MARS distribution to provide a substantial framework for implementing your own MARS Tool. A subclass that extends it by implementing at least its two abstract methods can be run not only from the Tools menu but also as a free-standing application that uses the MARS assembler and simulator in the background. Several Tools developed by subclassing AbstractMarsToolAndApplication are included with MARS: an Introduction to Tools, a Data Cache Simulator, a Memory Reference Visualizer, and a Floating Point tool. The last one is quite useful even when not connected to a MIPS program because it displays binary, hexadecimal and decimal representations for a 32 bit floating point value; when any of them is modified the other two are updated as well. Release 3.5 includes new tools, most notably a keyboard and display simulator that allows you to perform memory-mapped I/O (MMIO) using polled and interrupt-driven techniques as described in various references. Click its Help button for more details. If you wish to develop your own MARS Tool, you will first need to extract the MARS distribution from its JAR file if you have not already done so. All MARS tools must be stored in the mars/tools directory. Follow the Tutorial Materials link on the MARS homepage to find a tutorial that covers development of MARS Tools. Cool Capability: Extending the syscall set or reassigning syscall numbers Beginning with Release 3.1, system calls (syscall instruction) are implemented using a technique similar to that for tools. This permits anyone to add a new syscall by defining a new class that meets these requirements: It implements the mars.mips.instructions.syscalls.Syscall interface, or extends the mars.mips.instructions.syscalls.AbstractSyscall class (which provides default implementations of everything except the simulate() method). It is part of the mars.mips.instructions.syscalls package. It compiles cleanly into a ".class" file, stored in the mars/mips/instructions/syscalls directory. MARS will detect all qualifying syscall classes upon startup and the runtime simulator will invoke them when the syscall instruction is simulated and register $v0 contains the corresponding integer service number. Syscalls and syscall number assignments in MARs match those of SPIM for syscalls 1 through 17. However if you wish to change syscall number assignments, you may do so by editing the Syscall.properties file included in the release (this requires extraction from the JAR file). Follow the Tutorial Materials link on the MARS homepage to find a tutorial that covers development of system calls. Cool Capability: Extending the instruction set You can add customized pseudo-instructions to the MIPS instruction set by editing the PseudoOps.txt file included in the MARS distribution. Instruction specification formats are explained in the file itself. The specification of a pseudo-instruction is one line long. It consists of an example of the instruction, constructed using available instruction specification symbols, followed by a tab-separated list of the basic MIPS instructions it will expand to. Each is an instruction template constructed using instruction specification symbols combined with special template specification symbols. The latter permit substitution at program assembly time of operands from the user's program into the expanded pseudo-instruction. PseudoOps.txt is read and processed at MARS startup, and error messages will be produced if a specification is not correctly formatted. Note that if you wish to edit it you first have to extract it from the JAR file. Follow the Tutorial Materials link on the MARS homepage to find a tutorial that covers modification of the pseudo-instruction set. This document is available for printing on the MARS home page http://www.cs.missouristate.edu/MARS/. MARS Release History and Notes MARS - Mips Assembly and Runtime Simulator Release 4.3 January 2013 MARS Release History Mars 4.3 was released in January 2013. Enhancements and bug fixes include: A macro facility has been developed by Mr. Mohammad Sekhavat. It is documented in the MIPS help tab Macros. A text substitution facility similar to #define has been developed using the new .eqv directive. It is also documented in the MIPS help tab Macros. A text insertion facility similar to #include has been developed using the new .include directive. It is also documented in the MIPS help tab Macros. It permits a macro to be defined in one file and included wherever needed. Two new command mode options are now available: ic (Instruction Count) to display a count of statements executed upon program termination, and me (Messages to Error) to send MARS messages to System.err instead of System.out. Allows you to separate MARS messages from MIPS output using redirection, if desired. Redirect a stream in DOS with "1>” or “2>” for out and err,
respectively. To redirect both, use “> filename 2>&1”

Changed the default font family settings from Courier New to Monospaced.
This was in response to reports of Macs displaying left parentheses and vertical
bars incorrectly.

Changed the way operands for .byte and .half directives are range-checked.
It will now work like SPIM, which accepts any operand value but truncates high-end bits as
needed to fit the 1 (byte) or 2 (half) byte field. We’ll still issue a warning
but not an error.

For file reads, syscall 14, file descriptor 0 is always open for standard input. For file
writes, syscall 15, file descriptors 1 and 2 are always open for standard output and
standard error, respectively. This permits you to write I/O code that will
work either with files or standard I/O. When using the IDE, standard input and output
are performed in the Run I/O tab. File descriptors for regular files are
allocated starting with file descriptor 3.

Mars 4.2 was released in August 2011. Enhancements and bug fixes include:

Performing a Save operation on a new file will now use the file’s tab
label as the the default filename in the Save As dialog (e.g. mips1.asm).
Previously, it did not provide a default name.

When the “assemble all files in directory” setting is enabled (useful
for multi-file projects), you can now switch focus from one editor tab to another
without invalidating the current assemble operation. You can similarly open
additional project files. Previously, the open or tab selection would
invalidate the assemble operation and any paused execution state or
breakpoints would be lost.

The Read String syscall (syscall 8) has been fortified to prevent Java exceptions from occurring
when invalid values are placed in $a1.

Will now perform runtime test for unaligned doubleword address in
‘ldc1’ and ‘sdc1’ instructions and trap if not aligned.

Basic statements in the Text Segment display now renders immediates using
eight hex digits when displaying in hex. Previously it rendered only
four digits to conserve space. This led to confusing
results. For instance, -1 and 0xFFFF would both be displayed as 0xFFFF
but -1 expands to 0xFFFFFFFF and 0xFFFF expands to 0x0000FFFF.

Mars 4.1 was released in January 2011. Enhancements and bug fixes include:

The ability to view Data Segment contents interpreted as ASCII
characters has been added. You’ll find it on the bottom border of
the Data Segment Window as the checkbox “ASCII”. This overrides the
hexadecimal/decimal setting but only for the Data Segment display.
It does not persist across sessions. Cells cannot be edited in
ASCII format.

The Dump Memory feature in the File menu now provides an ASCII dump
format. Memory contents are interpreted as ASCII codes.

A command-mode option “ascii” has been added to display memory or
register contents interpreted as ASCII codes. It joins the existing
“dec” and “hex” options for displaying in decimal or hexadecimal,
respectively. Only one of the three may be specified.

The actual characters to display for all the ASCII display options
(data segment window, dump memory, command-mode option) are
specified in the config.properties file. This includes a “placeholder”
character to be displayed for all codes specified as non-printing.
ASCII codes 1-7, 14-31, and 127-255 are specified as
non-printing, but this can be changed in the properties file.

A new Help tab called Exceptions has been added. It explains the basics
of MIPS exceptions and interrupts as implemented in MARS. It also includes
tips for writing and using exception handlers.

A new Tool called Bitmap Display has been added. You can use it
to simulate a simple bitmap display. Each word of the specified address
space represents a 24 bit RGB color (red in bits 16-23, green in bits
8-15, blue in bits 0-7) and a word’s value will be displayed on the Tool’s
display area when the word is written to by the MIPS program. The base
address corresponds to the upper left corner of the display, and words are
displayed in row-major order. Version 1.0 is pretty basic, constructed
from the Memory Reference Visualization Tool code.

Additional operand formats
were added for the multiplication pseudo-instructions ‘mul’ and ‘mulu’.

The editor’s context-sensitive pop-up help will now appear below
the current line whenever possible. Originally it appeared either above,
centered to the side,
or below, depending on the current line’s vertical position in the editing
window. Displaying the pop-up above the current line tended to visually block
important information, since frequently a line of code uses the same operand
(especially registers) as the one immediately above it.

The editor will now auto-indent each new line when the Enter
key is pressed. Indentation of the new line will match that of the
line that precedes it. This feature can be disabled in the Editor settings dialog.

Two new command-mode options have been added. The “aeN” option, where
N is an integer, will terminate MARS with exit value N when an assemble error
occurs. The “seN” option will similarly terminate MARS with exit value
N when a simulation (MIPS runtime) error occurs. These options can be useful
when writing scripts for grading. Thanks to my Software
Engineering students Robert Anderson, Jonathan Barnes, Sean Pomeroy, and Melissa Tress
for designing and implementing these options.

An editor bug that affected Macintosh users has been fixed.
Command shortcuts, e.g. Command-s for save, did not
function and also inserted the character into the text.

A bug in Syscall 54 (InputDialogString) has been fixed. This syscall is
the GUI equivalent of Syscall 8 (ReadString), which follows the semantics
of UNIX ‘fgets’. Syscall 54 has been modified to also follow the ‘fgets’
semantics.

A bug in the Cache Simulator Tool has been fixed. The animator that
paints visualized blocks green or red (to show cache hit or miss) sometimes
paints the wrong block when set-associated caching is used. The underlying
caching algorithm is correct so the numeric results such as hit ratios
have always been correct. The animator has been corrected.
Thanks to Andreas Schafer and his student Carsten Demel for bringing this
to my attention.

Mars 4.0.1 was released in October 2010. It is a bug fix release to address three bugs.

The Edit and Execute tabs of the IDE, which were relocated in 4.0 from the top to the left edge and oriented vertically, have been
moved back to the top edge because Macintosh running Java 1.6 does not correctly render vertically-oriented tabs.

An exception may be thrown in multi-file assembles when the last file of the assembly is not the longest. This occurs
only when using the IDE, and has been corrected.

If an assemble operation fails due to a non-existing exception handler file (specified through the IDE Settings menu), unchecking
the exception handler setting does not prevent the same error from occuring on the next assemble. This has been corrected.

Mars 4.0 was released in August 2010. Enhancements and bug fixes include:

New Text Editor: Mars features an entirely new integrated text editor. It creates a new tab for each file
as it is opened. The editor now features language-aware
color highlighting of many MIPS assembly language elements with customizable
colors and styles. It also features automatic context-sensitive popup instruction
guides. There are two levels: one with help and autocompletion of instruction names
and a second with help information for operands. These and other new editor
features can be customized or disabled through
the expanded Editor Settings dialog. You can even revert to the previous
notepad-style editor if you wish (multi-file capability is retained).
The language-aware editor is based on
the open source jEdit Syntax Package (syntax.jedit.org). It is separate from
the assembler, so any syntax highlighting quirks will not affect assembly.

Improved Instruction Help: All the instruction examples in the help tabs (and new popup instruction guides)
now use realistic register names, e.g. $t1, $t2, instead of $1, $2. The instruction format
key displayed above the MIPS help tabs has been expanded to include explanations of the
various addressing modes for load and store instructions and pseudo-instructions.
Descriptions have been added to every example instruction and pseudo-instruction.

Improved Assembly Error Capability: If the assemble operation results in errors, the first error message
in the Mars Messages text area will be highighted and the corresponding erroneous instruction will be selected in the
text editor. In addition, you can click on any error message in the Mars Messages text area to select the corresponding
erroneous instruction in the text editor. The first feature does not select in every situation (such as when
assemble-on-open is set) but in the situations where it doesn’t work no harm is done plus
the second feature, clicking on error messages, can still be used.

Console input syscalls (5, 6, 7, 8, 12) executed in the IDE now receive input keystrokes directly in the Run I/O text
area instead of through a popup input dialog. Thanks to Ricardo Pascual for providing this feature!
If you prefer the popup dialogs, there is a setting to restore them.

The floor, ceil, trunc and round operations now all produce the MIPS default result 2^31-1 if the value is
infinity, NaN or out of 32-bit range. For consistency, the sqrt operations now produce the result NaN if the operand is negative
(instead of raising an exception). These cases are all consistent with FCSR (FPU Control and Status Register)
Invalid Operation flag being off. The ideal solution would be to simulate the FCSR register itself so all
MIPS specs for floating point instructions can be implemented, but that hasn’t happened yet.

The Basic column in the Text Segment Window now displays data and addresses in either decimal or
hexadecimal, depending on the current settings. Note that the “address” in branch instructions
is actually an offset relative to the PC, so is treated as data not address. Since data operands in
basic instructions are no more than 16 bits long, their hexadecimal display includes only 4 digits.

The Source column in the Text Segment Window now preserves tab spacing for a cleaner appearance (tab characters were previously not rendered).

Instruction mnemonics can now be used as labels, e.g. “b:”.

New syscall 36 will display an integer as an unsigned decimal.

A new tool, Digital Lab Sim, contributed by Didier Teifreto ( -fcomte.fr). This tool
features two seven-segment displays, a hexadecimal keypad, and a counter. It uses MMIO to explore
interrupt-driven I/O in an engaging setting. More information is available from its Help feature. Many thanks!

MARS 4.0 requires Java 1.5 (5.0) instead of 1.4. If this is an issue for you, let me know.

Mars 3.8 was released in January 2010. Enhancements and bug fixes include:

A new feature to temporarily suspend breakpoints you have previously set. Use it
when you feel confident enough to run your program without the breakpoints but not
confident enough to clear them! Use the Toggle Breakpoints item in the Run menu, or
simply click on the “Bkpt” column header in the Text Segment window. Repeat, to re-activate.

Two new Tools contributed by Ingo Kofler of Klagenfurt University in Austria.
One generates instruction statistics and the other simulates branch prediction using
a Branch History Table.

Two new print syscalls. Syscall 34 prints an integer in hexadecimal format.
Syscall 35 prints an integer in binary format. Suggested by Bernardo Cunha of Portugal.

A new Setting to control whether or not the MIPS program counter will be
initialized to the statement with global label ‘main’ if such a statement exists. If
the setting is unchecked or if checked and there is no ‘main’, the program counter
will be initialized to the default starting address. Release 3.7 was programmed
to automatically initialize it to the statement labeled ‘main’. This led to
problems with programs that use the standard SPIM exception handler exceptions.s
because it includes a short statement sequence at the default starting address
to do some initialization then branch to ‘main’. Under 3.7 the initialization
sequence was being bypassed. By default this setting is unchecked. This
option can be specified in command mode using the ‘sm’ (Start at Main) option.

Mars Tools that exist outside of Mars can now be included in the Tools
menu by placing them in a JAR and including it in a command that launches
the Mars IDE. For example: java -cp plugin.jar;Mars.jar Mars
Thanks to Ingo Kofler for thinking of this technique and providing the
patch to implement it.

Corrections and general improvements to the MIDI syscalls. Thanks to Max Hailperin
of Gustavus Adolphus College for supplying them.

Correction to an assembler bug that flagged misidentified invalid MIPS instructions
as directives.

Mars 3.7 was released in August 2009. Enhancements and bug fixes include:

A new feature for changing the address space configuration of the
simulated MIPS machine. The 32-bit address space configuration used by
all previous releases remains the default. We have defined two
alternative configurations for a compact 32KB address space. One starts the
text segment at address 0 and the other starts the data segment at address 0.
A 32KB address space permits commonly-used load/store pseudo-instructions
using labels, such as lw $t0,increment, to expand to a single basic
instruction since the label’s full address will fit into the 16-bit address
offset field without sign-extending to a negative value. This was done in response to
several requests over the years for smaller addresses and simplified expansions
to make assembly programs easier to comprehend. This release does not
include the ability to define your own customized configuration, although we
anticipate adding it in the future. It is available both through the command
mode (option mc) and the IDE.
See Memory Configuration… at the bottom of the Settings menu.
Related to the previous item: load and store pseudo-instructions of the form
lw $t0,label and lw $t0,label($t1) will expand to a single
instruction (addi for these examples) if the current memory configuration assures the
label’s full address will fit into the low-order 15 bits. Instructions
for which this was implemented are: la, lw, lh, lb, lhu, lbu, lwl, lwr, ll,
lwc1, ldc1, l.s, l.d, sw, sh, sb, swl, swr, sc, swc1, sdc1,
s.s, and s.d.
If a file contains a global statement label “main” (without quotes, case-sensitive), then execution will
begin at that statement regardless of its address. Previously, program execution
always started at the base address of the text segment. This will be handy for
multi-file projects because you no longer need to have the “main file” opened in
the editor in order to run the project. Note that main has to be declared global
using the .globl directive.
We have added a Find/Replace feature to the editor. This has been another
frequent request. Access it through the Edit menu or Ctrl-F. Look for major
enhancements to the editor in 2010!
The syscalls for Open File (13), Read from File (14), and Write to File (15)
all now place their return value into register $v0 instead of $a0. The table
in Computer Organization and Design’s Appendix B on SPIM specifies
$a0 but SPIM itself consistently uses $v0 for the return values.
Pseudo-instructions for div, divu, mulo, mulou, rem, remu, seq, sne, sge,
sgeu, sgt, sgtu, sle, sleu now accept a 16- or 32-bit immediate as their third operand.
Previously the third operand had to be a register.
Existing Tools were tested using reconfigured memory address space (see first item). Made some
adaptations to the Keyboard and Display Simulator Tool that allow it to be used for
Memory Mapped I/O (MMIO) even under the compact memory model, where the MMIO base address
is 0x00007f00 instead of 0xffff0000. Highlighting is not perfect in this scenario.
Bug Fix: The syscall for Open File (13) reversed the meanings of the
terms mode and flag. Flags are used to indicate the intended
use of the file (read/write). Mode is used to set file permissions in specific situations.
MARS implements selected flags as supported by Java file streams,
and ignores the mode if specified. For more details, see the Syscalls
tab under Help. The file example in that tab has been corrected.
Bug Fix: The assembler incorrectly generated an
error on Jump instructions located in the kernel text segment.
Bug Fix: The project (p) option in the command interface worked incorrectly
when MARS was invoked within the directory containing the files to be assembled.
Acknowledgement: The development of Release 3.7 was supported by a SIGCSE
Special Projects Grant.

Mars 3.6 was released in January 2009. Enhancements and bug fixes include:

We’ve finally implemented the most requested new feature: memory and register cells will
be highlighted when written to during timed or stepped simulation! The
highlighted memory/register cell thus represents the result of the instruction just completed.
During timed or stepped execution, this is NOT the highlighted instruction. During back-stepping,
this IS the highlighted instruction. The highlighted instruction is the next one
to be executed in the normal (forward) execution sequence.

In conjunction with cell highlighting, we’ve added the ability to customize the highlighting
color scheme and font. Select Highlighting in the Settings menu. In the resulting dialog,
you can select highlight background color, text color, and font for the different runtime tables (Text segment,
Data segment, Registers). You can also select them for normal, not just
highlighted, display by even- and odd-numbered row but not by table.

Cool new Labels Window feature: the table can be sorted in either ascending or descending
order based on either the Label (alphanumeric) or the Address (numeric) column. Just click on
the column heading to select and toggle between ascending (upright triangle) or descending
(inverted triangle). Addresses are sorted based on unsigned 32 bit values.
The setting persists across sessions.
The Messages panel, which includes the Mars Messages and Run I/O tabs, now displays using
a mono-spaced (fixed character width) font. This facilitates text-based graphics when running
from the IDE.
The Mars.jar distribution file now contains all files needed to produce
a new jar file. This will make it easier for you to expand the jar, modify source files,
recompile and produce a new jar for local use. CreatMarsJar.bat contains the jar instruction.
The Help window now includes a tab for Acknowledgements. This recognizes MARS contributors
and correspondents.
We’ve added a new system call (syscall) for generating MIDI tones synchronously, syscall 33.
The original MIDI call returns immediately when the tone is generated. The new one will not return
until the tone output is complete regardless of its duration.

The Data Segment display now scrolls 8 rows (half a table) rather than 16 when the
arrow buttons are clicked. This makes it easier to view a sequence of related cells that
happen to cross a table boundary. Note you can hold down either button for rapid scrolling.
The combo box with various data address boundaries also works better now.
Bug Fix: Two corrections to the Keyboard and Display Simulator Tool. Transmitter Ready bit was
not being reset based on instruction count
when running in the kernel text segment, and the Status register’s Exception Level bit was not
tested before enabling the interrupt service routine (could lead to looping if interrupts occur
w/i the interrupt service routine). Thanks to Michael Clancy and Carl Hauser for bringing these
to my attention and suggesting solutions.
Bug Fix: Stack segment byte addresses not on word boundaries were not being processed
correctly. This applies to little-endian byte order (big-endian is not enabled or tested in MARS).
Thanks to Saul Spatz for recognizing the problem and providing a patch.
Minor Bug Fixes include: Correcting a fault leading to failure when launching MARS in command
mode, clarifying assembler error message for too-few or too-many operands error, and correcting the
description of lhu and lbu instructions from “unaligned” to “unsigned”.

Mars 3.5 was released in August 2008. Major enhancements and bug fixes include:

A new Tool, the Keyboard and Display MMIO Simulator, that supports polled and interrupt-driven
input and output operations through Memory-Mapped I/O (MMIO) memory. The MIPS program writes to
memory locations which serve as registers for simulated devices. Supports keyboard input and a
simulated character-oriented display. Click the tool’s Help button for more details.
A new Tool, the Instruction Counter, contributed by MARS user Felipe Lessa. It will count the
number of MIPS instructions executed along with percentages for R-format, I-format, and J-format
instructions. Thanks, Felipe!
Program arguments can now be provided to the MIPS program at runtime, through either an IDE setting or
command mode. See the command mode “pa” option for more details on command mode operation. The argument
count (argc) is placed in $a0 and the address of an array of null-terminated strings containing the
arguments (argv) is placed in $a1. They are also available on the runtime stack ($sp).
Two related changes permit MARS to assemble source code produced by certain compilers such as gcc.
One change is to issue warnings rather than errors for unrecognized directives. MARS implements a
limited number of directives. Ignore these warnings at your risk, but the assembly can continue.
The second change is to allow statement labels to contain, and specifically begin with, ‘$’.
In command mode, final register values are displayed by giving the register name as an option.
Register names begin with ‘$’, which is intercepted by certain OS command shells. The
convention for escaping it is not uniform across shells. We have enhanced the options so now you can
give the register name without the ‘$’. For instance, you can use t0 instead of $t0 as the option.
You cannot refer to registers by number in this manner, since an integer option is interpreted by
the command parser as an instruction execution limit. Thanks to Lucien Chaubert for reporting
this problem.
Minor enhancements: The command mode dump feature has been extended to permit memory address ranges as well
as segment names. If you enter a new file extension into the Open dialog, the extension will remain available throughout
the interactive session. The data segment value repetition operator ‘:’ now
works for all numeric directives (.word, .half, .byte, .float, .double).
This allows you to initialize multiple consecutive memory locations to the same value. For
example:
ones: .half 1 : 8 # Store the value 1 in 8 consecutive halfwords
Major change: Hexadecimal constants containing less than 8 digits will be interpreted as though the
leading digits are 0’s. For instance, 0xFFFF will be interpreted as 0x0000FFFF, not 0xFFFFFFFF as before.
This was causing problems with immediate operands in the range 32768 through 65535, which were
misinterpreted by the logical operations as signed 32 bit values rather than unsigned 16 bit values.
Signed and unsigned 16 bit values are now distinguished by the tokenizer based on the prototype
symbols -100 for signed and 100 for unsigned (mainly logical operations).
Many thanks to Eric Shade of Missouri State University and Greg Gibeling of UC Berkeley for
their extended efforts in helping me address this situation.
Minor Bug Fixes: round.w.s and round.w.d have been modified to correctly perform IEEE
rounding by default. Thanks to Eric Shade for pointing this out.
Syscall 12 (read character) has been changed to leave the character in $v0 rather then $a0. The
original was based on a misprint in Appendix A of Computer Organization and Design.
MARS would not execute from the executable Mars.jar file if it was stored in a directory
path those directory names contain any non-ASCII characters. This has been corrected. Thanks to
Felipe Lessa for pointing this out and offering a solution.
MARS will now correctly detect the EOF condition when reading from a file using syscall 14.
Thanks to David Reimann for bringing this to our attention.

Mars 3.4.1 was released on 23 January 2008. It is a bug fix release to address two bugs.

One bug shows up in pseudo-instructions in which the expansion includes branch instructions. The fixed branch
offsets were no longer correct due to changes in the calculation of branch offsets in Release 3.4.
At the same time, we addressed the issue of expanding such pseudo-instructions when
delayed branching is enabled. Such expansions will now include a nop instruction following the
branch.

We also addressed an off-by-one error that occurred in generating the lui instruction in the
expansion of conditional branch pseudo-instructions whose second operand is a 32 bit immediate.

The expansions for a number of pseudo-instructions were modified to eliminate internal branches.
These and other expansions were also optimized for sign-extended loading of 16-bit immediate operands
by replacing the lui/ori or lui/sra sequence with addi. Pseudo-instructions affected by one
or both of these modifications include: abs, bleu, bgtu, beq, bne, seq, sge, sgeu, sle, sleu, sne,
li, sub and subi. These modifications were suggested by Eric Shade of Missouri State University.

Mars 3.4 was released in January 2008. Major enhancements are:

A new syscall (32) to support pauses of specified length in milliseconds (sleep) during simulated execution.

Five new syscalls (40-44) to support the use of pseudo-random number generators. An unlimited number of these generators are available,
each identified by an integer value, and for each you have the ability to: set the seed value, generate a 32 bit integer value from the Java
int range, generate a 32 bit integer value between 0 (inclusive) and a specified upper bound (exclusive), generate a 32-bit float value between 0 (inclusive) and 1 (exclusive),
and generate a 64-bit double value between 0 (inclusive) and 1 (exclusive). All are based on the java.util.Random class.

Ten new syscalls (50-59) to support message dialog windows and data input dialog windows. The latter are distinguished from
the standard data input syscalls in that a prompting message is specified as a syscall argument and displayed in the input dialog.
All are based on the javax.swing.JOptionPane class.

The capability to dump .text or .data memory contents to file in various formats. The dump can be performed
before or after program execution from either the IDE (File menu and toolbar) or from command mode. It can also be performed
during an execution pause from the IDE. Look for the “Dump Memory” menu item in the File menu, or the “dump” option in command
mode. A .text dump will include only locations containing an instruction. A .data dump will include a multiple
of 4KB “pages” starting at the segment base address and ending with the last 4KB “page” to be referenced by the
program. Current dump formats include pure binary (java.io.PrintStream.write() method), hexadecimal text with one word (32 bits)
per line, and binary text with one word per line. An interface, abstract class, and format loader have been developed to facilitate
development and deployment of additional dump formats. This capability was prototyped by Greg Gibeling of UC Berkeley.

Changed the calculation of branch offsets when Delayed Branching setting is disabled.
Branch instruction target addresses are represented by
the relative number of words to branch. With Release 3.4, this value reflects delayed branching,
regardless of whether the Delayed Branching setting is enabled or not.
The generated binary code for branches will now match that of examples in the Computer Organization
and Design textbook. This is a change from the past, and was made after extensive discussions
with several MARS adopters. Previously, the branch offset was 1 lower if the Delayed Branching setting
was enabled — the instruction label: beq $0,$0,label would generate 0x1000FFFF if
Delayed Branching was enabled and 0x10000000 if it was disabled. Now it will generate 0x1000FFFF in
either case. The simulator will always branch to the correct location; MARS does not allow assembly under one
setting and simulation under the other.

Bug fix: The mars.jar executable JAR file can now be run from a different working directory. Fix was
suggested by Zachary Kurmas of Grand Valley State University.

Bug fix: The problem of MARS hanging while assembling a pseudo-instruction with a label operand that
contains the substring “lab”, has been fixed.

Bug fix: No Swing-related code will be executed when MARS is run in command mode. This fixes a problem that
occurred when MARS was run on a “headless” system (no monitor). Swing is the Java library to support
programming Graphical User Interfaces. Fix was provided by Greg Gibeling of UC Berkeley.

The ‘\0’ character is now recognized when it appears in string literals.

MARS 3.3 was released in July 2007. Major enhancements are:

Support for MIPS delayed branching. All MIPS computers implement this but it can be confusing for
programmers, so it is disabled by default. Under delayed branching, the next instruction after a branch
or jump instruction will always be executed, even if the branch or jump is taken! Many
programmers and assemblers deal with this by inserting a do-nothing “nop” instruction after every branch or jump.
The MARS assembler does not insert a “nop”. Certain pseudo-instructions expand to
a sequence that includes a branch; such instructions will not work correctly under delayed
branching.
Delayed branching is available in command mode with the “db” option.
A new tool of interest mainly to instructors. The Screen Magnifier tool, when selected from
the Tools menu, can be used to produce an enlarged static image of the pixels that lie beneath it.
The image can be annotated by dragging the mouse over it to produce a scribble line. It enlarges
up to 4 times original size.
You now have the ability to set and modify the text editor font family, style and size. Select
“Editor…” from the Settings menu to get the dialog. Click the Apply button to see the new
settings while the dialog is still open. Font settings are retained from one session to the next.
The font family list begins with 6 fonts commonly used across platforms (selected from lists
found at www.codestyle.org), followed by a complete list.
Two of the six are monospaced fonts, two are proportional serif, and two are proportional sans serif.
The Labels window on the Execute pane, which displays symbol table information, has been
enhanced. When you click on a label name or its address, the contents of that address are
centered and highlighted in the Text Segment window or Data Segment window as appropriate. This makes
it easier to set breakpoints based on text labels, or to find the value stored at a label’s address.

If you re-order the columns in the Text Segment window by dragging a column header,
the new ordering will be remembered and applied from that time forward, even from one MARS session to the next. The Text Segment
window is where source code, basic code, binary code, code addresses, and breakpoints are displayed.

If a MIPS program terminates by “running off the bottom” of the program, MARS terminates, as
before, without an exception, but now will display a more descriptive termination message in the
Messages window. Previously, the termination message was the same as that generated after executing an Exit syscall.

A new system call (syscall) to obtain the system time is now available. It is service
30 and is not available in SPIM. Its value is obtained from the java.util.Date.getTime() method.
See the Syscall tab in MIPS help for further information.
A new system call (syscall) to produce simulated MIDI sound through your sound card is now available.
It is service 31 and is not available in SPIM. Its implementation is based on the
javax.sound.midi package. It has been tested only under Windows.
See the Syscall tab in MIPS help for further information.

MARS 3.2.1 was released in January 2007. It is a bug fix release that addresses the
following bug in 3.2: a NullPointerException occurs when MIPS program execution terminates
by “dropping off the bottom” of the program rather than by using one of the Exit system
calls.

MARS 3.2 was released in December 2006. Major enhancements are:

It fixes several minor bugs, including one that
could cause incorrect file sequencing in the Project feature.

It includes the
AbstractMarsToolAndApplication abstract class to serve as a framework for easily
constructing “tools” and equivalent free-standing applications that use the MARS assembler
and simulator engines (kudos to the SIGCSE 2006 audience member who suggested this capability!).
A subclass of this abstract class can be used both ways (tool or application).

The floating
point and data cache tools were elaborated in this release and a new tool for animating and
visualizing memory references was developed. All are AbstractMarsToolAndApplication
subclasses.

This release includes support for exception handlers: the kernel data and text
segments (.kdata and .ktext directives), the MIPS trap-related instructions, and the ability
to automatically include a selected exception (trap) handler with each assemble operation.

Items in the Settings menu became persistent with this release.

Added default assembly file extensions “asm” and “s” to the Config.properties file and used
those not only to filter files for the File Open dialog but also to filter them for the “assemble all”
setting.

Implemented a limit to the amount of text scrollable in the Mars Messages and Run I/O message
tabs – default 1 MB is set in the Config.properties file.

For programmer convenience, labels can now be referenced in the operand field of integer
data directives (.word, .half, .byte). The assembler will substitute the label’s address (low order
half for .half, low order byte for .byte).

For programmer convenience, character literals (e.g. ‘b’, ‘\n’, ‘\377’) can be used anywhere that integer literals are
permitted. The assembler converts them directly to their equivalent 8 bit integer value. Unicode is not supported and
octal values must be exactly 3 digits ranging from ‘\000’ to ‘\377’.

Replaced buttons for selecting Data Segment display base addresses with a combo box and added more
base addresses: MMIO (0xFFFF0000), .kdata (0x90000000), .extern (0x10000000).

MARS 3.1 was released in October 2006. The major issues and features are listed here:

It addressed several minor limits (Tools menu items
could not be run from the JAR file, non-standard shortcuts for Mac users, inflexible and
sometimes inappropriate sizing of
GUI components).

It changed the way SYSCALLs are implemented, to allow anyone to define
new customized syscall services without modifying MARS.

It added a primitive
Project capability through the “Assemble operation applies to all files in current directory.”
setting (also available as “p” option in command mode). The command mode also allows you
to list several file names not necessarily in the same directory to be assembled and linked.

Multi-file assembly also required implementing the “.globl” and “.extern” directives.

And although “Mars tools” are not officially part of MARS releases, MARS 3.1 includes the
initial versions of two tools: one for learning about floating point representation and another
for simulating data caching capability.

MARS 3.0 was released in August 2006, with one bug fix and two major additions.

The bug fix was corrected instruction format for the slti and sltiu instructions.

One major addition is a greatly expanded MIPS-32 instruction
set (trap instructions are the only significant ones to remain unimplemented). This includes, via
pseudo-instructions, all reasonable memory addressing modes for the load/store instructions.

The
second major addition is ability to interactively step “backward” through program execution
one instruction at a time to “undo” execution steps. It will buffer up to 2000 of the most
recent execution steps (this limit is stored in a properties file and can be changed).
It will undo changes made to MIPS memory, registers or condition flags,
but not console or file I/O. This should be a great debugging aid.
It is available anytime execution is paused and at termination (even if terminated due to
exception).

A number of IDE settings, described
above, are now available through the Settings menu.

MARS 2.2 was released in March 2006 with additional bug fixes and implemented command
line options (run MARS from command line with h option for command line help). This also coincides with our
SIGCSE 2006 paper “MARS: An Education-Oriented MIPS Assembly Language Simulator”.

MARS 2.1 was released in October 2005 with some bug fixes.

MARS 2.0 was released in September 2005. It incorporated significant
modifications to both the GUI and the assembler, floating point registers and instructions
most notably.

MARS 1.0 was released in January 2005 and
publicized during a poster presentation at SIGCSE 2005.

Dr. Ken Vollmar initiated MARS development in 2002 at Missouri State University. In
2003, Dr. Pete Sanderson of Otterbein College and his student Jason Bumgarner continued
implementation. Sanderson implemented the assembler and simulator that summer, and
the basic GUI the following summer, 2004.

The development of Releases 3.1 and 3.2 during fall 2006 was supported by the Otterbein College
sabbatical leave program. The development of Release 3.7 during summer 2009 was supported by
a SIGCSE Special Projects Grant.

This document is available for printing on the MARS home page
http://www.cs.missouristate.edu/MARS/.

The MIPS Instruction Set

The MIPS Instruction Set

Written by Walter Chang

Used by permission of the author. Copyright notice below.
Correct pronunciation is critical to get the cadence and beat to line
up; see the Pronunciation
Guide at the end of this document for how you should pronounce the various
assembler instructions.

To the tune of: The Major-General’s Song, from
Pirates of Penzance
Inspired by Tom Lehrer’s The Elements

There’s div and nor and mult and or and sllv sra

There’s xor and swl and beq and sll and bgezal jumps today

And multu, srav, and j combined with lhu and lui

And also slt and bne and instruction mthi

There’s sh and sb and lbu and blez and jal and then sltu

And of course there’s and and add and srl and sub and things to do

With the MIPS instructions I am very nimble on my feet

And though I sing assembler but I am really not a geek

There’s addu, ori, slti, swr, and bgez and jalr too

And loads of other fun instructions that were put in just for you

The MIPS instruction set is very simple to be memorized

Which will come in handy when you have your code to optimize!

There’s addi, divu, lh, rfe, and syscall, jr, mfcz

And mfc1, nop, and break, and bltzal with bczt

And srlv, xori, bltz, and lb, lwl, and addiu

andi, subu, lwr, and lwcz, mtcz, sltiu

There’s bczf, bgtz to branch if it’s greater than

And mflo and sw, these instructions are not any also-rans

There’s mtlo and swcz too, although I don’t know what they’re for

And lw – that’s obviously load word from mem bytes there are four

And now my song is through and I know all of my words by the heart

Which will come in handy when we have our projects multi-part

I live and breathe the MIPS instruction set on every night and day

Because the MIPS assembler will always try and work my way!

Pronunciation Guide

note: assembler is 4 syllables: ass-em-bell-er

The pronunciations suitable for this song are as follows:

div: div

nor: nor

mult: mult

or: or

sllv: s-l-l-v

sra: s-r-a

xor: zor

swl: swill

beq: beck

sll: sill

bgezal: beh-geezal

multu: mult-you

srav: srav (one syllable)

j: jay

lhu: l-h-u

lui: l-u-i

slt: slit

bne: b-n-e

mthi: m-t-high

sh: shih

sb: sib

lbu: l-b-u

blez: blez

jal: jal

sltu: slit-u

and: and

add: add

srl: srill

sub: sub

addu: add-u

ori: or-i

slti: slitty

swr: swir

bgez: beh-gez

jalr: jal-er

addi: addy

divu: div-u

lh: l-h

rfe: reef

syscall: sis-call

jr: junior

mfcz: miff-c-z

mfc1: m-f-c-one

nop: nopp

break: break

bltzal: blitz-al

bczt: b-c-z-t

srlv: s-r-l-v

xori: zorri

bltz: blitz

lb: l-b

lwl: lwill

addiu: addy-you

andi: andy

subu: sub-u

lwr: lwer

lwcz: lwiscz

mtcz: m-t-c-z

sltiu: slitty-u

bzcf: b-z-c-f

bgtz: b-g-t-z

mflo: em-flow

sw: swee

mtlo: m-t-low

swcz: swizzy

lw: lwee

http://www.cs.utexas.edu/users/walter/cs-songbook/instruction_set.html

Copyright Walter Chang. Permission granted for noncommercial use
as long as attribution is maintained. .edu

MIPS/SPIM Reference Card

CORE INSTRUCTION SET (INCLUDING PSEUDO INSTRUCTIONS)
MNE- FOR- OPCODE/
MON- MAT FUNCT

NAME IC OPERATION (in Verilog) (Hex)
Add add R R[rd]=R[rs]+R[rt] (1) 0/20
Add Immediate addi I R[rt]=R[rs]+SignExtImm (1)(2) 8
Add Imm. Unsigned addiu I R[rt]=R[rs]+SignExtImm (2) 9
Add Unsigned addu R R[rd]=R[rs]+R[rt] (2) 0/21
Subtract sub R R[rd]=R[rs]-R[rt] (1) 0/22
Subtract Unsigned subu R R[rd]=R[rs]-R[rt] 0/23
And and R R[rd]=R[rs]&R[rt] 0/24
And Immediate andi I R[rt]=R[rs]&ZeroExtImm (3) c
Nor nor R R[rd]=∼(R[rs]|R[rt]) 0/27
Or or R R[rd]=R[rs]|R[rt] 0/25
Or Immediate ori I R[rt]=R[rs]|ZeroExtImm (3) d
Xor xor R R[rd]=R[rs]ˆR[rt] 0/26
Xor Immediate xori I R[rt]=R[rs]ˆZeroExtImm e
Shift Left Logical sll R R[rd]=R[rs]�shamt 0/00
Shift Right Logical srl R R[rd]=R[rs]�shamt 0/02
Shift Right Arithmetic sra R R[rd]=R[rs]�>shamt 0/03
Shift Left Logical Var. sllv R R[rd]=R[rs]�R[rt] 0/04
Shift Right Logical Var. srlv R R[rd]=R[rs]�R[rt] 0/06
Shift Right Arithmetic Var. srav R R[rd]=R[rs]�>R[rt] 0/07
Set Less Than slt R R[rd]=(R[rs]R[rt]) PC=PC+4+BranchAddr
Branch Less Than Or Equal ble P if(R[rs]<=R[rt]) PC=PC+4+BranchAddr Branch Greater Than Or Equal bge P if(R[rs]>=R[rt]) PC=PC+4+BranchAddr
Jump j J PC=JumpAddr (5) 2
Jump And Link jal J R[31]=PC+4; (5) 2

PC=JumpAddr
Jump Register jr R PC=R[rs] 0/08
Jump And Link Register jalr R R[31]=PC+4; 0/09

PC=R[rs]
Move move P R[rd]=R[rs]
Load Byte lb I R[rt]={24’b0, M[R[rs]+ZeroExtImm](7:0)} (3) 20
Load Byte Unsigned lbu I R[rt]={24’b0, M[R[rs]+SignExtImm](7:0)} (2) 24
Load Halfword lh I R[rt]={16’b0, M[R[rs]+ZeroExtImm](15:0)} (3) 25
Load Halfword Unsigned lhu I R[rt]={16’b0, M[R[rs]+SignExtImm](15:0)} (2) 25
Load Upper Imm. lui I R[rt]={imm,16’b0} f
Load Word lw I R[rt]=M[R[rs]+SignExtImm] (2) 23
Load Immediate li P R[rd]=immediate
Load Address la P R[rd]=immediate
Store Byte sb I M[R[rs]+SignExtImm] (7:0)=R[rt](7:0) (2) 28
Store Halfword sh I M[R[rs]+SignExtImm] (15:0)=R[rt](15:0) (2) 29
Store Word sw I M[R[rs]+SignExtImm]=R[rt] (2) 2b
REGISTERS
NAME NMBR USE STORE?
$zero 0 The Constant Value 0 N.A.
$at 1 Assembler Temporary No

$v0-$v1 2-3 Values for Function Results and
Expression Evaluation

No

$a0-$a3 4-7 Arguments No
$t0-$t7 8-15 Temporaries No
$s0-$s7 16-23 Saved Temporaries Yes
$t8-$t9 24-25 Temporaries No
$k0-$k1 26-27 Reserved for OS Kernel No

$gp 28 Global Pointer Yes
$sp 29 Stack Pointer Yes
$fp 30 Frame Pointer Yes
$ra 31 Return Address Yes

$f0-$f31 0-31 Floating Point Registers Yes

(1) May cause overflow exception
(2) SignExtImm ={16{immediate[15]},immediate }
(3) ZeroExtImm ={16{1b’0},immediate }
(4) BranchAddr = {14{immediate[15]},immediate,2’b0 }
(4) JumpAddr = {PC[31:28], address, 2’b0 }
(6) Operands considered unsigned numbers (vs. 2 s comp.)

BASIC INSTRUCTION FORMATS,
FLOATING POINT INSTRUCTION FORMATS

R 31 opcode 2625 rs 2120 rt 1615 rd 1110 shamt 65 funct 0

I 31 opcode 2625 rs 2120 rt 1615 immediate 0

J 31 opcode 2625 immediate 0

FR 31 opcode 2625 fmt 2120 ft 1615 fs 1110 fd 65 funct 0

FI 31 opcode 2625 fmt 2120 rt 1615 immediate 0

Copyright c© 2007 Jan Wätzig, Staatliche Studienakademie Dresden (www.ba-dresden.de/∼jan)
This reference card may be used for educational purposes only.

http://www.ba-dresden.de/~jan

ARITHMETIC CORE INSTRUCTION SET
MNE- FOR- OPCODE/
MON- MAT FMT/FT/

NAME IC OPERATION (in Verilog) FUNCT
Divide div R Lo=R[rs]/R[rt]; 0/–/–/1a

Hi=R[rs]%R[rt]
Divide Unsigned divu R Lo=R[rs]/R[rt]; (6) 0/–/–/1b

Hi=R[rs]%R[rt]
Multiply mult R {Hi,Lo}=R[rs]∗R[rt] 0/–/–/18
Multiply Unsigned multu R {Hi,Lo}=R[rs]∗R[rt] (6) 0/–/–/19
Branch On FP True bc1t FI if(FPCond) PC=PC+4+BranchAddr (4) 11/8/1/–
Branch On FP False bc1f FR if(!FPCond) PC=PC+4+BranchAddr (4) 11/8/0/–
FP Compare Single c.x.s∗ FR FPCond=(F[fs] op F[ft])?1:0 11/10/–/y
FP Compare Double c.x.d∗ FR FPCond=({F[fs],F[fs+1]} op {F[ft],F[ft+1]})?1:0 11/11/–/y

∗(x is eq, lt or le) (op is ==, < or <=) (y is 32, 3c or 3e) FP Add Single add.s FR F[fd]=F[fs]+F[ft] 11/10/–/0 FP Divide Single div.s FR F[fd]=F[fs]/F[ft] 11/10/–/3 FP Multiply Single mul.s FR F[fd]=F[fs]∗F[ft] 11/10/–/2 FP Subtract Single sub.s FR F[fd]=F[fs]-F[ft] 11/10/–/1 FP Add Double add.d FR {F[fd],F[fd+1]}={F[fs],F[fs+1]}+{F[ft],F[ft+1]} 11/11/–/0 FP Divide Double div.d FR {F[fd],F[fd+1]}={F[fs],F[fs+1]}/{F[ft],F[ft+1]} 11/11/–/3 FP Multiply Double mul.d FR {F[fd],F[fd+1]}={F[fs],F[fs+1]}∗{F[ft],F[ft+1]} 11/11/–/2 FP Subtract Double sub.d FR {F[fd],F[fd+1]}={F[fs],F[fs+1]}-{F[ft],F[ft+1]} 11/11/–/1 Move From Hi mfhi R R[rd]=Hi 0/–/–/10 Move From Lo mflo R R[rd]=Lo 0/–/–/12 Move From Control mfc0 R R[rd]=CR[rs] 16/0/–/0 Load FP Single lwc1 I F[rt]=M[R[rs]+SignExtImm] (2) 31/–/–/– Load FP Double ldc1 I F[rt]=M[R[rs]+SignExtImm]; (2) 35/–/–/– F[rt+1]=M[R[rs]+SignExtImm+4] Store FP Single swc1 I M[R[rs]+SignExtImm]=F[rt] (2) 39/–/–/– Store FP Double sdc1 I M[R[rs]+SignExtImm]=F[rt]; (2) 3d/–/–/– M[R[rs]+SignExtImm+4]=F[rt+1] ASSEMBLER DIRECTIVES .data [addr]∗ Subsequent items are stored in the data segment .kdata [addr]∗ Subsequent items are stored in the kernel data segment .ktext [addr]∗ Subsequent items are stored in the kernel text segment .text [addr]∗ Subsequent items are stored in the text ∗ starting at [addr] if specified .ascii str Store string str in memory, but do not null-terminate it .asciiz str Store string str in memory and null-terminate it .byte b1, . . . , bn Store the n values in successive bytes of memory .double d1, . . . , dn Store the n floating-point double precision numbers in successive memory locations .float f1, . . . , f1 Store the n floating-point single precision numbers in successive memory locations .half h1, . . . , hn Store the n 16-bit quantities in successive memory halfwords .word w1, . . . , wn Store the n 32-bit quantities in successive memory words .space n Allocate n bytes of space in the current segment .extern symsize Declare that the datum stored at sym is size bytes large and is a global label .globl sym Declare that label sym is global and can be referenced from other files .align n Align the next datum on a 2n byte boundary, until the next .data or .kdata directive .set at Tells SPIM to complain if subsequent instructions use $at .set noat prevents SPIM from complaining if subsequent instructions use $at SYSCALLS SERVICE $v0 ARGS RESULT print_int 1 integer $a0 print_float 2 float $f12 print_double 3 double $f12/$f13 print_string 4 string $a0 read_int 5 integer (in $v0) read_float 6 float (in $f0) read_double 7 double (in $f0) read_string 8 buf $a0, buflen $a1 sbrk 9 amount $a address (in $v0) exit 10 EXCEPTION CODES Number Name Cause of Exception 0 Int Interrupt (hardware) 4 AdEL Address Error Exception (load or instruction fetch) 5 AdES Address Error Exception (store) 6 IBE Bus Error on Instruction Fetch 7 DBE Bus Error on Load or Store 8 Sys Syscall Exception 9 Bp Breakpoint Exception 10 RI Reserved Instruction Exception 11 CpU Coprocessor Unimplemented 12 Ov Arithmetic Overflow Exception 13 Tr Trap 15 FPE Floating Point Exception [1] Patterson, David A; Hennessy, John J.: Computer Organization and Design, 3rd Edition. Morgan Kaufmann Publishers. San Francisco, 2005. Copyright c© 2007 Jan Wätzig, Staatliche Studienakademie Dresden (www.ba-dresden.de/∼jan) This reference card may be used for educational purposes only. http://www.ba-dresden.de/~jan MIPS syscall functions available in MARS SYSCALL functions available in MARS Introduction A number of system services, mainly for input and output, are available for use by your MIPS program. They are described in the table below. MIPS register contents are not affected by a system call, except for result registers as specified in the table below. How to use SYSCALL system services Step 1. Load the service number in register $v0. Step 2. Load argument values, if any, in $a0, $a1, $a2, or $f12 as specified. Step 3. Issue the SYSCALL instruction. Step 4. Retrieve return values, if any, from result registers as specified. Example: display the value stored in $t0 on the console li $v0, 1 # service 1 is print integer add $a0, $t0, $zero # load desired value into argument register $a0, using pseudo-op syscall Table of Available Services Service Code in $v0 Arguments Result print integer 1 $a0 = integer to print   print float 2 $f12 = float to print   print double 3 $f12 = double to print   print string 4 $a0 = address of null-terminated string to print   read integer 5   $v0 contains integer read read float 6   $f0 contains float read read double 7   $f0 contains double read read string 8 $a0 = address of input buffer $a1 = maximum number of characters to read See note below table sbrk (allocate heap memory) 9 $a0 = number of bytes to allocate $v0 contains address of allocated memory exit (terminate execution) 10     print character 11 $a0 = character to print See note below table read character 12   $v0 contains character read open file 13 $a0 = address of null-terminated string containing filename $a1 = flags $a2 = mode $v0 contains file descriptor (negative if error). See note below table read from file 14 $a0 = file descriptor $a1 = address of input buffer $a2 = maximum number of characters to read $v0 contains number of characters read (0 if end-of-file, negative if error). See note below table write to file 15 $a0 = file descriptor $a1 = address of output buffer $a2 = number of characters to write $v0 contains number of characters written (negative if error). See note below table close file 16 $a0 = file descriptor   exit2 (terminate with value) 17 $a0 = termination result See note below table Services 1 through 17 are compatible with the SPIM simulator, other than Open File (13) as described in the Notes below the table. Services 30 and higher are exclusive to MARS. time (system time) 30   $a0 = low order 32 bits of system time $a1 = high order 32 bits of system time. See note below table MIDI out 31 $a0 = pitch (0-127) $a1 = duration in milliseconds $a2 = instrument (0-127) $a3 = volume (0-127) Generate tone and return immediately. See note below table sleep 32 $a0 = the length of time to sleep in milliseconds. Causes the MARS Java thread to sleep for (at least) the specified number of milliseconds. This timing will not be precise, as the Java implementation will add some overhead. MIDI out synchronous 33 $a0 = pitch (0-127) $a1 = duration in milliseconds $a2 = instrument (0-127) $a3 = volume (0-127) Generate tone and return upon tone completion. See note below table print integer in hexadecimal 34 $a0 = integer to print Displayed value is 8 hexadecimal digits, left-padding with zeroes if necessary. print integer in binary 35 $a0 = integer to print Displayed value is 32 bits, left-padding with zeroes if necessary. print integer as unsigned 36 $a0 = integer to print Displayed as unsigned decimal value. (not used) 37-39     set seed 40 $a0 = i.d. of pseudorandom number generator (any int). $a1 = seed for corresponding pseudorandom number generator. No values are returned. Sets the seed of the corresponding underlying Java pseudorandom number generator (java.util.Random). See note below table random int 41 $a0 = i.d. of pseudorandom number generator (any int). $a0 contains the next pseudorandom, uniformly distributed int value from this random number generator's sequence. See note below table random int range 42 $a0 = i.d. of pseudorandom number generator (any int). $a1 = upper bound of range of returned values. $a0 contains pseudorandom, uniformly distributed int value in the range 0 See note below table random float 43 $a0 = i.d. of pseudorandom number generator (any int). $f0 contains the next pseudorandom, uniformly distributed float value in the range 0.0 See note below table random double 44 $a0 = i.d. of pseudorandom number generator (any int). $f0 contains the next pseudorandom, uniformly distributed double value in the range 0.0 See note below table (not used) 45-49     ConfirmDialog 50 $a0 = address of null-terminated string that is the message to user $a0 contains value of user-chosen option 0: Yes 1: No 2: Cancel InputDialogInt 51 $a0 = address of null-terminated string that is the message to user $a0 contains int read $a1 contains status value 0: OK status -1: input data cannot be correctly parsed -2: Cancel was chosen -3: OK was chosen but no data had been input into field InputDialogFloat 52 $a0 = address of null-terminated string that is the message to user $f0 contains float read $a1 contains status value 0: OK status -1: input data cannot be correctly parsed -2: Cancel was chosen -3: OK was chosen but no data had been input into field InputDialogDouble 53 $a0 = address of null-terminated string that is the message to user $f0 contains double read $a1 contains status value 0: OK status -1: input data cannot be correctly parsed -2: Cancel was chosen -3: OK was chosen but no data had been input into field InputDialogString 54 $a0 = address of null-terminated string that is the message to user $a1 = address of input buffer $a2 = maximum number of characters to read See Service 8 note below table $a1 contains status value 0: OK status. Buffer contains the input string. -2: Cancel was chosen. No change to buffer. -3: OK was chosen but no data had been input into field. No change to buffer. -4: length of the input string exceeded the specified maximum. Buffer contains the maximum allowable input string plus a terminating null. MessageDialog 55 $a0 = address of null-terminated string that is the message to user $a1 = the type of message to be displayed: 0: error message, indicated by Error icon 1: information message, indicated by Information icon 2: warning message, indicated by Warning icon 3: question message, indicated by Question icon other: plain message (no icon displayed) N/A MessageDialogInt 56 $a0 = address of null-terminated string that is an information-type message to user $a1 = int value to display in string form after the first string N/A MessageDialogFloat 57 $a0 = address of null-terminated string that is an information-type message to user $f12 = float value to display in string form after the first string N/A MessageDialogDouble 58 $a0 = address of null-terminated string that is an information-type message to user $f12 = double value to display in string form after the first string N/A MessageDialogString 59 $a0 = address of null-terminated string that is an information-type message to user $a1 = address of null-terminated string to display after the first string N/A NOTES: Services numbered 30 and higher are not provided by SPIM Service 8 - Follows semantics of UNIX 'fgets'. For specified length n, string can be no longer than n-1. If less than that, adds newline to end. In either case, then pads with null byte If n = 1, input is ignored and null byte placed at buffer address. If n < 1, input is ignored and nothing is written to the buffer. Service 11 - Prints ASCII character corresponding to contents of low-order byte. Service 13 - MARS implements three flag values: 0 for read-only, 1 for write-only with create, and 9 for write-only with create and append. It ignores mode. The returned file descriptor will be negative if the operation failed. The underlying file I/O implementation uses java.io.FileInputStream.read() to read and java.io.FileOutputStream.write() to write. MARS maintains file descriptors internally and allocates them starting with 3. File descriptors 0, 1 and 2 are always open for: reading from standard input, writing to standard output, and writing to standard error, respectively (new in release 4.3). Services 13,14,15 - In MARS 3.7, the result register was changed to $v0 for SPIM compatability. It was previously $a0 as erroneously printed in Appendix B of Computer Organization and Design,. Service 17 - If the MIPS program is run under control of the MARS graphical interface (GUI), the exit code in $a0 is ignored. Service 30 - System time comes from java.util.Date.getTime() as milliseconds since 1 January 1970. Services 31,33 - Simulate MIDI output through sound card. Details below. Services 40-44 use underlying Java pseudorandom number generators provided by the java.util.Random class. Each stream (identified by $a0 contents) is modeled by a different Random object. There are no default seed values, so use the Set Seed service (40) if replicated random sequences are desired. Example of File I/O The sample MIPS program below will open a new file for writing, write text to it from a memory buffer, then close it. The file will be created in the directory in which MARS was run. # Sample MIPS program that writes to a new file. # by Kenneth Vollmar and Pete Sanderson .data fout: .asciiz "testout.txt" # filename for output buffer: .asciiz "The quick brown fox jumps over the lazy dog." .text ############################################################### # Open (for writing) a file that does not exist li $v0, 13 # system call for open file la $a0, fout # output file name li $a1, 1 # Open for writing (flags are 0: read, 1: write) li $a2, 0 # mode is ignored syscall # open a file (file descriptor returned in $v0) move $s6, $v0 # save the file descriptor ############################################################### # Write to file just opened li $v0, 15 # system call for write to file move $a0, $s6 # file descriptor la $a1, buffer # address of buffer from which to write li $a2, 44 # hardcoded buffer length syscall # write to file ############################################################### # Close the file li $v0, 16 # system call for close file move $a0, $s6 # file descriptor to close syscall # close file ############################################################### Using SYSCALL system services 31 and 33: MIDI output These system services are unique to MARS, and provide a means of producing sound. MIDI output is simulated by your system sound card, and the simulation is provided by the javax.sound.midi package. Service 31 will generate the tone then immediately return. Service 33 will generate the tone then sleep for the tone's duration before returning. Thus it essentially combines services 31 and 32. This service requires four parameters as follows: pitch ($a0) Accepts a positive byte value (0-127) that denotes a pitch as it would be represented in MIDI Each number is one semitone / half-step in the chromatic scale. 0 represents a very low C and 127 represents a very high G (a standard 88 key piano begins at 9-A and ends at 108-C). If the parameter value is outside this range, it applies a default value 60 which is the same as middle C on a piano. From middle C, all other pitches in the octave are as follows: 61 = C# or Db 62 = D 63 = D# or Eb 64 = E or Fb 65 = E# or F 66 = F# or Gb 67 = G 68 = G# or Ab 69 = A 70 = A# or Bb 71 = B or Cb 72 = B# or C To produce these pitches in other octaves, add or subtract multiples of 12. duration in milliseconds ($a1) Accepts a positive integer value that is the length of the tone in milliseconds. If the parameter value is negative, it applies a default value of one second (1000 milliseconds). instrument ($a2) Accepts a positive byte value (0-127) that denotes the General MIDI "patch" used to play the tone. If the parameter is outside this range, it applies a default value 0 which is an Acoustic Grand Piano. General MIDI standardizes the number associated with each possible instrument (often referred to as program change numbers), however it does not determine how the tone will sound. This is determined by the synthesizer that is producing the sound. Thus a Tuba (patch 58) on one computer may sound different than that same patch on another computer. The 128 available patches are divided into instrument families of 8: 0-7 Piano 64-71 Reed 8-15 Chromatic Percussion 72-79 Pipe 16-23 Organ 80-87 Synth Lead 24-31 Guitar 88-95 Synth Pad 32-39 Bass 96-103 Synth Effects 40-47 Strings 104-111 Ethnic 48-55 Ensemble 112-119 Percussion 56-63 Brass 120-127 Sound Effects Note that outside of Java, General MIDI usually refers to patches 1-128. When referring to a list of General MIDI patches, 1 must be subtracted to play the correct patch. For a full list of General MIDI instruments, see www.midi.org/about-midi/gm/gm1sound.shtml. The General MIDI channel 10 percussion key map is not relevant to the toneGenerator method because it always defaults to MIDI channel 1. volume ($a3) Accepts a positive byte value (0-127) where 127 is the loudest and 0 is silent. This value denotes MIDI velocity which refers to the initial attack of the tone. If the parameter value is outside this range, it applies a default value 100. MIDI velocity measures how hard a note on (or note off) message is played, perhaps on a MIDI controller like a keyboard. Most MIDI synthesizers will translate this into volume on a logarithmic scale in which the difference in amplitude decreases as the velocity value increases. Note that velocity value on more sophisticated synthesizers can also affect the timbre of the tone (as most instruments sound different when they are played louder or softer). System service 31 was developed and documented by Otterbein student Tony Brock in July 2007. MARS Acknowledgements MARS Acknowledgements Updated 3 January 2013 Pete and Ken would like to acknowledge the many helpful contributors to MARS. It has succeeded beyond our wildest expectations and for this we are most grateful. Its success would not be possible without your feedback, suggestions and assistance! We are pleased to recognize these contributions to release 4.3: Mohammad Sekhavat, a student from Sharif University, who developed the macro capability. We think you will find it quite useful. We also appreciate the contributions others have made to previous releases: Tom Bradford, Slava Pestov and others, who developed the jEdit Syntax Package (syntax.jedit.org) at the heart of the syntax-aware color highlighting editor. It is old but the licensing is right and it was written for embedding into Java applications. Greg Gibeling of UC Berkeley, who introduced capabilities into his customized version of MARS that have subsequently been expanded and integrated into our release. These include the ability to dump MIPS memory contents to file and parser improvements to distinguish signed from unsigned hexadecimal constants. Eric Shade of Missouri State University, who suggested several improvements to pseudo-instruction expansions such as elimination of internal branches and improvements to the sign-extended loading of 16-bit immediate operands. Saul Spatz of the University of Missouri Kansas City, who noticed and provided a solution for a flaw in the calculation of byte-oriented addresses in the simulated MIPS memory stack segment. He has also suggested several improvements that we have implemented. Zachary Kurmas of Grand Valley State University, who suggested several bug fixes and who encorporated MARS into his own successful JLSCircuitTester digital logic simulator software. Felipe Lessa, who contributed the Instruction Counter tool and suggested a solution for the problem of MARS inability to launch when stored in a directory whose name contained non-ASCII characters. Carl Hauser of Washington State University, who pointed out and provided a solution to a flaw in the Keyboard and Display Simulator Tool in how it used the Exception Level bit in the Coprocessor1 Status register. Also thanks to Michael Clancy of UC Berkeley for pointing out a flaw in the tool's mechanism for resetting the Transmit Ready bit when operating in kernel memory. Dave Poplawski of Michigan Technological University, for his assistance in working through some issues with signed/unsigned constants and with output redirection. Ingo Kofler of Klagenfurt University in Austria, who contributed two Tools: a tool to collect Instruction Statistics, and a tool to simulate branch prediction with a Branch History Table. Brad Richards and Steven Canfield from the University of Puget Sound, for providing a technique that improved file loading performance. Jan Schejbal and Jan-Peter Kleinhans of Darmstadt technical university in Germany, for suggesting and providing a patch to display Run I/O text in a constant-width font. Max Hailperin of Gustavus Adolphus College, who made several improvements to the MIDI syscalls. David Patterson of UC Berkeley, for making time in his busy schedule for Ken's demo of MARS. Denise Penrose and Nate McFadden of Morgan Kaufmann Publishers, for their assistance as editors of Computer Organization and Design. Ricardo Pascual of University of Murcia in Spain, who contributed the code to permit input syscall keystrokes to be typed directly into the Run I/O window instead of through a popup dialog. Didier Teifreto of Université de Franche-Comté in France, who contributed the Digital Lab Sim tool. Facundo Agriel of the University of Illinois at Chicago, who added font selection to the Keyboard and Display Simulator tool. Patrik Lundin for contributing the code to add scrolling to the keyboard and display simulator. Otterbein students Robert Anderson, Jonathan Barnes, Sean Pomeroy and Melissa Tress for contributing the new command-mode options for specifying MARS exit codes when assembly or simulation errors occur. This was sparked by a comment from Zheming Jim of the University of South Carolina. The unknown audience member at our SIGCSE 2006 conference presentation, who suggested that MARS would also be useful running in the background in support of an external application. This led directly to our development of the Tools framework and API that truly distinguishes MARS from all other MIPS simulators. We would also like to recognize many others who have contacted us to point out bugs, suggest improvements, or engaged us in interesting correspondence. The bugs have been addressed and the improvements either implemented or added to our wish list. Correspondents include: William Bai, Miguel Barao, James Baltimore, Jared Barneck, Bruce Barton, Battista Biggio, Carl Burch, Ram Busani, Gene Chase, Lucien Chaubert, David Chilson, Sangyeun Cho, Donald Cooley, Bernardo Cunha, John Donaldson, Abhik Ghosh, Michael Grant, Thomas Hain, John Ham, Kurtis Hardy, Justin Harlow, David Harris, Bill Hsu, Pierre von Kaenel, Amos Kittelson, klondike, Geoffrey Knauth, Sudheer Kumar, Jeremie Lumbroso, Paul Lynch, Richard McKenna, William McQuain, Adam Megacz, Alessandro Montano, Judy Mullins, William Obermeyer, Ivor Page, Gustavo Patino, Christoph von Praun, Klaus Ramelow, David Reimann, Patricia Renault, André Rodrigues, Robert Roos, Joseph Roth, Marco Salinas, Peter Schulthess, Ofer Shaham, Scott Sigman, Sasha Solganik, Timothy Stanley, Gene Stark, Josh Steinhurst, Michelle Strout, Didier Teifreto, Mitchell Theys, Massimo Tivoli, Dwayne Towell, Duy Truong, Judah Veichselfish, Vineeth, Daniel Walker, Janyce Weibe, Ben West, and Armin Zundel. The Mars.jar file contains all source code and, starting with Release 3.6, the files necessary to generate a new jar file should you wish to make changes to the source and repackage it for your own use. Let us know if you do this, so we can consider your changes for the general release. Thanks to everyone who uses MARS. Keep those cards and letters coming! mars/tools/DigitalLabSim.java mars/tools/DigitalLabSim.javapackage mars.tools; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; import mars.Globals; import mars.mips.hardware.AddressErrorException; import mars.mips.hardware.Coprocessor0; import mars.mips.hardware.Memory; import mars.mips.hardware.MemoryAccessNotice; import mars.simulator.Exceptions; @SuppressWarnings("serial") /* Add these two lines in exceptions.java file  * public static final int EXTERNAL_INTERRUPT_TIMER = 0x00000100; //Add for digital Lab Sim  * public static final int EXTERNAL_INTERRUPT_HEXA_KEYBOARD = 0x00000200;// Add for digital Lab Sim */ /*  * Didier Teifreto LIFC Université de franche-Comté www.lifc.univ-fcomte.fr/~teifreto  * didier.teifreto@univ-fcomte.fr  */ public class DigitalLabSim extends AbstractMarsToolAndApplication {     private static String heading =  "Digital Lab Sim";     private static String version = " Version 1.0 (Didier Teifreto)";     private static final int IN_ADRESS_DISPLAY_1=Memory.memoryMapBaseAddress+0x10;     private static final int IN_ADRESS_DISPLAY_2=Memory.memoryMapBaseAddress+0x11;     private static final int IN_ADRESS_HEXA_KEYBOARD=Memory.memoryMapBaseAddress+0x12;     private static final int IN_ADRESS_COUNTER=Memory.memoryMapBaseAddress+0x13;     private static final int OUT_ADRESS_HEXA_KEYBOARD=Memory.memoryMapBaseAddress+0x14;   public static final int EXTERNAL_INTERRUPT_TIMER = 0x00000100; //Add for digital Lab Sim   public static final int EXTERNAL_INTERRUPT_HEXA_KEYBOARD = 0x00000200;// Add for digital Lab Sim     // GUI Interface.      private static JPanel panelTools;     // Seven Segment display     private SevenSegmentPanel sevenSegPanel;     // Keyboard     private static int KeyBoardValueButtonClick=-1; // -1 no button click     private HexaKeyboard hexaKeyPanel;     private static boolean KeyboardInterruptOnOff=false;     // Counter     private static int CounterValueMax=30;      private static int CounterValue=CounterValueMax;     private static boolean CounterInterruptOnOff=false;     private static OneSecondCounter SecondCounter;     public DigitalLabSim(String title, String heading) {         super(title,heading);     }     public DigitalLabSim() {         super (heading+", "+version, heading);     }     public static void main(String[] args) {         new DigitalLabSim(heading+", "+version,heading).go();     }     public String getName() {         return "Digital Lab Sim";     }     protected void addAsObserver(){         addAsObserver(IN_ADRESS_DISPLAY_1, IN_ADRESS_DISPLAY_1);         addAsObserver(Memory.textBaseAddress, Memory.textLimitAddress);     }     public void update(Observable ressource, Object accessNotice){         MemoryAccessNotice notice = (MemoryAccessNotice) accessNotice;         int address=notice.getAddress();         char value=(char)notice.getValue();         if(address == IN_ADRESS_DISPLAY_1)                 updateSevenSegment(1, value);         else             if  (address == IN_ADRESS_DISPLAY_2)                 updateSevenSegment(0, value);             else                 if (address == IN_ADRESS_HEXA_KEYBOARD)                     updateHexaKeyboard(value);                 else                     if (address == IN_ADRESS_COUNTER)                         updateOneSecondCounter(value);         if  (CounterInterruptOnOff)             if (CounterValue >0){
                CounterValue–;
            }
            else{
                CounterValue=CounterValueMax;
                if((Coprocessor0.getValue(Coprocessor0.STATUS) & 2)==0){
                    mars.simulator.Simulator.externalInterruptingDevice = /*Exceptions.*/EXTERNAL_INTERRUPT_TIMER;
                }
            }
    }
    protected void reset(){
        sevenSegPanel.resetSevenSegment();
        hexaKeyPanel.resetHexaKeyboard();
        SecondCounter.resetOneSecondCounter();
    }
    protected JComponent buildMainDisplayArea() {
        panelTools=new JPanel(new GridLayout(1,2));
        sevenSegPanel=new SevenSegmentPanel();
        panelTools.add(sevenSegPanel);
        hexaKeyPanel = new HexaKeyboard();
        panelTools.add(hexaKeyPanel);
        SecondCounter= new OneSecondCounter();
        return panelTools;
    }
    private synchronized void updateMMIOControlAndData(int dataAddr, int dataValue) {
        if (!this.isBeingUsedAsAMarsTool || (this.isBeingUsedAsAMarsTool && connectButton.isConnected())) {
           synchronized (Globals.memoryAndRegistersLock) {
              try {
                    Globals.memory.setByte(dataAddr, dataValue);
              } 
                  catch (AddressErrorException aee) {
                    System.out.println(“Tool author specified incorrect MMIO address!”+aee);
                    System.exit(0);
                 }
           }
           if (Globals.getGui() != null && Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().getCodeHighlighting() ) {
              Globals.getGui().getMainPane().getExecutePane().getDataSegmentWindow().updateValues();
           }
        }
     }
    protected JComponent getHelpComponent() {
        final String helpContent = 
            ” This tool is composed of 3 parts : two seven-segment displays, an hexadecimal keyboard and counter \n”+
            “Seven segment display\n”+
            ” Byte value at address 0xFFFF0010 : command right seven segment display \n “+
            ” Byte value at address 0xFFFF0011 : command left seven segment display \n “+
            ” Each bit of these two bytes are connected to segments (bit 0 for a segment, 1 for b segment and 7 for point \n \n”+
            “Hexadecimal keyboard\n”+
            ” Byte value at address 0xFFFF0012 : command row number of hexadecimal keyboard (bit 0 to 3) and enable keyboard interrupt (bit 7) \n” +
            ” Byte value at address 0xFFFF0014 : receive row and column of the key pressed, 0 if not key pressed \n”+
            ” The mips program have to scan, one by one, each row (send 1,2,4,8…)”+
            ” and then observe if a key is pressed (that mean byte value at adresse 0xFFFF0014 is different from zero). “+
            ” This byte value is composed of row number (4 left bits) and column number (4 right bits)”+
            ” Here you’ll find the code for each key : 0x11,0x21,0x41,0x81,0x12,0x22,0x42,0x82,0x14,0x24,0x44,0x84,0x18,0x28,0x48,0x88. \n”+
            ” For exemple key number 2 return 0x41, that mean the key is on column 3 and row 1. \n”+
            ” If keyboard interruption is enable, an exception is started, with cause register bit number 11 set.\n \n”+
            “Counter\n”+
            ” Byte value at address 0xFFFF0013 : If one bit of this byte is set, the counter interruption is enable.\n”+
            ” If counter interruption is enable, every 30 instructions, an exception is started with cause register bit number 10.\n” +
            ”   (contributed by Didier Teifreto,  -fcomte.fr)”
            ;
        JButton help = new JButton(“Help”);
        help.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        JTextArea ja = new JTextArea(helpContent);
                        ja.setRows(20);
                        ja.setColumns(60);
                        ja.setLineWrap(true);
                        ja.setWrapStyleWord(true);
                        JOptionPane.showMessageDialog(theWindow, new JScrollPane(ja),
                        “Simulating the Hexa Keyboard and Seven segment display”, JOptionPane.INFORMATION_MESSAGE);
                    }
                });     
        return help;  
    }/* ………………..Seven Segment display start here…………………………….. */
   /* ………………………Seven segment display start here …………………………*/
    public void updateSevenSegment(int number,char value) {
        sevenSegPanel.display[number].modifyDisplay(value);
    }
    public class SevenSegmentDisplay extends JComponent {
        public char aff;
        public SevenSegmentDisplay(char aff){
            this.aff=aff;
            this.setPreferredSize(new Dimension(60,80));
        }
        public void modifyDisplay(char val){
            aff=val;
            this.repaint();
        }
        public void SwitchSegment(Graphics g,char segment){
            switch(segment){
            case ‘a’: //a segment
                int[]pxa1={12,9,12};
                int[]pxa2={36,39,36};
                int[]pya={5,8,11};
                g.fillPolygon(pxa1,pya, 3);
                g.fillPolygon(pxa2,pya, 3);
                g.fillRect(12,5,24,6);
                break;
            case ‘b’: //b segment   
                int[]pxb={37,40,43};
                int[]pyb1={12,9,12};
                int[]pyb2={36,39,36};
                g.fillPolygon(pxb,pyb1, 3);
                g.fillPolygon(pxb,pyb2, 3);
                g.fillRect(37,12,6,24);
                break;
            case ‘c’: // c segment
                int[]pxc={37,40,43};
                int[]pyc1={44,41,44};
                int[]pyc2={68,71,68};
                g.fillPolygon(pxc,pyc1, 3);
                g.fillPolygon(pxc,pyc2, 3);
                g.fillRect(37,44,6,24);
                break;
            case ‘d’: // d segment
                int[]pxd1={12,9,12};
                int[]pxd2={36,39,36};
                int[]pyd={69,72,75};
                g.fillPolygon(pxd1,pyd, 3);
                g.fillPolygon(pxd2,pyd, 3);
                g.fillRect(12,69,24,6);
                break;
            case ‘e’: // e segment
                int[]pxe={5,8,11};
                int[]pye1={44,41,44};
                int[]pye2={68,71,68};
                g.fillPolygon(pxe,pye1, 3);
                g.fillPolygon(pxe,pye2, 3);
                g.fillRect(5,44,6,24);
                break;
            case ‘f’: // f segment
                int[]pxf={5,8,11};
                int[]pyf1={12,9,12};
                int[]pyf2={36,39,36};
                g.fillPolygon(pxf,pyf1, 3);
                g.fillPolygon(pxf,pyf2, 3);
                g.fillRect(5,12,6,24);
                break;
            case ‘g’: // g segment 
                int[]pxg1={12,9,12};
                int[]pxg2={36,39,36};
                int[]pyg={37,40,43};
                g.fillPolygon(pxg1,pyg, 3);
                g.fillPolygon(pxg2,pyg, 3);
                g.fillRect(12,37,24,6);
                break;
            case ‘h’: // decimal point
                g.fillOval(49,68,8,8);
                break;
            }   
        }
        public void paint(Graphics g) {
            char c=’a’; 
            while(c<='h'){                           if ((aff & 0x1) == 1)                     g.setColor(Color.RED);                 else                     g.setColor(Color.LIGHT_GRAY);                 SwitchSegment(g,c);                 aff = (char)(aff  >>>1);
                c++;
            }
        }
    }
    public class SevenSegmentPanel extends JPanel {
        public SevenSegmentDisplay[] display;
        public SevenSegmentPanel(){
            int i;
            FlowLayout fl= new FlowLayout();
            this.setLayout(fl);
            display= new SevenSegmentDisplay[2];
            for (i=0;i<2;i++){                 display[i]= new SevenSegmentDisplay((char)(0));                  this.add(display[i]);             }         }            public void modifyDisplay(int num,char val){             display[num].modifyDisplay(val);              display[num].repaint();         }         public void resetSevenSegment() {             int i;             for (i=0;i<2;i++)                          modifyDisplay(i, (char)0);            }     }  /* ...........................Seven segment display end here ..............................*/ /* ....................Hexa Keyboard start here................................... */     public void updateHexaKeyboard(char row) {         int key = KeyBoardValueButtonClick;         if ((key !=-1)&& ((1 << (key / 4))==(row & 0xF))){               updateMMIOControlAndData(OUT_ADRESS_HEXA_KEYBOARD,                      (char)(1 << (key / 4)) | (1 << (4+(key%4))));         }         else{             updateMMIOControlAndData(OUT_ADRESS_HEXA_KEYBOARD, 0);         }         if ((row & 0xF0) != 0)              KeyboardInterruptOnOff = true;         else             KeyboardInterruptOnOff = false;     }     public class HexaKeyboard extends JPanel{         public JButton[] button;             public HexaKeyboard(){             int i;             GridLayout layout = new GridLayout(4,4);             this.setLayout(layout);             button = new JButton[16];             for (i=0;i<16;i++){                 button[i]= new JButton(Integer.toHexString(i));                  button[i].setBackground(Color.WHITE);                 button[i].setMargin(new Insets(10,10,10,10));                 button[i].addMouseListener(new EcouteurClick(i));                 this.add(button[i]);             }            }         public void resetHexaKeyboard(){             int i;             KeyBoardValueButtonClick=-1;             for(i=0;i<16;i++){                 button[i].setBackground(Color.WHITE);             }         }         public class EcouteurClick implements MouseListener{             private int buttonValue;             public EcouteurClick(int val){                  buttonValue=val;             }             public void mouseEntered(MouseEvent arg0) { }             public void mouseExited(MouseEvent arg0) {}                      public void mousePressed(MouseEvent arg0) {}             public void mouseReleased(MouseEvent arg0) {}             public void mouseClicked(MouseEvent arg0) {                 int i;                 if(KeyBoardValueButtonClick!=-1){//Button already pressed -> now realease
                    KeyBoardValueButtonClick = -1;
                    updateMMIOControlAndData(OUT_ADRESS_HEXA_KEYBOARD,0);
                    for(i=0;i<16;i++)                          button[i].setBackground(Color.WHITE);                 }                 else{ // new button pressed                     KeyBoardValueButtonClick = buttonValue;                     button[KeyBoardValueButtonClick].setBackground(Color.GREEN);                     if( KeyboardInterruptOnOff &&  (Coprocessor0.getValue(Coprocessor0.STATUS) & 2)==0){                         mars.simulator.Simulator.externalInterruptingDevice = /*Exceptions.*/EXTERNAL_INTERRUPT_HEXA_KEYBOARD;                     }                 }             }         }     } /* ....................Hexa Keyboard end here................................... */ /* ....................Timer start here................................... */     public void updateOneSecondCounter(char value) {         if (value !=0){             CounterInterruptOnOff=true;             CounterValue=CounterValueMax;         }         else{             CounterInterruptOnOff=false;         }     }     public class OneSecondCounter{         public OneSecondCounter(){             CounterInterruptOnOff=false;         }         public void resetOneSecondCounter(){             CounterInterruptOnOff=false;             CounterValue=CounterValueMax;         }     } } AbstractMarsToolAndApplication$MessageField package mars.tools; synchronized class AbstractMarsToolAndApplication$MessageField extends javax.swing.JTextField { public void AbstractMarsToolAndApplication$MessageField(AbstractMarsToolAndApplication, String); private void displayTerminatingMessage(String); private void displayNonTerminatingMessage(String); private void displayMessage(String, boolean); } mars/tools/IntroToTools.java mars/tools/IntroToTools.java   package mars.tools;    import javax.swing.*;    import java.awt.*;    import java.awt.event.*;    import mars.*;      /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */         /**      * The "hello world" of MarsTools!      */     public class IntroToTools extends AbstractMarsToolAndApplication {           private static String heading =  "Introduction to MARS Tools and Applications";         private static String version = " Version 1.0";                      /**      * Simple constructor, likely used to run a stand-alone memory reference visualizer.      * @param title String containing title for title bar      * @param heading String containing text for heading shown in upper part of window.      */        public IntroToTools(String title, String heading) {          super(title,heading);       }            /**       *  Simple constructor, likely used by the MARS Tools menu mechanism       */        public IntroToTools() {          super (heading+", "+version, heading);       }                         /**      * Main provided for pure stand-alone use.  Recommended stand-alone use is to write a       * driver program that instantiates a MemoryReferenceVisualization object then invokes its go() method.      * "stand-alone" means it is not invoked from the MARS Tools menu.  "Pure" means there      * is no driver program to invoke the application.      */        public static void main(String[] args) {          new IntroToTools(heading+", "+version,heading).go();       }                 /**       *  Required method to return Tool name.         *  @return  Tool name.  MARS will display this in menu item.       */        public String getName() {          return "Introduction to Tools";       }            /**      *  Implementation of the inherited abstract method to build the main       *  display area of the GUI.  It will be placed in the CENTER area of a       *  BorderLayout.  The title is in the NORTH area, and the controls are       *  in the SOUTH area.      */        protected JComponent buildMainDisplayArea() {          JTextArea message = new JTextArea();          message.setEditable(false);          message.setLineWrap(true);          message.setWrapStyleWord(true);          message.setFont(new Font("Ariel",Font.PLAIN,12));          message.setText(               "Hello!  This Tool does not do anything but you may use its "+               "source code as a starting point to build your own MARS Tool "+               "or Application."+               "\n\n"+               "A MARS Tool is a program listed in the MARS Tools menu.  It is launched "+               "when you select its menu item and typically interacts with executing MIPS "+               "programs to do something exciting and informative or at least interesting."+               "\n\n"+               "A MARS Application is a stand-alone program for similarly interacting with "+               "executing MIPS programs.  It uses MARS' MIPS assembler and "+               "runtime simulator in the background to control MIPS execution."+               "\n\n"+               "The basic requirements for building a MARS Tool are:"+               "\n"+               "  1. It must be a class that implements the MarsTool interface.  "+               "This has only two methods: 'String getName()' to return the "+               "name to be displayed in its Tools menu item, and "+               "'void action()' which is invoked when that menu item "+               "is selected by the MARS user."+               "\n"+               "  2. It must be stored in the mars.tools package (in folder "+               "mars/tools)"+               "\n"+               "  3. It must be successfully compiled in that package.  This "+               "normally means the MARS distribution needs to be extracted from the "+               "JAR file before you can develop your Tool."+               "\n\n"+               "If these requirements are met, MARS will recognize and load "+               "your Tool into its Tools menu the next time it runs."+               "\n\n"+               "There are no fixed requirements for building a MARS Application, a "+               "stand-alone program that utilizes the MARS API."+               "\n\n"+               "You can build a program that may be run as either a MARS Tool or an Application.  "+               "The easiest way is to extend an abstract class provided in the MARS distribution: "+               "mars.tools.AbstractMarsToolAndApplication.  "+               "\n"+               "  1. It defines a suite of methods and provides default definitions for "+               "all but two: getName() and buildMainDisplayArea()."+               "\n"+               "  2.  String getName() was introduced above."+               "\n"+               "  3.  JComponent buildMainDisplayArea() returns the JComponent to be placed in the "+               "BorderLayout.CENTER region of the tool/app's user interface.  The NORTH and "+               "SOUTH are defined to contain a heading and a set of button controls, respectively.  "+               "\n"+               "  4. It defines a default 'void go()' method to launch the application."+               "\n"+               "  5. Conventional usage is to define your application as a subclass then launch it "+               "by invoking its go() method."+               "\n\n"+               "The frame/dialog you are reading right now is an example of an "+               "AbstractMarsToolAndApplication subclass.  If you run it as an application, you "+               "will notice the set of controls at the bottom of the window differ from those "+               "you get when running it from MARS' Tools menu.  It includes additional controls "+               "to load and control the execution of pre-existing MIPS programs."+               "\n\n"+               "See the mars.tools.AbstractMarsToolAndApplication API or the source code of "+               "existing tool/apps for further information."+               "\n"             );                 message.setCaretPosition(0); // Assure first line is visible and at top of scroll pane.          return new JScrollPane(message);       }         } MemoryReferenceVisualization$8 package mars.tools; synchronized class MemoryReferenceVisualization$8 implements java.awt.event.ActionListener { void MemoryReferenceVisualization$8(MemoryReferenceVisualization); public void actionPerformed(java.awt.event.ActionEvent); } CacheSimulator$5 package mars.tools; synchronized class CacheSimulator$5 implements java.awt.event.ActionListener { void CacheSimulator$5(CacheSimulator); public void actionPerformed(java.awt.event.ActionEvent); } MemoryReferenceVisualization$ColorChooserControls$1 package mars.tools; synchronized class MemoryReferenceVisualization$ColorChooserControls$1 implements java.awt.event.ActionListener { void MemoryReferenceVisualization$ColorChooserControls$1(MemoryReferenceVisualization$ColorChooserControls); public void actionPerformed(java.awt.event.ActionEvent); } AbstractMarsToolAndApplication$CreateAssembleRunMIPSprogram package mars.tools; synchronized class AbstractMarsToolAndApplication$CreateAssembleRunMIPSprogram implements Runnable { private void AbstractMarsToolAndApplication$CreateAssembleRunMIPSprogram(AbstractMarsToolAndApplication); public void run(); } BitmapDisplay$4 package mars.tools; synchronized class BitmapDisplay$4 implements java.awt.event.ActionListener { void BitmapDisplay$4(BitmapDisplay); public void actionPerformed(java.awt.event.ActionEvent); } FloatRepresentation$InstructionsPane package mars.tools; synchronized class FloatRepresentation$InstructionsPane extends javax.swing.JLabel { void FloatRepresentation$InstructionsPane(FloatRepresentation, java.awt.Component); public void setText(String); } AbstractMarsToolAndApplication$1 package mars.tools; synchronized class AbstractMarsToolAndApplication$1 extends java.awt.event.WindowAdapter { void AbstractMarsToolAndApplication$1(AbstractMarsToolAndApplication); public void windowClosing(java.awt.event.WindowEvent); } mars/tools/FloatRepresentation.java mars/tools/FloatRepresentation.java   package mars.tools;    import mars.*;    import mars.util.*;    import mars.assembler.*;    import mars.mips.instructions.*;    import mars.mips.hardware.*;    import java.util.*;    import java.io.*;    import java.awt.*;    import java.awt.event.*;    import javax.swing.*;    import javax.swing.event.*;    import javax.swing.border.*;    import javax.swing.text.html.*;          /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */          /**     * Tool to help students learn about IEEE 754 representation of 32 bit      * floating point values.  This representation is used by MIPS "float"      * directive and instructions and also the Java (and most other languages)      * "float" data type.  As written, it can ALMOST be adapted to 64 bit by      * changing a few constants.     */                   public class FloatRepresentation extends AbstractMarsToolAndApplication {       private static String version = "Version 1.1";       private static String heading =  "32-bit IEEE 754 Floating Point Representation";       private static final String title = "Floating Point Representation, ";           private static final String defaultHex = "00000000";       private static final String defaultDecimal = "0.0";          private static final String defaultBinarySign = "0";       private static final String defaultBinaryExponent = "00000000";       private static final String defaultBinaryFraction = "00000000000000000000000";       private static final int maxLengthHex = 8;       private static final int maxLengthBinarySign = 1;       private static final int maxLengthBinaryExponent = 8;       private static final int maxLengthBinaryFraction = 23;       private static final int maxLengthBinaryTotal = maxLengthBinarySign+maxLengthBinaryExponent+maxLengthBinaryFraction;       private static final int maxLengthDecimal = 20;         private static final String denormalizedLabel = "                 significand (denormalized - no 'hidden bit')";       private static final String normalizedLabel =   "                 significand ('hidden bit' underlined)       ";       private static final Font instructionsFont = new Font("Arial",Font.PLAIN,14);       private static final Font hexDisplayFont = new Font("Courier",Font.PLAIN,32);       private static final Font binaryDisplayFont = new Font("Courier",Font.PLAIN,18);       private static final Font decimalDisplayFont = new Font("Courier",Font.PLAIN,18);       private static final Color hexDisplayColor = Color.red;       private static final Color binaryDisplayColor = Color.black;       private static final Color decimalDisplayColor = Color.blue;       private static final String expansionFontTag = "“;
      private static final String instructionFontTag = ““;
      private static final int exponentBias = 127;  // 32 bit floating point exponent bias
    
      private Register attachedRegister = null;
      private Register[] fpRegisters;
      private FloatRepresentation thisFloatTool;
    // Panels to hold binary displays and decorations (labels, arrows)
      private JPanel binarySignDecoratedDisplay,
                     binaryExponentDecoratedDisplay, binaryFractionDecoratedDisplay;
    // Editable fields for the hex, binary and decimal representations.
      private JTextField hexDisplay, decimalDisplay, 
                          binarySignDisplay, binaryExponentDisplay, binaryFractionDisplay;
    // Non-editable fields to display formula translating binary to decimal.
      private JLabel expansionDisplay;
      private JLabel significandLabel = new JLabel(denormalizedLabel, JLabel.CENTER);
      private BinaryToDecimalFormulaGraphic binaryToDecimalFormulaGraphic;
    // Non-editable field to display instructions
      private InstructionsPane instructions;
      private String defaultInstructions = “Modify any value then press the Enter key to update all values.”;
            
    /**
     * Simple constructor, likely used to run a stand-alone memory reference visualizer.
     * @param title String containing title for title bar
     * @param heading String containing text for heading shown in upper part of window.
     */
       public FloatRepresentation(String title, String heading) {
         super(title,heading);
         thisFloatTool = this;
      }
     
     /**
      *  Simple constructor, likely used by the MARS Tools menu mechanism
      */
       public FloatRepresentation() {
         this(title+version, heading);
      }
         
    /**
     * Main provided for pure stand-alone use.  Recommended stand-alone use is to write a 
     * driver program that instantiates a FloatRepresentation object then invokes its go() method.
     * “stand-alone” means it is not invoked from the MARS Tools menu.  “Pure” means there
     * is no driver program to invoke the application.
     */
       public static void main(String[] args) {
         new FloatRepresentation(title+version,heading).go();
      }
   
     /**
      *  Fetch tool name (for display in MARS Tools menu)
    *  @return String containing tool name
    */
       public String getName() {
         return “Floating Point Representation”;
      }
   
      /**
     *  Override the inherited method, which registers us as an Observer over the static data segment 
     *  (starting address 0x10010000) only.  This version will register us as observer over the selected
     *  floating point register, if any. If no register is selected, it will not do anything. 
     *  If you use the inherited GUI buttons, this method is invoked when you click “Connect” button 
     *  on MarsTool or the “Assemble and Run” button on a Mars-based app.
     */
       protected void addAsObserver() {
         addAsObserver(attachedRegister);
      }
    
      /**
     *  Delete this app/tool as an Observer of the attached register.  This overrides
     *  the inherited version which deletes only as an Observer of memory.
     *  This method is called when the default “Disconnect” button on a MarsTool is selected or 
     *  when the MIPS program execution triggered by the default “Assemble and run” on a stand-alone
     *  Mars app terminates (e.g. when the button is re-enabled).
     */          
       protected void deleteAsObserver() {
         deleteAsObserver(attachedRegister);
      }
    
    /**
     *  Method that constructs the main display area.  This will be vertically sandwiched between
     *  the standard heading area at the top and the control area at the bottom.
     *  @return the GUI component containing the application/tool-specific part of the user interface
     */      
       protected JComponent buildMainDisplayArea() {
         return buildDisplayArea();
      }
   
      /**
     * Override inherited update() to update display when “attached” register is modified 
     * either by MIPS program or by user editing it on the MARS user interface.  
     * The latter is the reason for overriding the inherited update() method.  
     * The inherited method will filter out notices triggered by the MARS GUI or the user.
     * @param register the attached register
     * @param accessNotice information provided by register in RegisterAccessNotice object
     */
       public void update(Observable register, Object accessNotice) {
         if (((AccessNotice)accessNotice).getAccessType()==AccessNotice.WRITE) {
            updateDisplays(new FlavorsOfFloat().buildOneFromInt(attachedRegister.getValue()));
         }
      }
            
    /**
     *  Method to reset display values to 0 when the Reset button selected.
     *  If attached to a MIPS register at the time, the register will be reset as well.
     *  Overrides inherited method that does nothing.
     */
       protected void reset() {
         instructions.setText(defaultInstructions);
         updateDisplaysAndRegister(new FlavorsOfFloat());
      }
     
    
      //////////////////////////////////////////////////////////////////////////////////////
      //  Private methods defined to support the above.
            
       protected JComponent buildDisplayArea() {
        // Panel to hold all floating point dislay and editing components
         Box mainPanel = Box.createVerticalBox();
         JPanel leftPanel = new JPanel(new GridLayout(5,1,0,0));
         JPanel rightPanel = new JPanel(new GridLayout(5,1,0,0));
         Box subMainPanel = Box.createHorizontalBox();
         subMainPanel.add(leftPanel);
         subMainPanel.add(rightPanel);
         mainPanel.add(subMainPanel);
      
        // Editable display for hexadecimal version of the float value
         hexDisplay = new JTextField(defaultHex, maxLengthHex+1);
         hexDisplay.setFont(hexDisplayFont);
         hexDisplay.setForeground(hexDisplayColor);
         hexDisplay.setHorizontalAlignment(JTextField.RIGHT);
         hexDisplay.setToolTipText(“”+maxLengthHex+”-digit hexadecimal (base 16) display”);
         hexDisplay.setEditable(true);
         hexDisplay.revalidate();
         hexDisplay.addKeyListener(new HexDisplayKeystrokeListener(8));
      
         JPanel hexPanel = new JPanel();
         hexPanel.add(hexDisplay);
        //################  Grid Row :  Hexadecimal ##################################
         leftPanel.add(hexPanel);
      
         HexToBinaryGraphicPanel hexToBinaryGraphic = new HexToBinaryGraphicPanel();        
        //################  Grid Row :  Hex-to-binary graphic ########################
         leftPanel.add(hexToBinaryGraphic);
        
        // Editable display for binary version of float value.
        // It is split into 3 separately editable components (sign,exponent,fraction)
      
         binarySignDisplay = new JTextField(defaultBinarySign, maxLengthBinarySign+1);              
         binarySignDisplay.setFont(binaryDisplayFont);
         binarySignDisplay.setForeground(binaryDisplayColor);
         binarySignDisplay.setHorizontalAlignment(JTextField.RIGHT);
         binarySignDisplay.setToolTipText(“The sign bit”);
         binarySignDisplay.setEditable(true);
         binarySignDisplay.revalidate();
      
         binaryExponentDisplay = new JTextField(defaultBinaryExponent, maxLengthBinaryExponent+1);          
         binaryExponentDisplay.setFont(binaryDisplayFont);
         binaryExponentDisplay.setForeground(binaryDisplayColor);
         binaryExponentDisplay.setHorizontalAlignment(JTextField.RIGHT);
         binaryExponentDisplay.setToolTipText(“”+maxLengthBinaryExponent+”-bit exponent”);
         binaryExponentDisplay.setEditable(true);
         binaryExponentDisplay.revalidate();
      
         binaryFractionDisplay = new BinaryFractionDisplayTextField(defaultBinaryFraction, maxLengthBinaryFraction+1);          
         binaryFractionDisplay.setFont(binaryDisplayFont);
         binaryFractionDisplay.setForeground(binaryDisplayColor);
         binaryFractionDisplay.setHorizontalAlignment(JTextField.RIGHT);
         binaryFractionDisplay.setToolTipText(“”+maxLengthBinaryFraction+”-bit fraction”);
         binaryFractionDisplay.setEditable(true);
         binaryFractionDisplay.revalidate();
                
         binarySignDisplay.addKeyListener(new BinaryDisplayKeystrokeListener(maxLengthBinarySign));
         binaryExponentDisplay.addKeyListener(new BinaryDisplayKeystrokeListener(maxLengthBinaryExponent));
         binaryFractionDisplay.addKeyListener(new BinaryDisplayKeystrokeListener(maxLengthBinaryFraction));
         JPanel binaryPanel = new JPanel(); 
        
         binarySignDecoratedDisplay = new JPanel(new BorderLayout());
         binaryExponentDecoratedDisplay = new JPanel(new BorderLayout());
         binaryFractionDecoratedDisplay = new JPanel(new BorderLayout());
         binarySignDecoratedDisplay.add(binarySignDisplay,BorderLayout.CENTER);
         binarySignDecoratedDisplay.add(new JLabel(“sign”,JLabel.CENTER),BorderLayout.SOUTH);
         binaryExponentDecoratedDisplay.add(binaryExponentDisplay,BorderLayout.CENTER);
         binaryExponentDecoratedDisplay.add(new JLabel(“exponent”,JLabel.CENTER),BorderLayout.SOUTH);
         binaryFractionDecoratedDisplay.add(binaryFractionDisplay,BorderLayout.CENTER);
         binaryFractionDecoratedDisplay.add(new JLabel(“fraction”,JLabel.CENTER),BorderLayout.SOUTH);       
      
         binaryPanel.add(binarySignDecoratedDisplay);
         binaryPanel.add(binaryExponentDecoratedDisplay);
         binaryPanel.add(binaryFractionDecoratedDisplay);
        
        //################  Grid Row :  Binary ##################################
         leftPanel.add(binaryPanel);
                
        //################  Grid Row :  Binary to decimal formula arrows  ##########
         binaryToDecimalFormulaGraphic = new BinaryToDecimalFormulaGraphic();
         binaryToDecimalFormulaGraphic.setBackground(leftPanel.getBackground());
         leftPanel.add(binaryToDecimalFormulaGraphic);
                
        // Non-Editable display for expansion of binary representation
        
         expansionDisplay = new JLabel(new FlavorsOfFloat().expansionString);
         expansionDisplay.setFont(new Font(“Monospaced”,Font.PLAIN,12));        
         expansionDisplay.setFocusable(false); // causes it to be skipped in “tab sequence”.
         expansionDisplay.setBackground(leftPanel.getBackground());
         JPanel expansionDisplayBox = new JPanel(new GridLayout(2,1));
         expansionDisplayBox.add(expansionDisplay);
         expansionDisplayBox.add(significandLabel); // initialized at top
        //################  Grid Row :  Formula mapping binary to decimal ########
         leftPanel.add(expansionDisplayBox);
                
        // Editable display for decimal version of float value.
         decimalDisplay = new JTextField(defaultDecimal, maxLengthDecimal+1);       
         decimalDisplay.setFont(decimalDisplayFont);
         decimalDisplay.setForeground(decimalDisplayColor);
         decimalDisplay.setHorizontalAlignment(JTextField.RIGHT);
         decimalDisplay.setToolTipText(“Decimal floating point value”);
         decimalDisplay.setMargin(new Insets(0,0,0,0));
         decimalDisplay.setEditable(true);
         decimalDisplay.revalidate();
         decimalDisplay.addKeyListener(new DecimalDisplayKeystokeListenter());
         Box decimalDisplayBox = Box.createVerticalBox();
         decimalDisplayBox.add(Box.createVerticalStrut(5));
         decimalDisplayBox.add(decimalDisplay);
         decimalDisplayBox.add(Box.createVerticalStrut(15));
        
         FlowLayout rightPanelLayout = new FlowLayout(FlowLayout.LEFT);
         JPanel place1 = new JPanel(rightPanelLayout);
         JPanel place2 = new JPanel(rightPanelLayout);
         JPanel place3 = new JPanel(rightPanelLayout);
         JPanel place4 = new JPanel(rightPanelLayout);
        
         JEditorPane hexExplain = new JEditorPane(“text/html”,expansionFontTag+”<  Hexadecimal representation”+”“);
         hexExplain.setEditable(false);
         hexExplain.setFocusable(false);
         hexExplain.setForeground(Color.black);
         hexExplain.setBackground(place1.getBackground());
         JEditorPane hexToBinExplain = new JEditorPane(“text/html”,expansionFontTag+”<  Each hex digit represents 4 bits”+”“);
         hexToBinExplain.setEditable(false);
         hexToBinExplain.setFocusable(false);
         hexToBinExplain.setBackground(place2.getBackground());
         JEditorPane binExplain = new JEditorPane(“text/html”,expansionFontTag+”<  Binary representation”+”“);
         binExplain.setEditable(false);
         binExplain.setFocusable(false);
         binExplain.setBackground(place3.getBackground());
         JEditorPane binToDecExplain = new JEditorPane(“text/html”,expansionFontTag+”<  Binary-to-decimal conversion”+”“);
         binToDecExplain.setEditable(false);
         binToDecExplain.setFocusable(false);
         binToDecExplain.setBackground(place4.getBackground());
         place1.add(hexExplain);    
         place2.add(hexToBinExplain);
         place3.add(binExplain);
         place4.add(binToDecExplain);
         //################  4 Grid Rows :  Explanations #########################
         rightPanel.add(place1);
         rightPanel.add(place2);
         rightPanel.add(place3);
         rightPanel.add(place4);
        //################  Grid Row :  Decimal ##################################
         rightPanel.add(decimalDisplayBox);
        
        //########  mainPanel is vertical box, instructions get a row #################
         JPanel instructionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
         instructions = new InstructionsPane(instructionsPanel);
         instructionsPanel.add(instructions);
         instructionsPanel.setBorder(new TitledBorder(“Instructions”));
         mainPanel.add(instructionsPanel);
        
        // Means of selecting and deselecting an attached floating point register
        
         fpRegisters = Coprocessor1.getRegisters();
         String[] registerList = new String[fpRegisters.length+1];
         registerList[0] = “None”;
         for (int i=0; i“+expansionFontTag
                   + “-1“+binaryString.substring(0,maxLengthBinarySign)+”  *  2
                   + stringExponent + HTMLspaces.substring(0, (5-stringExponent.length())*6) 
                 + “
  *  ”
                 + ((biasedExponent==0) ? ” .” : “1.”)
                   + binaryString.substring(maxLengthBinarySign+maxLengthBinaryExponent, maxLengthBinaryTotal)
                 + ” =“;                                    
         }
        
         // Handy utility to concatentate the binary field values into one 32 character string
          // Left-pad each field with zeroes as needed to reach its full length.
          private String getFullBinaryStringFromDisplays() {
            return addLeadingZeroes(binarySignDisplay.getText(), maxLengthBinarySign) +
                addLeadingZeroes(binaryExponentDisplay.getText(), maxLengthBinaryExponent) +
                addLeadingZeroes(binaryFractionDisplay.getText(), maxLengthBinaryFraction);
         }
      
          // Handy utility. Pads with leading zeroes to specified length, maximum 64 of ’em. 
          private String addLeadingZeroes(String str, int length) {
            return (str.length() < length)                 ? zeroes.substring(0,Math.min(zeroes.length(),length-str.length()))+str                : str;          }                    }      //Put here because inner class cannot have static members.       private static final String zeroes =           "0000000000000000000000000000000000000000000000000000000000000000"; //64       private static final String HTMLspaces = "        ";                // NOTE: It would be nice to use InputVerifier class to verify user input     // but I want keystroke-level monitoring to assure that no invalid     // keystrokes are echoed and that maximum string length is not exceeded.                       //////////////////////////////////////////////////////////////////     //     //  Class to handle input keystrokes for hexadecimal field     //        private class HexDisplayKeystrokeListener extends KeyAdapter {                 private int digitLength; // maximum number of digits long                    public HexDisplayKeystrokeListener(int length) {             digitLength = length;          }                         // Process user keystroke.  If not valid for the context, this         // will consume the stroke and beep.           public void keyTyped(KeyEvent e) {             JTextField source = (JTextField) e.getComponent();             if (e.getKeyChar()== KeyEvent.VK_BACK_SPACE || e.getKeyChar()== KeyEvent.VK_TAB )                 return;             if (!isHexDigit(e.getKeyChar()) ||                  source.getText().length()==digitLength && source.getSelectedText()==null) {                if (e.getKeyChar()!= KeyEvent.VK_ENTER && e.getKeyChar() != KeyEvent.VK_TAB) {                   Toolkit.getDefaultToolkit().beep();                   if (source.getText().length()==digitLength && source.getSelectedText()==null) {                      instructions.setText("Maximum length of this field is "+digitLength+".");                   }                    else {                      instructions.setText("Only digits and A-F (or a-f) are accepted in hexadecimal field.");                   }                }                e.consume();             }           }                  // Enter key is echoed on component after keyPressed but before keyTyped?         // Consuming the VK_ENTER event in keyTyped does not suppress it but this will.           public void keyPressed(KeyEvent e) {             if (e.getKeyChar()== KeyEvent.VK_ENTER || e.getKeyChar()== KeyEvent.VK_TAB) {                updateDisplaysAndRegister(new FlavorsOfFloat().buildOneFromHexString(((JTextField)e.getSource()).getText()));                instructions.setText(defaultInstructions);                e.consume();             }          }                      // handy utility.                  private boolean isHexDigit(char digit) {             boolean result = false;             switch (digit) {                case '0': case '1': case '2': case '3': case '4':                case '5': case '6': case '7': case '8': case '9':                case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':                            case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':                   result = true;             }             return result;                      }       }           //////////////////////////////////////////////////////////////////     //     //  Class to handle input keystrokes for binary field     //                  private class BinaryDisplayKeystrokeListener extends KeyAdapter {                   private int bitLength;  // maximum number of bits permitted                      public BinaryDisplayKeystrokeListener(int length) {             bitLength = length;          }                // Process user keystroke.  If not valid for the context, this         // will consume the stroke and beep.                       public void keyTyped(KeyEvent e) {             JTextField source = (JTextField) e.getComponent();             if (e.getKeyChar()== KeyEvent.VK_BACK_SPACE)                 return;             if (!isBinaryDigit(e.getKeyChar()) ||                 e.getKeyChar() == KeyEvent.VK_ENTER ||                  source.getText().length()==bitLength && source.getSelectedText()==null) {                if (e.getKeyChar()!= KeyEvent.VK_ENTER) {                   Toolkit.getDefaultToolkit().beep();                   if (source.getText().length()==bitLength && source.getSelectedText()==null) {                      instructions.setText("Maximum length of this field is "+bitLength+".");                   }                    else {                      instructions.setText("Only 0 and 1 are accepted in binary field.");                   }                }                e.consume();             }           }                            // Enter key is echoed on component after keyPressed but before keyTyped?         // Consuming the VK_ENTER event in keyTyped does not suppress it but this will.                    public void keyPressed(KeyEvent e) {             if (e.getKeyChar()== KeyEvent.VK_ENTER) {                updateDisplaysAndRegister(new FlavorsOfFloat().buildOneFromBinaryString());                instructions.setText(defaultInstructions);                e.consume();             }          }                  // handy utility           private boolean isBinaryDigit(char digit) {             boolean result = false;             switch (digit) {                case '0': case '1':                   result = true;             }             return result;                      }                          }                   //////////////////////////////////////////////////////////////////     //     //  Class to handle input keystrokes for decimal field     //                  private class DecimalDisplayKeystokeListenter extends KeyAdapter {                  // Process user keystroke.  If not valid for the context, this         // will consume the stroke and beep.                       public void keyTyped(KeyEvent e) {             JTextField source = (JTextField) e.getComponent();             if (e.getKeyChar()== KeyEvent.VK_BACK_SPACE)                 return;             if (!isDecimalFloatDigit(e.getKeyChar())) {                if (e.getKeyChar()!= KeyEvent.VK_ENTER) {                   instructions.setText("Only digits, period, signs and E (or e) are accepted in decimal field.");                   Toolkit.getDefaultToolkit().beep();                }                e.consume();             }           }                            // Enter key is echoed on component after keyPressed but before keyTyped?         // Consuming the VK_ENTER event in keyTyped does not suppress it but this will.                    public void keyPressed(KeyEvent e) {             if (e.getKeyChar()== KeyEvent.VK_ENTER) {                FlavorsOfFloat fof = new FlavorsOfFloat().buildOneFromDecimalString(((JTextField)e.getSource()).getText());                if (fof==null) {                   Toolkit.getDefaultToolkit().beep();                   instructions.setText("'"+((JTextField)e.getSource()).getText()+"' is not a valid floating point number.");                }                 else {                   updateDisplaysAndRegister(fof);                   instructions.setText(defaultInstructions);                }                e.consume();             }          }                  // handy utility           private boolean isDecimalFloatDigit(char digit) {             boolean result = false;             switch (digit) {                case '0': case '1': case '2': case '3': case '4':                case '5': case '6': case '7': case '8': case '9':                case '-': case '+': case '.': case 'e': case 'E':                   result = true;             }             return result;                      }                          }          ////////////////////////////////////////////////////////////////////////////     //     //  Use this to draw graphics visually relating the hexadecimal values     //  displayed above) to the binary values (displayed below).     //        class HexToBinaryGraphicPanel extends JPanel {                // This overrides inherited JPanel method.  Override is necessary to         // assure my drawn graphics get painted immediately after painting the         // underlying JPanel (see first statement).           public void paintComponent(Graphics g) {             super.paintComponent(g);             g.setColor(Color.red);               //FontMetrics fontMetrics = hexDisplay.getGraphics().getFontMetrics();             int upperY = 0;             int lowerY = 60;             int hexColumnWidth = hexDisplay.getWidth()/hexDisplay.getColumns();             // assume all 3 binary displays use same geometry, so column width same for all.             int binaryColumnWidth = binaryFractionDisplay.getWidth()/binaryFractionDisplay.getColumns();             Polygon p;             // loop will handle the lower order 5 "nibbles" (hex digits)             for (int i=1; i<6; i++) {                p = new Polygon();                p.addPoint(hexDisplay.getX()+hexColumnWidth*(hexDisplay.getColumns()-i)+hexColumnWidth/2, upperY);                p.addPoint(binaryFractionDecoratedDisplay.getX()+binaryColumnWidth*(binaryFractionDisplay.getColumns()-((i*5)-i)), lowerY);                p.addPoint(binaryFractionDecoratedDisplay.getX()+binaryColumnWidth*(binaryFractionDisplay.getColumns()-(((i*5)-i)-4)), lowerY);                g.fillPolygon(p);             }             // Nibble 5 straddles binary display of exponent and fraction.             p = new Polygon();             p.addPoint(hexDisplay.getX()+hexColumnWidth*(hexDisplay.getColumns()-6)+hexColumnWidth/2, upperY);             p.addPoint(binaryFractionDecoratedDisplay.getX()+binaryColumnWidth*(binaryFractionDisplay.getColumns()-20), lowerY);             p.addPoint(binaryExponentDecoratedDisplay.getX()+binaryColumnWidth*(binaryExponentDisplay.getColumns()-1), lowerY);             g.fillPolygon(p);             // Nibble 6 maps to binary display of exponent.             p = new Polygon();             p.addPoint(hexDisplay.getX()+hexColumnWidth*(hexDisplay.getColumns()-7)+hexColumnWidth/2, upperY);             p.addPoint(binaryExponentDecoratedDisplay.getX()+binaryColumnWidth*(binaryExponentDisplay.getColumns()-1), lowerY);             p.addPoint(binaryExponentDecoratedDisplay.getX()+binaryColumnWidth*(binaryExponentDisplay.getColumns()-5), lowerY);             g.fillPolygon(p);             // Nibble 7 straddles binary display of sign and exponent.             p = new Polygon();             p.addPoint(hexDisplay.getX()+hexColumnWidth*(hexDisplay.getColumns()-8)+hexColumnWidth/2, upperY);             p.addPoint(binaryExponentDecoratedDisplay.getX()+binaryColumnWidth*(binaryExponentDisplay.getColumns()-5), lowerY);             p.addPoint(binarySignDecoratedDisplay.getX(), lowerY);             g.fillPolygon(p);          }              }          //////////////////////////////////////////////////////////////////////     //     //  Panel to hold arrows explaining transformation of binary represntation     //  into formula for calculating decimal value.     //        class BinaryToDecimalFormulaGraphic extends JPanel {          final String subtractLabelTrailer = " - 127";          final int arrowHeadOffset = 5;          final int lowerY = 0;          final int upperY = 50;          int centerX, exponentCenterX;          int subtractLabelWidth, subtractLabelHeight;          int centerY = (upperY-lowerY)/2;          int upperYArrowHead = upperY-arrowHeadOffset;          int currentExponent = Binary.binaryStringToInt(defaultBinaryExponent);           public void paintComponent(Graphics g) {             super.paintComponent(g);                   // Arrow down from binary sign field             centerX = binarySignDecoratedDisplay.getX()+binarySignDecoratedDisplay.getWidth()/2;             g.drawLine(centerX,lowerY,centerX,upperY);             g.drawLine(centerX-arrowHeadOffset,upperYArrowHead,centerX,upperY);             g.drawLine(centerX+arrowHeadOffset,upperYArrowHead,centerX,upperY);             // Arrow down from binary exponent field             centerX = binaryExponentDecoratedDisplay.getX()+binaryExponentDecoratedDisplay.getWidth()/2;             g.drawLine(centerX,lowerY,centerX,upperY);             g.drawLine(centerX-arrowHeadOffset,upperYArrowHead,centerX,upperY);             g.drawLine(centerX+arrowHeadOffset,upperYArrowHead,centerX,upperY);             // Label on exponent arrow.  The two assignments serve to initialize two             // instance variables that are used by drawSubtractLabel().  They are             // initialized here because they cannot be initialized sooner AND because             // the drawSubtractLabel() method will later be called by updateDisplays(),             // an outsider which has no other access to that information.  Once set they             // do not change so it does no harm that they are "re-initialized" each time             // this method is called (which occurs only upon startup and when this portion             // of the GUI needs to be repainted).             exponentCenterX = centerX;              subtractLabelHeight = g.getFontMetrics().getHeight();             drawSubtractLabel(g, buildSubtractLabel(currentExponent));             // Arrow down from binary fraction field             centerX = binaryFractionDecoratedDisplay.getX()+binaryFractionDecoratedDisplay.getWidth()/2;                             g.drawLine(centerX,lowerY,centerX,upperY);             g.drawLine(centerX-arrowHeadOffset,upperYArrowHead,centerX,upperY);             g.drawLine(centerX+arrowHeadOffset,upperYArrowHead,centerX,upperY);          }                  // To be used only by "outsiders" to update the display of the exponent and bias.           public void drawSubtractLabel(int exponent) {             if (exponent != currentExponent) { // no need to redraw if it hasn't changed...                currentExponent = exponent;                drawSubtractLabel(getGraphics(), buildSubtractLabel(exponent));             }          }                      // Is called by both drawSubtractLabel() just above and by paintComponent().           private void drawSubtractLabel(Graphics g, String label) {             // Clear the existing subtract label.  The "+2" overwrites the arrow at initial paint when label width is 0.             // Originally used "clearRect()" but changed to "fillRect()" with background color, because when running             // as a MarsTool it would clear with a different color.             Color saved = g.getColor();             g.setColor(binaryToDecimalFormulaGraphic.getBackground());             g.fillRect(exponentCenterX-subtractLabelWidth/2,centerY-subtractLabelHeight/2,subtractLabelWidth+2,subtractLabelHeight);             g.setColor(saved);             subtractLabelWidth = g.getFontMetrics().stringWidth(label);             g.drawString(label,exponentCenterX-subtractLabelWidth/2,centerY+subtractLabelHeight/2-3); // -3 makes it more visually appealing                      }                  // format the label for a given integer exponent value...           private String buildSubtractLabel(int value) {             return Integer.toString(value) + subtractLabelTrailer;          }              }                /////////////////////////////////////////////////////////////////////////        //        //  Handly little class defined only to allow client to use "setText()" without          //  needing to know how/whether the text needs to be formatted.  This one is        //  used to display instructions.            class InstructionsPane extends JLabel {                  InstructionsPane(Component parent) {             super(defaultInstructions);             this.setFont(instructionsFont);             this.setBackground(parent.getBackground());          }                    public void setText(String text) {             super.setText(text);          }       }               ////////////////////////////////////////////////////////////////////////////     //     //  Use this to draw custom background in the binary fraction display.     //        class BinaryFractionDisplayTextField extends JTextField {                  public BinaryFractionDisplayTextField(String value, int columns) {             super(value,columns);          }                      // This overrides inherited JPanel method.  Override is necessary to         // assure my drawn graphics get painted immediately after painting the         // underlying JPanel (see first statement).           public void paintComponent(Graphics g) {             super.paintComponent(g);              // The code below is commented out because I decided to abandon             // my effort to provide "striped" background that alternates colors             // for every 4 characters (bits) of the display.  This would make             // the correspondence between bits and hex digits very clear.             // NOTE: this is the only reason for subclassing JTextField.                          /*             int columnWidth = getWidth()/getColumns();             Color shadedColor = Color.red;             Polygon p;             // loop will handle the lower order 5 "nibbles" (hex digits)             for (int i=3; i<20; i+=8) {                p = new Polygon();                p.addPoint(getX()+columnWidth*i, getY());                p.addPoint(getX()+columnWidth*i, getY()+getHeight());                p.addPoint(getX()+columnWidth*(i+4), getY()+getHeight());                p.addPoint(getX()+columnWidth*(i+4), getY());          //         System.out.println("Polygon vertices are:"+          //         " ("+(getX()+columnWidth*i)    +","+getY()              +") "+          //         " ("+(getX()+columnWidth*i)    +","+(getY()+getHeight())+") "+          //         " ("+(getX()+columnWidth*(i+4))+","+(getY()+getHeight())+") "+          //         " ("+(getX()+columnWidth*(i+4))+","+getY()              +") "          //         );                 g.setColor(shadedColor);                g.fillPolygon(p);             }*/             /*             // Nibble 5 straddles binary display of exponent and fraction.             p = new Polygon();             p.addPoint(hexDisplay.getX()+hexColumnWidth*(hexDisplay.getColumns()-6)+hexColumnWidth/2, upperY);             p.addPoint(binaryFractionDisplay.getX()+binaryColumnWidth*(binaryFractionDisplay.getColumns()-20), lowerY);             p.addPoint(binaryExponentDisplay.getX()+binaryColumnWidth*(binaryExponentDisplay.getColumns()-1), lowerY);             g.fillPolygon(p);             // Nibble 6 maps to binary display of exponent.             p = new Polygon();             p.addPoint(hexDisplay.getX()+hexColumnWidth*(hexDisplay.getColumns()-7)+hexColumnWidth/2, upperY);             p.addPoint(binaryExponentDisplay.getX()+binaryColumnWidth*(binaryExponentDisplay.getColumns()-1), lowerY);             p.addPoint(binaryExponentDisplay.getX()+binaryColumnWidth*(binaryExponentDisplay.getColumns()-5), lowerY);             g.fillPolygon(p);             // Nibble 7 straddles binary display of sign and exponent.             p = new Polygon();             p.addPoint(hexDisplay.getX()+hexColumnWidth*(hexDisplay.getColumns()-8)+hexColumnWidth/2, upperY);             p.addPoint(binaryExponentDisplay.getX()+binaryColumnWidth*(binaryExponentDisplay.getColumns()-5), lowerY);             p.addPoint(binarySignDisplay.getX(), lowerY);             g.fillPolygon(p);             */          }       }        } AbstractMarsToolAndApplication$3 package mars.tools; synchronized class AbstractMarsToolAndApplication$3 implements java.awt.event.ActionListener { void AbstractMarsToolAndApplication$3(AbstractMarsToolAndApplication); public void actionPerformed(java.awt.event.ActionEvent); } BitmapDisplay$6 package mars.tools; synchronized class BitmapDisplay$6 implements java.awt.event.ActionListener { void BitmapDisplay$6(BitmapDisplay); public void actionPerformed(java.awt.event.ActionEvent); } FloatRepresentation$1 package mars.tools; synchronized class FloatRepresentation$1 implements java.awt.event.ActionListener { void FloatRepresentation$1(FloatRepresentation); public void actionPerformed(java.awt.event.ActionEvent); } ScavengerHunt$ScavengerHuntDisplay package mars.tools; synchronized class ScavengerHunt$ScavengerHuntDisplay extends javax.swing.JPanel { private int width; private int height; private boolean clearTheDisplay; public void ScavengerHunt$ScavengerHuntDisplay(ScavengerHunt, int, int); public void redraw(); public void clear(); public void paintComponent(java.awt.Graphics); } AbstractMarsToolAndApplication$MessageField$MessageWriter package mars.tools; synchronized class AbstractMarsToolAndApplication$MessageField$MessageWriter implements Runnable { private String text; private boolean terminatingMessage; public void AbstractMarsToolAndApplication$MessageField$MessageWriter(AbstractMarsToolAndApplication$MessageField, String, boolean); public void run(); } KeyboardAndDisplaySimulator package mars.tools; public synchronized class KeyboardAndDisplaySimulator extends AbstractMarsToolAndApplication { private static String version; private static String heading; public static java.awt.Dimension preferredTextAreaDimension; private static java.awt.Insets textAreaInsets; private final KeyboardAndDisplaySimulator$TransmitterDelayTechnique[] delayTechniques; public static int RECEIVER_CONTROL; public static int RECEIVER_DATA; public static int TRANSMITTER_CONTROL; public static int TRANSMITTER_DATA; private boolean countingInstructions; private int instructionCount; private int transmitDelayInstructionCountLimit; private int currentDelayInstructionLimit; private char characterToDisplay; private boolean displayAfterDelay; private javax.swing.JPanel keyboardAndDisplay; private javax.swing.JScrollPane displayScrollPane; private javax.swing.JTextArea display; private javax.swing.JPanel displayPanel; private javax.swing.JPanel displayOptions; private javax.swing.JComboBox delayTechniqueChooser; private KeyboardAndDisplaySimulator$DelayLengthPanel delayLengthPanel; private javax.swing.JSlider delayLengthSlider; private javax.swing.JCheckBox displayAfterDelayCheckBox; private javax.swing.JPanel keyboardPanel; private javax.swing.JScrollPane keyAccepterScrollPane; private javax.swing.JTextArea keyEventAccepter; private javax.swing.JButton fontButton; private java.awt.Font defaultFont; static void ();
public void KeyboardAndDisplaySimulator(String, String);
public void KeyboardAndDisplaySimulator();
public static void main(String[]);
public String getName();
protected void initializePreGUI();
protected void addAsObserver();
protected javax.swing.JComponent buildMainDisplayArea();
protected void processMIPSUpdate(java.util.Observable, mars.mips.hardware.AccessNotice);
protected void initializePostGUI();
protected void reset();
protected javax.swing.JComponent getHelpComponent();
private javax.swing.JComponent buildDisplay();
private javax.swing.JComponent buildKeyboard();
private void updateMMIOControl(int, int);
private void updateMMIOControlAndData(int, int, int, int);
private synchronized void updateMMIOControlAndData(int, int, int, int, boolean);
private static boolean isReadyBitSet(int);
private static int readyBitSet(int);
private static int readyBitCleared(int);
private void initializeTransmitDelaySimulator();
private int generateDelay();
}

AbstractMarsToolAndApplication

package mars.tools;
public abstract synchronized class AbstractMarsToolAndApplication extends javax.swing.JFrame implements MarsTool, java.util.Observer {
protected boolean isBeingUsedAsAMarsTool;
protected AbstractMarsToolAndApplication thisMarsApp;
private javax.swing.JDialog dialog;
protected java.awt.Window theWindow;
javax.swing.JLabel headingLabel;
private String title;
private String heading;
private javax.swing.border.EmptyBorder emptyBorder;
private java.awt.Color backgroundColor;
private int lowMemoryAddress;
private int highMemoryAddress;
private volatile boolean observing;
private java.io.File mostRecentlyOpenedFile;
private Runnable interactiveGUIUpdater;
private AbstractMarsToolAndApplication$MessageField operationStatusMessages;
private javax.swing.JButton openFileButton;
private javax.swing.JButton assembleRunButton;
private javax.swing.JButton stopButton;
private boolean multiFileAssemble;
protected AbstractMarsToolAndApplication$ConnectButton connectButton;
protected void AbstractMarsToolAndApplication(String, String);
public abstract String getName();
protected abstract javax.swing.JComponent buildMainDisplayArea();
public void go();
public void action();
protected void initializePreGUI();
protected void initializePostGUI();
protected void reset();
protected javax.swing.JComponent buildHeadingArea();
protected javax.swing.JComponent buildButtonAreaMarsTool();
protected javax.swing.JComponent buildButtonAreaStandAlone();
public void update(java.util.Observable, Object);
protected void processMIPSUpdate(java.util.Observable, mars.mips.hardware.AccessNotice);
protected void performSpecialClosingDuties();
protected void addAsObserver();
protected void addAsObserver(int, int);
protected void addAsObserver(mars.mips.hardware.Register);
protected void deleteAsObserver();
protected void deleteAsObserver(mars.mips.hardware.Register);
protected boolean isObserving();
protected void updateDisplay();
protected javax.swing.JComponent getHelpComponent();
private void performToolClosingDuties();
private void performAppClosingDuties();
}

MarsBot$BotRunnable

package mars.tools;
synchronized class MarsBot$BotRunnable implements Runnable {
javax.swing.JPanel panel;
public void MarsBot$BotRunnable(MarsBot);
public void run();
}

mars/tools/BHTSimulator.java
mars/tools/BHTSimulator.java/*
Copyright (c) 2009,  Ingo Kofler, ITEC, Klagenfurt University, Austria

Developed by Ingo Kofler (ingo. -klu.ac.at)

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

package mars.tools;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;

import javax.swing.JComponent;

import mars.ProgramStatement;
import mars.mips.hardware.AccessNotice;
import mars.mips.hardware.AddressErrorException;
import mars.mips.hardware.Memory;
import mars.mips.hardware.MemoryAccessNotice;
import mars.mips.hardware.RegisterFile;
//import mars.tools.bhtsim.BHTSimGUI;
//import mars.tools.bhtsim.BHTableModel;

/**
 * A MARS tool for simulating branch prediction with a Branch History Table (BHT)
 * 

 * The simulation is based on observing the access to the instruction memory area (text segment). 
 * If a branch instruction is encountered, a prediction based on a BHT is performed. 
 * The outcome of the branch is compared with the prediction and the prediction is updated accordingly.
 * Statistics about the correct and incorrect number of predictions can be obtained for each BHT entry.  
 * The number of entries in the BHT and the history that is considered for each prediction can be configured interactively.
 * A change of the configuration however causes a re-initialization of the BHT.
 * 

 * The tool can be used to show how branch prediction works in case of loops and how effective such simple methods are. 
 * In case of nested loops the difference of BHT with 1 or 2 Bit history can be explored and visualized.
 * 
 * @author ingo. -klu.ac.at
 */
//@SuppressWarnings(“serial”)
public class BHTSimulator extends AbstractMarsToolAndApplication implements ActionListener {
    
    
    /** constant for the default size of the BHT */
    public static final int BHT_DEFAULT_SIZE = 16;
    
    /** constant for the default history size */
    public static final int BHT_DEFAULT_HISTORY = 1;

    /** constant for the default inital value */
    public static final boolean BHT_DEFAULT_INITVAL = false;
    
    /** the name of the tool */
    public static final String BHT_NAME = “BHT Simulator”;

    /** the version of the tool */  
    public static final String BHT_VERSION = “Version 1.0 (Ingo Kofler)”;
    
    /** the heading of the tool */
    public static final String BHT_HEADING = “Branch History Table Simulator”;
        
    /** the GUI of the BHT simulator */
    private BHTSimGUI m_gui;    
    
    /** the model of the BHT */
    private BHTableModel m_bhtModel;
            
    /** state variable that indicates that the last instruction was a branch instruction (if address != 0) or not (address == 0) */
    private int m_pendingBranchInstAddress;
    
    /** state variable that signals if the last branch was taken */
    private boolean m_lastBranchTaken;
    
    
    /**
     * Creates a BHT Simulator with given name and heading.
     */
    public BHTSimulator() {
        super(BHTSimulator.BHT_NAME+”, “+BHTSimulator.BHT_VERSION, BHTSimulator.BHT_HEADING);
    }
    
    
    /**
     *  Adds BHTSimulator as observer of the text segment.
     */
    protected void addAsObserver() { 
        addAsObserver(Memory.textBaseAddress, Memory.textLimitAddress);
        addAsObserver(RegisterFile.getProgramCounterRegister());
    }
    
    
    /**
     * Creates a GUI and initialize the GUI with the default values.
     */
    protected JComponent buildMainDisplayArea() {

        m_gui = new BHTSimGUI();                
        m_bhtModel = new BHTableModel(BHTSimulator.BHT_DEFAULT_SIZE, BHTSimulator.BHT_DEFAULT_HISTORY, BHT_DEFAULT_INITVAL);        
        
        m_gui.getTabBHT().setModel(m_bhtModel);                                                     
        m_gui.getCbBHThistory().setSelectedItem(new Integer(BHTSimulator.BHT_DEFAULT_HISTORY));
        m_gui.getCbBHTentries().setSelectedItem(new Integer(BHTSimulator.BHT_DEFAULT_SIZE));
        
        m_gui.getCbBHTentries().addActionListener(this);
        m_gui.getCbBHThistory().addActionListener(this);        
        m_gui.getCbBHTinitVal().addActionListener(this);
        
        return m_gui;
    }

    
    /**
     * Returns the name of the tool.
     * @return the tool’s name as String
     */
    public String getName() {
        return BHTSimulator.BHT_NAME;
    }

    /**
     * Performs a reset of the simulator.
     * This causes the BHT to be reseted and the log messages to be cleared.
     */
    protected void reset() {            
        resetSimulator();
    }
    
    
    /**
     * Handles the actions when selecting another value in one of the two combo boxes.
     * Selecting a different BHT size or history causes a reset of the simulator.
     */
    public void actionPerformed(ActionEvent event) {
        // change of the BHT size or BHT bit configuration
        // resets the simulator
        if (event.getSource() == m_gui.getCbBHTentries() || event.getSource() == m_gui.getCbBHThistory() || event.getSource() == m_gui.getCbBHTinitVal()) {         
            resetSimulator();
        }       
    }
    
    
    /**
     * Resets the simulator by clearing the GUI elements and resetting the BHT.  
     */
    protected void resetSimulator() {
        m_gui.getTfInstruction().setText(“”);
        m_gui.getTfAddress().setText(“”);
        m_gui.getTfIndex().setText(“”);
        m_gui.getTaLog().setText(“”);
        m_bhtModel.initBHT(((Integer)m_gui.getCbBHTentries().getSelectedItem()).intValue(), 
                ((Integer)m_gui.getCbBHThistory().getSelectedItem()).intValue(), 
                ((String)m_gui.getCbBHTinitVal().getSelectedItem()).equals(BHTSimGUI.BHT_TAKE_BRANCH));     
        
        m_pendingBranchInstAddress = 0;
        m_lastBranchTaken = false;
    }
    
    
    /**
     * Handles the execution branch instruction.
     * This method is called each time a branch instruction is executed.
     * Based on the address of the instruction the corresponding index into the BHT is calculated.
     * The prediction is obtained from the BHT at the calculated index and is visualized appropriately. 
     *  
     * @param stmt the branch statement that is executed 
     */
    protected void handlePreBranchInst(ProgramStatement stmt) {
        
        String strStmt = stmt.getBasicAssemblyStatement();
        int address = stmt.getAddress();
        int idx = m_bhtModel.getIdxForAddress(address);     
        
        // update the GUI
        m_gui.getTfInstruction().setText(strStmt);
        m_gui.getTfAddress().setText(“0x” + Integer.toHexString(address));
        m_gui.getTfIndex().setText(“” + idx);       
                        
        // mark the affected BHT row
        m_gui.getTabBHT().setSelectionBackground(BHTSimGUI.COLOR_PREPREDICTION);
        m_gui.getTabBHT().addRowSelectionInterval(idx, idx);
        
        // add output to log
        m_gui.getTaLog().append(“instruction ” + strStmt + ” at address 0x” + Integer.toHexString(address) + “, maps to index ” + idx + “\n”);
        m_gui.getTaLog().append(“branches to address 0x” + BHTSimulator.extractBranchAddress(stmt) + “\n”);     
        m_gui.getTaLog().append(“prediction is: ” + (m_bhtModel.getPredictionAtIdx(idx) ? “take” : “do not take”) + “…\n”);
        m_gui.getTaLog().setCaretPosition(m_gui.getTaLog().getDocument().getLength());
                
    }
            
    
    /**
     * Handles the execution of the branch instruction. 
     * The correctness of the prediction is visualized in both the table and the log message area.
     * The BHT is updated based on the information if the branch instruction was taken or not.  
     * 
     * @param branchInstAddr the address of the branch instruction 
     * @param branchTaken the information if the branch is taken or not (determined in a step before)
     */
    protected void handleExecBranchInst(int branchInstAddr, boolean branchTaken) {
                                        
        // determine the index in the BHT for the branch instruction
        int idx = m_bhtModel.getIdxForAddress(branchInstAddr);
        
        // check if the prediction is correct 
        boolean correctPrediction = m_bhtModel.getPredictionAtIdx(idx) == branchTaken;
        
        m_gui.getTabBHT().setSelectionBackground(correctPrediction ? BHTSimGUI.COLOR_PREDICTION_CORRECT: BHTSimGUI.COLOR_PREDICTION_INCORRECT);
                
        // add some output at the log
        m_gui.getTaLog().append(“branch ” + (branchTaken ? “taken” : “not taken”) + “, prediction was ” + ( correctPrediction ? “correct” : “incorrect”) + “\n\n”);     
        m_gui.getTaLog().setCaretPosition(m_gui.getTaLog().getDocument().getLength());
        
        // update the BHT -> causes refresh of the table
        m_bhtModel.updatePredictionAtIdx(idx, branchTaken);             
    }
    
    
    /**
     * Determines if the instruction is a branch instruction or not.
     * 
     * @param stmt the statement to investigate
     * @return true, if stmt is a branch instruction, otherwise false
     */
    protected static boolean isBranchInstruction(ProgramStatement stmt) {
        
        int opCode = stmt.getBinaryStatement() >>> (32-6);
        int funct = stmt.getBinaryStatement() & 0x1F;
                
        if (opCode == 0x01) {
            if (0x00 <= funct && funct <= 0x07) return true; //  bltz, bgez, bltzl, bgezl             if (0x10 <= funct && funct <= 0x13) return true; // bltzal, bgezal, bltzall, bgczall                     }         if (0x04 <= opCode && opCode <= 0x07) return true; // beq, bne, blez, bgtz         if (0x14 <= opCode && opCode <= 0x17) return true; // beql, bnel, blezl, bgtzl                  return false;     }               /**      * Checks if the branch instruction delivered as parameter will branch or not.      *       * @param stmt the branch instruction to be investigated      * @return true if the branch will be taken, otherwise false      */      protected static boolean willBranch(ProgramStatement stmt) {         int opCode = stmt.getBinaryStatement() >>> (32-6);
        int funct = stmt.getBinaryStatement() & 0x1F;
        int rs = stmt.getBinaryStatement() >>> (32-6-5) & 0x1F;
        int rt = stmt.getBinaryStatement() >>> (32-6-5-5) & 0x1F;
        
        int valRS = RegisterFile.getRegisters()[rs].getValue();
        int valRT = RegisterFile.getRegisters()[rt].getValue();
                    
        
        if (opCode == 0x01) {
            switch (funct) {            
            case 0x00: return valRS < 0; // bltz             case 0x01: return valRS >= 0; // bgez
            case 0x02: return valRS < 0; // bltzl             case 0x03: return valRS >= 0; // bgezl          
            }
        }

        switch (opCode) {
        case 0x04: return valRS == valRT;
        case 0x05: return valRS != valRT;
        case 0x06: return valRS <= 0;         case 0x07: return valRS >= 0;
        case 0x14: return valRS == valRT;
        case 0x15: return valRS != valRT;
        case 0x16: return valRS <= 0;         case 0x17: return valRS >= 0;
        }
        
        return true;
    }
    
    
    /**
     * Extracts the target address of the branch.
     * 
     * In MIPS the target address is encoded as 16-bit value. 
     * The target address is encoded relative to the address of the instruction after the branch instruction
     * 
     * @param stmt the branch instruction
     * @return the address of the instruction that is executed if the branch is taken
     */
    protected static int extractBranchAddress(ProgramStatement stmt) {
        short offset = (short)(stmt.getBinaryStatement() & 0xFFFF);                         
        return stmt.getAddress() + (offset<<2) + 4;                  }               /**      * Callback for text segment access by the MIPS simulator.      *       * The method is called each time the text segment is accessed to fetch the next instruction.      * If the next instruction to execute was a branch instruction, the branch prediction is performed and visualized.      * In case the last instruction was a branch instruction, the outcome of the branch prediction is analyzed and visualized.      *      * @param resource the observed resource      * @param notice signals the type of access (memory, register etc.)      */     protected void processMIPSUpdate(Observable resource, AccessNotice notice) {                          if (!notice.accessIsFromMIPS()) return;                               if (notice.getAccessType() == AccessNotice.READ && notice instanceof MemoryAccessNotice) {                                    // now it is safe to make a cast of the notice             MemoryAccessNotice memAccNotice = (MemoryAccessNotice) notice;                          try {                                // access the statement in the text segment without notifying other tools etc.                 ProgramStatement stmt = Memory.getInstance().getStatementNoNotify(memAccNotice.getAddress());                                  // necessary to handle possible null pointers at the end of the program                  // (e.g., if the simulator tries to execute the next instruction after the last instruction in the text segment)                  if (stmt != null) {                                                                       boolean clearTextFields = true;                                          // first, check if there's a pending branch to handle                     if (m_pendingBranchInstAddress != 0) {                                               handleExecBranchInst(m_pendingBranchInstAddress, m_lastBranchTaken);                         clearTextFields = false;                         m_pendingBranchInstAddress = 0;                     }                                                               // if current instruction is branch instruction                     if (BHTSimulator.isBranchInstruction(stmt)) {                                                handlePreBranchInst(stmt);                         m_lastBranchTaken = willBranch(stmt);                         m_pendingBranchInstAddress = stmt.getAddress();                         clearTextFields = false;                     }                                          // clear text fields and selection                     if (clearTextFields) {                         m_gui.getTfInstruction().setText("");                         m_gui.getTfAddress().setText("");                         m_gui.getTfIndex().setText("");                         m_gui.getTabBHT().clearSelection();                                          }                 }                                    else {                     // check if there's a pending branch to handle                     if (m_pendingBranchInstAddress != 0) {                                               handleExecBranchInst(m_pendingBranchInstAddress, m_lastBranchTaken);                                                 m_pendingBranchInstAddress = 0;                     }                 }             }              catch (AddressErrorException e) {                            // silently ignore these exceptions             }                                         }     } } AbstractMarsToolAndApplication$EnterKeyListener package mars.tools; public synchronized class AbstractMarsToolAndApplication$EnterKeyListener extends java.awt.event.KeyAdapter { javax.swing.AbstractButton myButton; public void AbstractMarsToolAndApplication$EnterKeyListener(AbstractMarsToolAndApplication, javax.swing.AbstractButton); public void keyPressed(java.awt.event.KeyEvent); } mars/tools/KeyboardAndDisplaySimulator.java mars/tools/KeyboardAndDisplaySimulator.java   package mars.tools;    import mars.util.Binary;    import mars.venus.*;    import javax.swing.*;    import javax.swing.border.*;    import javax.swing.event.*;    import java.awt.*;    import java.awt.event.*;    import java.util.*;    import mars.Globals;    import mars.venus.RunSpeedPanel;    import mars.mips.hardware.*;    import mars.simulator.Exceptions;    import javax.swing.text.DefaultCaret; /* Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */    /**      * Keyboard and Display Simulator.  It can be run either as a stand-alone Java application having      * access to the mars package, or through MARS as an item in its Tools menu.  It makes      * maximum use of methods inherited from its abstract superclass AbstractMarsToolAndApplication.      * Pete Sanderson
     * Version 1.0, 24 July 2008.
     * Version 1.1, 24 November 2008 corrects two omissions: (1) the tool failed to register as an observer
     *    of kernel text memory when counting instruction executions for transmitter ready bit
     *    reset delay, and (2) the tool failed to test the Status register’s Exception Level bit before
     *    raising the exception that results in the interrupt (if the Exception Level bit is 1, that
     *    means an interrupt is being processed, so disable further interrupts).
     *
     * Version 1.2, 6 August 2009, soft-codes the MMIO register locations for new memory configuration
     *    feature of MARS 3.7.  Previously memory segment addresses were fixed and final.  Now they
     *    can be modified dynamically so the tool has to get its values dynamically as well.
     *
     */
    public class KeyboardAndDisplaySimulator extends AbstractMarsToolAndApplication {

      private static String version = “Version 1.3”;
      private static String heading =  “Keyboard and Display MMIO Simulator”;
      public static Dimension preferredTextAreaDimension = new Dimension(400,200);
      private static Insets textAreaInsets = new Insets(4,4,4,4);

      // Time delay to process Transmitter Data is simulated by counting instruction executions.
    // After this many executions, the Transmitter Controller Ready bit set to 1.
      private final TransmitterDelayTechnique[] delayTechniques = {
                                new FixedLengthDelay(),
                                      new UniformlyDistributedDelay(),
                                      new NormallyDistributedDelay()
         };
      public static int RECEIVER_CONTROL;    // keyboard Ready in low-order bit
      public static int RECEIVER_DATA;       // keyboard character in low-order byte
      public static int TRANSMITTER_CONTROL; // display Ready in low-order bit
      public static int TRANSMITTER_DATA;    // display character in low-order byte
    // These are used to track instruction counts to simulate driver delay of Transmitter Data
      private boolean countingInstructions;
      private int instructionCount;
      private int transmitDelayInstructionCountLimit;
      private int currentDelayInstructionLimit;

    // Should the transmitted character be displayed before the transmitter delay period?
    // If not, hold onto it and print at the end of delay period.
      private char characterToDisplay;
      private boolean displayAfterDelay = true;

    // Major GUI components
      private JPanel keyboardAndDisplay;
      private JScrollPane displayScrollPane;
      private JTextArea display;
      private JPanel displayPanel, displayOptions;
      private JComboBox delayTechniqueChooser;
      private DelayLengthPanel delayLengthPanel;
      private JSlider delayLengthSlider;
      private JCheckBox displayAfterDelayCheckBox;
      private JPanel keyboardPanel;
      private JScrollPane keyAccepterScrollPane;
      private JTextArea keyEventAccepter;
      private JButton fontButton;
      private Font defaultFont = new Font(Font.MONOSPACED, Font.PLAIN, 12);
    /**
     * Simple constructor, likely used to run a stand-alone keyboard/display simulator.
     * @param title String containing title for title bar
     * @param heading String containing text for heading shown in upper part of window.
     */
       public KeyboardAndDisplaySimulator(String title, String heading) {
         super(title,heading);
      }

     /**
      *  Simple constructor, likely used by the MARS Tools menu mechanism
      */
       public KeyboardAndDisplaySimulator() {
         super(“Keyboard and Display MMIO Simulator, ” + version, heading);
      }

    /**
     * Main provided for pure stand-alone use.  Recommended stand-alone use is to write a
     * driver program that instantiates a KeyboardAndDisplaySimulator object then invokes its go() method.
     * “stand-alone” means it is not invoked from the MARS Tools menu.  “Pure” means there
     * is no driver program to invoke the application.
     */
       public static void main(String[] args) {
         new KeyboardAndDisplaySimulator(“Keyboard and Display MMIO Simulator stand-alone, “+version,heading).go();
      }

       /**
      *  Required MarsTool method to return Tool name.
      *  @return  Tool name.  MARS will display this in menu item.
      */
       public String getName() {
         return “Keyboard and Display Simulator”;
      }

    // Set the MMIO addresses.  Prior to MARS 3.7 these were final because
    // MIPS address space was final as well.  Now we will get MMIO base address
    // each time to reflect possible change in memory configuration. DPS 6-Aug-09
       protected void initializePreGUI() {
         RECEIVER_CONTROL    = Memory.memoryMapBaseAddress; //0xffff0000; // keyboard Ready in low-order bit
         RECEIVER_DATA       = Memory.memoryMapBaseAddress + 4; //0xffff0004; // keyboard character in low-order byte
         TRANSMITTER_CONTROL = Memory.memoryMapBaseAddress + 8; //0xffff0008; // display Ready in low-order bit
         TRANSMITTER_DATA    = Memory.memoryMapBaseAddress + 12; //0xffff000c; // display character in low-order byte
      }

      /**
     *  Override the inherited method, which registers us as an Observer over the static data segment
     *  (starting address 0x10010000) only.
     *
     *  When user enters keystroke, set RECEIVER_CONTROL and RECEIVER_DATA using the action listener.
     *  When user loads word (lw) from RECEIVER_DATA (we are notified of the read), then clear RECEIVER_CONTROL.
     *  When user stores word (sw) to TRANSMITTER_DATA (we are notified of the write), then clear TRANSMITTER_CONTROL, read TRANSMITTER_DATA,
     *  echo the character to display, wait for delay period, then set TRANSMITTER_CONTROL.
     *
     *  If you use the inherited GUI buttons, this method is invoked when you click “Connect” button on MarsTool or the
     *  “Assemble and Run” button on a Mars-based app.
     */
       protected void addAsObserver() {
        // Set transmitter Control ready bit to 1, means we’re ready to accept display character.
         updateMMIOControl(TRANSMITTER_CONTROL, readyBitSet(TRANSMITTER_CONTROL));
          // We want to be an observer only of MIPS reads from RECEIVER_DATA and writes to TRANSMITTER_DATA.
          // Use the Globals.memory.addObserver() methods instead of inherited method to achieve this.
         addAsObserver(RECEIVER_DATA,RECEIVER_DATA);
         addAsObserver(TRANSMITTER_DATA, TRANSMITTER_DATA);
        // We want to be notified of each instruction execution, because instruction count is the
        // basis for delay in re-setting (literally) the TRANSMITTER_CONTROL register.  SPIM does
        // this too.  This simulates the time required for the display unit to process the
        // TRANSMITTER_DATA.
         addAsObserver(Memory.textBaseAddress, Memory.textLimitAddress);
         addAsObserver(Memory.kernelTextBaseAddress, Memory.kernelTextLimitAddress);
      }

    /**
     *  Method that constructs the main display area.  It is organized vertically
     *  into two major components: the display and the keyboard.  The display itself
     *  is a JTextArea and it echoes characters placed into the low order byte of
     *  the Transmitter Data location, 0xffff000c.  They keyboard is also a JTextArea
     *  places each typed character into the Receive Data location 0xffff0004.
     *  @return the GUI component containing these two areas
     */
       protected JComponent buildMainDisplayArea() {
         keyboardAndDisplay = new JPanel(new GridLayout(2,1));
         keyboardAndDisplay.add(buildDisplay());
         keyboardAndDisplay.add(buildKeyboard());
         return keyboardAndDisplay;
      }

      //////////////////////////////////////////////////////////////////////////////////////
      //  Rest of the protected methods.  These all override do-nothing methods inherited from
    //  the abstract superclass.
      //////////////////////////////////////////////////////////////////////////////////////

      /**
     * Update display when connected MIPS program accesses (data) memory.
     * @param memory the attached memory
     * @param accessNotice information provided by memory in MemoryAccessNotice object
     */
       protected void processMIPSUpdate(Observable memory, AccessNotice accessNotice) {
         MemoryAccessNotice notice = (MemoryAccessNotice) accessNotice;
        // If MIPS program has just read (loaded) the receiver (keyboard) data register,
        // then clear the Ready bit to indicate there is no longer a keystroke available.
        // If Ready bit was initially clear, they’ll get the old keystroke — serves ’em right
        // for not checking!
         if (notice.getAddress()==RECEIVER_DATA && notice.getAccessType()==AccessNotice.READ) {
            updateMMIOControl(RECEIVER_CONTROL, readyBitCleared(RECEIVER_CONTROL));
         }
        // MIPS program has just written (stored) the transmitter (display) data register.  If transmitter
        // Ready bit is clear, device is not ready yet so ignore this event — serves ’em right for not checking!
        // If transmitter Ready bit is set, then clear it to indicate the display device is processing the character.
        // Also start an intruction counter that will simulate the delay of the slower
        // display device processing the character.
         if (isReadyBitSet(TRANSMITTER_CONTROL) && notice.getAddress()==TRANSMITTER_DATA && notice.getAccessType()==AccessNotice.WRITE) {
            updateMMIOControl(TRANSMITTER_CONTROL, readyBitCleared(TRANSMITTER_CONTROL));
            characterToDisplay = (char) (notice.getValue() & 0x000000FF);
            if (!displayAfterDelay) display.append(“”+characterToDisplay);
            this.countingInstructions = true;
            this.instructionCount = 0;
            this.transmitDelayInstructionCountLimit = generateDelay();
         }
        // We have been notified of a MIPS instruction execution.
        // If we are in transmit delay period, increment instruction count and if limit
        // has been reached, set the transmitter Ready flag to indicate the MIPS program
        // can write another character to the transmitter data register.  If the Interrupt-Enabled
        // bit had been set by the MIPS program, generate an interrupt!
         if (   this.countingInstructions &&
                notice.getAccessType()==AccessNotice.READ &&
                (Memory.inTextSegment(notice.getAddress()) || Memory.inKernelTextSegment(notice.getAddress()))) {
            this.instructionCount++;
            if (this.instructionCount >= this.transmitDelayInstructionCountLimit) {
               if (displayAfterDelay) display.append(“”+characterToDisplay);
               this.countingInstructions = false;
               int updatedTransmitterControl =  readyBitSet(TRANSMITTER_CONTROL);
               updateMMIOControl(TRANSMITTER_CONTROL, updatedTransmitterControl);
               if (updatedTransmitterControl != 1
                   && (Coprocessor0.getValue(Coprocessor0.STATUS) & 2)==0  // Added by Carl Hauser Nov 2008
                   && (Coprocessor0.getValue(Coprocessor0.STATUS) & 1)==1) {
               // interrupt-enabled bit is set in both Tranmitter Control and in
               // Coprocessor0 Status register, and Interrupt Level Bit is 0, so trigger external interrupt.
                  mars.simulator.Simulator.externalInterruptingDevice = Exceptions.EXTERNAL_INTERRUPT_DISPLAY;
               }
            }
         }
      }

    /**
     *  Initialization code to be executed after the GUI is configured.  Overrides inherited default.
     */

       protected void initializePostGUI() {
         initializeTransmitDelaySimulator();
         keyEventAccepter.requestFocusInWindow();
      }

    /**
     *  Method to reset counters and display when the Reset button selected.
     *  Overrides inherited method that does nothing.
     */
       protected void reset() {
         initializeTransmitDelaySimulator();
         display.setText(“”);
         keyEventAccepter.setText(“”);
         keyEventAccepter.requestFocusInWindow();
         updateMMIOControl(TRANSMITTER_CONTROL, readyBitSet(TRANSMITTER_CONTROL));
      }

     /**
      *  Overrides default method, to provide a Help button for this tool/app.
      */

       protected JComponent getHelpComponent() {
         final String helpContent =
                              “Use this program to simulate Memory-Mapped I/O (MMIO) for a keyboard input device and character “+
                              “display output device.  It may be run either from MARS’ Tools menu or as a stand-alone application. “+
                                    “For the latter, simply write a driver to instantiate a mars.tools.KeyboardAndDisplaySimulator object “+
                                    “and invoke its go() method.\n”+
                                    “\n”+
                                    “While the tool is connected to MIPS, each keystroke in the text area causes the corresponding ASCII “+
                                    “code to be placed in the Receiver Data register (low-order byte of memory word “+Binary.intToHexString(RECEIVER_DATA)+”), and the “+
                                    “Ready bit to be set to 1 in the Receiver Control register (low-order bit of “+Binary.intToHexString(RECEIVER_CONTROL)+”).  The Ready “+
                                    “bit is automatically reset to 0 when the MIPS program reads the Receiver Data using an ‘lw’ instruction.\n”+
                                    “\n”+
                                    “A program may write to the display area by detecting the Ready bit set (1) in the Transmitter Control “+
                                    “register (low-order bit of memory word “+Binary.intToHexString(TRANSMITTER_CONTROL)+”), then storing the ASCII code of the character to be “+
                                    “displayed in the Transmitter Data register (low-order byte of “+Binary.intToHexString(TRANSMITTER_DATA)+”) using a ‘sw’ instruction.  This “+
                                    “triggers the simulated display to clear the Ready bit to 0, delay awhile to simulate processing the data, “+
                                    “then set the Ready bit back to 1.  The delay is based on a count of executed MIPS instructions.\n”+
                                    “\n”+
                                    “In a polled approach to I/O, a MIPS program idles in a loop, testing the device’s Ready bit on each “+
                                    “iteration until it is set to 1 before proceeding.  This tool also supports an interrupt-driven approach “+
                                    “which requires the program to provide an interrupt handler but allows it to perform useful processing “+
                                    “instead of idly looping.  When the device is ready, it signals an interrupt and the MARS simuator will “+
                                    “transfer control to the interrupt handler.  Note: in MARS, the interrupt handler has to co-exist with the “+
                                    “exception handler in kernel memory, both having the same entry address.  Interrupt-driven I/O is enabled “+
                                    “when the MIPS program sets the Interrupt-Enable bit in the device’s control register.  Details below.\n”+
                                    “\n”+
                                    “Upon setting the Receiver Controller’s Ready bit to 1, its Interrupt-Enable bit (bit position 1) is tested. “+
                                    “If 1, then an External Interrupt will be generated.  Before executing the next MIPS instruction, the runtime “+
                                    “simulator will detect the interrupt, place the interrupt code (0) into bits 2-6 of Coprocessor 0’s Cause “+
                                    “register ($13), set bit 8 to 1 to identify the source as keyboard, place the program counter value (address “+
                                    “of the NEXT instruction to be executed) into its EPC register ($14), and check to see if an interrupt/trap “+
                                    “handler is present (looks for instruction code at address 0x80000180).  If so, the program counter is set to “+
                                    “that address.  If not, program execution is terminated with a message to the Run I/O tab.  The Interrupt-Enable “+
                                    “bit is 0 by default and has to be set by the MIPS program if interrupt-driven input is desired.  Interrupt-driven “+
                                    “input permits the program to perform useful tasks instead of idling in a loop polling the Receiver Ready bit!  “+
                                    “Very event-oriented.  The Ready bit is supposed to be read-only but in MARS it is not.\n”+
                                    “\n”+
                                    “A similar test and potential response occurs when the Transmitter Controller’s Ready bit is set to 1.  This “+
                                    “occurs after the simulated delay described above.  The only difference is the Cause register bit to identify “+
                                    “the (simulated) display as external interrupt source is bit position 9 rather than 8.  This permits you to “+
                                    “write programs that perform interrupt-driven output – the program can perform useful tasks while the “+
                                    “output device is processing its data.  Much better than idling in a loop polling the Transmitter Ready bit! “+
                                    “The Ready bit is supposed to be read-only but in MARS it is not.\n”+
                                    “\n”+
                                    “IMPORTANT NOTE: The Transmitter Controller Ready bit is set to its initial value of 1 only when you click the tool’s “+
                                    “‘Connect to MIPS’ button (‘Assemble and Run’ in the stand-alone version) or the tool’s Reset button!  If you run a “+
                                    “MIPS program and reset it in MARS, the controller’s Ready bit is cleared to 0!  Configure the Data Segment Window to “+
                                    “display the MMIO address range so you can directly observe values stored in the MMIO addresses given above.\n”+
                                    “\n”+
                                    “Contact Pete Sanderson at   with questions or comments.\n”;
         JButton help = new JButton(“Help”);
         help.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     JTextArea ja = new JTextArea(helpContent);
                     ja.setRows(30);
                     ja.setColumns(60);
                     ja.setLineWrap(true);
                     ja.setWrapStyleWord(true);
                     JOptionPane.showMessageDialog(theWindow, new JScrollPane(ja),
                         “Simulating the Keyboard and Display”, JOptionPane.INFORMATION_MESSAGE);
                  }
               });
         return help;
      }

      //////////////////////////////////////////////////////////////////////////////////////
      //  Private methods defined to support the above.
      //////////////////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////////////////////
    // UI components and layout for upper part of GUI, where simulated display is located.
       private JComponent buildDisplay() {
         displayPanel = new JPanel(new BorderLayout());
         TitledBorder tb = new TitledBorder(“DISPLAY: Characters stored to Transmitter Data Register (“+Binary.intToHexString(TRANSMITTER_DATA)+”) are echoed here”);
         tb.setTitleJustification(TitledBorder.CENTER);
         displayPanel.setBorder(tb);
         display = new JTextArea();
         display.setFont(defaultFont);
         display.setEditable(false);
         display.setMargin(textAreaInsets);

    // 2011-07-29: Patrik Lundin, 
    // Added code so display autoscrolls. 
        DefaultCaret caret = (DefaultCaret)display.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    // end added autoscrolling

         displayScrollPane = new JScrollPane(display);
         displayScrollPane.setPreferredSize(preferredTextAreaDimension);
         displayPanel.add(displayScrollPane);

         displayOptions = new JPanel();
         delayTechniqueChooser = new JComboBox(delayTechniques);
         delayTechniqueChooser.setToolTipText(“Technique for determining simulated transmitter device processing delay”);
         delayTechniqueChooser.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     transmitDelayInstructionCountLimit = generateDelay();
                  }
               });
         delayLengthPanel = new DelayLengthPanel();
         displayAfterDelayCheckBox = new JCheckBox(“DAD”, true);
         displayAfterDelayCheckBox.setToolTipText(“Display After Delay: if checked, transmitter data not displayed until after delay”);
         displayAfterDelayCheckBox.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     displayAfterDelay = displayAfterDelayCheckBox.isSelected();
                  }
               });
         
         //font button to display font
         fontButton = new JButton(“Font”);
         fontButton.setToolTipText(“Select the font for the display panel”);
         fontButton.addActionListener(new FontChanger()) ;
         displayOptions.add(fontButton);
         displayOptions.add(displayAfterDelayCheckBox);
         displayOptions.add(delayTechniqueChooser);
         displayOptions.add(delayLengthPanel);
         displayPanel.add(displayOptions,BorderLayout.SOUTH);
         return displayPanel;
      }

    //////////////////////////////////////////////////////////////////////////////////////
    // UI components and layout for lower part of GUI, where simulated keyboard is located.
       private JComponent buildKeyboard() {
         keyboardPanel = new JPanel(new BorderLayout());
         keyEventAccepter = new JTextArea();
         keyEventAccepter.setEditable(true);
         keyEventAccepter.setFont(defaultFont);
         keyEventAccepter.setMargin(textAreaInsets);
         keyAccepterScrollPane = new JScrollPane(keyEventAccepter);
         keyAccepterScrollPane.setPreferredSize(preferredTextAreaDimension);
         keyEventAccepter.addKeyListener(new KeyboardKeyListener());
         keyboardPanel.add(keyAccepterScrollPane);
         TitledBorder tb =new TitledBorder(“KEYBOARD: Characters typed in this text area are written to Receiver Data Register (“+Binary.intToHexString(RECEIVER_DATA)+”)”);
         tb.setTitleJustification(TitledBorder.CENTER);
         keyboardPanel.setBorder(tb);
         return keyboardPanel;
      }

     ////////////////////////////////////////////////////////////////////
       // update the MMIO Control register memory cell. We will delegate.
       private void updateMMIOControl(int addr, int intValue) {
         updateMMIOControlAndData(addr, intValue, 0, 0, true);
      }

     /////////////////////////////////////////////////////////////////////
       // update the MMIO Control and Data register pair — 2 memory cells. We will delegate.
       private void updateMMIOControlAndData(int controlAddr, int controlValue, int dataAddr, int dataValue) {
         updateMMIOControlAndData(controlAddr, controlValue, dataAddr, dataValue, false);
      }

     /////////////////////////////////////////////////////////////////////////////////////////////////////
       // This one does the work: update the MMIO Control and optionally the Data register as well
     // NOTE: last argument TRUE means update only the MMIO Control register; FALSE means update both Control and Data.
       private synchronized void updateMMIOControlAndData(int controlAddr, int controlValue, int dataAddr, int dataValue, boolean controlOnly) {
         if (!this.isBeingUsedAsAMarsTool || (this.isBeingUsedAsAMarsTool && connectButton.isConnected())) {
            synchronized (Globals.memoryAndRegistersLock) {
               try {
                  Globals.memory.setRawWord(controlAddr, controlValue);
                  if (!controlOnly) Globals.memory.setRawWord(dataAddr, dataValue);
               }
                   catch (AddressErrorException aee) {
                     System.out.println(“Tool author specified incorrect MMIO address!”+aee);
                     System.exit(0);
                  }
            }
            // HERE’S A HACK!!  Want to immediately display the updated memory value in MARS
            // but that code was not written for event-driven update (e.g. Observer) —
            // it was written to poll the memory cells for their values.  So we force it to do so.

            if (Globals.getGui() != null && Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().getCodeHighlighting() ) {
               Globals.getGui().getMainPane().getExecutePane().getDataSegmentWindow().updateValues();
            }
         }
      }

     /////////////////////////////////////////////////////////////////////
     // Return value of the given MMIO control register after ready (low order) bit set (to 1).
     // Have to preserve the value of Interrupt Enable bit (bit 1)
       private static boolean isReadyBitSet(int mmioControlRegister) {
         try {
            return (Globals.memory.get(mmioControlRegister, Memory.WORD_LENGTH_BYTES) & 1) == 1;
         }
             catch (AddressErrorException aee) {
               System.out.println(“Tool author specified incorrect MMIO address!”+aee);
               System.exit(0);
            }
         return false; // to satisfy the compiler — this will never happen.
      }

     /////////////////////////////////////////////////////////////////////
     // Return value of the given MMIO control register after ready (low order) bit set (to 1).
     // Have to preserve the value of Interrupt Enable bit (bit 1)
       private static int readyBitSet(int mmioControlRegister) {
         try {
            return Globals.memory.get(mmioControlRegister, Memory.WORD_LENGTH_BYTES) | 1;
         }
             catch (AddressErrorException aee) {
               System.out.println(“Tool author specified incorrect MMIO address!”+aee);
               System.exit(0);
            }
         return 1; // to satisfy the compiler — this will never happen.
      }

     /////////////////////////////////////////////////////////////////////
     //  Return value of the given MMIO control register after ready (low order) bit cleared (to 0).
     // Have to preserve the value of Interrupt Enable bit (bit 1). Bits 2 and higher don’t matter.
       private static int readyBitCleared(int mmioControlRegister) {
         try {
            return Globals.memory.get(mmioControlRegister, Memory.WORD_LENGTH_BYTES) & 2;
         }
             catch (AddressErrorException aee) {
               System.out.println(“Tool author specified incorrect MMIO address!”+aee);
               System.exit(0);
            }
         return 0; // to satisfy the compiler — this will never happen.
       }

    /////////////////////////////////////////////////////////////////////
    // Transmit delay is simulated by counting instruction executions.
    // Here we simly initialize (or reset) the variables.
       private void initializeTransmitDelaySimulator() {
         this.countingInstructions = false;
         this.instructionCount = 0;
         this.transmitDelayInstructionCountLimit = this.generateDelay();
      }

    /////////////////////////////////////////////////////////////////////
    //  Calculate transmitter delay (# instruction executions) based on
    //  current combo box and slider settings.

       private int generateDelay() {
         double sliderValue = delayLengthPanel.getDelayLength();
         TransmitterDelayTechnique technique = (TransmitterDelayTechnique) delayTechniqueChooser.getSelectedItem();
         return technique.generateDelay(sliderValue);
      }

    ///////////////////////////////////////////////////////////////////////////////////
    //
    //  Class to grab keystrokes going to keyboard echo area and send them to MMIO area
    //

       private class KeyboardKeyListener implements KeyListener {
          public void keyTyped(KeyEvent e) {
            int updatedReceiverControl = readyBitSet(RECEIVER_CONTROL);
            updateMMIOControlAndData(RECEIVER_CONTROL, updatedReceiverControl, RECEIVER_DATA,  e.getKeyChar() & 0x00000ff);
            if (updatedReceiverControl != 1
                && (Coprocessor0.getValue(Coprocessor0.STATUS) & 2)==0   // Added by Carl Hauser Nov 2008
                 && (Coprocessor0.getValue(Coprocessor0.STATUS) & 1)==1) {
               // interrupt-enabled bit is set in both Receiver Control and in
                // Coprocessor0 Status register, and Interrupt Level Bit is 0, so trigger external interrupt.
               mars.simulator.Simulator.externalInterruptingDevice = Exceptions.EXTERNAL_INTERRUPT_KEYBOARD;
            }
        }

        /* Ignore key pressed event from the text field. */
        public void keyPressed(KeyEvent e) {
        }

        /* Ignore key released event from the text field. */
        public void keyReleased(KeyEvent e) {
            }
        }

    //////////////////////////////////////////////////////////////////////////////////
    //
    //  Class for selecting transmitter delay lengths (# of MIPS instruction executions).
    //

        private class DelayLengthPanel extends JPanel {
         private final static int DELAY_INDEX_MIN = 0;
         private final static int DELAY_INDEX_MAX = 40;
         private final static int DELAY_INDEX_INIT = 4;
         private double[] delayTable = {
               1,    2,    3,    4,    5,   10,   20,   30,   40,   50,  100,  // 0-10
                    150,  200,  300,  400,  500,  600,  700,  800,  900, 1000,  //11-20
                  1500, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000,10000,  //21-30
                 20000,40000,60000,80000,100000,200000,400000,600000,800000,1000000//31-40
                };
         private JLabel sliderLabel=null;
         private volatile int delayLengthIndex = DELAY_INDEX_INIT;

          public DelayLengthPanel() {
            super(new BorderLayout());
            delayLengthSlider = new JSlider(JSlider.HORIZONTAL, DELAY_INDEX_MIN,DELAY_INDEX_MAX,DELAY_INDEX_INIT);
            delayLengthSlider.setSize(new Dimension(100,(int)delayLengthSlider.getSize().getHeight()));
            delayLengthSlider.setMaximumSize(delayLengthSlider.getSize());
            delayLengthSlider.addChangeListener(new DelayLengthListener());
            sliderLabel = new JLabel(setLabel(delayLengthIndex));
            sliderLabel.setHorizontalAlignment(JLabel.CENTER);
            sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
            this.add(sliderLabel, BorderLayout.NORTH);
            this.add(delayLengthSlider, BorderLayout.CENTER);
            this.setToolTipText(“Parameter for simulated delay length (MIPS instruction execution count)”);
         }

       // returns current delay length setting, in instructions.
          public double getDelayLength() {
            return delayTable[delayLengthIndex];
         }

       // set label wording depending on current speed setting
          private String setLabel(int index) {
            return “Delay length: “+((int)delayTable[index])+” instruction executions”;
         }

       // Both revises label as user slides and updates current index when sliding stops.
          private class DelayLengthListener implements ChangeListener {
             public void stateChanged(ChangeEvent e) {
               JSlider source = (JSlider)e.getSource();
               if (!source.getValueIsAdjusting()) {
                  delayLengthIndex = (int)source.getValue();
                  transmitDelayInstructionCountLimit = generateDelay();
               }
               else {
                  sliderLabel.setText(setLabel(source.getValue()));
               }
            }
         }
      }

    ///////////////////////////////////////////////////////////////////
    //
    //Interface and classes for Transmitter Delay-generating techniques.
        //

        private interface TransmitterDelayTechnique {
          public int generateDelay(double parameter);
      }

     // Delay value is fixed, and equal to slider value.
        private class FixedLengthDelay implements TransmitterDelayTechnique {
          public String toString() {
            return “Fixed transmitter delay, select using slider”;
         }
          public int generateDelay(double fixedDelay) {
            return (int) fixedDelay;
         }
      }

     // Randomly pick value from range 1 to slider setting, uniform distribution
     // (each value has equal probability of being chosen).
        private class UniformlyDistributedDelay implements TransmitterDelayTechnique {
         Random randu;
          public UniformlyDistributedDelay() {
            randu = new Random();
         }
          public String toString() {
            return “Uniformly distributed delay, min=1, max=slider”;
         }
          public int generateDelay(double max) {
            return randu.nextInt((int)max)+1;
         }
      }

    // Pretty badly-hacked normal distribution, but is more realistic than uniform!
    // Get sample from Normal(0,1) — mean=0, s.d.=1 — multiply it by slider
    // value, take absolute value to make sure we don’t get negative,
    // add 1 to make sure we don’t get 0.
        private class NormallyDistributedDelay implements TransmitterDelayTechnique {
            Random randn;
            public NormallyDistributedDelay() {
                randn = new Random();
            }
            public String toString() {
                return “‘Normally’ distributed delay: floor(abs(N(0,1)*slider)+1)”;
            }
            public int generateDelay(double mult) {
                return (int) (Math.abs(randn.nextGaussian()*mult)+1);
            }
        }

    /**
     *  Font dialog for the display panel
     *  Almost all of the code is used from the SettingsHighlightingAction
     *  class.
    */
        
    private class FontSettingDialog extends AbstractFontSettingDialog {
         private boolean resultOK;
      
          public FontSettingDialog(Frame owner, String title, Font currentFont) {
            super(owner, title, true, currentFont);
         }
         
          private Font showDialog() {
            resultOK = true;
           // Because dialog is modal, this blocks until user terminates the dialog.
            this.setVisible(true);
            return resultOK ? getFont() : null;
         }
        
          protected void closeDialog() {
            this.setVisible(false);
         }

         private void performCancel() {
            resultOK = false;
         }
        
        // Control buttons for the dialog.  
          protected Component buildControlPanel() {
            Box controlPanel = Box.createHorizontalBox();
            JButton okButton = new JButton(“OK”);
            okButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        apply(getFont());
                        closeDialog();
                     }
                  });
            JButton cancelButton = new JButton(“Cancel”);
            cancelButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        performCancel(); 
                        closeDialog();
                     }
                  });   
            JButton resetButton = new JButton(“Reset”);
            resetButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        reset();
                     }
                  });
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(okButton);
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(cancelButton);
            controlPanel.add(Box.createHorizontalGlue());        
            controlPanel.add(resetButton);
            controlPanel.add(Box.createHorizontalGlue());
            return controlPanel;
         }
      
        // Change the font for the keyboard and display
        protected void apply(Font font) {
            display.setFont(font);
            keyEventAccepter.setFont(font);
        }
      
     }
        
    private class FontChanger implements ActionListener {
          public void actionPerformed(ActionEvent e) {
            JButton button = (JButton) e.getSource();
            FontSettingDialog fontDialog = new FontSettingDialog(null, “Select Text Font”, display.getFont());
            Font newFont = fontDialog.showDialog();
          }
    }

}

CacheSimulator$3

package mars.tools;
synchronized class CacheSimulator$3 implements java.awt.event.ActionListener {
void CacheSimulator$3(CacheSimulator);
public void actionPerformed(java.awt.event.ActionEvent);
}

KeyboardAndDisplaySimulator$2

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$2 implements java.awt.event.ActionListener {
void KeyboardAndDisplaySimulator$2(KeyboardAndDisplaySimulator);
public void actionPerformed(java.awt.event.ActionEvent);
}

ScribblerSettings

package mars.tools;
synchronized class ScribblerSettings {
private int width;
private java.awt.Color color;
public void ScribblerSettings(int, java.awt.Color);
public int getLineWidth();
public java.awt.Color getLineColor();
public void setLineWidth(int);
public void setLineColor(java.awt.Color);
}

CacheSimulator

package mars.tools;
public synchronized class CacheSimulator extends AbstractMarsToolAndApplication {
private static boolean debug;
private static String version;
private static String heading;
private javax.swing.JComboBox cacheBlockSizeSelector;
private javax.swing.JComboBox cacheBlockCountSelector;
private javax.swing.JComboBox cachePlacementSelector;
private javax.swing.JComboBox cacheReplacementSelector;
private javax.swing.JComboBox cacheSetSizeSelector;
private javax.swing.JTextField memoryAccessCountDisplay;
private javax.swing.JTextField cacheHitCountDisplay;
private javax.swing.JTextField cacheMissCountDisplay;
private javax.swing.JTextField replacementPolicyDisplay;
private javax.swing.JTextField cachableAddressesDisplay;
private javax.swing.JTextField cacheSizeDisplay;
private javax.swing.JProgressBar cacheHitRateDisplay;
private CacheSimulator$Animation animations;
private javax.swing.JPanel logPanel;
private javax.swing.JScrollPane logScroll;
private javax.swing.JTextArea logText;
private javax.swing.JCheckBox logShow;
private javax.swing.border.EmptyBorder emptyBorder;
private java.awt.Font countFonts;
private java.awt.Color backgroundColor;
private int[] cacheBlockSizeChoicesInt;
private int[] cacheBlockCountChoicesInt;
private String[] cacheBlockSizeChoices;
private String[] cacheBlockCountChoices;
private String[] placementPolicyChoices;
private final int DIRECT;
private final int FULL;
private final int SET;
private String[] replacementPolicyChoices;
private final int LRU;
private final int RANDOM;
private String[] cacheSetSizeChoices;
private int defaultCacheBlockSizeIndex;
private int defaultCacheBlockCountIndex;
private int defaultPlacementPolicyIndex;
private int defaultReplacementPolicyIndex;
private int defaultCacheSetSizeIndex;
private CacheSimulator$AbstractCache theCache;
private int memoryAccessCount;
private int cacheHitCount;
private int cacheMissCount;
private double cacheHitRate;
private java.util.Random randu;
static void ();
public void CacheSimulator(String, String);
public void CacheSimulator();
public static void main(String[]);
public String getName();
protected javax.swing.JComponent buildMainDisplayArea();
private javax.swing.JComponent buildLogArea();
private javax.swing.JComponent buildOrganizationArea();
private javax.swing.JComponent buildPerformanceArea();
protected void processMIPSUpdate(java.util.Observable, mars.mips.hardware.AccessNotice);
protected void initializePreGUI();
protected void initializePostGUI();
protected void reset();
protected void updateDisplay();
private String[] determineSetSizeChoices(int, int);
private void updateCacheSetSizeSelector();
private CacheSimulator$AbstractCache createNewCache();
private void resetCounts();
private void updateMemoryAccessCountDisplay();
private void updateCacheHitCountDisplay();
private void updateCacheMissCountDisplay();
private void updateCacheHitRateDisplay();
private void updateCacheSizeDisplay();
private javax.swing.JPanel getPanelWithBorderLayout();
private void resetLogDisplay();
private void writeLog(String);
}

mars/tools/InstructionStatistics.java
mars/tools/InstructionStatistics.java/*
Copyright (c) 2009,  Ingo Kofler, ITEC, Klagenfurt University, Austria

Developed by Ingo Kofler (ingo. -klu.ac.at)
Based on the Instruction Counter tool by Felipe Lessa (felipe. )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
   package mars.tools;

   import java.awt.GridBagConstraints;
   import java.awt.GridBagLayout;
   import java.awt.Insets;
   import java.util.Observable;

   import javax.swing.JComponent;
   import javax.swing.JLabel;
   import javax.swing.JPanel;
   import javax.swing.JProgressBar;
   import javax.swing.JTextField;

   import mars.ProgramStatement;
   import mars.mips.hardware.AccessNotice;
   import mars.mips.hardware.AddressErrorException;
   import mars.mips.hardware.Memory;
   import mars.mips.hardware.MemoryAccessNotice;

/**
 * 
 * A MARS tool for obtaining instruction statistics by instruction category.  
 * 

 
 * The code of this tools is initially based on the Instruction counter tool by Felipe Lassa.  
 * 
 * @author Ingo Kofler 
 *
 */
   // @SuppressWarnings(“serial”)
    public class InstructionStatistics extends AbstractMarsToolAndApplication {
    
   /** name of the tool */
      private static String NAME    = “Instruction Statistics”;
   
   /** version and author information of the tool */
      private static String VERSION = “Version 1.0 (Ingo Kofler)”;
    
    /** heading of the tool */
      private static String HEADING = “”;
    
    
    
    /** number of instruction categories used by this tool */
      private static final int MAX_CATEGORY = 5;
    
    /** constant for ALU instructions category */
      private static final int CATEGORY_ALU = 0;
    
    /** constant for jump instructions category */
      private static final int CATEGORY_JUMP = 1;
    
    /** constant for branch instructions category */
      private static final int CATEGORY_BRANCH = 2;
    
    /** constant for memory instructions category */
      private static final int CATEGORY_MEM = 3;
    
    /** constant for any other instruction category */
      private static final int CATEGORY_OTHER = 4;    
   
        
    
    
    /** text field for visualizing the total number of instructions processed */
      private JTextField m_tfTotalCounter;
    
    /** array of text field – one for each instruction category */    
      private JTextField m_tfCounters[];
    
    /** array of progress pars – one for each instruction category */
      private JProgressBar m_pbCounters[];
    
    
    /** counter for the total number of instructions processed */
      private int m_totalCounter = 0;
   
    /** array of counter variables – one for each instruction category */
      private int m_counters[] = new int[MAX_CATEGORY];     
    
    /** names of the instruction categories as array */
      private String m_categoryLabels[] = { “ALU”, “Jump”, “Branch”, “Memory”, “Other” };
    
   
    // From Felipe Lessa’s instruction counter.  Prevent double-counting of instructions 
    // which happens because 2 read events are generated.   
    /**
     * The last address we saw. We ignore it because the only way for a
     * program to execute twice the same instruction is to enter an infinite
     * loop, which is not insteresting in the POV of counting instructions.
     */
      protected int lastAddress = -1;  
    
    /**
     * Simple constructor, likely used to run a stand-alone enhanced instruction counter.
     * @param title String containing title for title bar
     * @param heading String containing text for heading shown in upper part of window.
     */
       public InstructionStatistics(String title, String heading) {
         super(title, heading);
      }
    
    
    /**
     * Simple construction, likely used by the MARS Tools menu mechanism.
     */
       public InstructionStatistics() {
         super(InstructionStatistics.NAME + “, ” + InstructionStatistics.VERSION, InstructionStatistics.HEADING);        
      }
   
    
    /**
     * returns the name of the tool
     * 
     * @return the tools’s name
     */
       public String getName() {
         return NAME;
      }
   
   
   /**
    * creates the display area for the tool as required by the API
    * 
    * @return a panel that holds the GUI of the tool
    */
       protected JComponent buildMainDisplayArea() {
      
      // Create GUI elements for the tool
         JPanel panel = new JPanel(new GridBagLayout());
      
         m_tfTotalCounter = new JTextField(“0”, 10);
         m_tfTotalCounter.setEditable(false);
      
         m_tfCounters = new JTextField[MAX_CATEGORY];
         m_pbCounters = new JProgressBar[MAX_CATEGORY];
      
       // for each category a text field and a progress bar is created
         for (int i=0; i < InstructionStatistics.MAX_CATEGORY; i++) {             m_tfCounters[i] = new JTextField("0", 10);             m_tfCounters[i].setEditable(false);             m_pbCounters[i] = new JProgressBar(JProgressBar.HORIZONTAL);             m_pbCounters[i].setStringPainted(true);          }                       GridBagConstraints c = new GridBagConstraints();          c.anchor = GridBagConstraints.LINE_START;          c.gridheight = c.gridwidth = 1;              // create the label and text field for the total instruction counter          c.gridx = 2;                 c.gridy = 1;          c.insets = new Insets(0, 0, 17, 0);          panel.add(new JLabel("Total: "), c);                 c.gridx = 3;                     panel.add(m_tfTotalCounter, c);                 c.insets = new Insets(3, 3, 3, 3);              // create label, text field and progress bar for each category          for (int i=0; i < InstructionStatistics.MAX_CATEGORY; i++) {             c.gridy++;             c.gridx=2;             panel.add(new JLabel(m_categoryLabels[i] + ":   "), c);             c.gridx=3;             panel.add(m_tfCounters[i], c);             c.gridx=4;             panel.add(m_pbCounters[i], c);            }                               return panel;       }            /**     * registers the tool as observer for the text segment of the MIPS program     *      */        protected void addAsObserver() {           addAsObserver(Memory.textBaseAddress, Memory.textLimitAddress);       }            /**     * decodes the instruction and determines the category of the instruction.      *      * The instruction is decoded by extracting the operation and function code of the 32-bit instruction.      * Only the most relevant instructions are decoded and categorized.     *      * @param stmt the instruction to decode     * @return the category of the instruction     * @see InstructionStatistics#CATEGORY_ALU     * @see InstructionStatistics#CATEGORY_JUMP     * @see InstructionStatistics#CATEGORY_BRANCH      * @see InstructionStatistics#CATEGORY_MEM     * @see InstructionStatistics#CATEGORY_OTHER     */          protected int getInstructionCategory(ProgramStatement stmt) {                 int opCode = stmt.getBinaryStatement() >>> (32-6);
         int funct = stmt.getBinaryStatement() & 0x1F;
      
         if (opCode == 0x00) {          
            if (funct == 0x00 ) 
               return InstructionStatistics.CATEGORY_ALU; // sll
            if (0x02 <= funct && funct <= 0x07)                 return InstructionStatistics.CATEGORY_ALU; // srl, sra, sllv, srlv, srav             if (funct == 0x08 || funct == 0x09)                 return InstructionStatistics.CATEGORY_JUMP; // jr, jalr             if (0x10 <= funct && funct <= 0x2F)                 return InstructionStatistics.CATEGORY_ALU; // mfhi, mthi, mflo, mtlo, mult, multu, div, divu, add, addu, sub, subu, and, or, xor, nor, slt, sltu             return InstructionStatistics.CATEGORY_OTHER;                      }          if (opCode == 0x01) {             if (0x00 <= funct && funct <= 0x07)                 return InstructionStatistics.CATEGORY_BRANCH; // bltz, bgez, bltzl, bgezl             if (0x10 <= funct && funct <= 0x13)                 return InstructionStatistics.CATEGORY_BRANCH; // bltzal, bgezal, bltzall, bgczall             return InstructionStatistics.CATEGORY_OTHER;          }          if (opCode == 0x02 || opCode == 0x03)              return InstructionStatistics.CATEGORY_JUMP; // j, jal          if (0x04 <= opCode && opCode <= 0x07)              return InstructionStatistics.CATEGORY_BRANCH; // beq, bne, blez, bgtz          if (0x08 <= opCode && opCode <= 0x0F)              return InstructionStatistics.CATEGORY_ALU; // addi, addiu, slti, sltiu, andi, ori, xori, lui          if (0x14 <= opCode && opCode <= 0x17)              return InstructionStatistics.CATEGORY_BRANCH; // beql, bnel, blezl, bgtzl          if (0x20 <= opCode && opCode <= 0x26)              return InstructionStatistics.CATEGORY_MEM; // lb, lh, lwl, lw, lbu, lhu, lwr          if (0x28 <= opCode && opCode <= 0x2E)              return InstructionStatistics.CATEGORY_MEM; // sb, sh, swl, sw, swr                 return InstructionStatistics.CATEGORY_OTHER;       }             /**     * method that is called each time the MIPS simulator accesses the text segment.     * Before an instruction is executed by the simulator, the instruction is fetched from the program memory.      * This memory access is observed and the corresponding instruction is decoded and categorized by the tool.     * According to the category the counter values are increased and the display gets updated.      *      * @param resource the observed resource     * @param notice signals the type of access (memory, register etc.)     */        protected void processMIPSUpdate(Observable resource, AccessNotice notice) {                       if (!notice.accessIsFromMIPS())              return;                       // check for a read access in the text segment           if (notice.getAccessType() == AccessNotice.READ && notice instanceof MemoryAccessNotice) {                    // now it is safe to make a cast of the notice             MemoryAccessNotice memAccNotice = (MemoryAccessNotice) notice;                          // The next three statments are from Felipe Lessa's instruction counter.  Prevents double-counting.                         int a = memAccNotice.getAddress();             if (a == lastAddress)                 return;             lastAddress = a;                       try {                          // access the statement in the text segment without notifying other tools etc.                ProgramStatement stmt = Memory.getInstance().getStatementNoNotify(memAccNotice.getAddress());                          // necessary to handle possible null pointers at the end of the program              // (e.g., if the simulator tries to execute the next instruction after the last instruction in the text segment)                 if (stmt != null) {                                 int category = getInstructionCategory(stmt);                                            m_totalCounter ++;                   m_counters[category] ++;                   updateDisplay();                                  }                                             }                  catch (AddressErrorException e) {                           // silently ignore these exceptions                }                      }                 }            /**     * performs initialization tasks of the counters before the GUI is created.     *      */        protected void initializePreGUI() {          m_totalCounter = 0;              lastAddress = -1; // from Felipe Lessa's instruction counter tool          for (int i=0; i < InstructionStatistics.MAX_CATEGORY; i++)              m_counters[i] = 0;             }            /**     * resets the counter values of the tool and updates the display.     *      */        protected void reset() {          m_totalCounter = 0;              lastAddress = -1; // from Felipe Lessa's instruction counter tool          for (int i=0; i < InstructionStatistics.MAX_CATEGORY; i++)              m_counters[i] = 0;                updateDisplay();       }            /**     * updates the text fields and progress bars according to the current counter values.     *      */        protected void updateDisplay() {          m_tfTotalCounter.setText(String.valueOf(m_totalCounter));                 for (int i=0; i < InstructionStatistics.MAX_CATEGORY; i++) {             m_tfCounters[i].setText(String.valueOf(m_counters[i]));             m_pbCounters[i].setMaximum(m_totalCounter);             m_pbCounters[i].setValue(m_counters[i]);          }       }    } BitmapDisplay$2 package mars.tools; synchronized class BitmapDisplay$2 implements java.awt.event.ActionListener { void BitmapDisplay$2(BitmapDisplay); public void actionPerformed(java.awt.event.ActionEvent); } AbstractMarsToolAndApplication$7 package mars.tools; synchronized class AbstractMarsToolAndApplication$7 implements java.awt.event.ActionListener { void AbstractMarsToolAndApplication$7(AbstractMarsToolAndApplication); public void actionPerformed(java.awt.event.ActionEvent); } CacheSimulator$CacheAccessResult package mars.tools; synchronized class CacheSimulator$CacheAccessResult { private boolean hitOrMiss; private int blockNumber; public void CacheSimulator$CacheAccessResult(CacheSimulator, boolean, int); public boolean isHit(); public int getBlock(); } ScavengerHunt$PlayerData package mars.tools; synchronized class ScavengerHunt$PlayerData { int whereAmIX; int whereAmIY; int energy; int color; long finishTime; boolean[] hasVisitedLoc; boolean finis; private void ScavengerHunt$PlayerData(ScavengerHunt); public void setWhereAmI(int, int); public void setEnergy(int); public void setColor(int); public int getWhereAmIX(); public int getWhereAmIY(); public int getColor(); public boolean hasVisited(int); public void setVisited(int); public void setFinished(); public boolean isFinished(); public long getFinishTime(); public long getFinishMin(); public long getFinishSec(); public long getFinishMillisec(); public void setFinishTime(long); public int getEnergy(); } AbstractMarsToolAndApplication$5 package mars.tools; synchronized class AbstractMarsToolAndApplication$5 implements java.awt.event.ActionListener { void AbstractMarsToolAndApplication$5(AbstractMarsToolAndApplication); public void actionPerformed(java.awt.event.ActionEvent); } CacheSimulator$AbstractCache package mars.tools; abstract synchronized class CacheSimulator$AbstractCache { private int numberOfBlocks; private int blockSizeInWords; private int setSizeInBlocks; private int numberOfSets; protected CacheSimulator$CacheBlock[] blocks; protected void CacheSimulator$AbstractCache(CacheSimulator, int, int, int); public int getNumberOfBlocks(); public int getNumberOfSets(); public int getSetSizeInBlocks(); public int getBlockSizeInWords(); public int getCacheSizeInWords(); public int getCacheSizeInBytes(); public int getSetNumber(int); public int getTag(int); public int getFirstBlockToSearch(int); public int getLastBlockToSearch(int); public void reset(); public abstract CacheSimulator$CacheAccessResult isItAHitThenReadOnMiss(int); } CacheSimulator$Animation package mars.tools; synchronized class CacheSimulator$Animation { private javax.swing.Box animation; private javax.swing.JTextField[] blocks; public final java.awt.Color hitColor; public final java.awt.Color missColor; public final java.awt.Color defaultColor; public void CacheSimulator$Animation(CacheSimulator); private javax.swing.Box getAnimationBox(); public int getNumberOfBlocks(); public void showHit(int); public void showMiss(int); public void reset(); private void fillAnimationBoxWithCacheBlocks(); } CacheSimulator$1 package mars.tools; synchronized class CacheSimulator$1 implements java.awt.event.ItemListener { void CacheSimulator$1(CacheSimulator); public void itemStateChanged(java.awt.event.ItemEvent); } CacheSimulator$AnyCache package mars.tools; synchronized class CacheSimulator$AnyCache extends CacheSimulator$AbstractCache { private final int SET_FULL; private final int HIT; private final int MISS; public void CacheSimulator$AnyCache(CacheSimulator, int, int, int); public CacheSimulator$CacheAccessResult isItAHitThenReadOnMiss(int); private int selectBlockToReplace(int, int); } FloatRepresentation$HexToBinaryGraphicPanel package mars.tools; synchronized class FloatRepresentation$HexToBinaryGraphicPanel extends javax.swing.JPanel { void FloatRepresentation$HexToBinaryGraphicPanel(FloatRepresentation); public void paintComponent(java.awt.Graphics); } MagnifierImage$Scribbler package mars.tools; synchronized class MagnifierImage$Scribbler { private ScribblerSettings scribblerSettings; private java.awt.BasicStroke drawingStroke; protected int last_x; protected int last_y; void MagnifierImage$Scribbler(MagnifierImage, ScribblerSettings); public java.awt.Color getColor(); public int getLineWidth(); public void setColor(java.awt.Color); public void setLineWidth(int); private java.awt.BasicStroke getStroke(); private void setStroke(java.awt.BasicStroke); public void moveto(int, int); public void lineto(int, int, java.awt.Graphics2D); } KeyboardAndDisplaySimulator$FontChanger package mars.tools; synchronized class KeyboardAndDisplaySimulator$FontChanger implements java.awt.event.ActionListener { private void KeyboardAndDisplaySimulator$FontChanger(KeyboardAndDisplaySimulator); public void actionPerformed(java.awt.event.ActionEvent); } AbstractMarsToolAndApplication$2 package mars.tools; synchronized class AbstractMarsToolAndApplication$2 extends java.awt.event.WindowAdapter { void AbstractMarsToolAndApplication$2(AbstractMarsToolAndApplication); public void windowClosing(java.awt.event.WindowEvent); } BitmapDisplay package mars.tools; public synchronized class BitmapDisplay extends AbstractMarsToolAndApplication { private static String version; private static String heading; private javax.swing.JComboBox visualizationUnitPixelWidthSelector; private javax.swing.JComboBox visualizationUnitPixelHeightSelector; private javax.swing.JComboBox visualizationPixelWidthSelector; private javax.swing.JComboBox visualizationPixelHeightSelector; private javax.swing.JComboBox displayBaseAddressSelector; private java.awt.Graphics drawingArea; private javax.swing.JPanel canvas; private javax.swing.JPanel results; private javax.swing.border.EmptyBorder emptyBorder; private java.awt.Font countFonts; private java.awt.Color backgroundColor; private final String[] visualizationUnitPixelWidthChoices; private final int defaultVisualizationUnitPixelWidthIndex; private final String[] visualizationUnitPixelHeightChoices; private final int defaultVisualizationUnitPixelHeightIndex; private final String[] displayAreaPixelWidthChoices; private final int defaultDisplayWidthIndex; private final String[] displayAreaPixelHeightChoices; private final int defaultDisplayHeightIndex; private int unitPixelWidth; private int unitPixelHeight; private int displayAreaWidthInPixels; private int displayAreaHeightInPixels; private String[] displayBaseAddressChoices; private int[] displayBaseAddresses; private int defaultBaseAddressIndex; private int baseAddress; private BitmapDisplay$Grid theGrid; static void ();
public void BitmapDisplay(String, String);
public void BitmapDisplay();
public static void main(String[]);
public String getName();
protected void addAsObserver();
protected javax.swing.JComponent buildMainDisplayArea();
protected void processMIPSUpdate(java.util.Observable, mars.mips.hardware.AccessNotice);
protected void initializePreGUI();
protected void initializePostGUI();
protected void reset();
protected void updateDisplay();
protected javax.swing.JComponent getHelpComponent();
private javax.swing.JComponent buildOrganizationArea();
private javax.swing.JComponent buildVisualizationArea();
private void initializeDisplayBaseChoices();
private void updateBaseAddress();
private java.awt.Dimension getDisplayAreaDimension();
private void resetCounts();
private int getIntComboBoxSelection(javax.swing.JComboBox);
private javax.swing.JPanel getPanelWithBorderLayout();
private BitmapDisplay$Grid createNewGrid();
private void updateColorForAddress(mars.mips.hardware.MemoryAccessNotice);
}

AbstractMarsToolAndApplication$10

package mars.tools;
synchronized class AbstractMarsToolAndApplication$10 implements java.awt.event.ActionListener {
void AbstractMarsToolAndApplication$10(AbstractMarsToolAndApplication);
public void actionPerformed(java.awt.event.ActionEvent);
}

AbstractMarsToolAndApplication$GUIUpdater

package mars.tools;
synchronized class AbstractMarsToolAndApplication$GUIUpdater implements Runnable {
private void AbstractMarsToolAndApplication$GUIUpdater(AbstractMarsToolAndApplication);
public void run();
}

CacheSimulator$CacheBlock

package mars.tools;
synchronized class CacheSimulator$CacheBlock {
private boolean valid;
private int tag;
private int sizeInWords;
private int mostRecentAccessTime;
public void CacheSimulator$CacheBlock(CacheSimulator, int);
}

CacheSimulator$4

package mars.tools;
synchronized class CacheSimulator$4 implements java.awt.event.ActionListener {
void CacheSimulator$4(CacheSimulator);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/tools/InstructionCounter.java
mars/tools/InstructionCounter.java/*
Copyright (c) 2008,  Felipe Lessa

Developed by Felipe Lessa (felipe. )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
package mars.tools;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Observable;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;

import mars.ProgramStatement;
import mars.mips.hardware.AccessNotice;
import mars.mips.hardware.AddressErrorException;
import mars.mips.hardware.Memory;
import mars.mips.hardware.MemoryAccessNotice;
import mars.mips.instructions.BasicInstruction;
import mars.mips.instructions.BasicInstructionFormat;

/**
 * 
 * Instruction counter tool. Can be used to know how many instructions
 * were executed to complete a given program. 
 * 
 * Code slightly based on MemoryReferenceVisualization.
 * 
 * @author Felipe Lessa 
 *
 */
//@SuppressWarnings(“serial”)
public class InstructionCounter extends AbstractMarsToolAndApplication {
    private static String name    = “Instruction Counter”;
    private static String version = “Version 1.0 (Felipe Lessa)”;
    private static String heading = “Counting the number of instructions executed”;
    
    /**
     * Number of instructions executed until now.
     */
    protected int counter = 0;
    private JTextField counterField;
    
    /**
     * Number of instructions of type R.
     */
    protected int counterR = 0;
    private JTextField counterRField;
    private JProgressBar progressbarR;
    
    /**
     * Number of instructions of type I.
     */
    protected int counterI = 0;
    private JTextField counterIField;
    private JProgressBar progressbarI;
    
    /**
     * Number of instructions of type J.
     */
    protected int counterJ = 0;
    private JTextField counterJField;
    private JProgressBar progressbarJ;
    
    
    /**
     * The last address we saw. We ignore it because the only way for a
     * program to execute twice the same instruction is to enter an infinite
     * loop, which is not insteresting in the POV of counting instructions.
     */
    protected int lastAddress = -1;
    
    /**
     * Simple constructor, likely used to run a stand-alone memory reference visualizer.
     * @param title String containing title for title bar
     * @param heading String containing text for heading shown in upper part of window.
     */
    public InstructionCounter(String title, String heading) {
        super(title,heading);
    }
    
    /**
     * Simple construction, likely used by the MARS Tools menu mechanism.
     */
    public InstructionCounter() {
        super(name + “, ” + version, heading);
    }

//  @Override
    public String getName() {
        return name;
    }
    
//  @Override
    protected JComponent buildMainDisplayArea() {
        // Create everything
        JPanel panel = new JPanel(new GridBagLayout());

        counterField = new JTextField(“0”, 10);
        counterField.setEditable(false);
        
        counterRField = new JTextField(“0”, 10);
        counterRField.setEditable(false);
        progressbarR = new JProgressBar(JProgressBar.HORIZONTAL);
        progressbarR.setStringPainted(true);
        
        counterIField = new JTextField(“0”, 10);
        counterIField.setEditable(false);
        progressbarI = new JProgressBar(JProgressBar.HORIZONTAL);
        progressbarI.setStringPainted(true);
        
        counterJField = new JTextField(“0”, 10);
        counterJField.setEditable(false);
        progressbarJ = new JProgressBar(JProgressBar.HORIZONTAL);
        progressbarJ.setStringPainted(true);
        
        // Add them to the panel
        
        // Fields
        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.LINE_START;
        c.gridheight = c.gridwidth = 1;
        c.gridx = 3;
        c.gridy = 1;
        c.insets = new Insets(0, 0, 17, 0);
        panel.add(counterField, c);

        c.insets = new Insets(0, 0, 0, 0);
        c.gridy++;
        panel.add(counterRField, c);
        
        c.gridy++;
        panel.add(counterIField, c);
        
        c.gridy++;
        panel.add(counterJField, c);
        
        // Labels
        c.anchor = GridBagConstraints.LINE_END;
        c.gridx = 1;
        c.gridwidth = 2;
        c.gridy = 1;
        c.insets = new Insets(0, 0, 17, 0);
        panel.add(new JLabel(“Instructions so far: “), c);

        c.insets = new Insets(0, 0, 0, 0);
        c.gridx = 2;
        c.gridwidth = 1;
        c.gridy++;
        panel.add(new JLabel(“R-type: “), c);
        
        c.gridy++;
        panel.add(new JLabel(“I-type: “), c);
        
        c.gridy++;
        panel.add(new JLabel(“J-type: “), c);
        
        // Progress bars
        c.insets = new Insets(3, 3, 3, 3);
        c.gridx = 4;
        c.gridy = 2;
        panel.add(progressbarR, c);
        
        c.gridy++;
        panel.add(progressbarI, c);
        
        c.gridy++;
        panel.add(progressbarJ, c);
        
        return panel;
    }
    
//  @Override
    protected void addAsObserver() {
        addAsObserver(Memory.textBaseAddress, Memory.textLimitAddress);
    }

//  @Override
    protected void processMIPSUpdate(Observable resource, AccessNotice notice) {
        if (!notice.accessIsFromMIPS()) return;
        if (notice.getAccessType() != AccessNotice.READ) return;
        MemoryAccessNotice m = (MemoryAccessNotice) notice;
        int a = m.getAddress();
        if (a == lastAddress) return;
        lastAddress = a;
        counter++;
        try {
            ProgramStatement stmt = Memory.getInstance().getStatement(a);
            BasicInstruction instr = (BasicInstruction) stmt.getInstruction();
            BasicInstructionFormat format = instr.getInstructionFormat();
            if (format == BasicInstructionFormat.R_FORMAT)
                counterR++;
            else if (format == BasicInstructionFormat.I_FORMAT
                    || format == BasicInstructionFormat.I_BRANCH_FORMAT)
                counterI++;
            else if (format == BasicInstructionFormat.J_FORMAT)
                counterJ++;
        } catch (AddressErrorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        updateDisplay();
    }
    
//  @Override
    protected void initializePreGUI() {
        counter = counterR = counterI = counterJ = 0;
        lastAddress = -1;
    }
    
// @Override
    protected void reset() {
        counter = counterR = counterI = counterJ = 0;
        lastAddress = -1;       
        updateDisplay();
    }
    
//  @Override
    protected void updateDisplay() {
        counterField.setText(String.valueOf(counter));
        
        counterRField.setText(String.valueOf(counterR));
        progressbarR.setMaximum(counter);
        progressbarR.setValue(counterR);
        
        counterIField.setText(String.valueOf(counterI));
        progressbarI.setMaximum(counter);
        progressbarI.setValue(counterI);
        
        counterJField.setText(String.valueOf(counterJ));
        progressbarJ.setMaximum(counter);
        progressbarJ.setValue(counterJ);
        
        if (counter == 0) {
            progressbarR.setString(“0%”);
            progressbarI.setString(“0%”);
            progressbarJ.setString(“0%”);
        } else {
            progressbarR.setString((counterR * 100)/counter + “%”);
            progressbarI.setString((counterI * 100)/counter + “%”);
            progressbarJ.setString((counterJ * 100)/counter + “%”);
        }
    }
}

IntroToTools

package mars.tools;
public synchronized class IntroToTools extends AbstractMarsToolAndApplication {
private static String heading;
private static String version;
static void ();
public void IntroToTools(String, String);
public void IntroToTools();
public static void main(String[]);
public String getName();
protected javax.swing.JComponent buildMainDisplayArea();
}

FloatRepresentation$BinaryFractionDisplayTextField

package mars.tools;
synchronized class FloatRepresentation$BinaryFractionDisplayTextField extends javax.swing.JTextField {
public void FloatRepresentation$BinaryFractionDisplayTextField(FloatRepresentation, String, int);
public void paintComponent(java.awt.Graphics);
}

KeyboardAndDisplaySimulator$TransmitterDelayTechnique

package mars.tools;
abstract interface KeyboardAndDisplaySimulator$TransmitterDelayTechnique {
public abstract int generateDelay(double);
}

BitmapDisplay$5

package mars.tools;
synchronized class BitmapDisplay$5 implements java.awt.event.ActionListener {
void BitmapDisplay$5(BitmapDisplay);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/tools/CacheSimulator.java
mars/tools/CacheSimulator.java   package mars.tools;
   import javax.swing.*;
   import javax.swing.border.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.util.*;
    import mars.util.*;
   import mars.tools.*;
   import mars.mips.hardware.*;

/*
Copyright (c) 2003-2011,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
     * A data cache simulator.  It can be run either as a stand-alone Java application having
     * access to the mars package, or through MARS as an item in its Tools menu.  It makes
     * maximum use of methods inherited from its abstract superclass AbstractMarsToolOrApp.
     * Pete Sanderson, v 1.0: 16-18 October 2006, v 1.1: 7 November 2006. v 1.2: 23 December 2010.
     * 

Version 1.2 fixes a bug in the hit/miss animator under full or N-way set associative. It was
     * animating the block of initial access (first block of set).  Now it animates the block 
     * of final access (where address found or stored).  Also added log display to GUI (previously System.out).

     */
    public class CacheSimulator extends AbstractMarsToolAndApplication {
      private static boolean debug = false; // controls display of debugging info
      private static String version = “Version 1.2”;
      private static String heading =  “Simulate and illustrate data cache performance”;
    // Major GUI components
      private JComboBox cacheBlockSizeSelector, cacheBlockCountSelector, 
                        cachePlacementSelector, cacheReplacementSelector,
                            cacheSetSizeSelector;
      private JTextField memoryAccessCountDisplay, cacheHitCountDisplay, cacheMissCountDisplay,
                         replacementPolicyDisplay,cachableAddressesDisplay,
                             cacheSizeDisplay;
      private JProgressBar cacheHitRateDisplay;
      private Animation animations;
    
      private JPanel logPanel;
      private JScrollPane logScroll;
      private JTextArea logText;
      private JCheckBox logShow;
    
    // Some GUI settings
      private EmptyBorder emptyBorder = new EmptyBorder(4,4,4,4);
      private Font countFonts = new Font(“Times”, Font.BOLD,12);
      private Color backgroundColor = Color.WHITE;
    
    // Values for Combo Boxes
      private int[] cacheBlockSizeChoicesInt, cacheBlockCountChoicesInt;
      private String[] cacheBlockSizeChoices  = {“1″,”2″,”4″,”8″,”16″,”32″,”64″,”128″,”256″,”512″,”1024″,”2048”};
      private String[] cacheBlockCountChoices = {“1″,”2″,”4″,”8″,”16″,”32″,”64″,”128″,”256″,”512″,”1024″,”2048”};
      private String[] placementPolicyChoices = {“Direct Mapping”, “Fully Associative”, “N-way Set Associative” };
      private final int DIRECT = 0, FULL = 1, SET = 2; // NOTE: these have to match placementPolicyChoices order!
      private String[] replacementPolicyChoices =  {“LRU”,”Random”};
      private final int LRU = 0, RANDOM = 1; // NOTE: these have to match replacementPolicyChoices order!
      private String[] cacheSetSizeChoices; // will change dynamically based on the other selections
      private int defaultCacheBlockSizeIndex    = 2;
      private int defaultCacheBlockCountIndex   = 3;
      private int defaultPlacementPolicyIndex   = DIRECT;
      private int defaultReplacementPolicyIndex = LRU;
      private int defaultCacheSetSizeIndex      = 0;
    
    // Cache-related data structures
      private AbstractCache theCache;               
      private int memoryAccessCount, cacheHitCount, cacheMissCount;
      private double cacheHitRate;
      
    // RNG used for random replacement policy.  For testing, set seed for reproducible stream
      private Random randu = new Random(0);  
    
    /**
     * Simple constructor, likely used to run a stand-alone cache simulator.
     * @param title String containing title for title bar
     * @param heading String containing text for heading shown in upper part of window.
     */
       public CacheSimulator(String title, String heading) {
         super(title,heading);
      }
     
     /**
      *  Simple constructor, likely used by the MARS Tools menu mechanism
      */
       public CacheSimulator() {
         super (“Data Cache Simulation Tool, “+version, heading);
      }
         
         
    /**
     * Main provided for pure stand-alone use.  Recommended stand-alone use is to write a 
     * driver program that instantiates a CacheSimulator object then invokes its go() method.
     * “stand-alone” means it is not invoked from the MARS Tools menu.  “Pure” means there
     * is no driver program to invoke the Cache Simulator.
     */
       public static void main(String[] args) {
         new CacheSimulator(“Data Cache Simulator stand-alone, “+version,heading).go();
      }
    
   
       /**
      *  Required MarsTool method to return Tool name.  
      *  @return  Tool name.  MARS will display this in menu item.
      */
       public String getName() {
         return “Data Cache Simulator”;
      }
    
      
    /**
     *  Method that constructs the main cache simulator display area.  It is organized vertically
     *  into three major components: the cache configuration which an be modified
     *  using combo boxes, the cache performance which is updated as the
     *  attached MIPS program executes, and the runtime log which is optionally used 
         *  to display log of each cache access.
     *  @return the GUI component containing these three areas
     */
       protected JComponent buildMainDisplayArea() {
        // OVERALL STRUCTURE OF MAIN UI (CENTER)
         Box results = Box.createVerticalBox();
         results.add(buildOrganizationArea());
         results.add(buildPerformanceArea());
         results.add(buildLogArea());
         return results;
      }
    
    ////////////////////////////////////////////////////////////////////////////
       private JComponent buildLogArea() {
         logPanel = new JPanel();
         TitledBorder ltb =new TitledBorder(“Runtime Log”);
         ltb.setTitleJustification(TitledBorder.CENTER);
         logPanel.setBorder(ltb);
            logShow = new JCheckBox(“Enabled”,debug);
         logShow.addItemListener(
                new ItemListener() {
                   public void itemStateChanged(ItemEvent e) { 
                           debug = e.getStateChange() == ItemEvent.SELECTED;
                            resetLogDisplay();
                            logText.setEnabled(debug);
                            logText.setBackground( debug ? Color.WHITE : logPanel.getBackground() );
                  }
               });
            logPanel.add(logShow);
         logText = new JTextArea(5,70);
            logText.setEnabled(debug);
            logText.setBackground( debug ? Color.WHITE : logPanel.getBackground() );
            logText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
            logText.setToolTipText(“Displays cache activity log if enabled”);
         logScroll = new JScrollPane(logText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         logPanel.add(logScroll);
         return logPanel;
      }
   
   
    ////////////////////////////////////////////////////////////////////////////
       private JComponent buildOrganizationArea() {
         JPanel organization = new JPanel(new GridLayout(3,2));
         TitledBorder otb =new TitledBorder(“Cache Organization”);
         otb.setTitleJustification(TitledBorder.CENTER);
         organization.setBorder(otb);
         cachePlacementSelector = new JComboBox(placementPolicyChoices);
         cachePlacementSelector.setEditable(false);
         cachePlacementSelector.setBackground(backgroundColor);
         cachePlacementSelector.setSelectedIndex(defaultPlacementPolicyIndex);
         cachePlacementSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     updateCacheSetSizeSelector();
                     reset();
                  }
               });  
        
         cacheReplacementSelector = new JComboBox(replacementPolicyChoices);
         cacheReplacementSelector.setEditable(false);
         cacheReplacementSelector.setBackground(backgroundColor);
         cacheReplacementSelector.setSelectedIndex(defaultReplacementPolicyIndex);
                                    
         cacheBlockSizeSelector = new JComboBox(cacheBlockSizeChoices);
         cacheBlockSizeSelector.setEditable(false);
         cacheBlockSizeSelector.setBackground(backgroundColor);
         cacheBlockSizeSelector.setSelectedIndex(defaultCacheBlockSizeIndex);
         cacheBlockSizeSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     updateCacheSizeDisplay();
                     reset();
                  }
               });
         cacheBlockCountSelector = new JComboBox(cacheBlockCountChoices);
         cacheBlockCountSelector.setEditable(false);
         cacheBlockCountSelector.setBackground(backgroundColor);
         cacheBlockCountSelector.setSelectedIndex(defaultCacheBlockCountIndex);
         cacheBlockCountSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     updateCacheSetSizeSelector();
                     theCache = createNewCache();
                     resetCounts();
                     updateDisplay();
                     updateCacheSizeDisplay();
                     animations.fillAnimationBoxWithCacheBlocks();
                  }
               });          
      
         cacheSetSizeSelector = new JComboBox(cacheSetSizeChoices);
         cacheSetSizeSelector.setEditable(false);
         cacheSetSizeSelector.setBackground(backgroundColor);
         cacheSetSizeSelector.setSelectedIndex(defaultCacheSetSizeIndex);
         cacheSetSizeSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     reset();
                  }
               });
                      
         // ALL COMPONENTS FOR “CACHE ORGANIZATION” SECTION
         JPanel placementPolicyRow = getPanelWithBorderLayout();
         placementPolicyRow.setBorder(emptyBorder);
         placementPolicyRow.add(new JLabel(“Placement Policy “),BorderLayout.WEST);
         placementPolicyRow.add(cachePlacementSelector,BorderLayout.EAST);
      
         JPanel replacementPolicyRow = getPanelWithBorderLayout();
         replacementPolicyRow.setBorder(emptyBorder);
         replacementPolicyRow.add(new JLabel(“Block Replacement Policy “),BorderLayout.WEST);
      /*       replacementPolicyDisplay = new JTextField(“N/A”,6);
         replacementPolicyDisplay.setEditable(false);
         replacementPolicyDisplay.setBackground(backgroundColor);
         replacementPolicyDisplay.setHorizontalAlignment(JTextField.RIGHT); */
         replacementPolicyRow.add(cacheReplacementSelector, BorderLayout.EAST);
      
         JPanel cacheSetSizeRow = getPanelWithBorderLayout();
         cacheSetSizeRow.setBorder(emptyBorder);
         cacheSetSizeRow.add(new JLabel(“Set size (blocks) “),BorderLayout.WEST);
         cacheSetSizeRow.add(cacheSetSizeSelector,BorderLayout.EAST);
                    
      // Cachable address range “selection” removed for now…
      /*
         JPanel cachableAddressesRow = getPanelWithBorderLayout();
         cachableAddressesRow.setBorder(emptyBorder);
         cachableAddressesRow.add(new JLabel(“Cachable Addresses “),BorderLayout.WEST);
         cachableAddressesDisplay = new JTextField(“all data segment”);
         cachableAddressesDisplay.setEditable(false);
         cachableAddressesDisplay.setBackground(backgroundColor);
         cachableAddressesDisplay.setHorizontalAlignment(JTextField.RIGHT);
         cachableAddressesRow.add(cachableAddressesDisplay, BorderLayout.EAST);
      */
         JPanel cacheNumberBlocksRow = getPanelWithBorderLayout();
         cacheNumberBlocksRow.setBorder(emptyBorder);
         cacheNumberBlocksRow.add(new JLabel(“Number of blocks “), BorderLayout.WEST);
         cacheNumberBlocksRow.add(cacheBlockCountSelector, BorderLayout.EAST);
        
         JPanel cacheBlockSizeRow = getPanelWithBorderLayout();
         cacheBlockSizeRow.setBorder(emptyBorder);
         cacheBlockSizeRow.add(new JLabel(“Cache block size (words) “), BorderLayout.WEST);
         cacheBlockSizeRow.add(cacheBlockSizeSelector, BorderLayout.EAST);
        
         JPanel cacheTotalSizeRow = getPanelWithBorderLayout();
         cacheTotalSizeRow.setBorder(emptyBorder);
         cacheTotalSizeRow.add(new JLabel(“Cache size (bytes) “), BorderLayout.WEST);
         cacheSizeDisplay = new JTextField(8);
         cacheSizeDisplay.setHorizontalAlignment(JTextField.RIGHT);
         cacheSizeDisplay.setEditable(false);
         cacheSizeDisplay.setBackground(backgroundColor);
         cacheSizeDisplay.setFont(countFonts);
         cacheTotalSizeRow.add(cacheSizeDisplay, BorderLayout.EAST);
         updateCacheSizeDisplay();
        
        // Lay ’em out in the grid…
         organization.add(placementPolicyRow);
         organization.add(cacheNumberBlocksRow);
         organization.add(replacementPolicyRow);
         organization.add(cacheBlockSizeRow);
         //organization.add(cachableAddressesRow);
         organization.add(cacheSetSizeRow); 
         organization.add(cacheTotalSizeRow);      
         return organization;
      }
    
    
    ////////////////////////////////////////////////////////////////////////////
       private JComponent buildPerformanceArea() {
         JPanel performance = new JPanel(new GridLayout(1,2));
         TitledBorder ptb =new TitledBorder(“Cache Performance”);
         ptb.setTitleJustification(TitledBorder.CENTER);
         performance.setBorder(ptb);
         JPanel memoryAccessCountRow = getPanelWithBorderLayout();
         memoryAccessCountRow.setBorder(emptyBorder);
         memoryAccessCountRow.add(new JLabel(“Memory Access Count “), BorderLayout.WEST);
         memoryAccessCountDisplay = new JTextField(10);
         memoryAccessCountDisplay.setHorizontalAlignment(JTextField.RIGHT);
         memoryAccessCountDisplay.setEditable(false);
         memoryAccessCountDisplay.setBackground(backgroundColor);
         memoryAccessCountDisplay.setFont(countFonts);
         memoryAccessCountRow.add(memoryAccessCountDisplay, BorderLayout.EAST);
      
         JPanel cacheHitCountRow = getPanelWithBorderLayout();
         cacheHitCountRow.setBorder(emptyBorder);
         cacheHitCountRow.add(new JLabel(“Cache Hit Count “), BorderLayout.WEST);
         cacheHitCountDisplay = new JTextField(10);
         cacheHitCountDisplay.setHorizontalAlignment(JTextField.RIGHT);
         cacheHitCountDisplay.setEditable(false);
         cacheHitCountDisplay.setBackground(backgroundColor);
         cacheHitCountDisplay.setFont(countFonts);
         cacheHitCountRow.add(cacheHitCountDisplay, BorderLayout.EAST);
      
         JPanel cacheMissCountRow = getPanelWithBorderLayout();
         cacheMissCountRow.setBorder(emptyBorder);
         cacheMissCountRow.add(new JLabel(“Cache Miss Count “), BorderLayout.WEST);
         cacheMissCountDisplay = new JTextField(10);
         cacheMissCountDisplay.setHorizontalAlignment(JTextField.RIGHT);
         cacheMissCountDisplay.setEditable(false);
         cacheMissCountDisplay.setBackground(backgroundColor);
         cacheMissCountDisplay.setFont(countFonts);
         cacheMissCountRow.add(cacheMissCountDisplay, BorderLayout.EAST);   
      
         JPanel cacheHitRateRow = getPanelWithBorderLayout();
         cacheHitRateRow.setBorder(emptyBorder);
         cacheHitRateRow.add(new JLabel(“Cache Hit Rate “), BorderLayout.WEST);
         cacheHitRateDisplay = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
         cacheHitRateDisplay.setStringPainted(true);
         cacheHitRateDisplay.setForeground(Color.BLUE);
         cacheHitRateDisplay.setBackground(backgroundColor);
         cacheHitRateDisplay.setFont(countFonts);
         cacheHitRateRow.add(cacheHitRateDisplay, BorderLayout.EAST); 
      
         resetCounts();
         updateDisplay();
      
         // Vertically align these 4 measures in a grid, then add to left column of main grid.
         JPanel performanceMeasures = new JPanel(new GridLayout(4,1));
         performanceMeasures.add(memoryAccessCountRow);
         performanceMeasures.add(cacheHitCountRow);
         performanceMeasures.add(cacheMissCountRow);
         performanceMeasures.add(cacheHitRateRow);
         performance.add(performanceMeasures);
        
        // LET’S TRY SOME ANIMATION ON THE RIGHT SIDE…
         animations = new Animation();
         animations.fillAnimationBoxWithCacheBlocks();
         JPanel animationsPanel = new JPanel(new GridLayout(1,2));
         Box animationsLabel = Box.createVerticalBox();
         JPanel tableTitle1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
         JPanel tableTitle2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
         tableTitle1.add(new JLabel(“Cache Block Table”));
         tableTitle2.add(new JLabel(“(block 0 at top)”));
         animationsLabel.add(tableTitle1);
         animationsLabel.add(tableTitle2);
         Dimension colorKeyBoxSize = new Dimension(8,8);
        
         JPanel emptyKey = new JPanel(new FlowLayout(FlowLayout.LEFT));
         JPanel emptyBox = new JPanel();
         emptyBox.setSize(colorKeyBoxSize);
         emptyBox.setBackground(animations.defaultColor);
         emptyBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));
         emptyKey.add(emptyBox);
         emptyKey.add(new JLabel(” = empty”));
        
         JPanel missBox = new JPanel();
         JPanel missKey = new JPanel(new FlowLayout(FlowLayout.LEFT));
         missBox.setSize(colorKeyBoxSize);
         missBox.setBackground(animations.missColor);
         missBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));
         missKey.add(missBox);
         missKey.add(new JLabel(” = miss”));   
      
         JPanel hitKey = new JPanel(new FlowLayout(FlowLayout.LEFT));     
         JPanel hitBox = new JPanel();     
         hitBox.setSize(colorKeyBoxSize);
         hitBox.setBackground(animations.hitColor);
         hitBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));   
         hitKey.add(hitBox);
         hitKey.add(new JLabel(” = hit”));
        
         animationsLabel.add(emptyKey);
         animationsLabel.add(hitKey);
         animationsLabel.add(missKey);
         animationsLabel.add(Box.createVerticalGlue());
         animationsPanel.add(animationsLabel);
         animationsPanel.add(animations.getAnimationBox());
      
         performance.add(animationsPanel); 
         return performance;     
      }
   
   
   
      //////////////////////////////////////////////////////////////////////////////////////
      //  Rest of the protected methods.  These override do-nothing methods inherited from
    //  the abstract superclass.
      //////////////////////////////////////////////////////////////////////////////////////
    
      /**
     * Apply caching policies and update display when connected MIPS program accesses (data) memory.
     * @param memory the attached memory
     * @param accessNotice information provided by memory in MemoryAccessNotice object
     */
       protected void processMIPSUpdate(Observable memory, AccessNotice accessNotice) {
         MemoryAccessNotice notice = (MemoryAccessNotice) accessNotice;
         memoryAccessCount++;
         CacheAccessResult cacheAccessResult = theCache.isItAHitThenReadOnMiss(notice.getAddress());
         if (cacheAccessResult.isHit()) {
            cacheHitCount++;
            animations.showHit(cacheAccessResult.getBlock());
         } 
         else {
            cacheMissCount++;
            animations.showMiss(cacheAccessResult.getBlock());
         }
         cacheHitRate = cacheHitCount / (double)memoryAccessCount;
      }
    
   
    /** 
     *  Initialize all JComboBox choice structures not already initialized at declaration.  
       *  Also creates initial default cache object. Overrides inherited method that does nothing.
     */
       protected void initializePreGUI() {
         cacheBlockSizeChoicesInt = new int[cacheBlockSizeChoices.length];
         for (int i=0; itotalVerticalPixels)? 1 : totalVerticalPixels/numberOfBlocks;
            int blockPixelWidth = 40;
            Dimension blockDimension = new Dimension(blockPixelWidth, blockPixelHeight);
            blocks = new JTextField[numberOfBlocks];
            for (int i=0; i North (up), 90 –> East (right), etc.
      private boolean MarsBotLeaveTrack = false; // true –> leave track when moving, false –> do not …
      private double MarsBotXPosition = 0; // X pixel position of MarsBot
      private double MarsBotYPosition = 0; // Y pixel position of MarsBot
      private boolean MarsBotMoving = false; // true –> MarsBot is moving, false –> MarsBot not moving
   
    // The begin and end points of a “track” segment are kept in neighboring pairs
    // of elements of the array. arrayOfTrack[i] is the start pt, arrayOfTrack[i+1] is
    // the end point of a path that should leave a track.
      private final int trackPts = 256;  // TBD Hardcoded. Array contains start-end points for segments in track.
      private Point[] arrayOfTrack = new Point[trackPts];
      private int trackIndex = 0;
   
    // private inner class
       private class BotRunnable implements Runnable
      {
         JPanel panel;
          public BotRunnable() // constructor
         {
            final JFrame frame = new JFrame(“Bot”);
            panel = new JPanel(new BorderLayout());
            graphicArea = new MarsBotDisplay(GRAPHIC_WIDTH, GRAPHIC_HEIGHT);
            JPanel buttonPanel = new JPanel();
            JButton clearButton = new JButton(“Clear”);
            clearButton.addActionListener(
                   new ActionListener()
                  {
                      public void actionPerformed(ActionEvent e)
                     {
                        graphicArea.clear();
                        MarsBotLeaveTrack = false; // true –> leave track when moving, false –> do not …
                        MarsBotXPosition = 0; // X pixel position of MarsBot
                        MarsBotYPosition = 0; // Y pixel position of MarsBot
                        MarsBotMoving = false; // true –> MarsBot is moving, false –> MarsBot not moving
                     
                        trackIndex = 0;
                     
                     }
                  
                  });
            buttonPanel.add(clearButton);
            JButton closeButton = new JButton(“Close”);
            closeButton.addActionListener(
                   new ActionListener()
                  {
                      public void actionPerformed(ActionEvent e)
                     {
                        frame.setVisible(false);
                     
                     }
                  
                  });
            buttonPanel.add(closeButton);
            panel.add(graphicArea, BorderLayout.CENTER);
            panel.add(buttonPanel, BorderLayout.SOUTH);
            frame.getContentPane().add(panel);
            frame.pack();
            frame.setVisible(true);
            frame.setTitle(” This is the MarsBot”);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // changed 12/12/09 DPS (was EXIT)
            frame.setSize(GRAPHIC_WIDTH + 200, GRAPHIC_HEIGHT + 100); // TBD  SIZE
            frame.setVisible(true); // show();
         
         } // end BotRunnable() constructor
      
          public void run()
         {
         
            double tempAngle;
            // infinite loop: move the bot according to the current directives
            // (which may be to NOT move)
            do
            {
               if (MarsBotMoving)
               {
                    //System.out.println(“BotRunnable.run: bot IS moving.”);
                    // TBD This is an arbitrary distance for bot movement. This could just
                    // as easily be a random distance to simulate terrain, etc.
                    // adjust bot position.
                    // The “mathematical angle” is zero at east, 90 at north, etc.
                    // The “heading” is 0 at north, 90 at east, etc.
                    // Conversion: MathAngle = [(360 – heading) + 90] mod 360
                  tempAngle = ((360 – MarsBotHeading) + 90) % 360;
                  MarsBotXPosition += Math.cos(Math.toRadians(tempAngle)); // Math.cos parameter unit is radians
                  MarsBotYPosition += -Math.sin(Math.toRadians(tempAngle)); // Negate value because Y coord grows down
               
                    // Write this new information to MARS memory area
                  try
                  {
                     Globals.memory.setWord(ADDR_WHEREAREWEX, (int) MarsBotXPosition);
                     Globals.memory.setWord(ADDR_WHEREAREWEY, (int) MarsBotYPosition);
                  
                  }
                      catch ( AddressErrorException e)
                     {
                        // TBD TBD TBD No action
                     }
                    
                    //System.out.println(” ——- Heading is ” + MarsBotHeading + “, angle is ” + tempAngle);
                    //System.out.println(” ——- New X,Y is (” + MarsBotXPosition + “,” + MarsBotYPosition + “)” );
               
                    // Whether or not we’re leaving a track, write the current point to the
                    // current position in the array.
                    //   — If we are not leaving a track now, we will need the current point to
                    //      start a future track, and that goes into the array.
                    //   — If we are leaving a track now, the current point may end the track,
                    //      and that goes into the array.
                  arrayOfTrack[trackIndex] = new Point((int)MarsBotXPosition, (int)MarsBotYPosition);
               
               } 
               else
               {
                    // Action for if the MarsBot isn’t moving
                    // System.out.println(“BotRunnable.run: bot is not moving.”);
               }
            
                // TBD Pause whether the bot is or is not moving. This gives the MIPS program
                // opportunity to consider results of movement, or to make the bot move.
                // ??? What is relationship of robot speed to MARS’s
                // execution time for a single instruction? Does the robot speed have to
                // be slow enough to allow a MARS busy loop to detect the bot position
                // at a specific pixel?
               try
               {
                    //System.out.println(” Hello from the bot runner”);
                  Thread.sleep(40);
               }
                   catch (InterruptedException exception)
                  {// no action
                  }
                
               panel.repaint(); // show new bot position
            } while (true);
         
         } // end run method of BotRunnable class
      
      } // end BotRunnable class
   
    /* ————————————————————————- */
       private class MarsBotDisplay extends JPanel
      {
         private int width;
         private int height;
         private boolean clearTheDisplay = true;
        
      
          public MarsBotDisplay(int tw, int th)
         {
            width = tw;
            height = th;
         
         }
      
          public void redraw()
         {
            repaint();
         }
      
          public void clear()
         {
            // clear the graphic display
            clearTheDisplay = true;
            //System.out.println(“MarsBotDisplay.clear: called to clear the display”);
            repaint();
         }
      
          public void paintComponent(Graphics g)
         {
            long tempN;
            // System.out.println(“MarsBotDisplay.paintComponent: I’m painting! n is ” + n);
         
         
            // Recover Graphics2D
            Graphics2D g2 = (Graphics2D) g;
            
            /*
            if (clearTheDisplay)
            {
                g2.setColor(Color.lightGray);
                g2.fillRect(0, 0, width – 1, height – 1); // Clear all previous drawn information
                clearTheDisplay = false;
            }
            */
         
            // Draw the track left behind, for each segment of the path
            g2.setColor(Color.blue);
            for (int i = 1; i <= trackIndex; i += 2) // Index grows by two (begin-end pair)             {                //System.out.print(".");                try                {                   g2.drawLine((int)arrayOfTrack[i-1].getX(), (int)arrayOfTrack[i-1].getY(),                              (int)arrayOfTrack[i].getX(), (int)arrayOfTrack[i].getY() );                }                    catch (ArrayIndexOutOfBoundsException e)                   {                   // No action   TBD sloppy                   }                    catch (NullPointerException e)                   {                   // No action   TBD sloppy                   }             }                       g2.setColor(Color.black);             g2.fillRect((int) MarsBotXPosition, (int) MarsBotYPosition, 20, 20); // Draw bot at its current position                       /*              g2.setColor(Color.blue);              g2.setFont(new Font(g2.getFont().getName(), g2.getFont().getStyle(), 20) );  // same font and style in larger size              g2.drawOval( width/2 - 30,  // TBD Hardcoded oval size              height/2 - 30,              60,              60);              g2.drawString(" " + n, width/2, height/2);              */                              }              } // end private inner class MarsBotDisplay         /* ------------------------------------------------------------------------- */                public String getName()       {          return "Mars Bot";       }         /*      * This will set up the Bot's GUI.  Invoked when Bot menu item selected.      */        public void action()       {          BotRunnable br1 = new BotRunnable();          Thread t1 = new Thread(br1);          t1.start();         // New: DPS 27 Feb 2006.  Register observer for memory subrange.          try {             Globals.memory.addObserver(this,0xffff8000,0xffff8060);          }               catch (AddressErrorException aee) {                 System.out.println(aee);             }        }         /*      * This method observes MIPS program directives to modify Bot activity (that is,      * MIPS program write to MMIO) and updates instance variables to reflect that      * directive.      */        public void update(Observable o, Object arg)       {          MemoryAccessNotice notice;          int address;          if (arg instanceof MemoryAccessNotice)          {             notice = (MemoryAccessNotice) arg;             address = notice.getAddress();             if (address < 0 && notice.getAccessType() == AccessNotice.WRITE)             {                String message = "";                if (address == ADDR_HEADING)                {                   message = "MarsBot.update: got move heading value: ";                   MarsBotHeading = notice.getValue();                     //System.out.println(message + notice.getValue() );                }                else if (address == ADDR_LEAVETRACK)                {                   message = "MarsBot.update: got leave track directive value ";                                          // If we HAD NOT been leaving a track, but we should NOW leave                     // a track, put start point into array.                   if (MarsBotLeaveTrack == false && notice.getValue() == 1)                   {                      MarsBotLeaveTrack = true;                      arrayOfTrack[trackIndex] = new Point((int) MarsBotXPosition, (int) MarsBotYPosition);                      trackIndex++;  // the index of the end point                   }                     // If we HAD NOT been leaving a track, and get another directive                     // to NOT leave a track, do nothing (nothing to do).                   else if (MarsBotLeaveTrack == false && notice.getValue() == 0)                   {                       // NO ACTION                   }                     // If we HAD been leaving a track, and get another directive                     // to LEAVE a track, do nothing (nothing to do).                   else if (MarsBotLeaveTrack == true && notice.getValue() == 1)                   {                       // NO ACTION                   }                     // If we HAD been leaving a track, and get another directive                     // to NOT leave a track, put end point into array.                   else if (MarsBotLeaveTrack == true && notice.getValue() == 0)                   {                      MarsBotLeaveTrack = false;                      arrayOfTrack[trackIndex] = new Point((int) MarsBotXPosition, (int) MarsBotYPosition);                      trackIndex++;  // the index of the next start point                   }                                     //System.out.println("MarsBotDisplay.paintComponent: putting point in track array at " + trackIndex);                                     //System.out.println(message + notice.getValue() );                }                else if (address == ADDR_MOVE)                {                   message = "MarsBot.update: got move control value: ";                   if (notice.getValue() == 0) MarsBotMoving = false;                   else MarsBotMoving = true;                     //System.out.println(message + notice.getValue() );                }                else if (address == ADDR_WHEREAREWEX ||                          address == ADDR_WHEREAREWEY)                {                   // Ignore these memory writes, because the writes originated within                   // this tool. This tool is being notified of the writes in the usual                   // manner, but the writes are already known to this tool.                   // NO ACTION                }                else                {                     //message = "MarsBot.update: HEY!!! unknown address of " + Integer.toString(address) + ", value: ";                     //System.out.println(message + notice.getValue() );                }                          }          }              }        } MarsTool package mars.tools; public abstract interface MarsTool { public abstract String getName(); public abstract void action(); } AbstractMarsToolAndApplication$4 package mars.tools; synchronized class AbstractMarsToolAndApplication$4 implements java.awt.event.ActionListener { void AbstractMarsToolAndApplication$4(AbstractMarsToolAndApplication); public void actionPerformed(java.awt.event.ActionEvent); } BitmapDisplay$1 package mars.tools; synchronized class BitmapDisplay$1 implements java.awt.event.ActionListener { void BitmapDisplay$1(BitmapDisplay); public void actionPerformed(java.awt.event.ActionEvent); } CaptureDisplayAlignmentStrategy package mars.tools; abstract interface CaptureDisplayAlignmentStrategy { public abstract void setScrollBarValue(javax.swing.JScrollBar); } InstructionStatistics package mars.tools; public synchronized class InstructionStatistics extends AbstractMarsToolAndApplication { private static String NAME; private static String VERSION; private static String HEADING; private static final int MAX_CATEGORY = 5; private static final int CATEGORY_ALU = 0; private static final int CATEGORY_JUMP = 1; private static final int CATEGORY_BRANCH = 2; private static final int CATEGORY_MEM = 3; private static final int CATEGORY_OTHER = 4; private javax.swing.JTextField m_tfTotalCounter; private javax.swing.JTextField[] m_tfCounters; private javax.swing.JProgressBar[] m_pbCounters; private int m_totalCounter; private int[] m_counters; private String[] m_categoryLabels; protected int lastAddress; static void ();
public void InstructionStatistics(String, String);
public void InstructionStatistics();
public String getName();
protected javax.swing.JComponent buildMainDisplayArea();
protected void addAsObserver();
protected int getInstructionCategory(mars.ProgramStatement);
protected void processMIPSUpdate(java.util.Observable, mars.mips.hardware.AccessNotice);
protected void initializePreGUI();
protected void reset();
protected void updateDisplay();
}

FloatRepresentation$DecimalDisplayKeystokeListenter

package mars.tools;
synchronized class FloatRepresentation$DecimalDisplayKeystokeListenter extends java.awt.event.KeyAdapter {
private void FloatRepresentation$DecimalDisplayKeystokeListenter(FloatRepresentation);
public void keyTyped(java.awt.event.KeyEvent);
public void keyPressed(java.awt.event.KeyEvent);
private boolean isDecimalFloatDigit(char);
}

DigitalLabSim$SevenSegmentPanel

package mars.tools;
public synchronized class DigitalLabSim$SevenSegmentPanel extends javax.swing.JPanel {
public DigitalLabSim$SevenSegmentDisplay[] display;
public void DigitalLabSim$SevenSegmentPanel(DigitalLabSim);
public void modifyDisplay(int, char);
public void resetSevenSegment();
}

KeyboardAndDisplaySimulator$1

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$1 implements java.awt.event.ActionListener {
void KeyboardAndDisplaySimulator$1(KeyboardAndDisplaySimulator, String);
public void actionPerformed(java.awt.event.ActionEvent);
}

FloatRepresentation$BinaryDisplayKeystrokeListener

package mars.tools;
synchronized class FloatRepresentation$BinaryDisplayKeystrokeListener extends java.awt.event.KeyAdapter {
private int bitLength;
public void FloatRepresentation$BinaryDisplayKeystrokeListener(FloatRepresentation, int);
public void keyTyped(java.awt.event.KeyEvent);
public void keyPressed(java.awt.event.KeyEvent);
private boolean isBinaryDigit(char);
}

KeyboardAndDisplaySimulator$NormallyDistributedDelay

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$NormallyDistributedDelay implements KeyboardAndDisplaySimulator$TransmitterDelayTechnique {
java.util.Random randn;
public void KeyboardAndDisplaySimulator$NormallyDistributedDelay(KeyboardAndDisplaySimulator);
public String toString();
public int generateDelay(double);
}

KeyboardAndDisplaySimulator$DelayLengthPanel$DelayLengthListener

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$DelayLengthPanel$DelayLengthListener implements javax.swing.event.ChangeListener {
private void KeyboardAndDisplaySimulator$DelayLengthPanel$DelayLengthListener(KeyboardAndDisplaySimulator$DelayLengthPanel);
public void stateChanged(javax.swing.event.ChangeEvent);
}

SettingsDialog

package mars.tools;
synchronized class SettingsDialog extends javax.swing.JDialog {
javax.swing.JButton applyButton;
javax.swing.JButton cancelButton;
javax.swing.JCheckBox captureResizeCheckBox;
javax.swing.JCheckBox captureMoveCheckBox;
javax.swing.JCheckBox captureRescaleCheckBox;
javax.swing.JRadioButton captureDisplayCenteredButton;
javax.swing.JRadioButton captureDisplayUpperleftButton;
Integer[] scribblerLineWidthSettings;
javax.swing.JComboBox lineWidthSetting;
javax.swing.JButton lineColorSetting;
javax.swing.JCheckBox dialogCentered;
javax.swing.JDialog dialog;
java.awt.Color scribblerLineColorSetting;
static final String SETTINGS_APPLY_TOOLTIP_TEXT = Apply current settings and close the dialog.;
static final String SETTINGS_CANCEL_TOOLTIP_TEXT = Close the dialog without applying any setting changes.;
static final String SETTINGS_SCRIBBLER_WIDTH_TOOLTIP_TEXT = Scribbler line thickness in pixels.;
static final String SETTINGS_SCRIBBLER_COLOR_TOOLTIP_TEXT = Click here to change Scribbler line color.;
static final String SETTINGS_DIALOG_CENTERED_TOOLTIP_TEXT = Whether to center this dialog over the Magnifier.;
void SettingsDialog(javax.swing.JFrame);
private javax.swing.JPanel getButtonRowPanel();
private javax.swing.JPanel getAutomaticCaptureSettingsPanel();
private javax.swing.JPanel getCaptureDisplayPanel();
private javax.swing.JPanel getScribblerPanel(javax.swing.JDialog);
}

mars/tools/ScreenMagnifier.java
mars/tools/ScreenMagnifier.java   package mars.tools;

   import java.text.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.awt.image.*;
   import java.awt.geom.*;
   import javax.swing.*;
   import javax.swing.event.*;
   import javax.swing.border.*;
    
    /*
Copyright (c) 2003-2007,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 *  Handy little tool to magnify a selected section of the screen
 *  by a given scale and display it.  The screen image snapshot 
 *  will be of the screen pixels beneath the tool’s frame.  The
 *  scale can be adjusted.  The image is displayed in the tool’s
 *  scrollable panel.  You can highlight items on the image using
 *  the scribbler (hold down mouse button and move it on the
 *  image).  The magnification scale adjustment is on the tool’s
 *  window, but other settings can be modified on a button-
 *  triggered dialog.  It will capture the contents of the
 *  underlying MARS graphical user interface, but NOT the
 *  contents of other Mars Tools frames.
 *  @author Pete Sanderson
 *  @version 1.0.
 *  9 July 2007.
 */
    public class ScreenMagnifier implements MarsTool {
   
       public String getName() {
         return “Screen Magnifier”;
      }
   
       public void action() {
         Magnifier mag = new Magnifier();
      }
    
    // Permits stand-alone execution.
    
       public static void main(String[] args) {
         new Thread(
                new Runnable() {
                   public void run() {
                     new ScreenMagnifier().action();
                  }
               }).start();
      }
    
   
   }
/* Technique comes from the Javaworld article “Capture the Screen: Build a 
   screen-capture utility based on Java’s Robot class”.  By Jeff Friesen, 
    JavaWorld.com, 4/24/06.
   http://www.javaworld.com/javaworld/jw-04-2006/jw-0424-funandgames.html
*/

    class Magnifier extends JFrame implements ComponentListener {
      static Robot robot;
      JButton close, capture, settings;
      JSpinner scaleAdjuster;
      JScrollPane view;
      Dimension frameSize;
      Dimension viewSize;
      MagnifierImage magnifierImage;
      ActionListener captureActionListener;
      CaptureModel captureResize, captureMove, captureRescale;
      CaptureModel captureDisplayCenter, captureDisplayUpperleft;
      CaptureModel dialogDisplayCenter;
      ScribblerSettings scribblerSettings;
      static final double SCALE_MINIMUM   = 1.0;
      static final double SCALE_MAXIMUM   = 4.0;
      static final double SCALE_INCREMENT = 0.5;
      static final double SCALE_DEFAULT   = 2.0;
      double scale = SCALE_DEFAULT;
      CaptureDisplayAlignmentStrategy alignment;
      CaptureRectangleStrategy captureLocationSize = new CaptureMagnifierRectangle();
      JFrame frame;
      static final String CAPTURE_TOOLTIP_TEXT = “Capture, scale, and display pixels that lay beneath the Magnifier.”;
      static final String SETTINGS_TOOLTIP_TEXT = “Show dialog for changing tool settings.”;
      static final String SCALE_TOOLTIP_TEXT = “Magnification scale for captured image.”;
      static final String CLOSE_TOOLTIP_TEXT = “Exit the Screen Magnifier.  Changed settings are NOT retained.”;
    
       Magnifier() {
         super(“Screen Magnifier 1.0”);
         frame = this;
         createSettings();
        // If running withint MARS, set to its icon image; if not fuggetit.
         try {
            this.setIconImage(mars.Globals.getGui().getIconImage());
         } 
             catch (Exception e) { }
         getContentPane().setLayout(new BorderLayout());
        // Will capture an image each time frame is moved/resized.
         addComponentListener(this);
         try  {
            robot = new Robot ();
         }
             catch (AWTException e) {   }
             catch (SecurityException e) {  } 
        
         close = new JButton(“Close”);
         close.setToolTipText(CLOSE_TOOLTIP_TEXT);
         close.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     setVisible(false);
                  }
               });
         settings = new JButton(“Settings…”);
         settings.setToolTipText(SETTINGS_TOOLTIP_TEXT);
         settings.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     new SettingsDialog(frame);
                  }
               });
         magnifierImage = new MagnifierImage(this);
         view = new JScrollPane(magnifierImage);
         viewSize = new Dimension(200,150);
         view.setSize(viewSize); 
        
         capture = new JButton(“Capture”);
         capture.setToolTipText(CAPTURE_TOOLTIP_TEXT);
         captureActionListener = 
             new ActionListener() {
                public void actionPerformed (ActionEvent e) {          
                  magnifierImage.setImage(MagnifierImage.getScaledImage(captureScreenSection(captureLocationSize.getCaptureRectangle(getFrameRectangle())), scale)); 
                  alignment.setScrollBarValue(view.getHorizontalScrollBar()); 
                  alignment.setScrollBarValue(view.getVerticalScrollBar());
               }
            };
         JLabel scaleLabel = new JLabel(“Scale: “);
         SpinnerModel scaleModel = new SpinnerNumberModel(SCALE_DEFAULT, SCALE_MINIMUM, SCALE_MAXIMUM, SCALE_INCREMENT);
         scaleAdjuster = new JSpinner(scaleModel);
         scaleAdjuster.setToolTipText(SCALE_TOOLTIP_TEXT);
         JSpinner.NumberEditor scaleEditor = new JSpinner.NumberEditor(scaleAdjuster, “0.0”);
         scaleEditor.getTextField().setEditable(false);
         scaleAdjuster.setEditor(scaleEditor);
         scaleAdjuster.addChangeListener(
                new ChangeListener() {
                   public void stateChanged(ChangeEvent e) {
                     scale =  ((Double) scaleAdjuster.getValue()).doubleValue();
                     if (captureRescale.isEnabled()) {
                        captureActionListener.actionPerformed(
                            new ActionEvent(frame, 0, “capture”)); 
                     }
                  }
               });
         JPanel scalePanel = new JPanel();
         scalePanel.add(scaleLabel);
         scalePanel.add(scaleAdjuster);
         capture.addActionListener(captureActionListener);
         Box buttonRow = Box.createHorizontalBox();
         buttonRow.add(Box.createHorizontalStrut(4));
         buttonRow.add(capture);
         buttonRow.add(Box.createHorizontalGlue());
         buttonRow.add(settings);
         buttonRow.add(scalePanel);
         buttonRow.add(Box.createHorizontalGlue());
         buttonRow.add(getHelpButton());
         buttonRow.add(Box.createHorizontalGlue());
         buttonRow.add(close);
         buttonRow.add(Box.createHorizontalStrut(4));
         getContentPane().add(view, BorderLayout.CENTER);
         getContentPane().add(buttonRow, BorderLayout.SOUTH);
         pack();
         setSize(500,400);
         setLocationRelativeTo(null); // center on screen
         setVisible(true);
        // For some strange reason, the image has to be captured
        // and displayed an extra time for the display justification
        // to be recognized for the scrollbars.  The first capture
        // will justify left-center no matter what (scrollbar
        // positions 0).
         captureActionListener.actionPerformed(
                new ActionEvent(frame, 0, “capture”)); 
         captureActionListener.actionPerformed(
                new ActionEvent(frame, 0, “capture”)); 
      }
    
    /*
     *  Create the default Screen Magnifier tool settings.  These can
     *  all be changed through the Settings dialog but are not persistent
     *  across activations of the tool.
     */
       private void createSettings() {
         // Which events will cause automatic re-capture?  Pick any
        // or all of these three: resize the frame, move the frame,
        // change the magnification scale (using spinner).
         captureResize = new CaptureModel(false);
         captureMove = new CaptureModel(false);
         captureRescale = new CaptureModel(true);
        // When capture is taken, how shall it be displayed in the view
        // panel?  Scrollbars will be present since the displayed image
        // has to be larger than the viewing panel.  Display it either
        // with scrollbars centered, or scrollbars at initial position
        // (upper-left corner of image at upper-left corner of viewer).
         alignment = new CaptureDisplayCentered();// CaptureDisplayUpperleft();
        // Once the alignment is set, these will correctly self-set.
         captureDisplayCenter = new CaptureModel(alignment instanceof CaptureDisplayCentered);
         captureDisplayUpperleft = new CaptureModel(alignment instanceof CaptureDisplayUpperleft);
        // Scribbler has two settings: line width in pixels and line color.
         scribblerSettings = new ScribblerSettings(2, Color.RED);
        // Whether or not to center the Settings dialog over the Magnifier frame.
         dialogDisplayCenter = new CaptureModel(true);
      }
   
      // A simple explanation of what the tool does.
       private JButton getHelpButton() {
         final String helpContent = 
                              “Use this utility tool to display a magnified image of a\n”+
                              “screen section and highlight things on the image.  This\n”+ 
                                    “will be of interest mainly to instructors.\n”+
                                    “\n”+
                                    “To capture an image, size and position the Screen Magnifier\n”+
                                    “over the screen segment to be magnified and click \”Capture\”.\n”+
                                    “The pixels beneath the magnifier will be captured, scaled,\n”+
                                    “and displayed in a scrollable window.\n”+
                                    “\n”+
                                    “To highlight things in the image, just drag the mouse over\n”+
                                    “the image to make a scribble line.  This line is ephemeral\n”+
                                    “(is not repainted if covered then uncovered).\n”+
                                    “\n”+
                                    “The magnification scale can be adjusted using the spinner.\n”+
                                    “Other settings can be adjusted through the Settings dialog.\n”+
                                    “Settings include: justification of displayed image, automatic\n”+
                                    “capture upon certain tool events, and the thickness and color\n”+
                                    “of the scribble line.\n”+
                                    “\n”+
                                    “LIMITS: The image is static; it is not updated when the\n”+
                                    “underlying pixels change.  Scale changes do not take effect\n”+
                                    “until the next capture (but you can set auto-capture).  The\n”+
                                    “Magnifier does not capture frame contents of other tools.\n”+
                                    “Setting changes are not saved when the tool is closed.\n”+
                                    “\n”+
                                    “Contact Pete Sanderson at   with\n”+
                                    “questions or comments.\n”;
         JButton help = new JButton(“Help”);
         help.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     JOptionPane.showMessageDialog(frame, helpContent);
                  }
               });      
         return help;  
      } 
   
   
     /**
      *  Capture the pixels of the specified screen rectangle into an ImageBuffer.
    *  The trick is the ScreenMagnifier’s frame has to be made invisible first
    *  so it does not show up in the image.
    *  @param section A rectangle specifying the range of pixels to capture.
    *  @return A BufferedImage containing the captured pixel range.
    */
       BufferedImage captureScreenSection(Rectangle section) {
         // Hide Frame so that it does not appear in the screen capture.
         setVisible (false);
        // For some reason, the graphic extent vacated by the above call
        // is not redrawn before the screen capture unless I explicitly
         // force it to be redrawn by telling the Mars GUI to update.
        // If this doesn’t work, e.g. getGui() returns null, then there
        // are no alternatives so just let what would happen, happen.
         try {
            mars.Globals.getGui().update(mars.Globals.getGui().getGraphics());
         } 
             catch (Exception e) { }
         // Perform the screen capture.
         BufferedImage imageOfSection;
         imageOfSection = robot.createScreenCapture(section);
         setVisible(true);  
         return imageOfSection;
      }
    
    /**
     *  Place the current frame size and location into a Rectangle object.
     *  @return A Rectangle containing the ScreenMagnifier’s location, plus
     *  width and height in pixels.
     */
       Rectangle getFrameRectangle() {
         return new Rectangle(getLocation().x, getLocation().y, 
                               getSize().width, getSize().height);
      }
    
    /**
     *  Place the current screen size and location into a Rectangle object.
     *  @return A Rectangle containing the current screen location (0,0), 
     *  plus width and height in pixels.
     */
       Rectangle getScreenRectangle() {
         return new Rectangle (Toolkit.getDefaultToolkit ().getScreenSize ());
      }
   
   
      //////////////////////////////////////////////////////////////////////   
      //////
      ////// These four methods are required for ComponentListener interface.
    ////// Note: due to single inheritance, I can’t extend ComponentAdaptor. 
      //////
      //////////////////////////////////////////////////////////////////////  
       /** 
      *  Respond to frame movement event by showing new image based on
      *  the screen section of interest for this new position.  This event
      *  may occur once at the end of the move or it may occur
      *  at multiple points during the move.  The latter causes a flashing
      *  image, but I have not been able to determine how to limit it
      *  to one event occurance.
      */
      
      // Regarding the above comment, I want to have only one capture
      // occur, at the end of the move.  But the number and timing of
      // the generated events seems to vary depending on what machine
      // I am running the program on!  I have seen a technique in which
      // componentMoved would start up a timer to go off every 100 ms or
      // so to determine if the frame location had changed since the
      // previous timer check.  If so, the frame is moving so do nothing.
      // If not, the move is assumed to be over and the image is captured
      // and the timer stopped.  The latter would also handle the case
      // where componentMoved is triggered only at the end of the move.
      // componentMoved would also have to determine whether or not
      // such a timer was already running (e.g. is this the
      // first componentMoved event?) in case it is called multiple
      // times throughout the move, not just at the end.
       public void componentMoved(ComponentEvent e) {
         if (captureMove.isEnabled()) {
            captureActionListener.actionPerformed(
                            new ActionEvent(e.getComponent(), e.getID(), “capture”)); 
         }
      }
   
       /** 
      *  Respond to frame resize event by showing new image based on
      *  the screen section of interest for this new size.   This event
      *  may occur once at the end of the resize or it may occur
      *  at multiple points during the resize.  The latter causes a flashing
      *  image, but I have not been able to determine how to limit it
      *  to one event occurance.
      */   
     // See comments above for possible technique for assuring only one
     // capture at the end of the resize.
       public void componentResized(ComponentEvent e) {
         if (captureResize.isEnabled()) {
            captureActionListener.actionPerformed(
                            new ActionEvent(e.getComponent(), e.getID(), “capture”)); 
         }
      }
    
    /**
     * Invoked when setVisible(true) is called, do nothing. 
     */
       public void componentShown(ComponentEvent e) {  }
         
    /**
     * Invoked when setVisible(false) is called, do nothing. 
     */
       public void componentHidden(ComponentEvent e) { }
    
   }

      
/**
 *  Specialized class for the magnifier’s settings dialog.
 */
 
    class SettingsDialog extends JDialog {
      JButton applyButton, cancelButton;
      JCheckBox captureResizeCheckBox, captureMoveCheckBox, captureRescaleCheckBox;
      JRadioButton captureDisplayCenteredButton, captureDisplayUpperleftButton;
      Integer[] scribblerLineWidthSettings = { new Integer(1), new Integer(2), 
                                              new Integer(3), new Integer(4),
                                                         new Integer(5), new Integer(6),
                                                         new Integer(7), new Integer(8) };
      JComboBox lineWidthSetting;
      JButton lineColorSetting;
      JCheckBox dialogCentered; // Whether or not dialog appears centered over the magnfier frame.
      JDialog dialog;
    // temporary storage until committed with “Apply”.  Needed because it is returned
    // by same call that shows the color selection dialog, so cannot be retrieved
    // later from the model (as you can with buttons, checkboxes, etc).
      Color scribblerLineColorSetting;      
    // Text for tool tips.
      static final String SETTINGS_APPLY_TOOLTIP_TEXT = “Apply current settings and close the dialog.”;
      static final String SETTINGS_CANCEL_TOOLTIP_TEXT = “Close the dialog without applying any setting changes.”;
      static final String SETTINGS_SCRIBBLER_WIDTH_TOOLTIP_TEXT = “Scribbler line thickness in pixels.”;
      static final String SETTINGS_SCRIBBLER_COLOR_TOOLTIP_TEXT = “Click here to change Scribbler line color.”;
      static final String SETTINGS_DIALOG_CENTERED_TOOLTIP_TEXT = “Whether to center this dialog over the Magnifier.”;
    
       SettingsDialog(JFrame frame) {
         super(frame, “Magnifier Tool Settings”);
         dialog = this;
         setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
         Container contentPane = this.getContentPane();
         contentPane.setLayout(new BorderLayout());
         JPanel settingsPanel = new JPanel();
         JPanel selectionsPanel = new JPanel(new GridLayout(2,1));
         selectionsPanel.add(getCaptureDisplayPanel());
         JPanel secondRow = new JPanel(new GridLayout(1,2));
         secondRow.add(getAutomaticCaptureSettingsPanel());
         secondRow.add(getScribblerPanel(this));
         selectionsPanel.add(secondRow);
         contentPane.add(selectionsPanel);
         contentPane.add(getButtonRowPanel(), BorderLayout.SOUTH);
         pack();
         if (dialogCentered.isSelected()) {
            setLocationRelativeTo(frame);
         }
         setVisible(true);
      }
    
       // This panel contains the control buttons for the Settings Dialog.
       private JPanel getButtonRowPanel() {
         JPanel buttonRow = new JPanel();
         applyButton = new JButton(“Apply and Close”);
         applyButton.setToolTipText(SETTINGS_APPLY_TOOLTIP_TEXT);
        // Action to perform when APply button pressed: commit GUI settings to the models
         applyButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     // commit settings
                     ((Magnifier)getOwner()).captureResize.setEnabled(captureResizeCheckBox.isSelected());
                     ((Magnifier)getOwner()).captureMove.setEnabled(captureMoveCheckBox.isSelected());
                     ((Magnifier)getOwner()).captureRescale.setEnabled(captureRescaleCheckBox.isSelected());
                     ((Magnifier)getOwner()).captureDisplayCenter.setEnabled(captureDisplayCenteredButton.isSelected());
                     ((Magnifier)getOwner()).captureDisplayUpperleft.setEnabled(captureDisplayUpperleftButton.isSelected());
                     ((Magnifier)getOwner()).dialogDisplayCenter.setEnabled(dialogCentered.isSelected());
                     if (captureDisplayCenteredButton.isSelected()) {
                        ((Magnifier)getOwner()).alignment = new CaptureDisplayCentered();
                     } 
                     else if (captureDisplayUpperleftButton.isSelected()) {
                        ((Magnifier)getOwner()).alignment = new CaptureDisplayUpperleft();
                     }
                     ((Magnifier)getOwner()).scribblerSettings.setLineWidth(scribblerLineWidthSettings[lineWidthSetting.getSelectedIndex()].intValue());            
                     ((Magnifier)getOwner()).scribblerSettings.setLineColor(lineColorSetting.getBackground());
                     dialog.dispose();
                  }
               });
         cancelButton = new JButton(“Cancel”);
         cancelButton.setToolTipText(SETTINGS_CANCEL_TOOLTIP_TEXT);
         cancelButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     dialog.dispose();
                  }
               });
      // By default, display dialog centered over the Magnifier’s frame.  This
      // can be changed however to display at upper left corner of screen.  Why
      // would you want to change this?  So you can use the settings dialog to
      // to change scribbler color and/or width without wiping out current
      // scribbler marks.  If the dialog is centered, its mere display may
      // wipe out existing scribbler marks (because they are not repainted
      // when the underlying image is repainted). 
         dialogCentered = new JCheckBox(“Dialog centered”, ((Magnifier)getOwner()).dialogDisplayCenter.isEnabled());
         dialogCentered.setToolTipText(SETTINGS_DIALOG_CENTERED_TOOLTIP_TEXT);
         buttonRow.add(applyButton);
         buttonRow.add(cancelButton);
         buttonRow.add(dialogCentered);
         return buttonRow;
      }
    
       // Panel that contains settings for automatically performing an image
     // capture.  These are a convenience, as the image can always be
     // manually captured by clicking the “Capture” button.
       private JPanel getAutomaticCaptureSettingsPanel() {
         JPanel automaticCaptureSettings = new JPanel();
         automaticCaptureSettings.setBorder(new TitledBorder(“Automatic Capture”));
         Box automaticCaptureSettingsBox = Box.createHorizontalBox();
         automaticCaptureSettings.add(automaticCaptureSettingsBox);
         captureResizeCheckBox = new JCheckBox(“Capture upon resize”,((Magnifier)getOwner()).captureResize.isEnabled());
         captureMoveCheckBox = new JCheckBox(“Capture upon move”,((Magnifier)getOwner()).captureMove.isEnabled());
         captureRescaleCheckBox = new JCheckBox(“Capture upon rescale”,((Magnifier)getOwner()).captureRescale.isEnabled());
         JPanel checkboxColumn = new JPanel(new GridLayout(3,1));
         checkboxColumn.add(captureResizeCheckBox);
         checkboxColumn.add(captureMoveCheckBox);
         checkboxColumn.add(captureRescaleCheckBox);
         automaticCaptureSettingsBox.add(checkboxColumn); 
         return automaticCaptureSettings;
      }
   
       // Panel that contains settings for extent and display of image upon
     // capture.  In version 1.0, the extent is fixed; it is same as that 
     // of the tool’s frame itself.  The term “extent” refers to the location
     // and dimension of the rectangle.
       private JPanel getCaptureDisplayPanel() {
         JPanel captureDisplaySetting = new JPanel();
         captureDisplaySetting.setBorder(new TitledBorder(“Capture and Display”));
         Box captureDisplaySettingsBox = Box.createHorizontalBox();
         captureDisplaySetting.add(captureDisplaySettingsBox);
         captureDisplayCenteredButton = new JRadioButton(“Capture area behind magnifier and display centered”,
                                   ((Magnifier)getOwner()).captureDisplayCenter.isEnabled());
         captureDisplayUpperleftButton = new JRadioButton(“Capture area behind magnifier and display upper-left”,
                                   ((Magnifier)getOwner()).captureDisplayUpperleft.isEnabled());
         ButtonGroup displayButtonGroup = new ButtonGroup();
         displayButtonGroup.add(captureDisplayCenteredButton);
         displayButtonGroup.add(captureDisplayUpperleftButton);
         JPanel radioColumn = new JPanel(new GridLayout(2,1));
         radioColumn.add(captureDisplayCenteredButton);
         radioColumn.add(captureDisplayUpperleftButton);
         JPanel radioLabelColumn = new JPanel(new GridLayout(1,1));
         captureDisplaySettingsBox.add(radioColumn);
         return captureDisplaySetting;
      }
   
      // Panel that contains settings for the Scribbler part of the tool.
    // The only settings here are choice of line width (thickness) in pixels
    // and line color.
       private JPanel getScribblerPanel(final JDialog dialog) {
         JPanel scribblerSettings = new JPanel();
         scribblerSettings.setBorder(new TitledBorder(“Scribbler”));
         Box scribblerSettingsBox = Box.createHorizontalBox();
         scribblerSettings.add(scribblerSettingsBox);
         lineWidthSetting = new JComboBox(scribblerLineWidthSettings);
         lineWidthSetting.setToolTipText(SETTINGS_SCRIBBLER_WIDTH_TOOLTIP_TEXT);
         lineWidthSetting.setSelectedIndex(((Magnifier)getOwner()).scribblerSettings.getLineWidth()-1);
         lineColorSetting = new JButton(”   “);
         lineColorSetting.setToolTipText(SETTINGS_SCRIBBLER_COLOR_TOOLTIP_TEXT);
         lineColorSetting.setBackground(((Magnifier)getOwner()).scribblerSettings.getLineColor());
         lineColorSetting.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     Color newColor = JColorChooser.showDialog(dialog, “Scribbler line color”, lineColorSetting.getBackground());
                     lineColorSetting.setBackground(newColor);
                  }
               });
         scribblerLineColorSetting = lineColorSetting.getBackground();
         JPanel settingsColumn = new JPanel(new GridLayout(2,1,5,5));
         settingsColumn.add(lineWidthSetting);
         settingsColumn.add(lineColorSetting);
         JPanel labelColumn = new JPanel(new GridLayout(2,1,5,5));
         labelColumn.add(new JLabel(“Line width “,SwingConstants.LEFT));
         labelColumn.add(new JLabel(“Line color “,SwingConstants.LEFT));
         scribblerSettingsBox.add(labelColumn);
         scribblerSettingsBox.add(settingsColumn);   
         return scribblerSettings;
      }
   
   }

  /**
   * Represents an automatic capture “event” which is enabled
    * if the capture operation is to be performed automatically
    * upon occurance.
    */
    class CaptureModel  {
      private boolean enabled;
    /**
     *  Create a new CaptureModel.
     *  @param set True if capture is to be automatically performed when
     *  associated event occurs, false otherwise.
     */
       public CaptureModel(boolean set) {
         enabled = set;
      }
    /**
     * Determine whether or not capture will automatically occur.
     * @return True if automatic capture will occur, false otherwise.
     */
       public boolean isEnabled() {
         return enabled;
      }
      /**
     *  Specify whether or not capture will automatically occur.
     *  @param set True if capture is to be automatically performed when
     *  associated event occurs, false otherwise.
     */
       public void setEnabled(boolean set) {
         enabled = set;
      }
   
   }

/**
 *  This class defines a specialized panel for displaying a captured image.
 */

    class MagnifierImage extends JPanel  {
    
      // Enclosing JFrame for this panel — the Screen Magnifier itself.
      private Magnifier frame;      
      // Rectangle representing screen pixels to be magnified.
      private Rectangle screenRectangle;    
      // Robot used to perform the screen capture.
      private static Robot robot;   
      // Displayed image’s Image object, which is actually a BufferedImage.
      private Image image;
    // Scribbler for highlighting image using mouse.
      private Scribbler scribbler;
   
       
   /**
    *  Construct an MagnifierImage component.
    */
   
       public MagnifierImage(Magnifier frame) {
         this.frame = frame;
         this.scribbler = new Scribbler(frame.scribblerSettings);
        
         addMouseListener (
                new MouseAdapter ()  {
                   public void mousePressed (MouseEvent e)  {
                     scribbler.moveto(e.getX(), e.getY()); // Move to click position
                  }
               });
      
      // Install a mouse motion listener to draw the scribble.
         addMouseMotionListener (
                new MouseMotionAdapter () {
                   public void mouseDragged (MouseEvent e) {
                     scribbler.lineto(e.getX(), e.getY(),(Graphics2D)getGraphics()); 
                  }
               });
      }
   
     
   /**
    *  Return the current image.
    *
    *  @return Image reference to current image
    */
   
       public Image getImage () {
         return image;
      }
   
   /**
    *  Repaint the MagnifierImage with the current image’s pixels.
    *
    *  @param g graphics context
    */
   
       public void paintComponent (Graphics g) {
         // Repaint the component’s background.
         super.paintComponent (g);
         // If an image has been defined, draw that image using the Component
         // layer of this MagnifierImage object as the ImageObserver.
         if (image != null)
            g.drawImage (image, 0, 0, this);
      }
   
   /**
    *  Establish a new image and update the display.
    *
    *  @param image new image’s Image reference
    */
   
       public void setImage (Image image) {
         // Save the image for later repaint.
         this.image = image;
         // Set this panel’s preferred size to the image’s size, to influence the
         // display of scrollbars.
         setPreferredSize (new Dimension (image.getWidth (this),
                                       image.getHeight (this)));
         // Present scrollbars as necessary.
         revalidate ();
         // Update the image displayed on the panel.
         repaint ();
      }
    
    /**
     *  Get a scaled version of the image.  Ignores scaling values between .99 and 1.01.
     *  @param image the original image
     *  @param scale the magnification scale as a double
     *  @param scaleAlgorithm Scaling algorithm to use: Image.SCALE_DEFAULT,
     *  Image.SCALE_FAST, Image.SCALE_SMOOTH.
     */
       static Image getScaledImage(Image image, double scale, int scaleAlgorithm) {
         // Don’t bother if it is close to 1.  I anticipate this will be used mainly to
        // enlarge the image, so short circuit evalution will apply most of the time.
         return (scale < 1.01 && scale > 0.99) 
                ? image 
                 : image.getScaledInstance((int)(image.getWidth(null)*scale),
                                          (int)(image.getHeight(null)*scale),
                                          scaleAlgorithm);
      }
   
    /**
     *  Get a scaled version of the image using default scaling algorithm.
     *  Ignores scaling values between .99 and 1.01.
     *  @param image the original image
     *  @param scale the magnification scale as a double
     */     
       static Image getScaledImage(Image image, double scale) {
         return getScaledImage(image, scale, Image.SCALE_DEFAULT);
      }
    
       /*
      *  Little class to allow user to scribble over the image using the
      *  mouse.  The scribble is ephemeral; it is drawn but specifications
      *  are not saved.
      */    
       private class Scribbler {
         private ScribblerSettings scribblerSettings;
         private BasicStroke drawingStroke;
         // coordinates of previous mouse position 
         protected int last_x, last_y; 
        
          Scribbler(ScribblerSettings scribblerSettings) {
            this.scribblerSettings = scribblerSettings;
            drawingStroke = new BasicStroke(scribblerSettings.getLineWidth());
         }
        
        /** Get the scribbler’s drawing color. */
          public Color getColor() {
            return scribblerSettings.getLineColor();//color;
         }
        
        /** Get the scribbler’s line (stroke) width. */
          public int getLineWidth() {
            this.drawingStroke = new BasicStroke(scribblerSettings.getLineWidth());
            return scribblerSettings.getLineWidth();//width;
         }
      
        /** Set the scribbler’s drawing color. */
          public void setColor(Color newColor) {
            scribblerSettings.setLineColor(newColor);// this.color = newColor;
         }
        
        /** Set the scribbler’s line (stroke) width. */
          public void setLineWidth(int newWidth) {
            scribblerSettings.setLineWidth(newWidth);// this.width = newWidth;
            this.drawingStroke = new BasicStroke(newWidth);
         }
            
        /** Get the scribbler’s drawing (stroke) object. */
          private BasicStroke getStroke() {
            return drawingStroke;
         }
        
        /** Set the scribbler’s drawing (stroke) object. */
          private void setStroke(BasicStroke newStroke) {
            this.drawingStroke = newStroke;
         }      
        
          /** Remember the specified point */
          public void moveto(int x, int y) {
            last_x = x;
            last_y = y;
         }
      
          /** Draw from the last point to this point, then remember new point */
          public void lineto(int x, int y, Graphics2D g2d) {
         // System.out.println(drawingStroke.getLineWidth());
            g2d.setStroke(new BasicStroke(scribblerSettings.getLineWidth()));
            g2d.setColor(scribblerSettings.getLineColor()); // Tell it what color to use
            g2d.draw(new Line2D.Float(last_x, last_y, x, y));
            moveto(x, y); // Save the current point
         }      
      }
      
   }
    
    
    /**
     *  Class to represent current settings for the scribbler tool.
     */
    class ScribblerSettings {
      private int width;
      private Color color;
    
    /**
     *  Build a new ScribblerSettings object.
     */
       public ScribblerSettings(int width, Color color) {
         this.width = width;
         this.color = color;
      }
    
      /**
     *  Fetch the current line width for the scribbler tool.
     */
       public int getLineWidth() {
         return width;
      }
   
      /**
     *  Fetch the current line color for the scribbler tool.
     */
       public Color getLineColor() {
         return color;
      }     
   
      /**
     *  Set the current line width for the scribbler tool.
     */
       public void setLineWidth(int newWidth) {
         width = newWidth; 
      }
   
      /**
     *  Set the current line color for the scribbler tool.
     */
       public void setLineColor(Color newColor) {
         color = newColor;
      }
   }
    
    
    /**
    *  Interface to specify strategy for determining the size and location
    *  of the screen rectangle to capture.
    */
    interface CaptureRectangleStrategy {
       public Rectangle getCaptureRectangle(Rectangle magnifierRectangle);
   }
    
   /**
    *  Upon screen capture, capture the same rectangle as the magnifier
    *  itself.  Pixels that lie directly beneath it.
    */
    class CaptureMagnifierRectangle implements CaptureRectangleStrategy {
       public Rectangle getCaptureRectangle(Rectangle magnifierRectangle) {
         return magnifierRectangle;
      }
   }
   /**
    *  Upon screen capture, capture a rectangle whose size and location is
    *  determined by the current magnification scale.  For instance, if the
    *  scale is 2.0, the capture rectangle will have half the width and 
     *  height of the magnifier and its location will be offset so it is
     *  centered within the magnifier rectangle — except when the magnifier 
     *  is near the edge of the screen in which case the location is adjusted
     *  such that the boundary pixels will be captured.
     */         
    class CaptureScaledRectangle implements CaptureRectangleStrategy {
       public Rectangle getCaptureRectangle(Rectangle magnifierRectangle) {
         throw new UnsupportedOperationException(); // This is not implementated yet!
            //return new Rectangle();
      }
   }
    
        
    /**
     *  Interface to specify strategy for determining initial scrollbar settings
     *  when displaying captured and scaled image.
     */
    interface CaptureDisplayAlignmentStrategy {
       public  void setScrollBarValue(JScrollBar scrollBar);
   }
   /**
     *  Captured and scaled image should be displayed centerd in the panel.
     */
    class CaptureDisplayCentered implements CaptureDisplayAlignmentStrategy {
      /**
       *  Set the scrollbar value to inticate the captured and scaled image
       *  is displayed centered in the panel.
       *  @param scrollBar The scrollbar to be adjusted.
       */
       public void setScrollBarValue(JScrollBar scrollBar) {
         scrollBar.setValue(( scrollBar.getModel().getMaximum() 
                            – scrollBar.getModel().getMinimum() 
                            – scrollBar.getModel().getExtent() 
                           ) / 2 
                            );
      }
   }
   
    /**
     *  Captured and scaled image should be displayed so that its upper left
     *  corner is initially displayed in the upper left corner of the panel.
     */
    class CaptureDisplayUpperleft implements CaptureDisplayAlignmentStrategy {
         /**
          *  Set the scrollbar value to inticate the captured and scaled image
          *  is displayed with the upper left corner initially visible in the panel.
          *  @param scrollBar The scrollbar to be adjusted.
          */
       public void setScrollBarValue(JScrollBar scrollBar) {
         scrollBar.setValue(0);
      }
   }
   

ScreenMagnifier$1

package mars.tools;
synchronized class ScreenMagnifier$1 implements Runnable {
void ScreenMagnifier$1();
public void run();
}

CacheSimulator$2

package mars.tools;
synchronized class CacheSimulator$2 implements java.awt.event.ActionListener {
void CacheSimulator$2(CacheSimulator);
public void actionPerformed(java.awt.event.ActionEvent);
}

KeyboardAndDisplaySimulator$3

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$3 implements java.awt.event.ActionListener {
void KeyboardAndDisplaySimulator$3(KeyboardAndDisplaySimulator);
public void actionPerformed(java.awt.event.ActionEvent);
}

KeyboardAndDisplaySimulator$FontSettingDialog

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$FontSettingDialog extends mars.venus.AbstractFontSettingDialog {
private boolean resultOK;
public void KeyboardAndDisplaySimulator$FontSettingDialog(KeyboardAndDisplaySimulator, java.awt.Frame, String, java.awt.Font);
private java.awt.Font showDialog();
protected void closeDialog();
private void performCancel();
protected java.awt.Component buildControlPanel();
protected void apply(java.awt.Font);
}

mars/tools/MemoryReferenceVisualization.java
mars/tools/MemoryReferenceVisualization.java   package mars.tools;
   import javax.swing.*;
   import javax.swing.border.*;
   import javax.swing.event.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.util.*;
   import mars.tools.*;
   import mars.mips.hardware.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
     * Memory reference visualization.  It can be run either as a stand-alone Java application having
     * access to the mars package, or through MARS as an item in its Tools menu.  It makes
     * maximum use of methods inherited from its abstract superclass AbstractMarsToolAndApplication.
     * Pete Sanderson, verison 1.0, 14 November 2006.
     */
    public class MemoryReferenceVisualization extends AbstractMarsToolAndApplication {
   
      private static String version = “Version 1.0”;
      private static String heading =  “Visualizing memory reference patterns”;
    
    // Major GUI components
      private JComboBox wordsPerUnitSelector, visualizationUnitPixelWidthSelector, visualizationUnitPixelHeightSelector,
                        visualizationPixelWidthSelector, visualizationPixelHeightSelector, displayBaseAddressSelector;
      private JCheckBox drawHashMarksSelector;
      private Graphics drawingArea;
      private JPanel canvas;
      private JPanel results;
    
    // Some GUI settings
      private EmptyBorder emptyBorder = new EmptyBorder(4,4,4,4);
      private Font countFonts = new Font(“Times”, Font.BOLD,12);
      private Color backgroundColor = Color.WHITE;
    
    // Values for Combo Boxes
    
      private final String[] wordsPerUnitChoices  = {“1″,”2″,”4″,”8″,”16″,”32″,”64″,”128″,”256″,”512″,”1024″,”2048”};
      private final int defaultWordsPerUnitIndex  = 0;
      private final String[] visualizationUnitPixelWidthChoices  = {“1″,”2″,”4″,”8″,”16″,”32”};
      private final int defaultVisualizationUnitPixelWidthIndex  = 4;
      private final String[] visualizationUnitPixelHeightChoices  = {“1″,”2″,”4″,”8″,”16″,”32”};
      private final int defaultVisualizationUnitPixelHeightIndex  = 4;
      private final String[] displayAreaPixelWidthChoices  = {“64″,”128″,”256″,”512″,”1024”};
      private final int defaultDisplayWidthIndex  = 2;
      private final String[] displayAreaPixelHeightChoices  = {“64″,”128″,”256″,”512″,”1024”};
      private final int defaultDisplayHeightIndex  = 2;
      private final boolean defaultDrawHashMarks = true;
   
      // Values for display canvas.  Note their initialization uses the identifiers just above.
   
      private int unitPixelWidth = Integer.parseInt(visualizationUnitPixelWidthChoices[defaultVisualizationUnitPixelWidthIndex]);
      private int unitPixelHeight = Integer.parseInt(visualizationUnitPixelHeightChoices[defaultVisualizationUnitPixelHeightIndex]);
      private int wordsPerUnit = Integer.parseInt(wordsPerUnitChoices[defaultWordsPerUnitIndex]);
      private int visualizationAreaWidthInPixels = Integer.parseInt(displayAreaPixelWidthChoices[defaultDisplayWidthIndex]);
      private int visualizationAreaHeightInPixels = Integer.parseInt(displayAreaPixelHeightChoices[defaultDisplayHeightIndex]);
    
    //`Values for mapping of reference counts to colors for display.
    
    // This array of (count,color) pairs must be kept sorted! count is low end of subrange. 
    // This array will grow if user adds colors at additional counter points (see below).
      private CounterColor[] defaultCounterColors = 
                                             { new CounterColor(0, Color.black),
                                               new CounterColor(1, Color.blue), 
                                               new CounterColor(2, Color.green), 
                                               new CounterColor(3, Color.yellow), 
                                               new CounterColor(5, Color.orange), 
                                               new CounterColor(10, Color.red)
                                                        }; 
    /*  Values for reference count color slider. These are all possible counter values for which 
     *  colors can be assigned.  As you can see just above, not all these values are assigned
     *  a default color.
     */
      private int[] countTable = { 
               0,    1,    2,    3,    4,     5,     6,      7,      8,       9,   10,   // 0-10
                    20,   30,   40,   50,   100,   200,    300,    400,     500, 1000,   // 11-20
                  2000, 3000, 4000, 5000, 10000, 50000, 100000, 500000, 1000000          // 21-29
                };
      private final int COUNT_INDEX_INIT = 10;  // array element #10, arbitrary starting point
           
    // The next four are initialized dynamically in initializeDisplayBaseChoices()
      private String[] displayBaseAddressChoices;
      private int[] displayBaseAddresses;
      private int defaultBaseAddressIndex;
      private int baseAddress;
    
      private Grid theGrid;
      private CounterColorScale counterColorScale;
                
    /**
     * Simple constructor, likely used to run a stand-alone memory reference visualizer.
     * @param title String containing title for title bar
     * @param heading String containing text for heading shown in upper part of window.
     */
       public MemoryReferenceVisualization(String title, String heading) {
         super(title,heading);
      }
     
     /**
      *  Simple constructor, likely used by the MARS Tools menu mechanism
      */
       public MemoryReferenceVisualization() {
         super (“Memory Reference Visualization, “+version, heading);
      }
         
         
    /**
     * Main provided for pure stand-alone use.  Recommended stand-alone use is to write a 
     * driver program that instantiates a MemoryReferenceVisualization object then invokes its go() method.
     * “stand-alone” means it is not invoked from the MARS Tools menu.  “Pure” means there
     * is no driver program to invoke the application.
     */
       public static void main(String[] args) {
         new MemoryReferenceVisualization(“Memory Reference Visualization stand-alone, “+version,heading).go();
      }
    
   
       /**
      *  Required MarsTool method to return Tool name.  
      *  @return  Tool name.  MARS will display this in menu item.
      */
       public String getName() {
         return “Memory Reference Visualization”;
      }
    
    
      /**
     *  Override the inherited method, which registers us as an Observer over the static data segment 
     *  (starting address 0x10010000) only.  This version will register us as observer over the 
     *  the memory range as selected by the base address combo box and capacity of the visualization display 
     *  (number of visualization elements times the number of memory words each one represents). 
     *  It does so by calling the inherited 2-parameter overload of this method. 
     *  If you use the inherited GUI buttons, this 
     *  method is invoked when you click “Connect” button on MarsTool or the 
     *  “Assemble and Run” button on a Mars-based app.
     */
       protected void addAsObserver() {
         int highAddress = baseAddress+theGrid.getRows()*theGrid.getColumns()*Memory.WORD_LENGTH_BYTES*wordsPerUnit;
        // Special case: baseAddress<0 means we're in kernel memory (0x80000000 and up) and most likely         // in memory map address space (0xffff0000 and up).  In this case, we need to make sure the high address         // does not drop off the high end of 32 bit address space.  Highest allowable word address is 0xfffffffc,         // which is interpreted in Java int as -4.          if (baseAddress < 0 && highAddress > -4) {
            highAddress = -4;
         }
         addAsObserver(baseAddress, highAddress);
      }
   
      
    /**
     *  Method that constructs the main display area.  It is organized vertically
     *  into two major components: the display configuration which an be modified
     *  using combo boxes, and the visualization display which is updated as the
     *  attached MIPS program executes.
     *  @return the GUI component containing these two areas
     */
       protected JComponent buildMainDisplayArea() {
         results = new JPanel();
         results.add(buildOrganizationArea());
         results.add(buildVisualizationArea());
         return results;
      }
   
   
      //////////////////////////////////////////////////////////////////////////////////////
      //  Rest of the protected methods.  These override do-nothing methods inherited from
    //  the abstract superclass.
      //////////////////////////////////////////////////////////////////////////////////////
    
      /**
     * Update display when connected MIPS program accesses (data) memory.
     * @param memory the attached memory
     * @param accessNotice information provided by memory in MemoryAccessNotice object
     */
       protected void processMIPSUpdate(Observable memory, AccessNotice accessNotice) {
         incrementReferenceCountForAddress(((MemoryAccessNotice)accessNotice).getAddress());
         updateDisplay();
      }
    
   
    /** 
     *  Initialize all JComboBox choice structures not already initialized at declaration.  
       *  Overrides inherited method that does nothing.
     */
       protected void initializePreGUI() {
         initializeDisplayBaseChoices();
         counterColorScale = new CounterColorScale(defaultCounterColors);
        // NOTE: Can’t call “createNewGrid()” here because it uses settings from
        //       several combo boxes that have not been created yet.  But a default grid
        //       needs to be allocated for initial canvas display.
         theGrid = new Grid(visualizationAreaHeightInPixels/unitPixelHeight,
                            visualizationAreaWidthInPixels/unitPixelWidth);
      }
   
   
    /** 
     *  The only post-GUI initialization is to create the initial Grid object based on the default settings
     *  of the various combo boxes. Overrides inherited method that does nothing.
     */
    
       protected void initializePostGUI() {
         wordsPerUnit = getIntComboBoxSelection(wordsPerUnitSelector);
         theGrid = createNewGrid();
         updateBaseAddress();
      }
    
    
    /**
     *  Method to reset counters and display when the Reset button selected.
     *  Overrides inherited method that does nothing.
     */
       protected void reset() {
         resetCounts();
         updateDisplay();
      }
   
    /**
     *  Updates display immediately after each update (AccessNotice) is processed, after
     *  display configuration changes as needed, and after each execution step when Mars
     *  is running in timed mode.  Overrides inherited method that does nothing.
     */
       protected void updateDisplay() {
         canvas.repaint();
      }
   
       
     /**
      *  Overrides default method, to provide a Help button for this tool/app.
      */
       protected JComponent getHelpComponent() {
           final String helpContent = 
                                 “Use this program to visualize dynamic memory reference\n”+
                                 “patterns in MIPS assembly programs.  It may be run either\n”+
                                        “from MARS’ Tools menu or as a stand-alone application.  For\n”+
                                        “the latter, simply write a small driver to instantiate a\n”+
                                        “MemoryReferenceVisualization object and invoke its go() method.\n”+
                                        “\n”+
                                        “You can easily learn to use this small program by playing with\n”+
                                        “it!  For the best animation, set the MIPS program to run in\n”+
                                        “timed mode using the Run Speed slider.  Each rectangular unit\n”+
                                        “on the display represents one or more memory words (default 1)\n”+
                                        “and each time a memory word is accessed by the MIPS program,\n”+
                                        “its reference count is incremented then rendered in the color\n”+
                                        “assigned to the count value.  You can change the count-color\n”+
                                        “assignments using the count slider and color patch.  Select a\n”+
                                        “counter value then click on the color patch to change the color.\n”+
                                        “This color will apply beginning at the selected count and\n”+
                                        “extending up to the next slider-provided count.\n”+
                                        “\n”+
                                        “Contact Pete Sanderson at   with\n”+
                                        “questions or comments.\n”;
         JButton help = new JButton(“Help”);
         help.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     JOptionPane.showMessageDialog(theWindow, helpContent);
                  }
               });      
         return help;  
      }
    
      //////////////////////////////////////////////////////////////////////////////////////
      //  Private methods defined to support the above.
      //////////////////////////////////////////////////////////////////////////////////////
        
    // UI components and layout for left half of GUI, where settings are specified.
       private JComponent buildOrganizationArea() {
         JPanel organization = new JPanel(new GridLayout(9,1));
        
         drawHashMarksSelector = new JCheckBox();
         drawHashMarksSelector.setSelected(defaultDrawHashMarks);
         drawHashMarksSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     updateDisplay();
                  }
               });  
         wordsPerUnitSelector = new JComboBox(wordsPerUnitChoices);
         wordsPerUnitSelector.setEditable(false);
         wordsPerUnitSelector.setBackground(backgroundColor);
         wordsPerUnitSelector.setSelectedIndex(defaultWordsPerUnitIndex);
         wordsPerUnitSelector.setToolTipText(“Number of memory words represented by one visualization element (rectangle)”);
         wordsPerUnitSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     wordsPerUnit = getIntComboBoxSelection(wordsPerUnitSelector);
                     reset();
                  }
               });                      
         visualizationUnitPixelWidthSelector = new JComboBox(visualizationUnitPixelWidthChoices);
         visualizationUnitPixelWidthSelector.setEditable(false);
         visualizationUnitPixelWidthSelector.setBackground(backgroundColor);
         visualizationUnitPixelWidthSelector.setSelectedIndex(defaultVisualizationUnitPixelWidthIndex);
         visualizationUnitPixelWidthSelector.setToolTipText(“Width in pixels of rectangle representing memory access”);
         visualizationUnitPixelWidthSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     unitPixelWidth = getIntComboBoxSelection(visualizationUnitPixelWidthSelector);
                     theGrid = createNewGrid();
                     updateDisplay();
                  }
               });
         visualizationUnitPixelHeightSelector = new JComboBox(visualizationUnitPixelHeightChoices);
         visualizationUnitPixelHeightSelector.setEditable(false);
         visualizationUnitPixelHeightSelector.setBackground(backgroundColor);
         visualizationUnitPixelHeightSelector.setSelectedIndex(defaultVisualizationUnitPixelHeightIndex);
         visualizationUnitPixelHeightSelector.setToolTipText(“Height in pixels of rectangle representing memory access”);
         visualizationUnitPixelHeightSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     unitPixelHeight = getIntComboBoxSelection(visualizationUnitPixelHeightSelector);
                     theGrid = createNewGrid();
                     updateDisplay();
                  }
               });                  
         visualizationPixelWidthSelector = new JComboBox(displayAreaPixelWidthChoices);
         visualizationPixelWidthSelector.setEditable(false);
         visualizationPixelWidthSelector.setBackground(backgroundColor);
         visualizationPixelWidthSelector.setSelectedIndex(defaultDisplayWidthIndex);
         visualizationPixelWidthSelector.setToolTipText(“Total width in pixels of visualization area”);
         visualizationPixelWidthSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     visualizationAreaWidthInPixels = getIntComboBoxSelection(visualizationPixelWidthSelector);
                     canvas.setPreferredSize(getDisplayAreaDimension());
                     canvas.setSize(getDisplayAreaDimension());
                     theGrid = createNewGrid();
                     canvas.repaint();
                     updateDisplay();
                  }
               });
         visualizationPixelHeightSelector = new JComboBox(displayAreaPixelHeightChoices);
         visualizationPixelHeightSelector.setEditable(false);
         visualizationPixelHeightSelector.setBackground(backgroundColor);
         visualizationPixelHeightSelector.setSelectedIndex(defaultDisplayHeightIndex);
         visualizationPixelHeightSelector.setToolTipText(“Total height in pixels of visualization area”);
         visualizationPixelHeightSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     visualizationAreaHeightInPixels = getIntComboBoxSelection(visualizationPixelHeightSelector);
                     canvas.setPreferredSize(getDisplayAreaDimension());
                     canvas.setSize(getDisplayAreaDimension());
                     theGrid = createNewGrid();
                     canvas.repaint();
                     updateDisplay();
                  }
               });          
         displayBaseAddressSelector = new JComboBox(displayBaseAddressChoices);
         displayBaseAddressSelector.setEditable(false);
         displayBaseAddressSelector.setBackground(backgroundColor);
         displayBaseAddressSelector.setSelectedIndex(defaultBaseAddressIndex);
         displayBaseAddressSelector.setToolTipText(“Base address for visualization area (upper left corner)”);
         displayBaseAddressSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                    // This may also affect what address range we should be registered as an Observer
                    // for.  The default (inherited) address range is the MIPS static data segment 
                    // starting at 0x10010000. To change this requires override of
                    // AbstractMarsToolAndApplication.addAsObserver().  The no-argument version of 
                    // that method is called automatically  when “Connect” button is clicked for MarsTool 
                    // and when “Assemble and Run” button is clicked for Mars application.
                     updateBaseAddress();
                    // If display base address is changed while connected to MIPS (this can only occur
                    // when being used as a MarsTool), we have to delete ourselves as an observer and re-register.
                     if (connectButton != null && connectButton.isConnected()) {
                        deleteAsObserver();
                        addAsObserver();
                     }
                     theGrid = createNewGrid();
                     updateDisplay();
                  }
               });          
      
         // ALL COMPONENTS FOR “ORGANIZATION” SECTION
      
         JPanel hashMarksRow = getPanelWithBorderLayout();
         hashMarksRow.setBorder(emptyBorder);
         hashMarksRow.add(new JLabel(“Show unit boundaries (grid marks)”), BorderLayout.WEST);
         hashMarksRow.add(drawHashMarksSelector, BorderLayout.EAST);
        
         JPanel wordsPerUnitRow = getPanelWithBorderLayout();
         wordsPerUnitRow.setBorder(emptyBorder);
         wordsPerUnitRow.add(new JLabel(“Memory Words per Unit “),BorderLayout.WEST);
         wordsPerUnitRow.add(wordsPerUnitSelector,BorderLayout.EAST);
      
         JPanel unitWidthInPixelsRow = getPanelWithBorderLayout();
         unitWidthInPixelsRow.setBorder(emptyBorder);
         unitWidthInPixelsRow.add(new JLabel(“Unit Width in Pixels “),BorderLayout.WEST);
         unitWidthInPixelsRow.add(visualizationUnitPixelWidthSelector, BorderLayout.EAST);
      
         JPanel unitHeightInPixelsRow = getPanelWithBorderLayout();
         unitHeightInPixelsRow.setBorder(emptyBorder);
         unitHeightInPixelsRow.add(new JLabel(“Unit Height in Pixels “),BorderLayout.WEST);
         unitHeightInPixelsRow.add(visualizationUnitPixelHeightSelector,BorderLayout.EAST);                     
      
         JPanel widthInPixelsRow = getPanelWithBorderLayout();
         widthInPixelsRow.setBorder(emptyBorder);
         widthInPixelsRow.add(new JLabel(“Display Width in Pixels “),BorderLayout.WEST);
         widthInPixelsRow.add(visualizationPixelWidthSelector, BorderLayout.EAST);
      
         JPanel heightInPixelsRow = getPanelWithBorderLayout();
         heightInPixelsRow.setBorder(emptyBorder);
         heightInPixelsRow.add(new JLabel(“Display Height in Pixels “),BorderLayout.WEST);
         heightInPixelsRow.add(visualizationPixelHeightSelector,BorderLayout.EAST);                     
      
         JPanel baseAddressRow = getPanelWithBorderLayout();
         baseAddressRow.setBorder(emptyBorder);
         baseAddressRow.add(new JLabel(“Base address for display “),BorderLayout.WEST);
         baseAddressRow.add(displayBaseAddressSelector,BorderLayout.EAST);                      
      
         ColorChooserControls colorChooserControls = new ColorChooserControls();
      
        // Lay ’em out in the grid…
         organization.add(hashMarksRow);
         organization.add(wordsPerUnitRow);
         organization.add(unitWidthInPixelsRow);
         organization.add(unitHeightInPixelsRow);     
         organization.add(widthInPixelsRow);
         organization.add(heightInPixelsRow);  
         organization.add(baseAddressRow); 
         organization.add(colorChooserControls.colorChooserRow);
         organization.add(colorChooserControls.countDisplayRow);
         return organization;
      }
    
    // UI components and layout for right half of GUI, the visualization display area.
       private JComponent buildVisualizationArea() {
         canvas = new GraphicsPanel();
         canvas.setPreferredSize(getDisplayAreaDimension());
         canvas.setToolTipText(“Memory reference count visualization area”);
         return canvas;
      }
   
      // For greatest flexibility, initialize the display base choices directly from
      // the constants defined in the Memory class.  This method called prior to 
      // building the GUI.  Here are current values from Memory.java:
      //textBaseAddress=0x00400000, dataSegmentBaseAddress=0x10000000, globalPointer=0x10008000
      //dataBaseAddress=0x10010000, heapBaseAddress=0x10040000, memoryMapBaseAddress=0xffff0000 
       private void initializeDisplayBaseChoices() {
         int[] displayBaseAddressArray = {Memory.textBaseAddress, Memory.dataSegmentBaseAddress, Memory.globalPointer, Memory.dataBaseAddress,
                                          Memory.heapBaseAddress, Memory.memoryMapBaseAddress };
        // Must agree with above in number and order…
         String[] descriptions =         { ” (text)”, ” (global data)”, ” ($gp)”, ” (static data)”, ” (heap)”, ” (memory map)” };
         displayBaseAddresses = displayBaseAddressArray;
         displayBaseAddressChoices = new String[displayBaseAddressArray.length];
         for (int i=0; i 10 characters long, slice off the first
             10 and apply Integer.parseInt() to it to get custom base address.
        */
      }
    
     // Returns Dimension object with current width and height of display area as determined
       // by current settings of respective combo boxes.
       private Dimension getDisplayAreaDimension() {
         return new Dimension(visualizationAreaWidthInPixels, visualizationAreaHeightInPixels);
      }
    
    // reset all counters in the Grid.
       private void resetCounts() {
         theGrid.reset();
      }
    
    // Will return int equivalent of specified combo box’s current selection.
    // The selection must be a String that parses to an int.
       private int getIntComboBoxSelection(JComboBox comboBox) {
         try {
            return Integer.parseInt((String)comboBox.getSelectedItem());
         } 
             catch (NumberFormatException nfe) {
                // Can occur only if initialization list contains badly formatted numbers.  This
                // is a developer’s error, not a user error, and better be caught before release.
               return 1;
            }
      }
    
     // Use this for consistent results.
       private JPanel getPanelWithBorderLayout() {
         return new JPanel(new BorderLayout(2,2));
      }
    
     // Method to determine grid dimensions based on durrent control settings.
     // Each grid element corresponds to one visualization unit. 
       private Grid createNewGrid() {
         int rows = visualizationAreaHeightInPixels/unitPixelHeight;
         int columns = visualizationAreaWidthInPixels/unitPixelWidth;
         return new Grid(rows,columns);
      }
    
     // Given memory address, increment the counter for the corresponding grid element.
     // Need to consider words per unit (number of memory words that each visual element represents).
     // If address maps to invalid grid element (e.g. is outside the current bounds based on all
     // display settings) then nothing happens.
       private void incrementReferenceCountForAddress(int address) {
         int offset = (address – baseAddress)/Memory.WORD_LENGTH_BYTES/wordsPerUnit;
        // If you care to do anything with it, the following will return -1 if the address
        // maps outside the dimensions of the grid (e.g. below the base address or beyond end).
         theGrid.incrementElement(offset / theGrid.getColumns(), offset % theGrid.getColumns());
      }
      
      
      //////////////////////////////////////////////////////////////////////////////////////
      //  Specialized inner classes for modeling and animation.
      //////////////////////////////////////////////////////////////////////////////////////
    
   
    /////////////////////////////////////////////////////////////////////////////
    //  Class that represents the panel for visualizing and animating memory reference
    //  patterns.
       private class GraphicsPanel extends JPanel {
          // override default paint method to assure visualized reference pattern is produced every time
         // the panel is repainted.
          public void paint(Graphics g) {
            paintGrid(g, theGrid);
            if (drawHashMarksSelector.isSelected()) {
               paintHashMarks(g, theGrid);
            }
         }
      
         // Paint (ash marks on the grid.  Their color is chosef to be in
        // “contrast” to the current color for reference count of zero.
          private void paintHashMarks(Graphics g, Grid grid) {
            g.setColor(getContrastingColor(counterColorScale.getColor(0)));
            int leftX=0;
            int rightX=visualizationAreaWidthInPixels;
            int upperY=0;
            int lowerY=visualizationAreaHeightInPixels;  
            // draw vertical hash marks
            for (int j=0; j= 10) {
               spaces = ” “;
            } 
            else if (value >=100) {
               spaces = “”;
            }
            return “Counter value “+spaces+value; 
         }
      
         // Listener that both revises label as user slides and updates current index when sliding stops.
          private class ColorChooserListener implements ChangeListener {
             public void stateChanged(ChangeEvent e) { 
               JSlider source = (JSlider)e.getSource(); 
               if (!source.getValueIsAdjusting()) { 
                  counterIndex = (int)source.getValue();
               } 
               else {
                  int count = countTable[(int)source.getValue()];
                  sliderLabel.setText(setLabel(count));
                  currentColorButton.setBackground(counterColorScale.getColor(count));
               }
            } 
         }
      }
      
        
    ////////////////////////////////////////////////////////////////////////////////
    // Object that represents mapping from counter value to color it is displayed as.
    //
       private class CounterColorScale {
         CounterColor[] counterColors;
        
          CounterColorScale(CounterColor[] colors) {
            counterColors = colors;
         }
      
        // return color associated with specified counter value
          private Color getColor(int count) {
            Color result = counterColors[0].associatedColor;
            int index=0;
            while (index < counterColors.length && count >= counterColors[index].colorRangeStart) {
               result = counterColors[index].associatedColor;
               index++;
            }
            return result;
         }      
        
         // For a given counter value, return the counter value at the high end of the range of
         // counter values having the same color.
          private int getHighEndOfRange(int count) {
            int highEnd = Integer.MAX_VALUE;
            if (count < counterColors[counterColors.length-1].colorRangeStart) {                int index=0;                while (index < counterColors.length-1 && count >= counterColors[index].colorRangeStart) {
                  highEnd = counterColors[index+1].colorRangeStart – 1;
                  index++;
               }
            }
            return highEnd;
         }
        
        // The given entry should either be inserted into the the scale or replace an existing
        // element.  The latter occurs if the new CounterColor has same starting counter value
        // as an existing one.
          private void insertOrReplace(CounterColor newColor) {
            int index = Arrays.binarySearch(counterColors, newColor);
            if (index >= 0) { // found, so replace
               counterColors[index] = newColor;
            } 
            else { // not found, so insert
               int insertIndex = -index-1;
               CounterColor[] newSortedArray = new CounterColor[counterColors.length+1]; 
               System.arraycopy(counterColors, 0, newSortedArray, 0, insertIndex); 
               System.arraycopy(counterColors, insertIndex, newSortedArray, insertIndex+1, counterColors.length-insertIndex); 
               newSortedArray[insertIndex] = newColor; 
               counterColors = newSortedArray;
            }
         }
      }
    
    
    ///////////////////////////////////////////////////////////////////////////////////////
      // Each object represents beginning of a counter value range (non-negative integer) and
    // color for rendering the range.  High end of the range is defined as low end of the
    // next range minus 1.  For last range, high end is Integer.MAX_VALUE.
       private class CounterColor implements Comparable {
         private int colorRangeStart;
         private Color associatedColor;
          public CounterColor(int start, Color color) {
            this.colorRangeStart = start;
            this.associatedColor = color;
         }
        
        // Necessary for sorting in ascending order of range low end.
          public int compareTo(Object other) {
            if (other instanceof CounterColor) {
               return this.colorRangeStart – ((CounterColor)other).colorRangeStart;
            } 
            else {
               throw new ClassCastException();
            }
         }
      }
      
    
      ////////////////////////////////////////////////////////////////////////
    // Represents grid of memory access counts
       private class Grid {
      
         int[][] grid;
         int rows, columns;
                  
          private Grid(int rows, int columns) {
            grid = new int[rows][columns];
            this.rows = rows;
            this.columns = columns;
          // automatically initialized to 0, so I won’t bother to….
         }
       
          private int getRows() {
            return rows;
         }
        
          private int getColumns() {
            return columns;
         }
      
        // Returns value in given grid element; -1 if row or column is out of range.            
          private int getElement(int row, int column) {
            return (row>=0 && row<=rows && column>=0 && column<=columns) ? grid[row][column] : -1;                    }                // Returns value in given grid element without doing any row/column index checking.         // Is faster than getElement but will throw array index out of bounds exception if         // parameter values are outside the bounds of the grid.                    private int getElementFast(int row, int column) {             return grid[row][column];                     }                          // Increment the given grid element and return incremented value.         // Returns -1 if row or column is out of range.           private int incrementElement(int row, int column) {             return (row>=0 && row<=rows && column>=0 && column<=columns) ? ++grid[row][column] : -1;          }                  // Just set all grid elements to 0.           private void reset() {             for (int i=0; i();
public void ScavengerHunt();
public String getName();
public void action();
public void update(java.util.Observable, Object);
private void toolSetWord(int, int);
private int toolGetWord(int);
private int toolReadPlayerData(int, int);
private void toolWritePlayerData(int, int, int);
private void initializeScavengerData();
}

KeyboardAndDisplaySimulator$UniformlyDistributedDelay

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$UniformlyDistributedDelay implements KeyboardAndDisplaySimulator$TransmitterDelayTechnique {
java.util.Random randu;
public void KeyboardAndDisplaySimulator$UniformlyDistributedDelay(KeyboardAndDisplaySimulator);
public String toString();
public int generateDelay(double);
}

ScavengerHunt$ScavengerHuntRunnable

package mars.tools;
synchronized class ScavengerHunt$ScavengerHuntRunnable implements Runnable {
javax.swing.JPanel panel;
public void ScavengerHunt$ScavengerHuntRunnable(ScavengerHunt);
public void run();
}

BitmapDisplay$3

package mars.tools;
synchronized class BitmapDisplay$3 implements java.awt.event.ActionListener {
void BitmapDisplay$3(BitmapDisplay);
public void actionPerformed(java.awt.event.ActionEvent);
}

AbstractMarsToolAndApplication$6

package mars.tools;
synchronized class AbstractMarsToolAndApplication$6 implements java.awt.event.ActionListener {
void AbstractMarsToolAndApplication$6(AbstractMarsToolAndApplication);
public void actionPerformed(java.awt.event.ActionEvent);
}

MemoryReferenceVisualization$GraphicsPanel

package mars.tools;
synchronized class MemoryReferenceVisualization$GraphicsPanel extends javax.swing.JPanel {
private void MemoryReferenceVisualization$GraphicsPanel(MemoryReferenceVisualization);
public void paint(java.awt.Graphics);
private void paintHashMarks(java.awt.Graphics, MemoryReferenceVisualization$Grid);
private void paintGrid(java.awt.Graphics, MemoryReferenceVisualization$Grid);
private java.awt.Color getContrastingColor(java.awt.Color);
}

MarsBot

package mars.tools;
public synchronized class MarsBot implements java.util.Observer, MarsTool {
private static final int GRAPHIC_WIDTH = 512;
private static final int GRAPHIC_HEIGHT = 512;
private static final int ADDR_HEADING = -32752;
private static final int ADDR_LEAVETRACK = -32736;
private static final int ADDR_WHEREAREWEX = -32720;
private static final int ADDR_WHEREAREWEY = -32704;
private static final int ADDR_MOVE = -32688;
private MarsBot$MarsBotDisplay graphicArea;
private int MarsBotHeading;
private boolean MarsBotLeaveTrack;
private double MarsBotXPosition;
private double MarsBotYPosition;
private boolean MarsBotMoving;
private final int trackPts;
private java.awt.Point[] arrayOfTrack;
private int trackIndex;
public void MarsBot();
public String getName();
public void action();
public void update(java.util.Observable, Object);
}

ScreenMagnifier

package mars.tools;
public synchronized class ScreenMagnifier implements MarsTool {
public void ScreenMagnifier();
public String getName();
public void action();
public static void main(String[]);
}

MemoryReferenceVisualization$3

package mars.tools;
synchronized class MemoryReferenceVisualization$3 implements java.awt.event.ActionListener {
void MemoryReferenceVisualization$3(MemoryReferenceVisualization);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/tools/MarsTool.java
mars/tools/MarsTool.javapackage mars.tools;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 *  Interface for any tool that interacts with an executing MIPS program.
 *  A qualifying tool must be a class in the Tools package that 
 *  implements the MarsTool interface, must be compiled into a .class file, 
 *  and its .class file must be in the same Tools folder as MarsTool.class.
 *  Mars will detect a qualifying tool upon startup, create an instance 
 *  using its no-argument constructor and add it to its Tools menu.  
 *  When its menu item is selected, the action() method will be invoked.
 *
 * 

A tool may receive communication from MIPS system resources
 *  (registers or memory) by registering as an Observer with 
 *  Mars.Memory and/or Mars.Register objects.  
 *
 *  It may also
 *  communicate directly with those resources through their
 *  published methods PROVIDED any such communication is
 *  wrapped inside a block synchronized on the 
 *  Mars.Globals.memoryAndRegistersLock object.
 */
 
public interface MarsTool {
 /**
  *  Return a name you have chosen for this tool.  It will appear as the
  *  menu item.
  */
  public abstract String getName();
  
  /**
   * Performs tool functions.  It will be invoked when the tool is selected
    * from the Tools menu.
    */
    
  public abstract void action();
}

Magnifier

package mars.tools;
synchronized class Magnifier extends javax.swing.JFrame implements java.awt.event.ComponentListener {
static java.awt.Robot robot;
javax.swing.JButton close;
javax.swing.JButton capture;
javax.swing.JButton settings;
javax.swing.JSpinner scaleAdjuster;
javax.swing.JScrollPane view;
java.awt.Dimension frameSize;
java.awt.Dimension viewSize;
MagnifierImage magnifierImage;
java.awt.event.ActionListener captureActionListener;
CaptureModel captureResize;
CaptureModel captureMove;
CaptureModel captureRescale;
CaptureModel captureDisplayCenter;
CaptureModel captureDisplayUpperleft;
CaptureModel dialogDisplayCenter;
ScribblerSettings scribblerSettings;
static final double SCALE_MINIMUM = 1.0;
static final double SCALE_MAXIMUM = 4.0;
static final double SCALE_INCREMENT = 0.5;
static final double SCALE_DEFAULT = 2.0;
double scale;
CaptureDisplayAlignmentStrategy alignment;
CaptureRectangleStrategy captureLocationSize;
javax.swing.JFrame frame;
static final String CAPTURE_TOOLTIP_TEXT = Capture, scale, and display pixels that lay beneath the Magnifier.;
static final String SETTINGS_TOOLTIP_TEXT = Show dialog for changing tool settings.;
static final String SCALE_TOOLTIP_TEXT = Magnification scale for captured image.;
static final String CLOSE_TOOLTIP_TEXT = Exit the Screen Magnifier. Changed settings are NOT retained.;
void Magnifier();
private void createSettings();
private javax.swing.JButton getHelpButton();
java.awt.image.BufferedImage captureScreenSection(java.awt.Rectangle);
java.awt.Rectangle getFrameRectangle();
java.awt.Rectangle getScreenRectangle();
public void componentMoved(java.awt.event.ComponentEvent);
public void componentResized(java.awt.event.ComponentEvent);
public void componentShown(java.awt.event.ComponentEvent);
public void componentHidden(java.awt.event.ComponentEvent);
}

BitmapDisplay$Grid

package mars.tools;
synchronized class BitmapDisplay$Grid {
java.awt.Color[][] grid;
int rows;
int columns;
private void BitmapDisplay$Grid(BitmapDisplay, int, int);
private int getRows();
private int getColumns();
private java.awt.Color getElement(int, int);
private java.awt.Color getElementFast(int, int);
private void setElement(int, int, int);
private void setElement(int, int, java.awt.Color);
private void reset();
}

KeyboardAndDisplaySimulator$FontSettingDialog$3

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$FontSettingDialog$3 implements java.awt.event.ActionListener {
void KeyboardAndDisplaySimulator$FontSettingDialog$3(KeyboardAndDisplaySimulator$FontSettingDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

ScavengerHunt$ScavengerHuntRunnable$1

package mars.tools;
synchronized class ScavengerHunt$ScavengerHuntRunnable$1 implements java.awt.event.ActionListener {
void ScavengerHunt$ScavengerHuntRunnable$1(ScavengerHunt$ScavengerHuntRunnable);
public void actionPerformed(java.awt.event.ActionEvent);
}

Magnifier$4

package mars.tools;
synchronized class Magnifier$4 implements javax.swing.event.ChangeListener {
void Magnifier$4(Magnifier);
public void stateChanged(javax.swing.event.ChangeEvent);
}

CaptureMagnifierRectangle

package mars.tools;
synchronized class CaptureMagnifierRectangle implements CaptureRectangleStrategy {
void CaptureMagnifierRectangle();
public java.awt.Rectangle getCaptureRectangle(java.awt.Rectangle);
}

BHTSimGUI$1

package mars.tools;
synchronized class BHTSimGUI$1 extends javax.swing.table.DefaultTableCellRenderer {
private java.text.DecimalFormat formatter;
void BHTSimGUI$1(BHTSimGUI);
public void setValue(Object);
}

KeyboardAndDisplaySimulator$FontSettingDialog$1

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$FontSettingDialog$1 implements java.awt.event.ActionListener {
void KeyboardAndDisplaySimulator$FontSettingDialog$1(KeyboardAndDisplaySimulator$FontSettingDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

MemoryReferenceVisualization$1

package mars.tools;
synchronized class MemoryReferenceVisualization$1 implements java.awt.event.ActionListener {
void MemoryReferenceVisualization$1(MemoryReferenceVisualization);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/tools/BHTSimGUI.java
mars/tools/BHTSimGUI.java/*
Copyright (c) 2009,  Ingo Kofler, ITEC, Klagenfurt University, Austria

Developed by Ingo Kofler (ingo. -klu.ac.at)

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

package mars.tools;//.bhtsim;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.text.DecimalFormat;
import java.util.Vector;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;

/**
 * Represents the GUI of the BHT Simulator Tool.
 * 

 * 
 * The GUI consists of mainly four parts:
 * 

     * 

  • A configuration panel to select the number of entries and the history size
     * 

  • A information panel that displays the most recent branch instruction including its address and BHT index
     * 

  • A table representing the BHT with all entries and their internal state and statistics
     * 

  • A log panel that summarizes the predictions in a textual form
     * 

 * 
 * @author ingo. -klu.ac.at
 */
//@SuppressWarnings(“serial”)
public class BHTSimGUI extends JPanel {
    
    /** text field presenting the most recent branch instruction */
    private JTextField m_tfInstruction;
    
    /** text field representing the address of the most recent branch instruction */
    private JTextField m_tfAddress;
    
    /** text field representing the resulting BHT index of the branch instruction */
    private JTextField m_tfIndex;

    /** combo box for selecting the number of BHT entries */
    private JComboBox m_cbBHTentries;
    
    /** combo box for selecting the history size */
    private JComboBox m_cbBHThistory;
    
    /** combo box for selecting the initial value */
    private JComboBox m_cbBHTinitVal;
    
    /** the table representing the BHT */
    private JTable m_tabBHT;
    
    /** text field for log output */
    private JTextArea m_taLog;
    
    /** constant for the color that highlights the current BHT entry */
    public final static Color COLOR_PREPREDICTION = Color.yellow;
    
    /** constant for the color to signal a correct prediction */
    public final static Color COLOR_PREDICTION_CORRECT = Color.green;
    
    /** constant for the color to signal a misprediction */
    public final static Color COLOR_PREDICTION_INCORRECT = Color.red;
    
    /** constant for the String representing “take the branch” */
    public final static String BHT_TAKE_BRANCH = “TAKE”;
    
    /** constant for the String representing “do not take the branch” */
    public final static String BHT_DO_NOT_TAKE_BRANCH = “NOT TAKE”;
    
    
    
    /**
     * Creates the GUI components of the BHT Simulator 
     * The GUI is a subclass of JPanel which is integrated in the GUI of the MARS tool 
     */
    public BHTSimGUI() {                            
        BorderLayout layout = new BorderLayout();
        layout.setVgap(10);
        layout.setHgap(10);     
        setLayout(layout);
        
        m_tabBHT = createAndInitTable();
        
        add(buildConfigPanel(), BorderLayout.NORTH);
        add(buildInfoPanel(), BorderLayout.WEST);
        add(new JScrollPane(m_tabBHT), BorderLayout.CENTER);
        add(buildLogPanel(), BorderLayout.SOUTH);           
    }
    
    /**
     * Creates and initializes the JTable representing the BHT.
     * 
     * @return the JTable representing the BHT
     */ 
    private JTable createAndInitTable() {
        // create the table
        JTable theTable = new JTable();                 
        
        // create a default renderer for double values (percentage) 
        DefaultTableCellRenderer doubleRenderer = new DefaultTableCellRenderer() {
            private DecimalFormat formatter = new DecimalFormat(“##0.00”);
            
            public void setValue(Object value) {                                       
                setText((value == null) ? “” : formatter.format(value));
            }   
        };              
        doubleRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        
        // create a default renderer for all other values with center alignment
        DefaultTableCellRenderer defRenderer = new DefaultTableCellRenderer();
        defRenderer.setHorizontalAlignment(SwingConstants.CENTER);      
        
        theTable.setDefaultRenderer(Double.class, doubleRenderer);
        theTable.setDefaultRenderer(Integer.class, defRenderer);
        theTable.setDefaultRenderer(String.class, defRenderer);
        
        theTable.setSelectionBackground(BHTSimGUI.COLOR_PREPREDICTION);
        theTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        
        return theTable;

    }
    
    
    /**
     * Creates and initializes the panel holding the instruction, address and index text fields.
     * 
     * @return the info panel 
     */ 
    private JPanel buildInfoPanel() {
        m_tfInstruction = new JTextField();     
        m_tfAddress = new JTextField();
        m_tfIndex = new JTextField();       
        
        m_tfInstruction.setColumns(10);     
        m_tfInstruction.setEditable(false);
        m_tfInstruction.setHorizontalAlignment(JTextField.CENTER);
        m_tfAddress.setColumns(10);
        m_tfAddress.setEditable(false);
        m_tfAddress.setHorizontalAlignment(JTextField.CENTER);
        m_tfIndex.setColumns(10);
        m_tfIndex.setEditable(false);
        m_tfIndex.setHorizontalAlignment(JTextField.CENTER);            
        
        JPanel panel = new JPanel();    
        JPanel outerPanel = new JPanel();
        outerPanel.setLayout(new BorderLayout());       
        
        GridBagLayout gbl = new GridBagLayout();        
        panel.setLayout(gbl);
        
        GridBagConstraints c = new GridBagConstraints();                
        
        c.insets = new Insets(5, 5, 2, 5);
        c.gridx = 1;         
        c.gridy = 1;
        
        panel.add(new JLabel(“Instruction”), c);
        c.gridy++;
        panel.add(m_tfInstruction, c);
        c.gridy++;
        panel.add(new JLabel(“@ Address”), c);      
        c.gridy++;
        panel.add(m_tfAddress, c);
        c.gridy++;
        panel.add(new JLabel(“-> Index”), c);
        c.gridy++;
        panel.add(m_tfIndex, c);
                        
        outerPanel.add(panel, BorderLayout.NORTH);
        return outerPanel;
    }
    
    
    /**
     * Creates and initializes the panel for the configuration of the tool
     * The panel contains two combo boxes for selecting the number of BHT entries and the history size.
     * 
     * @return a panel for the configuration
     */ 
    private JPanel buildConfigPanel() {
        JPanel panel = new JPanel();
        
        Vector sizes = new Vector();
        sizes.add(new Integer(8));
        sizes.add(new Integer(16));
        sizes.add(new Integer(32));
        
        Vector bits = new Vector();
        bits.add(new Integer(1));
        bits.add(new Integer(2));
        
        Vector initVals = new Vector();     
        initVals.add(BHTSimGUI.BHT_DO_NOT_TAKE_BRANCH);
        initVals.add(BHTSimGUI.BHT_TAKE_BRANCH);        
        
        m_cbBHTentries = new JComboBox(sizes);
        m_cbBHThistory = new JComboBox(bits);
        m_cbBHTinitVal = new JComboBox(initVals);
        
        panel.add(new JLabel(“# of BHT entries”));
        panel.add(m_cbBHTentries);
        panel.add(new JLabel(“BHT history size”));
        panel.add(m_cbBHThistory);
        panel.add(new JLabel(“Initial value”));
        panel.add(m_cbBHTinitVal);
        
        return panel;
    }
    
    
    /**
     * Creates and initializes the panel containing the log text area.
     * 
     * @return the panel for the logging output
     */ 
    private JPanel buildLogPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        m_taLog = new JTextArea();
        m_taLog.setRows(6);
        m_taLog.setEditable(false);

        panel.add(new JLabel(“Log”), BorderLayout.NORTH);
        panel.add(new JScrollPane(m_taLog), BorderLayout.CENTER);
        
        return panel;
    }
    

    /***
     * Returns the combo box for selecting the number of BHT entries.
     * 
     * @return the reference to the combo box
     */
    public JComboBox getCbBHTentries() {
        return m_cbBHTentries;
    }
    
    
    /***
     * Returns the combo box for selecting the size of the BHT history.
     * 
     * @return the reference to the combo box
     */ 
    public JComboBox getCbBHThistory() {
        return m_cbBHThistory;
    }

    
    /***
     * Returns the combo box for selecting the initial value of the BHT
     * 
     * @return the reference to the combo box
     */     
    public JComboBox getCbBHTinitVal() {
        return m_cbBHTinitVal;
    }
    
    /***
     * Returns the table representing the BHT.
     * 
     * @return the reference to the table
     */
    public JTable getTabBHT() {
        return m_tabBHT;
    }

    
    /***
     * Returns the text area for log purposes.
     * 
     * @return the reference to the text area
     */
    public JTextArea getTaLog() {
        return m_taLog;
    }
    
    
    /***
     * Returns the text field for displaying the most recent branch instruction 
     * 
     * @return the reference to the text field
     */
    public JTextField getTfInstruction() {
        return m_tfInstruction;
    }
    
    
    /***
     * Returns the text field for displaying the address of the most recent branch instruction 
     * 
     * @return the reference to the text field
     */
    public JTextField getTfAddress() {
        return m_tfAddress;
    }
    
    
    /***
     * Returns the text field for displaying the corresponding index into the BHT 
     * 
     * @return the reference to the text field
     */
    public JTextField getTfIndex() {
        return m_tfIndex;
    }

}

mars/tools/BHTableModel.java
mars/tools/BHTableModel.java/*
Copyright (c) 2009,  Ingo Kofler, ITEC, Klagenfurt University, Austria

Developed by Ingo Kofler (ingo. -klu.ac.at)

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

package mars.tools;//.bhtsim;

import java.util.Vector;

import javax.swing.table.AbstractTableModel;

/**
 * Simulates the actual functionality of a Branch History Table (BHT).
 * 

 * The BHT consists of a number of BHT entries which are used to perform branch prediction.
 * The entries of the BHT are stored as a Vector of BHTEntry objects.
 * The number of entries is configurable but has to be a power of 2.
 * The history kept by each BHT entry is also configurable during run-time.
 * A change of the configuration however causes a complete reset of the BHT.
 * 

 * The typical interaction is as follows:
 * 

     * 

  • Construction of a BHT with a certain number of entries with a given history size.
  •  * 

  • When encountering a branch instruction the index of the relevant BHT entry is calculated via the {@link BHTableModel#getIdxForAddress(int)} method.
  •  * 

  • The current prediction of the BHT entry at the calculated index is obtained via the {@link BHTableModel#getPredictionAtIdx(int)} method.
  •  * 

  • After detecting if the branch was really taken or not, this feedback is provided to the BHT by the {@link BHTableModel#updatePredictionAtIdx(int, boolean)} method.
  •  * 

 * 

 * Additionally it serves as TableModel that can be directly used to render the state of the BHT in a JTable.
 * Feedback provided to the BHT causes a change of the internal state and a repaint of the table(s) associated to this model. 
 * 
 * @author ingo. -klu.ac.at
 */

//@SuppressWarnings(“serial”)
public class BHTableModel extends AbstractTableModel {

    /** vector holding the entries of the BHT */ 
    private Vector m_entries;
    
    /** number of entries in the BHT */
    private int m_entryCnt;
    
    /** number of past branch events to remember */
    private int m_historySize;
    
    /** name of the table columns */
    private String m_columnNames[] = { “Index”, “History”, “Prediction”, “Correct”, “Incorrect”, “Precision”};
    
    /** type of the table columns */
    //@SuppressWarnings(“unchecked”)
    private Class m_columnClasses[] = { Integer.class, String.class, String.class, Integer.class, Integer.class, Double.class};

    
    /**
     * Constructs a new BHT with given number of entries and history size.
     * 
     * @param numEntries number of entries in the BHT
     * @param historySize size of the history (in bits/number of past branches)
     */
    public BHTableModel (int numEntries, int historySize, boolean initVal) {
        initBHT(numEntries, historySize, initVal);
    }   
    
    
    /**
     * Returns the name of the i-th column of the table.
     * Required by the TableModel interface. 
     * 
     * @param i the index of the column
     * @return name of the i-th column
     */
    public String getColumnName(int i) {
        if (i < 0 || i > m_columnNames.length) 
            throw new IllegalArgumentException(“Illegal column index ”  + i + ” (must be in range 0..” + (m_columnNames.length-1) + “)”);
        
        return m_columnNames[i];
    }
        
    
    /**
     * Returns the class/type of the i-th column of the table.
     * Required by the TableModel interface.
     * 
     * @param i the index of the column
     * @return class representing the type of the i-th column
     */    
    public Class getColumnClass(int i) {
        if (i < 0 || i > m_columnClasses.length) 
            throw new IllegalArgumentException(“Illegal column index ”  + i + ” (must be in range 0..” + (m_columnClasses.length-1) + “)”);
        
        return m_columnClasses[i];      
    }
    
    
    /**
     * Returns the number of columns.
     * Required by the TableModel interface. 
     * 
     * @return currently the constant 6
     */
    public int getColumnCount() {
        return 6;
    }
    

    /**
     * Returns the number of entries of the BHT.
     * Required by the TableModel interface.
     * 
     * @return number of rows / entries of the BHT
     */
    public int getRowCount() {      
        return m_entryCnt;
    }

    
    /**
     * Returns the value of the cell at the given row and column
     * Required by the TableModel interface.
     * 
     * @param row the row index
     * @param col the column index
     * @return the value of the cell
     */
    public Object getValueAt(int row, int col) { 
                
        BHTEntry e = (BHTEntry) m_entries.elementAt(row);
        if (e==null) return “”;
        
        if (col==0) return new Integer(row);        
        if (col==1) return e.getHistoryAsStr();
        if (col==2) return e.getPredictionAsStr();
        if (col==3) return new Integer(e.getStatsPredCorrect());
        if (col==4) return new Integer(e.getStatsPredIncorrect());
        if (col==5) return new Double(e.getStatsPredPrecision());
        
        return “”;
    }
    
    
    /**
     * Initializes the BHT with the given size and history.
     * All previous data like the BHT entries’ history and statistics will get lost.
     * A refresh of the table that use this BHT as model will be triggered. 
     *  
     * @param numEntries number of entries in the BHT (has to be a power of 2)
     * @param historySize size of the history to consider
     * @param initVal initial value for each entry (true means take branch, false do not take branch) 
     */
    public void initBHT(int numEntries, int historySize, boolean initVal) {
        
        if (numEntries <= 0 || (numEntries & (numEntries-1)) != 0)              throw new IllegalArgumentException("Number of entries must be a positive power of 2.");          if (historySize < 1 || historySize > 2) 
            throw new IllegalArgumentException(“Only history sizes of 1 or 2 supported.”);
        
        m_entryCnt = numEntries;
        m_historySize = historySize;
        
        m_entries = new Vector();
        
        for (int i=0; i < m_entryCnt; i++) {             m_entries.add(new BHTEntry(m_historySize, initVal));         }         // refresh the table(s)         fireTableStructureChanged();     }               /**       * Returns the index into the BHT for a given branch instruction address.      * A simple direct mapping is used.      *       * @param address the address of the branch instruction       * @return the index into the BHT      */     public int getIdxForAddress(int address) {         if (address < 0)              throw new IllegalArgumentException("No negative addresses supported");                  return (address >> 2) % m_entryCnt;     
    }
        
    
    /** 
     * Retrieve the prediction for the i-th BHT entry.
     * 
     * @param index the index of the entry in the BHT 
     * @return the prediction to take (true) or do not take (false) the branch
     */
    public boolean getPredictionAtIdx(int index) {
        if (index < 0 || index > m_entryCnt) 
            throw new IllegalArgumentException(“Only indexes in the range 0 to ” + (m_entryCnt-1) + ” allowed”);
        
        return ((BHTEntry) m_entries.elementAt(index)).getPrediction();
    }
    
    
    /**
     * Updates the BHT entry with the outcome of the branch instruction. 
     * This causes a change in the model and signals to update the connected table(s). 
     * 
     * @param index the index of the entry in the BHT 
     * @param branchTaken 
     */
    public void updatePredictionAtIdx(int index, boolean branchTaken) {
        if (index < 0 || index > m_entryCnt) 
            throw new IllegalArgumentException(“Only indexes in the range 0 to ” + (m_entryCnt-1) + ” allowed”);
        
        ((BHTEntry) m_entries.elementAt(index)).updatePrediction(branchTaken);
        fireTableRowsUpdated(index, index);
    }

}

SettingsDialog$2

package mars.tools;
synchronized class SettingsDialog$2 implements java.awt.event.ActionListener {
void SettingsDialog$2(SettingsDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

BHTSimGUI

package mars.tools;
public synchronized class BHTSimGUI extends javax.swing.JPanel {
private javax.swing.JTextField m_tfInstruction;
private javax.swing.JTextField m_tfAddress;
private javax.swing.JTextField m_tfIndex;
private javax.swing.JComboBox m_cbBHTentries;
private javax.swing.JComboBox m_cbBHThistory;
private javax.swing.JComboBox m_cbBHTinitVal;
private javax.swing.JTable m_tabBHT;
private javax.swing.JTextArea m_taLog;
public static final java.awt.Color COLOR_PREPREDICTION;
public static final java.awt.Color COLOR_PREDICTION_CORRECT;
public static final java.awt.Color COLOR_PREDICTION_INCORRECT;
public static final String BHT_TAKE_BRANCH = TAKE;
public static final String BHT_DO_NOT_TAKE_BRANCH = NOT TAKE;
static void ();
public void BHTSimGUI();
private javax.swing.JTable createAndInitTable();
private javax.swing.JPanel buildInfoPanel();
private javax.swing.JPanel buildConfigPanel();
private javax.swing.JPanel buildLogPanel();
public javax.swing.JComboBox getCbBHTentries();
public javax.swing.JComboBox getCbBHThistory();
public javax.swing.JComboBox getCbBHTinitVal();
public javax.swing.JTable getTabBHT();
public javax.swing.JTextArea getTaLog();
public javax.swing.JTextField getTfInstruction();
public javax.swing.JTextField getTfAddress();
public javax.swing.JTextField getTfIndex();
}

CaptureDisplayCentered

package mars.tools;
synchronized class CaptureDisplayCentered implements CaptureDisplayAlignmentStrategy {
void CaptureDisplayCentered();
public void setScrollBarValue(javax.swing.JScrollBar);
}

AbstractMarsToolAndApplication$8

package mars.tools;
synchronized class AbstractMarsToolAndApplication$8 implements java.awt.event.ActionListener {
void AbstractMarsToolAndApplication$8(AbstractMarsToolAndApplication);
public void actionPerformed(java.awt.event.ActionEvent);
}

InstructionCounter

package mars.tools;
public synchronized class InstructionCounter extends AbstractMarsToolAndApplication {
private static String name;
private static String version;
private static String heading;
protected int counter;
private javax.swing.JTextField counterField;
protected int counterR;
private javax.swing.JTextField counterRField;
private javax.swing.JProgressBar progressbarR;
protected int counterI;
private javax.swing.JTextField counterIField;
private javax.swing.JProgressBar progressbarI;
protected int counterJ;
private javax.swing.JTextField counterJField;
private javax.swing.JProgressBar progressbarJ;
protected int lastAddress;
static void ();
public void InstructionCounter(String, String);
public void InstructionCounter();
public String getName();
protected javax.swing.JComponent buildMainDisplayArea();
protected void addAsObserver();
protected void processMIPSUpdate(java.util.Observable, mars.mips.hardware.AccessNotice);
protected void initializePreGUI();
protected void reset();
protected void updateDisplay();
}

MarsBot$MarsBotDisplay

package mars.tools;
synchronized class MarsBot$MarsBotDisplay extends javax.swing.JPanel {
private int width;
private int height;
private boolean clearTheDisplay;
public void MarsBot$MarsBotDisplay(MarsBot, int, int);
public void redraw();
public void clear();
public void paintComponent(java.awt.Graphics);
}

KeyboardAndDisplaySimulator$KeyboardKeyListener

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$KeyboardKeyListener implements java.awt.event.KeyListener {
private void KeyboardAndDisplaySimulator$KeyboardKeyListener(KeyboardAndDisplaySimulator);
public void keyTyped(java.awt.event.KeyEvent);
public void keyPressed(java.awt.event.KeyEvent);
public void keyReleased(java.awt.event.KeyEvent);
}

DigitalLabSim

package mars.tools;
public synchronized class DigitalLabSim extends AbstractMarsToolAndApplication {
private static String heading;
private static String version;
private static final int IN_ADRESS_DISPLAY_1;
private static final int IN_ADRESS_DISPLAY_2;
private static final int IN_ADRESS_HEXA_KEYBOARD;
private static final int IN_ADRESS_COUNTER;
private static final int OUT_ADRESS_HEXA_KEYBOARD;
public static final int EXTERNAL_INTERRUPT_TIMER = 256;
public static final int EXTERNAL_INTERRUPT_HEXA_KEYBOARD = 512;
private static javax.swing.JPanel panelTools;
private DigitalLabSim$SevenSegmentPanel sevenSegPanel;
private static int KeyBoardValueButtonClick;
private DigitalLabSim$HexaKeyboard hexaKeyPanel;
private static boolean KeyboardInterruptOnOff;
private static int CounterValueMax;
private static int CounterValue;
private static boolean CounterInterruptOnOff;
private static DigitalLabSim$OneSecondCounter SecondCounter;
static void ();
public void DigitalLabSim(String, String);
public void DigitalLabSim();
public static void main(String[]);
public String getName();
protected void addAsObserver();
public void update(java.util.Observable, Object);
protected void reset();
protected javax.swing.JComponent buildMainDisplayArea();
private synchronized void updateMMIOControlAndData(int, int);
protected javax.swing.JComponent getHelpComponent();
public void updateSevenSegment(int, char);
public void updateHexaKeyboard(char);
public void updateOneSecondCounter(char);
}

MemoryReferenceVisualization$ColorChooserControls$ColorChooserListener

package mars.tools;
synchronized class MemoryReferenceVisualization$ColorChooserControls$ColorChooserListener implements javax.swing.event.ChangeListener {
private void MemoryReferenceVisualization$ColorChooserControls$ColorChooserListener(MemoryReferenceVisualization$ColorChooserControls);
public void stateChanged(javax.swing.event.ChangeEvent);
}

Magnifier$2

package mars.tools;
synchronized class Magnifier$2 implements java.awt.event.ActionListener {
void Magnifier$2(Magnifier);
public void actionPerformed(java.awt.event.ActionEvent);
}

CaptureModel

package mars.tools;
synchronized class CaptureModel {
private boolean enabled;
public void CaptureModel(boolean);
public boolean isEnabled();
public void setEnabled(boolean);
}

BHTSimulator

package mars.tools;
public synchronized class BHTSimulator extends AbstractMarsToolAndApplication implements java.awt.event.ActionListener {
public static final int BHT_DEFAULT_SIZE = 16;
public static final int BHT_DEFAULT_HISTORY = 1;
public static final boolean BHT_DEFAULT_INITVAL = 0;
public static final String BHT_NAME = BHT Simulator;
public static final String BHT_VERSION = Version 1.0 (Ingo Kofler);
public static final String BHT_HEADING = Branch History Table Simulator;
private BHTSimGUI m_gui;
private BHTableModel m_bhtModel;
private int m_pendingBranchInstAddress;
private boolean m_lastBranchTaken;
public void BHTSimulator();
protected void addAsObserver();
protected javax.swing.JComponent buildMainDisplayArea();
public String getName();
protected void reset();
public void actionPerformed(java.awt.event.ActionEvent);
protected void resetSimulator();
protected void handlePreBranchInst(mars.ProgramStatement);
protected void handleExecBranchInst(int, boolean);
protected static boolean isBranchInstruction(mars.ProgramStatement);
protected static boolean willBranch(mars.ProgramStatement);
protected static int extractBranchAddress(mars.ProgramStatement);
protected void processMIPSUpdate(java.util.Observable, mars.mips.hardware.AccessNotice);
}

mars/tools/AbstractMarsToolAndApplication.java
mars/tools/AbstractMarsToolAndApplication.java   package mars.tools;
   import javax.swing.*;
   import javax.swing.border.*;
   import javax.swing.filechooser.FileFilter;
   import java.awt.*;
   import java.awt.event.*;
   import java.util.*;
   import java.io.*;
   import mars.*;
   import mars.util.*;
   import mars.tools.*;
   import mars.mips.hardware.*;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
     * An abstract class that provides generic components to facilitate implementation of
     * a MarsTool and/or stand-alone Mars-based application.  Provides default definitions
     * of both the action() method required to implement MarsTool and the go() method 
     * conventionally used to launch a Mars-based stand-alone application. It also provides
     * generic definitions for interactively controlling the application.  The generic controls
     * for MarsTools are 3 buttons:  connect/disconnect to MIPS resource (memory and/or
     * registers), reset, and close (exit).  The generic controls for stand-alone Mars apps
     * include: button that triggers a file open dialog, a text field to display status
     * messages, the run-speed slider to control execution rate when running a MIPS program,
     * a button that assembles and runs the current MIPS program, a button to interrupt
     * the running MIPS program, a reset button, and an exit button.
     * Pete Sanderson, 14 November 2006.
     */
    public abstract class AbstractMarsToolAndApplication extends JFrame implements MarsTool, Observer {
      protected boolean isBeingUsedAsAMarsTool = false;  // can use to determine whether invoked as MarsTool or stand-alone.
      protected AbstractMarsToolAndApplication thisMarsApp;
      private JDialog dialog;  // used only for MarsTool use.  This is the pop-up dialog that appears when menu item selected.
      protected Window theWindow;  // highest level GUI component (a JFrame for app, a JDialog for MarsTool)
    
    // Major GUI components
      JLabel headingLabel;
      private String title;  // descriptive title for title bar provided to constructor.
      private String heading; // Text to be displayed in the top portion of the main window.
    
    // Some GUI settings
      private EmptyBorder emptyBorder = new EmptyBorder(4,4,4,4);
      private Color backgroundColor = Color.WHITE;
    
    
      private int lowMemoryAddress = Memory.dataSegmentBaseAddress;
      private int highMemoryAddress = Memory.stackBaseAddress;
    // For MarsTool, is set true when “Connect” clicked, false when “Disconnect” clicked.
    // For app, is set true when “Assemble and Run” clicked, false when program terminates.
      private volatile boolean observing = false;
   
    // Several structures required for stand-alone use only (not MarsTool use)
      private File mostRecentlyOpenedFile = null; 
      private Runnable interactiveGUIUpdater = new GUIUpdater();
      private MessageField operationStatusMessages;
      private JButton openFileButton, assembleRunButton, stopButton;
      private boolean multiFileAssemble = false;
    
      // Structure required for MarsTool use only (not stand-alone use). Want subclasses to have access.
      protected ConnectButton connectButton;      
   
   
      /**
     * Simple constructor
     * @param title String containing title bar text
     */
       protected AbstractMarsToolAndApplication(String title,String heading) {
         thisMarsApp = this;
         this.title = title;
         this.heading = heading;
      }
   
   //////////////////////////////////////////////////////////////////////////////////////
   //////////////////////////////      ABSTRACT METHODS       ///////////////////////////
   //////////////////////////////////////////////////////////////////////////////////////
   
       /**
      *  Required MarsTool method to return Tool name.  Must be defined by subclass.
      *  @return  Tool name.  MARS will display this in menu item.
      */
       public abstract String getName();
   
      /**
     *  Abstract method that must be instantiated by subclass to build the main display area
     *  of the GUI.  It will be placed in the CENTER area of a BorderLayout.  The title
     *  is in the NORTH area, and the controls are in the SOUTH area.
     */
       protected abstract JComponent buildMainDisplayArea();
   
   //////////////////////////////////////////////////////////////////////////////////////
   /////////////////////////////  METHODS WITH DEFAULT IMPLEMENTATIONS //////////////////   
   //////////////////////////////////////////////////////////////////////////////////////
    
    /** 
     * Run the simulator as stand-alone application.  For this default implementation, 
     * the user-defined main display of the user interface is identical for both stand-alone
     * and MARS Tools menu use, but the control buttons are different because the stand-alone
     * must include a mechansim for controlling the opening, assembling, and executing of
     * an underlying MIPS program.  The generic controls include: a button that triggers a 
     * file open dialog, a text field to display status messages, the run-speed slider 
     * to control execution rate when running a MIPS program, a button that assembles and 
     * runs the current MIPS program, a reset button, and an exit button.
     * This method calls 3 methods that can be defined/overriden in the subclass: initializePreGUI()
     * for any special initialization that must be completed before building the user 
     * interface (e.g. data structures whose properties determine default GUI settings), 
     * initializePostGUI() for any special initialization that cannot be
     * completed until after the building the user interface (e.g. data structure whose
     * properties are determined by default GUI settings), and buildMainDisplayArea()
     * to contain application-specific displays of parameters and results.
     */
       public void go() {
         theWindow = this;
         this.isBeingUsedAsAMarsTool = false;
         thisMarsApp.setTitle(this.title);
         mars.Globals.initialize(true);                 
        // assure the dialog goes away if user clicks the X
         thisMarsApp.addWindowListener(
                new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                     performAppClosingDuties();
                  }
               });
         initializePreGUI();
      
         JPanel contentPane = new JPanel(new BorderLayout(5,5));
         contentPane.setBorder(emptyBorder);
         contentPane.setOpaque(true);
         contentPane.add(buildHeadingArea(), BorderLayout.NORTH);
         contentPane.add(buildMainDisplayArea(), BorderLayout.CENTER);
         contentPane.add(buildButtonAreaStandAlone(), BorderLayout.SOUTH);
        
         thisMarsApp.setContentPane(contentPane);
         thisMarsApp.pack(); 
         thisMarsApp.setLocationRelativeTo(null); // center on screen     
         thisMarsApp.setVisible(true);
         initializePostGUI();
      }
    
    
     /** 
      * Required MarsTool method to carry out Tool functions.  It is invoked when MARS 
      * user selects this tool from the Tools menu.  This default implementation provides
        * generic definitions for interactively controlling the tool.  The generic controls
        * for MarsTools are 3 buttons:  connect/disconnect to MIPS resource (memory and/or
        * registers), reset, and close (exit).  Like “go()” above, this default version
      * calls 3 methods that can be defined/overriden in the subclass: initializePreGUI()
      * for any special initialization that must be completed before building the user 
      * interface (e.g. data structures whose properties determine default GUI settings), 
      * initializePostGUI() for any special initialization that cannot be
      * completed until after the building the user interface (e.g. data structure whose
      * properties are determined by default GUI settings), and buildMainDisplayArea()
      * to contain application-specific displays of parameters and results.
      */
   
       public void action() {
         this.isBeingUsedAsAMarsTool = true;
         dialog = new JDialog(Globals.getGui(), this.title);
        // assure the dialog goes away if user clicks the X
         dialog.addWindowListener(
                new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                     performToolClosingDuties();
                  }
               });      
         theWindow = dialog;
         initializePreGUI();
         JPanel contentPane = new JPanel(new BorderLayout(5,5));
         contentPane.setBorder(emptyBorder);
         contentPane.setOpaque(true);
         contentPane.add(buildHeadingArea(), BorderLayout.NORTH);
         contentPane.add(buildMainDisplayArea(),BorderLayout.CENTER);
         contentPane.add(buildButtonAreaMarsTool(), BorderLayout.SOUTH);
         initializePostGUI();
         dialog.setContentPane(contentPane);
         dialog.pack();      
         dialog.setLocationRelativeTo(Globals.getGui());
         dialog.setVisible(true);
      }
    
   
      /**
     *  Method that will be called once just before the GUI is constructed in the go() and action()
     *  methods.  Use it to initialize any data structures needed for the application whose values
     *  will be needed to determine the initial state of GUI components.  By default it does nothing.
     */
       protected void initializePreGUI() {
      }
   
      /**
     *  Method that will be called once just after the GUI is constructed in the go() and action()
     *  methods.  Use it to initialize data structures needed for the application whose values
     *  may depend on the initial state of GUI components.  By default it does nothing.
     */
       protected void initializePostGUI() {
      }
   
      /**
     *  Method that will be called each time the default Reset button is clicked.
     *  Use it to reset any data structures and/or GUI components.  By default it does nothing.
     */
       protected void reset() {
      }
   
      
    /**
     *  Constructs GUI header as label with default positioning and font.  May be overridden.
     */ 
       protected JComponent buildHeadingArea() {
        // OVERALL STRUCTURE OF MESSAGE (TOP)
         headingLabel = new JLabel();
         Box headingPanel = Box.createHorizontalBox();//new JPanel(new BorderLayout());
         headingPanel.add(Box.createHorizontalGlue());
         headingPanel.add(headingLabel);
         headingPanel.add(Box.createHorizontalGlue());
        // Details for heading area (top)
         headingLabel.setText(heading);
         headingLabel.setHorizontalTextPosition(JLabel.CENTER);
         headingLabel.setFont(new Font(headingLabel.getFont().getFontName(),Font.PLAIN,18));
         return headingPanel;
      } 
   
   
   
      /**
     *  The MarsTool default set of controls has one row of 3 buttons.  It includes a dual-purpose button to 
     *  attach or detach simulator to MIPS memory, a button to reset the cache, and one to close the tool.
     */
       protected JComponent buildButtonAreaMarsTool() {
         Box buttonArea = Box.createHorizontalBox();
         TitledBorder tc =new TitledBorder(“Tool Control”);
         tc.setTitleJustification(TitledBorder.CENTER);
         buttonArea.setBorder(tc);
         connectButton = new ConnectButton();
         connectButton.setToolTipText(“Control whether tool will respond to running MIPS program”);
         connectButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     if (connectButton.isConnected()) {
                        connectButton.disconnect();
                     } 
                     else {
                        connectButton.connect();
                     }
                  }
               });
         connectButton.addKeyListener(new EnterKeyListener(connectButton));
        
         JButton resetButton = new JButton(“Reset”);
         resetButton.setToolTipText(“Reset all counters and other structures”);
         resetButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     reset();
                  }
               });
         resetButton.addKeyListener(new EnterKeyListener(resetButton));
        
         JButton closeButton = new JButton(“Close”);
         closeButton.setToolTipText(“Close (exit) this tool”);
         closeButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     performToolClosingDuties();
                  }
               });
         closeButton.addKeyListener(new EnterKeyListener(closeButton));
      
        // Add all the buttons…
         buttonArea.add(connectButton);
         buttonArea.add(Box.createHorizontalGlue());
         buttonArea.add(resetButton);
         buttonArea.add(Box.createHorizontalGlue());
         JComponent helpComponent = getHelpComponent();
         if (helpComponent != null) {
            buttonArea.add(helpComponent);
            buttonArea.add(Box.createHorizontalGlue());
         }
         buttonArea.add(closeButton);
         return buttonArea;
      }
   
      /**
     *  The Mars stand-alone app default set of controls has two rows of controls.  It includes a text field for
     *  displaying status messages, a button to trigger an open file dialog, the MARS run speed slider
     *  to control timed execution, a button to assemble and run the program, a reset button
     *  whose action is determined by the subclass reset() method, and an exit button.
     */
   
       protected JComponent buildButtonAreaStandAlone() {
         // Overall structure of control area (two rows).
         Box operationArea = Box.createVerticalBox();
         Box fileControlArea = Box.createHorizontalBox();
         Box buttonArea = Box.createHorizontalBox();
         operationArea.add(fileControlArea);
         operationArea.add(Box.createVerticalStrut(5));
         operationArea.add(buttonArea);
         TitledBorder ac =new TitledBorder(“Application Control”);
         ac.setTitleJustification(TitledBorder.CENTER);
         operationArea.setBorder(ac);
        
        // Top row of controls consists of button to launch file open operation, 
        // text field to show filename, and run speed slider.
         openFileButton = new JButton(“Open MIPS program…”);
         openFileButton.setToolTipText(“Select MIPS program file to assemble and run”);
         openFileButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     JFileChooser fileChooser = new JFileChooser();
                     JCheckBox multiFileAssembleChoose = new JCheckBox(“Assemble all in selected file’s directory”,multiFileAssemble);
                     multiFileAssembleChoose.setToolTipText(“If checked, selected file will be assembled first and all other assembly files in directory will be assembled also.”);
                     fileChooser.setAccessory(multiFileAssembleChoose);
                     if (mostRecentlyOpenedFile != null) {
                        fileChooser.setSelectedFile(mostRecentlyOpenedFile);
                     }
                     // DPS 13 June 2007.  The next 4 lines add file filter to file chooser.
                     FileFilter defaultFileFilter = FilenameFinder.getFileFilter(Globals.fileExtensions, “Assembler Files”, true);
                     fileChooser.addChoosableFileFilter(defaultFileFilter); 
                     fileChooser.addChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
                     fileChooser.setFileFilter(defaultFileFilter);      
                  
                     if (fileChooser.showOpenDialog(thisMarsApp) == JFileChooser.APPROVE_OPTION) {
                        multiFileAssemble = multiFileAssembleChoose.isSelected();
                        File theFile = fileChooser.getSelectedFile();
                        try {
                           theFile = theFile.getCanonicalFile();
                        } 
                            catch (IOException ioe) {
                           // nothing to do, theFile will keep current value
                           }
                        String currentFilePath = theFile.getPath();
                        mostRecentlyOpenedFile = theFile;
                        operationStatusMessages.setText(“File: “+currentFilePath);
                        operationStatusMessages.setCaretPosition(0);
                        assembleRunButton.setEnabled(true);
                     }
                  }
               });
         openFileButton.addKeyListener(new EnterKeyListener(openFileButton));
                
         operationStatusMessages = new MessageField(“No file open.”);
         operationStatusMessages.setColumns(40);
         operationStatusMessages.setMargin(new Insets(0, 3, 0, 3)); //(top, left, bottom, right)
         operationStatusMessages.setBackground(backgroundColor);
         operationStatusMessages.setFocusable(false);
         operationStatusMessages.setToolTipText(“Display operation status messages”);
        
         mars.venus.RunSpeedPanel speed = mars.venus.RunSpeedPanel.getInstance();
      
         // Bottom row of controls consists of the three buttons defined here.
         assembleRunButton = new JButton(“Assemble and Run”);
         assembleRunButton.setToolTipText(“Assemble and run the currently selected MIPS program”);
         assembleRunButton.setEnabled(false);
         assembleRunButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     assembleRunButton.setEnabled(false);
                     openFileButton.setEnabled(false);
                     stopButton.setEnabled(true);
                     new Thread(new CreateAssembleRunMIPSprogram()).start();
                  }
               });
         assembleRunButton.addKeyListener(new EnterKeyListener(assembleRunButton));
      
         stopButton = new JButton(“Stop”);
         stopButton.setToolTipText(“Terminate MIPS program execution”);
         stopButton.setEnabled(false);
         stopButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     mars.simulator.Simulator.getInstance().stopExecution(null);
                  }
               });
         stopButton.addKeyListener(new EnterKeyListener(stopButton));
        
         JButton resetButton = new JButton(“Reset”);
         resetButton.setToolTipText(“Reset all counters and other structures”);
         resetButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     reset();
                  }
               });
         resetButton.addKeyListener(new EnterKeyListener(resetButton)); 
            
         JButton closeButton = new JButton(“Exit”);
         closeButton.setToolTipText(“Exit this application”);
         closeButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     performAppClosingDuties();
                  }
               });
         closeButton.addKeyListener(new EnterKeyListener(closeButton));
      
                
        // Add top row of controls…
         //fileControlArea.add(Box.createHorizontalStrut(5));
      
         Box fileDisplayBox = Box.createVerticalBox();
         fileDisplayBox.add(Box.createVerticalStrut(8));
         fileDisplayBox.add(operationStatusMessages);
         fileDisplayBox.add(Box.createVerticalStrut(8));
         fileControlArea.add(fileDisplayBox);
      
         fileControlArea.add(Box.createHorizontalGlue());
         fileControlArea.add(speed);
        
        // Add bottom row of buttons…
        
         buttonArea.add(openFileButton);
         buttonArea.add(Box.createHorizontalGlue());            
         buttonArea.add(assembleRunButton);
         buttonArea.add(Box.createHorizontalGlue());
         buttonArea.add(stopButton);
         buttonArea.add(Box.createHorizontalGlue());
         buttonArea.add(resetButton);
         buttonArea.add(Box.createHorizontalGlue());
         JComponent helpComponent = getHelpComponent();
         if (helpComponent != null) {
            buttonArea.add(helpComponent);
            buttonArea.add(Box.createHorizontalGlue());
         }
         buttonArea.add(closeButton);
         return operationArea;
      }
   
      //////////////////////////////////////////////////////////////////////////////////////
      //  Rest of the methods.  Some are used by stand-alone (JFrame-based) only, some are
    //  used by MarsTool (JDialog-based) only, others are used by both.
      //////////////////////////////////////////////////////////////////////////////////////
    
      /**
     * Called when receiving notice of access to MIPS memory or registers.  Default
     * implementation of method required by Observer interface.  This method will filter out
     * notices originating from the MARS GUI or from direct user editing of memory or register
     * displays.  Only notices arising from MIPS program access are allowed in.  
     * It then calls two methods to be overridden by the subclass (since they do 
     * nothing by default): processMIPSUpdate() then updateDisplay().
     * @param resource the attached MIPS resource 
     * @param accessNotice AccessNotice information provided by the resource
     */
       public void update(Observable resource, Object accessNotice) {
         if (((AccessNotice)accessNotice).accessIsFromMIPS()) { 
            processMIPSUpdate(resource, (AccessNotice)accessNotice);
            updateDisplay();
         }
      }
    
    /**
     * Override this method to process a received notice from MIPS Observable (memory or register)
     * It will only be called if the notice was generated as the result of MIPS instruction execution.
     * By default it does nothing. After this method is complete, the updateDisplay() method will be 
     * invoked automatically.
     */
       protected void processMIPSUpdate(Observable resource, AccessNotice notice) {
      }
    
    /**
     *  This method is called when tool/app is exited either through the close/exit button or the window’s X box.
     *  Override it to perform any special housecleaning needed.  By default it does nothing.
     */
       protected void performSpecialClosingDuties() {
      }
     
   
      /**
     *  Add this app/tool as an Observer of desired MIPS Observables (memory and registers).
     *  By default, will add as an Observer of the entire Data Segment in memory.
     *  Override if you want something different.  Note that the Memory methods to add an 
     *  Observer to memory are flexible (you can register for a range of addresses) but
     *  may throw an AddressErrorException that you need to catch.
     *  This method is called whenever the default “Connect” button on a MarsTool or the 
     *  default “Assemble and run” on a stand-alone Mars app is selected.  The corresponding
     *  NOTE: if you do not want to register as an Observer of the entire data segment
     *  (starts at address 0x10000000) then override this to either do some alternative
     *  or nothing at all.  This method is also overloaded to allow arbitrary memory
     *  subrange.
     */
    
       protected void addAsObserver() {
         addAsObserver(lowMemoryAddress, highMemoryAddress);
      }
   
      /**
     *  Add this app/tool as an Observer of the specified subrange of MIPS memory.  Note
     *  that this method is not invoked automatically like the no-argument version, but
     *  if you use this method, you can still take advantage of provided default deleteAsObserver()
     *  since it will remove the app as a memory observer regardless of the subrange
     *  or number of subranges it is registered for.
     *  @param lowEnd low end of memory address range.
     *  @param highEnd high end of memory address range; must be >= lowEnd
     */
    
       protected void addAsObserver(int lowEnd, int highEnd) {
         String errorMessage = “Error connecting to MIPS memory”;
         try {
            Globals.memory.addObserver(thisMarsApp,lowEnd, highEnd);
         } 
             catch (AddressErrorException aee) {
               if (this.isBeingUsedAsAMarsTool) {
                  headingLabel.setText(errorMessage);
               } 
               else {
                  operationStatusMessages.displayTerminatingMessage(errorMessage);
               }
            }        
      }
   
      /**
     *  Add this app/tool as an Observer of the specified MIPS register.
     */
       protected void addAsObserver(Register reg) {
         if (reg != null) {
            reg.addObserver(thisMarsApp);
         }
      }
   
     
      /**
     *  Delete this app/tool as an Observer of MIPS Observables (memory and registers).
     *  By default, will delete as an Observer of memory.
     *  Override if you want something different.
     *  This method is called when the default “Disconnect” button on a MarsTool is selected or 
     *  when the MIPS program execution triggered by the default “Assemble and run” on a stand-alone
     *  Mars app terminates (e.g. when the button is re-enabled).
     */      
     
       protected void deleteAsObserver() {
         Globals.memory.deleteObserver(thisMarsApp);
      }
   
      /**
     * Delete this app/tool as an Observer of the specified MIPS register
     */
     
       protected void deleteAsObserver(Register reg) {
         if (reg != null) {
            reg.deleteObserver(thisMarsApp);
         }
      }
    
    /**
     * Query method to let you know if the tool/app is (or could be) currently 
     * “observing” any MIPS resources.  When running as a MarsTool, this
     * will be true by default after clicking the “Connect to MIPS” button until “Disconnect
     * from MIPS” is clicked.  When running as a stand-alone app, this will be
     * true by default after clicking the “Assemble and Run” button until until
     * program execution has terminated either normally or by clicking the “Stop”
     * button.  The phrase “or could be” was added above because depending on how
     * the tool/app operates, it may be possible to run the MIPS program without 
     * first registering as an Observer — i.e. addAsObserver() is overridden and 
     * takes no action.
     * @return true if tool/app is (or could be) currently active as an Observer.
     */
     
       protected boolean isObserving() {
         return observing;
      }
    
    /**
     * Override this method to implement updating of GUI after each MIPS instruction is executed,
     * while running in “timed” mode (user specifies execution speed on the slider control).
     * Does nothing by default.
     */
       protected void updateDisplay() {
      }
   
      /**
     * Override this method to provide a JComponent (probably a JButton) of your choice
     * to be placed just left of the Close/Exit button.  Its anticipated use is for a 
     * “help” button that launches a help message or dialog.  But it can be any valid
     * JComponent that doesn’t mind co-existing among a bunch of JButtons.
     */
       protected JComponent getHelpComponent() {
         return null;
      }
   
   //////////////////////////////////////////////////////////////////////////////////
   ////////////////////  PRIVATE HELPER METHODS    //////////////////////////////////
   //////////////////////////////////////////////////////////////////////////////////
   
       // Closing duties for MarsTool only.
       private void performToolClosingDuties() {
         performSpecialClosingDuties();
         if (connectButton.isConnected()) {
            connectButton.disconnect();
         }
         dialog.setVisible(false);
         dialog.dispose();
      }
    
    // Closing duties for stand-alone application only.
       private void performAppClosingDuties() {
         performSpecialClosingDuties();
         thisMarsApp.setVisible(false);
         System.exit(0);
      }
   
   
   //////////////////////////////////////////////////////////////////////////////////
   ////////////////////  PRIVATE HELPER CLASSES    //////////////////////////////////
   //  Specialized inner classes.  Either used by stand-alone (JFrame-based) only  //
   //  or used by MarsTool (JDialog-based) only.                                   //
   //////////////////////////////////////////////////////////////////////////////////
    
     //////////////////////////////////////////////////////////////////////     
     // Little class for this dual-purpose button.  It is used only by the MarsTool
     // (not by the stand-alone app).
       protected class ConnectButton extends JButton {
         private static final String connectText = “Connect to MIPS”;
         private static final String disconnectText = “Disconnect from MIPS”;
        
          public ConnectButton() {
            super();
            disconnect();
         }
        
          public void connect() {
            observing = true;
            synchronized (Globals.memoryAndRegistersLock) {// DPS 23 July 2008
               addAsObserver();
            }
            setText(disconnectText);
         }
        
          public void disconnect() {
            synchronized (Globals.memoryAndRegistersLock) {// DPS 23 July 2008
               deleteAsObserver();
            }
            observing = false;
            setText(connectText);
         }
        
          public boolean isConnected() {
            return observing;
         }
      }
   
    
       ///////////////////////////////////////////////////////////////////////
     //  Every control button will get one of these so when it has focus
     //  the Enter key can be used instead of a mouse click to perform
     //  its associated action.  It will do nothing if no action listeners
     //  are attached to the button at the time of the call.  Otherwise,
     //  it will call actionPerformed for the first action listener in the
     //  button’s list.
       protected class EnterKeyListener extends KeyAdapter {
         AbstractButton myButton;
          public EnterKeyListener(AbstractButton who) {
            myButton = who;
         }
          public void keyPressed(KeyEvent e) {
            if (e.getKeyChar()== KeyEvent.VK_ENTER) {
               e.consume();
               try {
                  myButton.getActionListeners()[0].actionPerformed(new ActionEvent(myButton, 0, myButton.getText()));
               } 
                   catch (ArrayIndexOutOfBoundsException oob) {
                   // do nothing, since there is no action listener.
                  }
            }
         }
      }
            
         /////////////////////////////////////////////////////////////////////////////////          
     // called when the Assemble and Run button is pressed.  Used only by stand-alone app.
       private class CreateAssembleRunMIPSprogram implements Runnable { 
          public void run() {
            String noSupportForExceptionHandler = null;  // no auto-loaded exception handlers.
           // boolean extendedAssemblerEnabled = true;     // In this context, no reason to constrain.
           // boolean warningsAreErrors = false;           // Ditto.
           
            String exceptionHandler = null;
            if (Globals.getSettings().getExceptionHandlerEnabled() &&
                   Globals.getSettings().getExceptionHandler() != null &&
                   Globals.getSettings().getExceptionHandler().length() > 0) {
               exceptionHandler = Globals.getSettings().getExceptionHandler();
            }
           
            Thread.currentThread().setPriority(Thread.NORM_PRIORITY-1);
            Thread.yield();
            MIPSprogram program = new MIPSprogram();
            mars.Globals.program = program; // Shouldn’t have to do this…
            String fileToAssemble = mostRecentlyOpenedFile.getPath();
            ArrayList filesToAssemble = null;
            if (multiFileAssemble) {// setting (check box in file open dialog) calls for multiple file assembly 
               filesToAssemble = FilenameFinder.getFilenameList(
                               new File(fileToAssemble).getParent(), Globals.fileExtensions);
            } 
            else {
               filesToAssemble = new ArrayList();
               filesToAssemble.add(fileToAssemble);
            }
            ArrayList programsToAssemble = null;
            try {
               operationStatusMessages.displayNonTerminatingMessage(“Assembling “+fileToAssemble);
               programsToAssemble = program.prepareFilesForAssembly(filesToAssemble, fileToAssemble, exceptionHandler);
            } 
                catch (mars.ProcessingException pe) {
                  operationStatusMessages.displayTerminatingMessage(“Error reading file(s): “+fileToAssemble);
                  return;
               } 
         
            try {
               program.assemble(programsToAssemble, Globals.getSettings().getExtendedAssemblerEnabled(), Globals.getSettings().getWarningsAreErrors());
            }
                catch (mars.ProcessingException pe) {
                  operationStatusMessages.displayTerminatingMessage(“Assembly Error: “+fileToAssemble);
                  return;
               } 
            // Moved these three register resets from before the try block to after it.  17-Dec-09 DPS. 
            RegisterFile.resetRegisters();
            Coprocessor1.resetRegisters();
            Coprocessor0.resetRegisters();
            
            addAsObserver();
            observing = true;
            String terminatingMessage = “Normal termination: “;
            try {
               operationStatusMessages.displayNonTerminatingMessage(“Running “+fileToAssemble);
               program.simulate(-1); // unlimited steps
            }
                catch (NullPointerException npe) { 
                 // This will occur if program execution is interrupted by Stop button.
                  terminatingMessage = “User interrupt: “;
               }
                catch (mars.ProcessingException pe) {
                  terminatingMessage = “Runtime error: “;
               }
            finally {
               deleteAsObserver();
               observing = false;
               operationStatusMessages.displayTerminatingMessage(terminatingMessage+fileToAssemble);
            } 
            return;
         }
      }
   
   
       //////////////////////////////////////////////////////////////////////////
     //  Class for text message field used to update operation status when
     //  assembling and running MIPS programs.
       private class MessageField extends JTextField {
         
          public MessageField(String text) {
            super(text);
         }
        
          private void displayTerminatingMessage(String text) {
            displayMessage(text, true);
         }
        
          private void displayNonTerminatingMessage(String text) {
            displayMessage(text, false);
         }
        
          private void displayMessage(String text, boolean terminating) {
            SwingUtilities.invokeLater(new MessageWriter(text, terminating));           
         }
        
       /////////////////////////////////////////////////////////////////////////////////            
       // Little inner-inner class to display processing error message on AWT thread.  
       // Used only by stand-alone app.
          private class MessageWriter implements Runnable {
            private String text;
            private boolean terminatingMessage;
             public MessageWriter(String text, boolean terminating) {
               this.text = text;
               this.terminatingMessage = terminating;
            }
             public void run() {
               if (text!=null) {
                  operationStatusMessages.setText(text);
                  operationStatusMessages.setCaretPosition(0);
               }
               if (terminatingMessage) {
                  assembleRunButton.setEnabled(true);
                  openFileButton.setEnabled(true);
                  stopButton.setEnabled(false);
               }
            }
         }      
      }
        
     //////////////////////////////////////////////////////////////////////     
       //  For scheduling GUI update on timed runs…used only by stand-alone app.      
       private class GUIUpdater implements Runnable {
          public void run() {
            updateDisplay();
         }
      }
               
   }

MemoryReferenceVisualization$5

package mars.tools;
synchronized class MemoryReferenceVisualization$5 implements java.awt.event.ActionListener {
void MemoryReferenceVisualization$5(MemoryReferenceVisualization);
public void actionPerformed(java.awt.event.ActionEvent);
}

BHTEntry

package mars.tools;
public synchronized class BHTEntry {
private boolean[] m_history;
private boolean m_prediction;
private int m_incorrect;
private int m_correct;
public void BHTEntry(int, boolean);
public boolean getPrediction();
public void updatePrediction(boolean);
public int getStatsPredIncorrect();
public int getStatsPredCorrect();
public double getStatsPredPrecision();
public String getHistoryAsStr();
public String getPredictionAsStr();
}

MemoryReferenceVisualization$7

package mars.tools;
synchronized class MemoryReferenceVisualization$7 implements java.awt.event.ActionListener {
void MemoryReferenceVisualization$7(MemoryReferenceVisualization);
public void actionPerformed(java.awt.event.ActionEvent);
}

BitmapDisplay$GraphicsPanel

package mars.tools;
synchronized class BitmapDisplay$GraphicsPanel extends javax.swing.JPanel {
private void BitmapDisplay$GraphicsPanel(BitmapDisplay);
public void paint(java.awt.Graphics);
private void paintGrid(java.awt.Graphics, BitmapDisplay$Grid);
}

MarsBot$BotRunnable$2

package mars.tools;
synchronized class MarsBot$BotRunnable$2 implements java.awt.event.ActionListener {
void MarsBot$BotRunnable$2(MarsBot$BotRunnable, javax.swing.JFrame);
public void actionPerformed(java.awt.event.ActionEvent);
}

DigitalLabSim$SevenSegmentDisplay

package mars.tools;
public synchronized class DigitalLabSim$SevenSegmentDisplay extends javax.swing.JComponent {
public char aff;
public void DigitalLabSim$SevenSegmentDisplay(DigitalLabSim, char);
public void modifyDisplay(char);
public void SwitchSegment(java.awt.Graphics, char);
public void paint(java.awt.Graphics);
}

AbstractMarsToolAndApplication$ConnectButton

package mars.tools;
public synchronized class AbstractMarsToolAndApplication$ConnectButton extends javax.swing.JButton {
private static final String connectText = Connect to MIPS;
private static final String disconnectText = Disconnect from MIPS;
public void AbstractMarsToolAndApplication$ConnectButton(AbstractMarsToolAndApplication);
public void connect();
public void disconnect();
public boolean isConnected();
}

MagnifierImage$1

package mars.tools;
synchronized class MagnifierImage$1 extends java.awt.event.MouseAdapter {
void MagnifierImage$1(MagnifierImage);
public void mousePressed(java.awt.event.MouseEvent);
}

DigitalLabSim$1

package mars.tools;
synchronized class DigitalLabSim$1 implements java.awt.event.ActionListener {
void DigitalLabSim$1(DigitalLabSim);
public void actionPerformed(java.awt.event.ActionEvent);
}

MemoryReferenceVisualization$Grid

package mars.tools;
synchronized class MemoryReferenceVisualization$Grid {
int[][] grid;
int rows;
int columns;
private void MemoryReferenceVisualization$Grid(MemoryReferenceVisualization, int, int);
private int getRows();
private int getColumns();
private int getElement(int, int);
private int getElementFast(int, int);
private int incrementElement(int, int);
private void reset();
}

DigitalLabSim$HexaKeyboard

package mars.tools;
public synchronized class DigitalLabSim$HexaKeyboard extends javax.swing.JPanel {
public javax.swing.JButton[] button;
public void DigitalLabSim$HexaKeyboard(DigitalLabSim);
public void resetHexaKeyboard();
}

SettingsDialog$3

package mars.tools;
synchronized class SettingsDialog$3 implements java.awt.event.ActionListener {
void SettingsDialog$3(SettingsDialog, javax.swing.JDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

DigitalLabSim$HexaKeyboard$EcouteurClick

package mars.tools;
public synchronized class DigitalLabSim$HexaKeyboard$EcouteurClick implements java.awt.event.MouseListener {
private int buttonValue;
public void DigitalLabSim$HexaKeyboard$EcouteurClick(DigitalLabSim$HexaKeyboard, int);
public void mouseEntered(java.awt.event.MouseEvent);
public void mouseExited(java.awt.event.MouseEvent);
public void mousePressed(java.awt.event.MouseEvent);
public void mouseReleased(java.awt.event.MouseEvent);
public void mouseClicked(java.awt.event.MouseEvent);
}

ScavengerHunt$ScavengerHuntRunnable$2

package mars.tools;
synchronized class ScavengerHunt$ScavengerHuntRunnable$2 extends java.awt.event.WindowAdapter {
void ScavengerHunt$ScavengerHuntRunnable$2(ScavengerHunt$ScavengerHuntRunnable, javax.swing.JDialog);
public void windowClosing(java.awt.event.WindowEvent);
}

DigitalLabSim$OneSecondCounter

package mars.tools;
public synchronized class DigitalLabSim$OneSecondCounter {
public void DigitalLabSim$OneSecondCounter(DigitalLabSim);
public void resetOneSecondCounter();
}

AbstractMarsToolAndApplication$9

package mars.tools;
synchronized class AbstractMarsToolAndApplication$9 implements java.awt.event.ActionListener {
void AbstractMarsToolAndApplication$9(AbstractMarsToolAndApplication);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/tools/ScavengerHunt.java
mars/tools/ScavengerHunt.java   package mars.tools;
   import mars.*;
   import mars.mips.hardware.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.util.*;
   import javax.swing.JOptionPane;
   import mars.util.*;

/**
 * Demo of Mars tool capability.    Ken Vollmar, 27 Oct 2006  
 * This tool displays movements by a series of players in a game of ScavengerHunt.
 * Players will read and write MIPS memory-mapped locations to move and regain energy.
 * See accompanying documentation for memory-mapped addresses, rules of the game, etc.
 */

    public class ScavengerHunt implements Observer, MarsTool
   {
      private static final int GRAPHIC_WIDTH = 712;
      private static final int GRAPHIC_HEIGHT = 652;
   
      private static final int NUM_PLAYERS = 22;    // Number of players in the game, including “baseline” player
      private static final int MAX_X_MOVEMENT = 2;  // Max. movement in X direction
      private static final int MAX_Y_MOVEMENT = 2;  // Max. movement in X direction
      private static final double MAX_MOVE_DISTANCE = 2.5;  // Max. distance (Euclidean measure)
      private static final int ENERGY_AWARD = 20;    // Energy awarded for each task completion
      private static final int ENERGY_PER_MOVE = 1;  // Energy used in making each move (regardless of distance)
      private static final int SIZE_OF_TASK = 20;   // Number of elements in the task
   
      private static final int NUM_LOCATIONS = 7;  // Number of locations to which ScavengerHunt players travel.
    // The first (n-1) locations are “random” locations, the last is START_AND_END_LOCATION
   
      private static final int START_AND_END_LOCATION = 255; // Start and end location of the ScavengerHunt
      private static final int ADMINISTRATOR_ID = 999;  // Special ID for administrator
    
    
    // MIPS addresses of administrative memory space.
    // The administrator MIPS program writes a value to the Authentication field prior to writing a new
    // value to the PlayerID field. The value of the Authentication field is not itself verified until
    // the PlayerID field changes. Each new value of the Authentication field is one of some sequence
    // known to the Tool program (one-time pad system).
    // Each change of data in the PlayerID field is a signal for the Tool to check the value of the Authentication
    // field. If the value of the Authentication field is correct, the value of the PlayerID field is used
    // for memory bounds checking. A new value of the Authentication field is expected at each change of the
    // PlayerID field (one-time pad system).
      private static final int ADDR_AUTHENTICATION = 0xffffe000;  // MIPS byte address of Authentication field
      private static final int ADDR_PLAYER_ID = 0xffffe004;  // MIPS byte address of PlayerID field
      private static final int ADDR_GAME_ON = 0xffffe008;  // MIPS byte address of signal that administration has initialized data
      private static final int ADDR_NUM_TURNS = 0xffffe00c;  // MIPS byte address of number of turns remaining in the game
   
   
    
    // MIPS addresses of various data in each player’s memory space.
    // Each player’s assigned memory is the MEM_PER_PLAYER bytes which begin at
    // location ADDR_BASE + (ID *  MEM_PER_PLAYER)
      private static final int ADDR_BASE = 0xffff8000;  // MIPS byte address of memory space for first player
      private static final int MEM_PER_PLAYER = 0x400;  // MIPS bytes of memory space given to each player
      private static final int OFFSET_WHERE_AM_I_X = 0x0;  // MIPS byte offset to this field
      private static final int OFFSET_WHERE_AM_I_Y = 0x4;  // MIPS byte offset to this field
      private static final int OFFSET_MOVE_TO_X = 0x8;  // MIPS byte offset to this field
      private static final int OFFSET_MOVE_TO_Y = 0xc;  // MIPS byte offset to this field
      private static final int OFFSET_MOVE_READY = 0x10;  // MIPS byte offset to this field
      private static final int OFFSET_ENERGY = 0x14;  // MIPS byte offset to this field
      private static final int OFFSET_NUMBER_LOCATIONS = 0x18;  // MIPS byte offset to this field
      private static final int OFFSET_PLAYER_COLOR = 0x1c;  // MIPS byte offset to this field
      private static final int OFFSET_SIZE_OF_TASK  = 0x20;  // MIPS byte offset to this field
      private static final int OFFSET_LOC_ARRAY = 0x24;  // MIPS byte offset to this field
      private static final int OFFSET_TASK_COMPLETE = 0x124;  // MIPS byte offset to this field
      private static final int OFFSET_TASK_ARRAY = 0x128;  // MIPS byte offset to this field
    // Other MIPS memory locations are available to the player’s use.
   
      private ScavengerHuntDisplay graphicArea;
      private int authenticationValue = 0;
      private boolean GameOn = false;  // MIPS programs readiness
      private static int SetWordCounter = 0;
      private static int accessCounter = 0;
      private static int playerID = ADMINISTRATOR_ID;   // Range 0…(NUM_PLAYERS-1), plus ADMINISTRATOR_ID
      private boolean KENVDEBUG = false;
   
   
    // Used to define (X,Y) coordinate of a location to which ScavengerHunt players
    // will travel.
       private class Location
      {
         public int X;
         public int Y;
      }
    
    // private inner class to provide the data on each player needed for display
       private class PlayerData
      {
         int whereAmIX = START_AND_END_LOCATION;   // Read only. Memory Address:  Base
         int whereAmIY = START_AND_END_LOCATION;   // Read only. Memory Address:  Base + 0x4
      //int moveToX;    //  Memory Address:  Base + 0x8
      //int moveToY;    //  Memory Address:  Base + 0xc
      //int goalX;     // Read only. Memory Address:  Base + 0x10
      //int goalY;     // Read only. Memory Address:  Base + 0x14
         int energy = 20;    // Read only. Memory Address:  Base + 0x18
         int color = 0;    // Memory Address:  Base + 0x1c
         long finishTime;
      //int locID;  // ID of the location to which ScavengerHunt players are headed. Not used by player.
         boolean hasVisitedLoc[] = new boolean[NUM_LOCATIONS];  // boolean: player has visited each location
         boolean finis = false;
      
      // Class PlayerData has no constructor
      
          public void setWhereAmI(int gX, int gY) {  whereAmIX = gX; whereAmIY = gY; }
      //public void setGoal(int gX, int gY) {  goalX = gX; goalY = gY; }
          public void setEnergy(int e) {  energy = e; }
          public void setColor(int c) {  color = c; }
          public int getWhereAmIX() {  
            return whereAmIX; }
          public int getWhereAmIY() {  
            return whereAmIY; }
          public int getColor() {  
            return color; }
          public boolean hasVisited(int i) { 
            return hasVisitedLoc[i]; }
          public void setVisited(int i) { hasVisitedLoc[i] = true; }
          public void setFinished() { finis = true; }
          public boolean isFinished() { 
            return finis; }
          public long getFinishTime() { 
            return finishTime; }
          public long getFinishMin() { 
            return (finishTime / 60000); }   // Minutes portion of finishTime
          public long getFinishSec() {
            return (finishTime % 60000) / 1000;  // Seconds portion of finishTime
         }  // Seconds portion of finishTime
          public long getFinishMillisec() { 
            return (finishTime % 1000); }  // Millisec portion of finishTime
          public void setFinishTime(long t) { finishTime = t; }
      //public int getGoalX() {  return goalX; }
      //public int getGoalY() {  return goalY; }
      //public int getMoveToX() {  return moveToX; }
      //public int getMoveToY() {  return moveToY; }
          public int getEnergy() {  
            return energy; }
      //public int getLocationID() {  return locID; }
      } // end class PlayerData
    
      private static PlayerData[] pd = new PlayerData[NUM_PLAYERS];
      private static Location[] loc = new Location[NUM_LOCATIONS];
      private Random randomStream;
      private long startTime;
   
    
    // private inner class
       private class ScavengerHuntRunnable implements Runnable
      {
         JPanel panel;
          public ScavengerHuntRunnable() // constructor
         {
            // final JFrame frame = new JFrame(“ScavengerHunt”);
            // Recommended by Pete Sanderson, 2 Nov. 2006, so that the Tool window and
            // MARS window can be on the screen at the same time.
            final JDialog frame = new JDialog(Globals.getGui(),”ScavengerHunt”);
         
            // System.out.println(“ScavengerHuntRunnable.constructor: starting….”);
         
            panel = new JPanel(new BorderLayout());
            graphicArea = new ScavengerHuntDisplay(GRAPHIC_WIDTH, GRAPHIC_HEIGHT);
            JPanel buttonPanel = new JPanel();
            JButton resetButton = new JButton(“Reset”);
            resetButton.addActionListener(
                   new ActionListener()
                  {
                      public void actionPerformed(ActionEvent e)
                     {
                        graphicArea.clear();
                     
                        // TBD ——- TBD
                        // Reset actions here
                        initializeScavengerData();
                       //JOptionPane.showMessageDialog(null, “Reset needs to be implemented!” );
                     
                     }
                  
                  });
            buttonPanel.add(resetButton);
         
            
            panel.add(graphicArea, BorderLayout.CENTER);
            panel.add(buttonPanel, BorderLayout.SOUTH);
         
         
            // Snippet by Pete Sanderson, 2 Nov. 2006, to be a window-closing sequence
            frame.addWindowListener(
                   new WindowAdapter() {
                      public void windowClosing(WindowEvent e) {
                        frame.setVisible(false);
                        frame.dispose();
                     }
                  });
         
            frame.getContentPane().add(panel);
                frame.setLocationRelativeTo(null);
            frame.pack();
            frame.setVisible(true);
            frame.setTitle(” This is the ScavengerHunt”);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // TBD — This should close only the Tool, not the entire MARS
            frame.setPreferredSize(new Dimension(GRAPHIC_WIDTH, GRAPHIC_HEIGHT)); // TBD  SIZE
            frame.setVisible(true); // show();
         
         } // end ScavengerHuntRunnable() constructor
      
          public void run()
         {
         
            double tempAngle;
         
            // infinite loop: play the Scavenger Hunt game
            do
            {
            
                // Pause to slow down the redisplay of the game. This is separate from
                // the execution speed of the MIPS program, so the display may lag behind
                // the state of the MIPS program.
               try
               {
                    // System.out.println(” Hello from the ScavengerHuntRunnable runner, sleeping here …”);
                    // System.out.print(“.”);
                  Thread.sleep(100);   // millisec
               }
                   catch (InterruptedException exception)
                  {// no action
                  }
            
               panel.repaint(); // show new ScavengerHunt position
            } while (true);
         
         } // end run method of ScavengerHuntRunnable class
      
      } // end ScavengerHuntRunnable class
   
    /* ————————————————————————- */
    /** ScavengerHuntDisplay does not have access to the same MIPS Memory class object used by
      * the ScavengerHunt class object. Need read-only access to a similar data structure maintained
        * within ScavengerHunt.
        *
        */
       private class ScavengerHuntDisplay extends JPanel
      {
         private int width;
         private int height;
         private boolean clearTheDisplay = true;
        
      
          public ScavengerHuntDisplay(int tw, int th)
         {
            // System.out.println(“ScavengerHuntDisplay.constructor: starting….”);
            width = tw;
            height = th;
         
         }
      
          public void redraw()
         {
            repaint();
         }
      
          public void clear()
         {
            // clear the graphic display
            clearTheDisplay = true;
            //System.out.println(“ScavengerHuntDisplay.clear: called to clear the display”);
            repaint();
         }
      
        /** paintComponent does not have access to the same MIPS Memory class object used by
        * the ScavengerHunt class object. Need read-only access to a similar data structure maintained
        * within ScavengerHunt.
        *
        */
          public void paintComponent(Graphics g)
         {
            long tempN;
            int xCoord;
            int yCoord;
         
            // System.out.println(“ScavengerHuntDisplay.paintComponent: I’m painting! n is ” + n);
         
         
            // Recover Graphics2D
            Graphics2D g2 = (Graphics2D) g;
            
            if (! GameOn)    // Make sure game is ready before continuing
            {
               g2.setColor(Color.lightGray);
               g2.fillRect(0, 0, width – 1, height – 1); // Clear all previous drawn information
               g2.setColor(Color.black);
               g2.drawString(” ScavengerHunt not yet initialized by MIPS administrator program.”,
                                100, 200);
               return;
            }
            
             // Clear all previous drawn information
            g2.setColor(Color.lightGray);
            g2.fillRect(0, 0, width – 1, height – 1);
         
         
            // Draw the locations to which the players will be moving
            // All players have the same location data.
            for (int i = 0; i < NUM_LOCATIONS; i++)             {                xCoord = loc[i].X; // toolReadPlayerData(0, OFFSET_LOC_ARRAY + (i*8) + 0);                yCoord = loc[i].Y; // toolReadPlayerData(0, OFFSET_LOC_ARRAY + (i*8) + 4);                g2.setColor(Color.blue);                g2.fillRect( xCoord, yCoord, 20, 20);  // coord is upper left corner of oval                g2.setColor(Color.white);                g2.drawString(" " + i, xCoord + 4, yCoord + 15);  // coord is lower left corner of string text box                             /*                System.out.println("ScavengerHuntDisplay.paintComponent: drew loc " + i + " at (" +                                    xCoord +                                    ", " +                                    yCoord +                                    ")" );                */             }                       //System.out.println("ScavengerHuntDisplay.paintComponent: special exit!");             //System.exit(0);                                 // Draw scoreboard             g2.setColor(Color.black);             g2.drawString("Player", width - 160, 30);             g2.drawString("Locations", width - 110, 30);             g2.drawString("Energy", width - 50, 30);             g2.drawLine( width - 160, 35, width - 10, 35); // line under column headings             g2.drawLine( width - 120, 35, width - 120, 35 + (NUM_PLAYERS * 15)); // vertical line for location-visited marks             g2.drawLine( width - 50, 35, width - 50, 35 + (NUM_PLAYERS * 15)); // vertical line for location-visited marks             for (int i = 0; i < NUM_PLAYERS; i++)             {                  // Draw player's symbol                g2.setColor( new Color(pd[i].getColor()) );                  // g2.setColor(Color.red);  // TBD hardcoded                                                    xCoord = pd[i].getWhereAmIX();                yCoord = pd[i].getWhereAmIY();                               // ystem.out.println("paintComponent loop " + i + ": Loc coord is (" + xCoord + ", " + yCoord);                                    // Draw player symbol and label it with player ID number.                  // Hardcoded size of location graphic and label.                g2.drawOval( xCoord, yCoord, 20, 20);  // coord is upper left corner of oval                g2.drawString(" " + i, xCoord + 4, yCoord + 15);  // coord is lower left corner of string text box                                    // Draw player's info on scoreboard                g2.setColor(Color.black);                g2.drawString(" " + i, width - 150, 50 + (i*15));  // Player's ID on scoreboard                g2.drawString(" " + pd[i].getEnergy(), width - 40, 50 + (i*15));  // Player's energy on scoreboard                               // Display player's progress or finishing time, whichever is applicable                if (pd[i].isFinished())                {                     // Display finishing time                     // This doesn't display leading zeroes to align time components (e.g. 27 millisec ought to print as 027)                   g2.drawString (pd[i].getFinishMin() + ":" +  // Minutes                                    pd[i].getFinishSec() + ":" +   // Seconds                                    pd[i].getFinishMillisec() ,   // Milliseconds                                    width - 115, 50 + (i*15));                     // System.out.println("Time is " +  pd[i].getFinishTime());                     //g2.drawString (" " + pd[i].getFinishTime(),                     //               width - 255, 50 + (i*15));                }                else  // player either has not finished or is just now finishing                {                   int visCount = 0;                   for (int j = 0; j < NUM_LOCATIONS; j++)                   {                      if (pd[i].hasVisited(j))  // count number of locations that player has visited                      {                         visCount++;                      }                   }                   if (visCount == NUM_LOCATIONS)  // player has visited every location -- finished!                   {                      pd[i].setFinished();                      pd[i].setFinishTime( System.currentTimeMillis() - startTime );                                      }                   else // player has not yet visited every location                   {                       // Display locations that the player has actually visited                      for (int j = 0; j < NUM_LOCATIONS; j++)                      {                         if (pd[i].hasVisited(j))  // Player has visited this location                         {                            g2.fillRect ((width -120)+(j*10), 42 + (i*15), 10, 8);                         }                      }                   }                } // end player had not previously finished                               } // end display score/results for each player                       // System.out.println("paintComponent: Player " + 0 + " is at (" + pd[0].getWhereAmIX() + ", " + pd[0].getWhereAmIY() + ")" );                                                     /*              g2.setColor(Color.blue);              g2.setFont(new Font(g2.getFont().getName(), g2.getFont().getStyle(), 20) );  // same font and style in larger size              g2.drawOval( width/2 - 30,  // TBD Hardcoded oval size              height/2 - 30,              60,              60);              g2.drawString(" " + n, width/2, height/2);              */                              }              } // end private inner class ScavengerHuntDisplay     /* ------------------------------------------------------------------------- */                 // A constructor for ScavengerHunt would be called immediately on MARS startup, perhaps     // before all MARS classes have been created. Do not include any action in a constructor     // but rather postpone any action until the action() class,     // at which time all MARS classes will be ready for use.        public ScavengerHunt()       {         // System.out.println("ScavengerHunt.constructor: starting....");       }             public String getName()       {          return "ScavengerHunt";       }         /*      * This will set up the ScavengerHunt's GUI.  Invoked when ScavengerHunt menu item selected.      */        public void action()       {                               ScavengerHuntRunnable shr = new ScavengerHuntRunnable();          Thread t1 = new Thread(shr);          t1.start();                         // Register as observer for a particular MIPS data range. Other ranges         // are not used by this Tool.          try {             Globals.memory.addObserver(this, 0xffff8000, 0xfffffff0);  // must be on word boundaries          }              catch (AddressErrorException e)             {                System.out.println("\n\nScavengerHunt.action: Globals.memory.addObserver caused AddressErrorException.\n\n");                System.exit(0);             }              } // end ScavengerHunt.action()         /*      * This method observes MIPS memory for directives to modify ScavengerHunt activity (that is,      * MIPS program write to MMIO) and updates instance variables to reflect that directive.      * This method takes action when it "observes" MIPS memory changes -- but this method      * must not write to those memory locations in order to prevent an infinite cycle of events.      * This method observes certain locations and then may (and does) write to OTHER locations.      */        public void update(Observable o, Object arg)       {          MemoryAccessNotice notice;          int address;          int data;          boolean isWrite;          boolean isRead;          int energyLevel;                // Here we are only interested in MemoryAccessNotice. For anything else, just return.          if ( ! (arg instanceof MemoryAccessNotice))              return;                // Get pertinent information about this MemoryAccessNotice.          notice = (MemoryAccessNotice) arg;          address = notice.getAddress();          data = notice.getValue();          isWrite = (notice.getAccessType() == AccessNotice.WRITE);          isRead = ! isWrite;                       // If we are only interested in MIPS memory WRITES, then just return on READS.         // That's a matter of policy: perhaps players should be prohibited from         // reading each other's memory spaces.          if ( ! isWrite)               return;                     //System.out.println("ScavengerHunt.update: observed write access by player " + playerID + " on Mem[ " +            //            Binary.intToHexString(address) + " ]");                // TBD TBD DEBUGGING SPECIAL         /*             accessCounter++;             if (accessCounter > 100000)
            {
              System.out.println(“\n\nScavengerHunt.update: hardcoded exit to prevent runaway” );
              System.exit(0);
            }
            */
            // TBD TBD DEBUGGING SPECIAL
      
      
      
      
        // Take the appropriate action, depending on data written and priority of user.
         if (isWrite && playerID == ADMINISTRATOR_ID && address == ADDR_GAME_ON)
         {
         
                      // ADMINISTRATOR_ID can write to any location, because it’s trusted software
                  //System.out.println( “ScavengerHunt.update(): Administrator wrote to  Mem[ ” +
                    //   Binary.intToHexString(address) + ” ] == ” + Binary.intToHexString(data) );
         
                  // No need to authenticate since administrator runs first, then
                  // this location has no effect thereafter.
            GameOn = true;
                  // System.out.println( “ScavengerHunt.update(): Administrator wrote GAME_ON!” );
         
            initializeScavengerData();
         }
         else if (isWrite && address == ADDR_AUTHENTICATION)
         {
          // Anyone is allowed to write to the authentication location — but if that value is not
          // correct (authentic) then action can be taken.
          // NO ACTION HERE
         }
         else if (isWrite && address == ADDR_NUM_TURNS)
         {
          // Anyone is allowed to write to the “number of turns” location
          // NO ACTION HERE
         }
         else if (isWrite && address == ADDR_PLAYER_ID)   // if the data written will change the PlayerID, authenticate the write
         {
                  // 2006 Oct 31  dummy validation scheme, suitable for distribution
                  // to students for development: Initial authentication value is zero.
                  // Each successive authentication value is one greater
                  // than the preceding value, modulo 0xffffffff.
            authenticationValue += 1;  // “server’s” updated version of the authenticationValue
            if (toolGetWord(ADDR_AUTHENTICATION) == authenticationValue) // Compare to “client’s” version of the authenticationValue
            {
               playerID = toolGetWord(ADDR_PLAYER_ID); // Use the new player ID
                     //System.out.println( “ScavengerHunt.update(): New playerID of ” + playerID);
            }
            else
            {
               System.out.println( “ScavengerHunt.update(): Invalid write of player ID! \nPlayer ” +
                      playerID + ” tried to write.  Expected:   ” +
                      Binary.intToHexString(authenticationValue) +
                      “, got:  ” + Binary.intToHexString(toolGetWord(ADDR_AUTHENTICATION)) + “\n” );
            }
         }
         
         else if (isWrite &&
                  address == (ADDR_BASE + (playerID * MEM_PER_PLAYER) + OFFSET_MOVE_READY) &&
                  data != 0)  //  Player wrote data to his/her assigned MoveReady location
         {
            /*
         System.out.println(” ******** ScavengerHunt.update: Player ” + playerID + ” requests move to (” +
                        toolReadPlayerData(playerID, OFFSET_MOVE_TO_X) + “, ” +
                        toolReadPlayerData(playerID, OFFSET_MOVE_TO_Y) + “)” );
            */
         
            energyLevel = toolReadPlayerData(playerID, OFFSET_ENERGY); // find if player has energy
            if (energyLevel <= 0)  // No energy. Player not allowed to move             {                        //JOptionPane.showMessageDialog(null, "Player " + playerID + " can't move -- no energy.\n" +                        //                                    "(This msg. in ScavengerHunt.update()" );                        // System.out.println("Player " + playerID + " can't move -- no energy.");                return;             }                       if (toolReadPlayerData(playerID, OFFSET_MOVE_TO_X) < 0 ||                         toolReadPlayerData(playerID, OFFSET_MOVE_TO_X) > GRAPHIC_WIDTH ||
                        toolReadPlayerData(playerID, OFFSET_MOVE_TO_Y) < 0 ||                         toolReadPlayerData(playerID, OFFSET_MOVE_TO_Y) > GRAPHIC_HEIGHT
                        )  // Out of bounds. Player not allowed to move
            {
                       //JOptionPane.showMessageDialog(null, “Player ” + playerID + ” can’t move — out of bounds.\n” +
                       //                                    “(This msg. in ScavengerHunt.update()” );
               System.out.println(“Player ” + playerID + ” can’t move — out of bounds.”);
               return;
            }
         
         
                    // Verify movement is allowed (does not exceed maximum movement)
            if (Math.sqrt(
                                      Math.pow( toolReadPlayerData(playerID, OFFSET_WHERE_AM_I_X) –
                                                toolReadPlayerData(playerID, OFFSET_MOVE_TO_X), 2.0)
                                        +
                                      Math.pow( toolReadPlayerData(playerID, OFFSET_WHERE_AM_I_Y) –
                                                toolReadPlayerData(playerID, OFFSET_MOVE_TO_Y), 2.0) )
                           <= MAX_MOVE_DISTANCE)             {                                     // Write the new position of the player                toolWritePlayerData(playerID, OFFSET_WHERE_AM_I_X,                                  toolReadPlayerData(playerID, OFFSET_MOVE_TO_X));                toolWritePlayerData(playerID, OFFSET_WHERE_AM_I_Y,                                  toolReadPlayerData(playerID, OFFSET_MOVE_TO_Y));                pd[playerID].setWhereAmI( toolReadPlayerData(playerID, OFFSET_WHERE_AM_I_X),                                                  toolReadPlayerData(playerID, OFFSET_WHERE_AM_I_Y) );                                     // Write the new (reduced) energy of the player                        // Policy: Constant ENERGY_PER_MOVE for any move regardless of length.                toolWritePlayerData(playerID, OFFSET_ENERGY,                                  toolReadPlayerData(playerID, OFFSET_ENERGY) - ENERGY_PER_MOVE);                pd[playerID].setEnergy( toolReadPlayerData(playerID, OFFSET_ENERGY) );                                                                       // TBD FUTURE --- need to keep track of locations that the player has actually got to                        // -- be able to tell that the player has reached a certain location                        // -- be able to tell that the player has reached every location                for (int i = 0; i < NUM_LOCATIONS; i++)                {                   if (toolReadPlayerData(playerID, OFFSET_WHERE_AM_I_X) == loc[i].X &&                              toolReadPlayerData(playerID, OFFSET_WHERE_AM_I_Y) == loc[i].Y )                   {                      pd[playerID].setVisited(i);  // Player has visited this location                   }                }                                                  // Write 0 to "move ready" location, signifying that the move request was processed                        // Here we must write to the same location that we're now reading from, and we                        // can't cause an infinite loop. Temporarily switch player ID to that of the administrator,                        // and restore ID after the write. With the playerID set to administrator, the event                        // caused by the write will not go through this same logic.                int tempPlayerID = playerID;                playerID = ADMINISTRATOR_ID;                toolWritePlayerData(tempPlayerID, OFFSET_MOVE_READY, 0);                playerID = tempPlayerID;                                     }             else             {                System.out.println( "Player " + playerID + " can't move -- exceeded max. movement." );                System.out.println("    Player is at (" +                                            toolReadPlayerData(playerID, OFFSET_WHERE_AM_I_X) + ", " +                                            toolReadPlayerData(playerID, OFFSET_WHERE_AM_I_Y) + "), wants to go to (" +                                            toolReadPlayerData(playerID, OFFSET_MOVE_TO_X) + "," +                                            toolReadPlayerData(playerID, OFFSET_MOVE_TO_Y) + ")" );                             return;             }                    } // end if Player wrote nonzero data to his/her assigned MoveReady location                                            else if (isWrite &&                   address == (ADDR_BASE + (playerID * MEM_PER_PLAYER) + OFFSET_TASK_COMPLETE) &&                   data != 0)  //  Player wrote data to his/her assigned TaskComplete location          {                        //  System.out.println(" ******** ScavengerHunt.update: Player " + playerID + " requests more energy (task complete)" );                            // Player indicates he/she has completed a task. Check to see if task is completed correctly.              // Task for this assignment: Numbers are sorted in ascending order.             int prevData, currentData;             prevData = toolReadPlayerData(playerID, OFFSET_TASK_ARRAY);             for (int i = 1; i < SIZE_OF_TASK; i++)             {                currentData = toolReadPlayerData(playerID, OFFSET_TASK_ARRAY + (i*4));                if (prevData > currentData)
               {
                  // Task failure! Task not completed correctly!
                  System.out.println(“Whoops! Player has NOT completed task correctly”);
                  return;
               }
               prevData = currentData; // update for next iteration
               
            }
             
             // If program flow has reached this point, the task is completed correctly.
             // Award energy, reset TaskComplete, and set new task values for future use.
            toolWritePlayerData(playerID, OFFSET_ENERGY, ENERGY_AWARD);
            toolWritePlayerData(playerID, OFFSET_TASK_COMPLETE, 0);
            for (int j = 0; j < SIZE_OF_TASK; j++)   // Initialize the task data for this player             {                toolWritePlayerData(playerID, OFFSET_TASK_ARRAY + (j * 4),                       (int)(randomStream.nextDouble() * Integer.MAX_VALUE) );   // Set a random number for the task (sort them)             }              // System.out.println("Player has  completed task correctly and been awarded energy");             pd[playerID].setEnergy( ENERGY_AWARD );                    } // end if Player wrote nonzero data to his/her assigned TaskComplete location                              else if (isWrite &&                   address == (ADDR_BASE + (playerID * MEM_PER_PLAYER) + OFFSET_PLAYER_COLOR))                   //  Player wrote data to his/her assigned PlayerColor location          {                // PPlayer indicates he/she has changed the color of display             pd[playerID].setColor( toolReadPlayerData(playerID, OFFSET_PLAYER_COLOR) );          }                              // TBD TBD TBD          // TBD TBD TBD          // TBD TBD TBD          // Yet to be implemented: Enforce only one write of MoveRequest per player per turn                              else if (isWrite &&                   address >= (ADDR_BASE + (playerID * MEM_PER_PLAYER)) &&
                  address <  (ADDR_BASE + ((playerID + 1) * MEM_PER_PLAYER)) )                     //  Player wrote data elsewhere within his/her assigned location          {                   // Player can write to any location within his/her assigned location                  //System.out.println( "ScavengerHunt.update(): Player " + playerID + " wrote to valid location");          }          else if (isWrite && playerID == ADMINISTRATOR_ID)          {                   // ADMINISTRATOR_ID can write to any location, because it's trusted software                  //System.out.println( "ScavengerHunt.update(): Administrator wrote to  Mem[ " +                  //     Binary.intToHexString(address) + " ] == " + Binary.intToHexString(data) );          }          else if (isWrite)          {                   // This player is writing outside his/her assigned memory location                   /*             System.out.println("ScavengerHunt.update(): Player " + playerID + " writing outside assigned mem. loc. at address " +                                 Binary.intToHexString(address) +                                 " -- not implemented!");                     */                       JOptionPane.showMessageDialog(null,                                "ScavengerHunt.update(): Player " + playerID + " writing outside assigned mem. loc. at address " +                                 Binary.intToHexString(address) +                                 " -- not implemented!");          }          else if (isRead)          {             // Policy: anyone can read any location.          }                            } // end ScavengerHunt.update()                      // Write one word to MIPS memory. This is a wrapper to isolate the try..catch blocks.        private void toolSetWord(int address, int data)       {                 if (KENVDEBUG)          {             System.out.println("   ScavengerHunt.toolSetWord: Setting MIPS Memory[" +                Binary.intToHexString(address) + "] to " + Binary.intToHexString(data) + " = " + data );          }          SetWordCounter++;                 try {             Globals.memory.setWord(address, data); // Write          }              catch ( AddressErrorException e) {                System.out.println("ScavengerHunt.toolSetWord: deliberate exit on AEE exception.");                System.out.println("     SetWordCounter = " + SetWordCounter);                System.out.println("     address = " + Binary.intToHexString(address) );                System.out.println("     data = " + data );                System.exit(0);             }              catch ( Exception e) {                System.out.println("ScavengerHunt.toolSetWord: deliberate exit on " + e.getMessage() + " exception.");                System.out.println("     SetWordCounter = " + SetWordCounter);                System.out.println("     address = " + Binary.intToHexString(address) );                System.out.println("     data = " + data );                System.exit(0);             }                 if (KENVDEBUG)          {          // Verify data written correctly             int verifyData = toolGetWord(address);             if (verifyData != data)             {                System.out.println("\n\nScavengerHunt.toolSetWord: Can't verify data! Special exit.");                System.out.println("     address = " + Binary.intToHexString(address) );                System.out.println("     data = " + data);                System.out.println("     verifyData = " + verifyData);                System.exit(0);             }             else                System.out.println("  ScavengerHunt.toolSetWord: Mem[" +                   Binary.intToHexString(address) +                   " verified as " + Binary.intToHexString(data));          }              } // end toolSetWord                     // Read one word from MIPS memory. This is a wrapper to isolate the try..catch blocks.        private int toolGetWord(int address)       {                 int returnValue;                //System.out.println("ScavengerHunt.toolGetWord: called with address " +         //   Binary.intToHexString(address) );                 try {          /*          System.out.println("ScavengerHunt.toolGetWord: returning " +            Binary.intToHexString(Globals.memory.getWord(address)) +            " which is at MIPS Memory[" + Binary.intToHexString(address) + "]" );          */             returnValue = Globals.memory.getWord(address);                    /*          System.out.println("ScavengerHunt.toolGetWord: Mem[" +           Binary.intToHexString(address) + "] = " +           Binary.intToHexString(returnValue) + " --- returning normally");          */                       return returnValue;          }              catch ( AddressErrorException e) {                System.out.println("ScavengerHunt.toolGetWord: deliberate exit on AEE exception.");                System.out.println("     SetWordCounter = " + SetWordCounter);                System.out.println("     address = " + Binary.intToHexString(address) );                System.exit(0);             }              catch ( Exception e) {                System.out.println("ScavengerHunt.toolGetWord: deliberate exit on " + e.getMessage() + " exception.");                System.out.println("     SetWordCounter = " + SetWordCounter);                System.out.println("     address = " + Binary.intToHexString(address) );                System.exit(0);             }                 return 0; // Must have return statement       } // end toolGetWord                     // Read player's data field.        private int toolReadPlayerData(int p, int offset)       {                 if (KENVDEBUG)          {             System.out.println("ScavengerHunt.toolReadPlayerData: called with player " +  p +                ", offset = " +                Binary.intToHexString(offset) + " ---> address ” +
               Binary.intToHexString(ADDR_BASE + (p * MEM_PER_PLAYER) + offset)
               );
         }
      
         int returnValue = toolGetWord( ADDR_BASE + (p * MEM_PER_PLAYER) + offset);
      
         if (KENVDEBUG)
         {
         //if ((ADDR_BASE + (p * MEM_PER_PLAYER) + offset) >= 0xffff8000 &&
         //     (ADDR_BASE + (p * MEM_PER_PLAYER) + offset) < 0xffff8800)  // Show debug for player 0 and 1 only          //{          //System.out.println("   ScavengerHunt.toolReadPlayerData: Reading MIPS Memory[" +          //    Binary.intToHexString(ADDR_BASE + (p * MEM_PER_PLAYER) + offset) +          //    "] which is " + Binary.intToHexString(returnValue) +          //   " = " + Binary.intToHexString( returnValue) );          //}                       System.out.println("ScavengerHunt.toolReadPlayerData: Mem[" +                Binary.intToHexString(ADDR_BASE + (p * MEM_PER_PLAYER) + offset) + "] = " +                Binary.intToHexString(returnValue) + " --- returning normally");          }                 return returnValue;       } // end toolReadPlayerData         // Write player's data field.        private void toolWritePlayerData(int p, int offset, int data)       {                 int address = ADDR_BASE + (p * MEM_PER_PLAYER) + offset;                 if (KENVDEBUG)          {             System.out.println("ScavengerHunt.toolWritePlayerData: called with player " +  p +                ", offset = " + Binary.intToHexString(offset) +                ", data = " + Binary.intToHexString(data)  );          }                 toolSetWord( address, data);                 if (KENVDEBUG)          {             int verifyData = toolGetWord(address);             if (data != verifyData)             {                System.out.println("\n\nScavengerHunt.toolWritePlayerData: MAYDAY data not verified !");                System.out.println("      requested data to be written was " + Binary.intToHexString(data));                System.out.println("      actual data at that loc is " + Binary.intToHexString(toolGetWord(address)));                System.exit(0);             }             else                System.out.println("  ScavengerHunt.toolWritePlayerData: Mem[" +                   Binary.intToHexString(address) +                   " verified as " + Binary.intToHexString(data));          }              } // end toolWritePlayerData                private void initializeScavengerData()       {                //GameOn = false;  // MIPS programs readiness          authenticationValue = 0;          playerID = ADMINISTRATOR_ID;          startTime = System.currentTimeMillis();  // Clock time for program run                       // This is a dubious use of the tool (this Java program) to initialize data values for the game.                // The administrator portion of the MIPS program should initialize all data for each                // player -- but it's easier to work with random numbers in the Java program                // Initialize the locations and task data for each player          randomStream = new Random(42);  // TBD Use a seed for development. Remove seed for randomizing.                 for (int j = 0; j < NUM_LOCATIONS - 1; j++) // The first (n-1) locations are "random"          {  // Two coordinates (x and y) for each location             loc[j] = new Location(); // Initialize each location element             loc[j].X = (int)(randomStream.nextDouble() * GRAPHIC_WIDTH); // X coord.             loc[j].Y = (int)(randomStream.nextDouble() * (GRAPHIC_HEIGHT - 50)); // Y coord. (leave room for buttons in window)                               /*                     System.out.println("ScavengerHunt.update(): set up a location at (" +                                         loc[j].X +                                         ", " +                                         loc[j].Y +                                         ")" );                     */                               }          loc[NUM_LOCATIONS - 1] = new Location();  // The last location is a return to the starting position          loc[NUM_LOCATIONS - 1].X = START_AND_END_LOCATION;          loc[NUM_LOCATIONS - 1].Y = START_AND_END_LOCATION;                 for (int i = 0; i < NUM_PLAYERS; i++)  // Initialize data for each player          {                               //System.out.println("ScavengerHunt.update(): Player loop " + i);                       pd[i] = new PlayerData();  // Initialize each player data structure.                       for (int j = 0; j < NUM_LOCATIONS; j++)  // Initialize the locations this player goes to             {                toolWritePlayerData(i, OFFSET_LOC_ARRAY + (j * 8) + 0, loc[j].X);  // Set the same locations for each player                toolWritePlayerData(i, OFFSET_LOC_ARRAY + (j * 8) + 4, loc[j].Y);  // Set the same locations for each player             }                       for (int j = 0; j < SIZE_OF_TASK; j++)   // Initialize the task data for this player             {                toolWritePlayerData(i, OFFSET_TASK_ARRAY + (j * 4),                                 (int)(randomStream.nextDouble() * Integer.MAX_VALUE) );   // Set a random number for the task (sort them)             }          }              } // end initializeScavengerData         } // end ScavengerHunt mars/tools/BHTEntry.java mars/tools/BHTEntry.java/* Copyright (c) 2009,  Ingo Kofler, ITEC, Klagenfurt University, Austria Developed by Ingo Kofler (ingo. -klu.ac.at) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ package mars.tools;//.bhtsim; /**  * Represents a single entry of the Branch History Table.  * 

 * The entry holds the information about former branch predictions and outcomes.
 * The number of past branch outcomes can be configured and is called the history.
 * The semantics of the history of size n is as follows. 
 * The entry will change its prediction, if it mispredicts the branch n times in series.
 * The prediction of the entry can be obtained by the {@link BHTEntry#getPrediction()} method.
 * Feedback of taken or not taken branches is provided to the entry via the {@link BHTEntry#updatePrediction(boolean)} method.
 * This causes the history and the prediction to be updated.  
 * 

 * Additionally the entry keeps track about how many times the prediction was correct or incorrect.
 * The statistics can be obtained by the methods {@link BHTEntry#getStatsPredCorrect()}, {@link BHTEntry#getStatsPredIncorrect()} and {@link BHTEntry#getStatsPredPrecision()}.
 * 
 * @author ingo. -klu.ac.at
 */

public class BHTEntry {
    
    /** the history of the BHT entry. Each boolean value signals if the branch was taken or not. The value at index n-1 represents the most recent branch outcome. */
    private boolean m_history[];

    /** the current prediction */
    private boolean m_prediction;
    
    /** absolute number of incorrect predictions */
    private int m_incorrect;
    
    /** absolute number of correct predictions */
    private int m_correct;
    
    
    /**
     * Constructs a BHT entry with a given history size.  
     * 
     * The size of the history can only be set via the constructor and cannot be changed afterwards. 
     * 
     * @param historySize number of past branch outcomes to remember
     * @param initVal the initial value of the entry (take or do not take) 
     */
    public BHTEntry(int historySize, boolean initVal) {
        m_prediction = initVal; 
        m_history = new boolean[historySize];
        
        for (int i=0; i < historySize; i++) {             m_history[i] = initVal;         }                m_correct = m_incorrect = 0;                     }               /**      * Returns the branch prediction based on the history.      *       * @return true if prediction is to take the branch, false otherwise      */     public boolean getPrediction() {         return m_prediction;     }               /**      * Updates the entry's history and prediction.       * This method provides feedback for a prediction.       * The history and the statistics are updated accordingly.      * Based on the updated history a new prediction is calculated       *       * @param branchTaken signals if the branch was taken (true) or not (false)      */      public void updatePrediction(boolean branchTaken) {                  // update history         for (int i=0; i < m_history.length-1; i++) {             m_history[i] = m_history[i+1];         }         m_history[m_history.length-1] = branchTaken;                           // if the prediction was correct, update stats and keep prediction         if (branchTaken == m_prediction) {             m_correct ++;         }         else {             m_incorrect ++;                          // check if the prediction should change             boolean changePrediction = true;                          for (int i=0; i < m_history.length; i++) {                               if (m_history[i] != branchTaken)                      changePrediction = false;                            }                          if (changePrediction)                  m_prediction = !m_prediction;                      }     }                  /**      * Get the absolute number of mispredictions.      *        * @return number of incorrect predictions (mispredictions)      */     public int getStatsPredIncorrect() {         return m_incorrect;     }               /**      * Get the absolute number of correct predictions.      *       * @return number of correct predictions      */     public int getStatsPredCorrect() {         return m_correct;     }               /**      * Get the percentage of correct predictions.      *       * @return the percentage of correct predictions      */     public double getStatsPredPrecision() {         int sum = m_incorrect + m_correct;               return (sum==0) ? 0 : m_correct * 100.0 / sum;     }               /***      * Builds a string representation of the BHT entry's history.      * The history is a sequence of flags that signal if the branch was taken (T) or not taken (NT).       *       * @return a string representation of the BHT entry's history      */     public String getHistoryAsStr() {         String result = "";                  for (int i=0; i0) result = result + “, “; 
            result += m_history[i] ? “T” : “NT”;
        }
        return result;
    }   
    
    
    /***
     * Returns a string representation of the BHT entry’s current prediction.
     * The prediction can be either to TAKE or do NOT TAKE the branch.
     *  
     * @return a string representation of the BHT entry’s current prediction
     */
    public String getPredictionAsStr() {
        return m_prediction ? “TAKE” : “NOT TAKE”;
    }
}

FloatRepresentation$BinaryToDecimalFormulaGraphic

package mars.tools;
synchronized class FloatRepresentation$BinaryToDecimalFormulaGraphic extends javax.swing.JPanel {
final String subtractLabelTrailer;
final int arrowHeadOffset;
final int lowerY;
final int upperY;
int centerX;
int exponentCenterX;
int subtractLabelWidth;
int subtractLabelHeight;
int centerY;
int upperYArrowHead;
int currentExponent;
void FloatRepresentation$BinaryToDecimalFormulaGraphic(FloatRepresentation);
public void paintComponent(java.awt.Graphics);
public void drawSubtractLabel(int);
private void drawSubtractLabel(java.awt.Graphics, String);
private String buildSubtractLabel(int);
}

BHTableModel

package mars.tools;
public synchronized class BHTableModel extends javax.swing.table.AbstractTableModel {
private java.util.Vector m_entries;
private int m_entryCnt;
private int m_historySize;
private String[] m_columnNames;
private Class[] m_columnClasses;
public void BHTableModel(int, int, boolean);
public String getColumnName(int);
public Class getColumnClass(int);
public int getColumnCount();
public int getRowCount();
public Object getValueAt(int, int);
public void initBHT(int, int, boolean);
public int getIdxForAddress(int);
public boolean getPredictionAtIdx(int);
public void updatePredictionAtIdx(int, boolean);
}

Magnifier$5

package mars.tools;
synchronized class Magnifier$5 implements java.awt.event.ActionListener {
void Magnifier$5(Magnifier);
public void actionPerformed(java.awt.event.ActionEvent);
}

CaptureRectangleStrategy

package mars.tools;
abstract interface CaptureRectangleStrategy {
public abstract java.awt.Rectangle getCaptureRectangle(java.awt.Rectangle);
}

SettingsDialog$1

package mars.tools;
synchronized class SettingsDialog$1 implements java.awt.event.ActionListener {
void SettingsDialog$1(SettingsDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

MemoryReferenceVisualization$2

package mars.tools;
synchronized class MemoryReferenceVisualization$2 implements java.awt.event.ActionListener {
void MemoryReferenceVisualization$2(MemoryReferenceVisualization);
public void actionPerformed(java.awt.event.ActionEvent);
}

KeyboardAndDisplaySimulator$FontSettingDialog$2

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$FontSettingDialog$2 implements java.awt.event.ActionListener {
void KeyboardAndDisplaySimulator$FontSettingDialog$2(KeyboardAndDisplaySimulator$FontSettingDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

KeyboardAndDisplaySimulator$DelayLengthPanel

package mars.tools;
synchronized class KeyboardAndDisplaySimulator$DelayLengthPanel extends javax.swing.JPanel {
private static final int DELAY_INDEX_MIN = 0;
private static final int DELAY_INDEX_MAX = 40;
private static final int DELAY_INDEX_INIT = 4;
private double[] delayTable;
private javax.swing.JLabel sliderLabel;
private volatile int delayLengthIndex;
public void KeyboardAndDisplaySimulator$DelayLengthPanel(KeyboardAndDisplaySimulator);
public double getDelayLength();
private String setLabel(int);
}

FloatRepresentation$FlavorsOfFloat

package mars.tools;
synchronized class FloatRepresentation$FlavorsOfFloat {
String hexString;
String binaryString;
String decimalString;
String expansionString;
int intValue;
private void FloatRepresentation$FlavorsOfFloat(FloatRepresentation);
public FloatRepresentation$FlavorsOfFloat buildOneFromHexString(String);
private FloatRepresentation$FlavorsOfFloat buildOneFromBinaryString();
private FloatRepresentation$FlavorsOfFloat buildOneFromDecimalString(String);
private FloatRepresentation$FlavorsOfFloat buildOneFromInt(int);
public String buildExpansionFromBinaryString(String);
private String getFullBinaryStringFromDisplays();
private String addLeadingZeroes(String, int);
}

mars/tools/BitmapDisplay.java
mars/tools/BitmapDisplay.java   package mars.tools;
   import javax.swing.*;
   import javax.swing.border.*;
   import javax.swing.event.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.util.*;
   import mars.tools.*;
   import mars.mips.hardware.*;

/*
Copyright (c) 2010-2011,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
     * Bitmapp display simulator.  It can be run either as a stand-alone Java application having
     * access to the mars package, or through MARS as an item in its Tools menu.  It makes
     * maximum use of methods inherited from its abstract superclass AbstractMarsToolAndApplication.
     * Pete Sanderson, verison 1.0, 23 December 2010.
     */
    public class BitmapDisplay extends AbstractMarsToolAndApplication {
   
      private static String version = “Version 1.0”;
      private static String heading =  “Bitmap Display”;
    
    // Major GUI components
      private JComboBox visualizationUnitPixelWidthSelector, visualizationUnitPixelHeightSelector,
                        visualizationPixelWidthSelector, visualizationPixelHeightSelector, displayBaseAddressSelector;
      private Graphics drawingArea;
      private JPanel canvas;
      private JPanel results;
    
    // Some GUI settings
      private EmptyBorder emptyBorder = new EmptyBorder(4,4,4,4);
      private Font countFonts = new Font(“Times”, Font.BOLD,12);
      private Color backgroundColor = Color.WHITE;
    
    // Values for Combo Boxes
    
      private final String[] visualizationUnitPixelWidthChoices  = {“1″,”2″,”4″,”8″,”16″,”32”};
      private final int defaultVisualizationUnitPixelWidthIndex  = 0;
      private final String[] visualizationUnitPixelHeightChoices  = {“1″,”2″,”4″,”8″,”16″,”32”};
      private final int defaultVisualizationUnitPixelHeightIndex  = 0;
      private final String[] displayAreaPixelWidthChoices  = {“64″,”128″,”256″,”512″,”1024”};
      private final int defaultDisplayWidthIndex  = 3;
      private final String[] displayAreaPixelHeightChoices  = {“64″,”128″,”256″,”512″,”1024”};
      private final int defaultDisplayHeightIndex  = 2;
   
      // Values for display canvas.  Note their initialization uses the identifiers just above.
   
      private int unitPixelWidth = Integer.parseInt(visualizationUnitPixelWidthChoices[defaultVisualizationUnitPixelWidthIndex]);
      private int unitPixelHeight = Integer.parseInt(visualizationUnitPixelHeightChoices[defaultVisualizationUnitPixelHeightIndex]);
      private int displayAreaWidthInPixels = Integer.parseInt(displayAreaPixelWidthChoices[defaultDisplayWidthIndex]);
      private int displayAreaHeightInPixels = Integer.parseInt(displayAreaPixelHeightChoices[defaultDisplayHeightIndex]);
    
           
    // The next four are initialized dynamically in initializeDisplayBaseChoices()
      private String[] displayBaseAddressChoices;
      private int[] displayBaseAddresses;
      private int defaultBaseAddressIndex;
      private int baseAddress;
    
      private Grid theGrid;
                
    /**
     * Simple constructor, likely used to run a stand-alone bitmap display tool.
     * @param title String containing title for title bar
     * @param heading String containing text for heading shown in upper part of window.
     */
       public BitmapDisplay(String title, String heading) {
         super(title,heading);
      }
     
     /**
      *  Simple constructor, likely used by the MARS Tools menu mechanism
      */
       public BitmapDisplay() {
         super (“Bitmap Display, “+version, heading);
      }
         
         
    /**
     * Main provided for pure stand-alone use.  Recommended stand-alone use is to write a 
     * driver program that instantiates a Bitmap object then invokes its go() method.
     * “stand-alone” means it is not invoked from the MARS Tools menu.  “Pure” means there
     * is no driver program to invoke the application.
     */
       public static void main(String[] args) {
         new BitmapDisplay(“Bitmap Display stand-alone, “+version,heading).go();
      }
    
   
       /**
      *  Required MarsTool method to return Tool name.  
      *  @return  Tool name.  MARS will display this in menu item.
      */
       public String getName() {
         return “Bitmap Display”;
      }
    
    
      /**
     *  Override the inherited method, which registers us as an Observer over the static data segment 
     *  (starting address 0x10010000) only.  This version will register us as observer over the 
     *  the memory range as selected by the base address combo box and capacity of the visualization display 
     *  (number of visualization elements times the number of memory words each one represents). 
     *  It does so by calling the inherited 2-parameter overload of this method. 
     *  If you use the inherited GUI buttons, this 
     *  method is invoked when you click “Connect” button on MarsTool or the 
     *  “Assemble and Run” button on a Mars-based app.
     */
       protected void addAsObserver() {
         int highAddress = baseAddress+theGrid.getRows()*theGrid.getColumns()*Memory.WORD_LENGTH_BYTES;
        // Special case: baseAddress<0 means we're in kernel memory (0x80000000 and up) and most likely         // in memory map address space (0xffff0000 and up).  In this case, we need to make sure the high address         // does not drop off the high end of 32 bit address space.  Highest allowable word address is 0xfffffffc,         // which is interpreted in Java int as -4.          if (baseAddress < 0 && highAddress > -4) {
            highAddress = -4;
         }
         addAsObserver(baseAddress, highAddress);
      }
   
      
    /**
     *  Method that constructs the main display area.  It is organized vertically
     *  into two major components: the display configuration which an be modified
     *  using combo boxes, and the visualization display which is updated as the
     *  attached MIPS program executes.
     *  @return the GUI component containing these two areas
     */
       protected JComponent buildMainDisplayArea() {
         results = new JPanel();
         results.add(buildOrganizationArea());
         results.add(buildVisualizationArea());
         return results;
      }
   
   
      //////////////////////////////////////////////////////////////////////////////////////
      //  Rest of the protected methods.  These override do-nothing methods inherited from
    //  the abstract superclass.
      //////////////////////////////////////////////////////////////////////////////////////
    
      /**
     * Update display when connected MIPS program accesses (data) memory.
     * @param memory the attached memory
     * @param accessNotice information provided by memory in MemoryAccessNotice object
     */
       protected void processMIPSUpdate(Observable memory, AccessNotice accessNotice) {
         if (accessNotice.getAccessType() == AccessNotice.WRITE) {
            updateColorForAddress((MemoryAccessNotice)accessNotice);
         }
      }
    
   
    /** 
     *  Initialize all JComboBox choice structures not already initialized at declaration.  
       *  Overrides inherited method that does nothing.
     */
       protected void initializePreGUI() {
         initializeDisplayBaseChoices();
        // NOTE: Can’t call “createNewGrid()” here because it uses settings from
        //       several combo boxes that have not been created yet.  But a default grid
        //       needs to be allocated for initial canvas display.
         theGrid = new Grid(displayAreaHeightInPixels/unitPixelHeight,
                            displayAreaWidthInPixels/unitPixelWidth);
      }
   
   
    /** 
     *  The only post-GUI initialization is to create the initial Grid object based on the default settings
     *  of the various combo boxes. Overrides inherited method that does nothing.
     */
    
       protected void initializePostGUI() {
         theGrid = createNewGrid();
         updateBaseAddress();
      }
    
    
    /**
     *  Method to reset counters and display when the Reset button selected.
     *  Overrides inherited method that does nothing.
     */
       protected void reset() {
         resetCounts();
         updateDisplay();
      }
   
    /**
     *  Updates display immediately after each update (AccessNotice) is processed, after
     *  display configuration changes as needed, and after each execution step when Mars
     *  is running in timed mode.  Overrides inherited method that does nothing.
     */
       protected void updateDisplay() {
         canvas.repaint();
      }
   
       
     /**
      *  Overrides default method, to provide a Help button for this tool/app.
      */
       protected JComponent getHelpComponent() {
         final String helpContent = 
                              “Use this program to simulate a basic bitmap display where\n”+
                              “each memory word in a specified address space corresponds to\n”+
                                    “one display pixel in row-major order starting at the upper left\n”+
                                    “corner of the display.  This tool may be run either from the\n”+
                                    “MARS Tools menu or as a stand-alone application.\n”+
                                    “\n”+
                                    “You can easily learn to use this small program by playing with\n”+
                                    “it!   Each rectangular unit on the display represents one memory\n”+
                                    “word in a contiguous address space starting with the specified\n”+
                                    “base address.  The value stored in that word will be interpreted\n”+
                                    “as a 24-bit RGB color value with the red component in bits 16-23,\n”+
                                    “the green component in bits 8-15, and the blue component in bits 0-7.\n”+                                  
                                    “Each time a memory word within the display address space is written\n”+
                                    “by the MIPS program, its position in the display will be rendered\n”+
                                    “in the color that its value represents.\n”+
                                    “\n”+
                                    “Version 1.0 is very basic and was constructed from the Memory\n”+
                                    “Reference Visualization tool’s code.  Feel free to improve it and\n”+
                                    “send me your code for consideration in the next MARS release.\n”+
                                    “\n”+
                                    “Contact Pete Sanderson at   with\n”+
                                    “questions or comments.\n”;
         JButton help = new JButton(“Help”);
         help.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     JOptionPane.showMessageDialog(theWindow, helpContent);
                  }
               });      
         return help;  
      }
    
      //////////////////////////////////////////////////////////////////////////////////////
      //  Private methods defined to support the above.
      //////////////////////////////////////////////////////////////////////////////////////
        
    // UI components and layout for left half of GUI, where settings are specified.
       private JComponent buildOrganizationArea() {
         JPanel organization = new JPanel(new GridLayout(8,1));
        
         visualizationUnitPixelWidthSelector = new JComboBox(visualizationUnitPixelWidthChoices);
         visualizationUnitPixelWidthSelector.setEditable(false);
         visualizationUnitPixelWidthSelector.setBackground(backgroundColor);
         visualizationUnitPixelWidthSelector.setSelectedIndex(defaultVisualizationUnitPixelWidthIndex);
         visualizationUnitPixelWidthSelector.setToolTipText(“Width in pixels of rectangle representing memory word”);
         visualizationUnitPixelWidthSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     unitPixelWidth = getIntComboBoxSelection(visualizationUnitPixelWidthSelector);
                     theGrid = createNewGrid();
                     updateDisplay();
                  }
               });
         visualizationUnitPixelHeightSelector = new JComboBox(visualizationUnitPixelHeightChoices);
         visualizationUnitPixelHeightSelector.setEditable(false);
         visualizationUnitPixelHeightSelector.setBackground(backgroundColor);
         visualizationUnitPixelHeightSelector.setSelectedIndex(defaultVisualizationUnitPixelHeightIndex);
         visualizationUnitPixelHeightSelector.setToolTipText(“Height in pixels of rectangle representing memory word”);
         visualizationUnitPixelHeightSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     unitPixelHeight = getIntComboBoxSelection(visualizationUnitPixelHeightSelector);
                     theGrid = createNewGrid();
                     updateDisplay();
                  }
               });                  
         visualizationPixelWidthSelector = new JComboBox(displayAreaPixelWidthChoices);
         visualizationPixelWidthSelector.setEditable(false);
         visualizationPixelWidthSelector.setBackground(backgroundColor);
         visualizationPixelWidthSelector.setSelectedIndex(defaultDisplayWidthIndex);
         visualizationPixelWidthSelector.setToolTipText(“Total width in pixels of display area”);
         visualizationPixelWidthSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     displayAreaWidthInPixels = getIntComboBoxSelection(visualizationPixelWidthSelector);
                     canvas.setPreferredSize(getDisplayAreaDimension());
                     canvas.setSize(getDisplayAreaDimension());
                     theGrid = createNewGrid();
                     updateDisplay();
                  }
               });
         visualizationPixelHeightSelector = new JComboBox(displayAreaPixelHeightChoices);
         visualizationPixelHeightSelector.setEditable(false);
         visualizationPixelHeightSelector.setBackground(backgroundColor);
         visualizationPixelHeightSelector.setSelectedIndex(defaultDisplayHeightIndex);
         visualizationPixelHeightSelector.setToolTipText(“Total height in pixels of display area”);
         visualizationPixelHeightSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     displayAreaHeightInPixels = getIntComboBoxSelection(visualizationPixelHeightSelector);
                     canvas.setPreferredSize(getDisplayAreaDimension());
                     canvas.setSize(getDisplayAreaDimension());
                     theGrid = createNewGrid();
                     updateDisplay();
                  }
               });          
         displayBaseAddressSelector = new JComboBox(displayBaseAddressChoices);
         displayBaseAddressSelector.setEditable(false);
         displayBaseAddressSelector.setBackground(backgroundColor);
         displayBaseAddressSelector.setSelectedIndex(defaultBaseAddressIndex);
         displayBaseAddressSelector.setToolTipText(“Base address for display area (upper left corner)”);
         displayBaseAddressSelector.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                    // This may also affect what address range we should be registered as an Observer
                    // for.  The default (inherited) address range is the MIPS static data segment 
                    // starting at 0x10010000. To change this requires override of
                    // AbstractMarsToolAndApplication.addAsObserver().  The no-argument version of 
                    // that method is called automatically  when “Connect” button is clicked for MarsTool 
                    // and when “Assemble and Run” button is clicked for Mars application.
                     updateBaseAddress();
                    // If display base address is changed while connected to MIPS (this can only occur
                    // when being used as a MarsTool), we have to delete ourselves as an observer and re-register.
                     if (connectButton != null && connectButton.isConnected()) {
                        deleteAsObserver();
                        addAsObserver();
                     }
                     theGrid = createNewGrid();
                     updateDisplay();
                  }
               });          
      
         // ALL COMPONENTS FOR “ORGANIZATION” SECTION
      
         JPanel unitWidthInPixelsRow = getPanelWithBorderLayout();
         unitWidthInPixelsRow.setBorder(emptyBorder);
         unitWidthInPixelsRow.add(new JLabel(“Unit Width in Pixels “),BorderLayout.WEST);
         unitWidthInPixelsRow.add(visualizationUnitPixelWidthSelector, BorderLayout.EAST);
      
         JPanel unitHeightInPixelsRow = getPanelWithBorderLayout();
         unitHeightInPixelsRow.setBorder(emptyBorder);
         unitHeightInPixelsRow.add(new JLabel(“Unit Height in Pixels “),BorderLayout.WEST);
         unitHeightInPixelsRow.add(visualizationUnitPixelHeightSelector,BorderLayout.EAST);                     
      
         JPanel widthInPixelsRow = getPanelWithBorderLayout();
         widthInPixelsRow.setBorder(emptyBorder);
         widthInPixelsRow.add(new JLabel(“Display Width in Pixels “),BorderLayout.WEST);
         widthInPixelsRow.add(visualizationPixelWidthSelector, BorderLayout.EAST);
      
         JPanel heightInPixelsRow = getPanelWithBorderLayout();
         heightInPixelsRow.setBorder(emptyBorder);
         heightInPixelsRow.add(new JLabel(“Display Height in Pixels “),BorderLayout.WEST);
         heightInPixelsRow.add(visualizationPixelHeightSelector,BorderLayout.EAST);                     
      
         JPanel baseAddressRow = getPanelWithBorderLayout();
         baseAddressRow.setBorder(emptyBorder);
         baseAddressRow.add(new JLabel(“Base address for display “),BorderLayout.WEST);
         baseAddressRow.add(displayBaseAddressSelector,BorderLayout.EAST);                      
      
      
        // Lay ’em out in the grid…
         organization.add(unitWidthInPixelsRow);
         organization.add(unitHeightInPixelsRow);     
         organization.add(widthInPixelsRow);
         organization.add(heightInPixelsRow);  
         organization.add(baseAddressRow); 
         return organization;
      }
    
    // UI components and layout for right half of GUI, the visualization display area.
       private JComponent buildVisualizationArea() {
         canvas = new GraphicsPanel();
         canvas.setPreferredSize(getDisplayAreaDimension());
         canvas.setToolTipText(“Bitmap display area”);
         return canvas;
      }
   
      // For greatest flexibility, initialize the display base choices directly from
      // the constants defined in the Memory class.  This method called prior to 
      // building the GUI.  Here are current values from Memory.java:
      //dataSegmentBaseAddress=0x10000000, globalPointer=0x10008000
      //dataBaseAddress=0x10010000, heapBaseAddress=0x10040000, memoryMapBaseAddress=0xffff0000 
       private void initializeDisplayBaseChoices() {
         int[] displayBaseAddressArray = {Memory.dataSegmentBaseAddress, Memory.globalPointer, Memory.dataBaseAddress,
                                          Memory.heapBaseAddress, Memory.memoryMapBaseAddress };
        // Must agree with above in number and order…
         String[] descriptions =         { ” (global data)”, ” ($gp)”, ” (static data)”, ” (heap)”, ” (memory map)” };
         displayBaseAddresses = displayBaseAddressArray;
         displayBaseAddressChoices = new String[displayBaseAddressArray.length];
         for (int i=0; i 10 characters long, slice off the first
             10 and apply Integer.parseInt() to it to get custom base address.
        */
      }
    
     // Returns Dimension object with current width and height of display area as determined
       // by current settings of respective combo boxes.
       private Dimension getDisplayAreaDimension() {
         return new Dimension(displayAreaWidthInPixels, displayAreaHeightInPixels);
      }
    
    // reset all counters in the Grid.
       private void resetCounts() {
         theGrid.reset();
      }
    
    // Will return int equivalent of specified combo box’s current selection.
    // The selection must be a String that parses to an int.
       private int getIntComboBoxSelection(JComboBox comboBox) {
         try {
            return Integer.parseInt((String)comboBox.getSelectedItem());
         } 
             catch (NumberFormatException nfe) {
                // Can occur only if initialization list contains badly formatted numbers.  This
                // is a developer’s error, not a user error, and better be caught before release.
               return 1;
            }
      }
    
     // Use this for consistent results.
       private JPanel getPanelWithBorderLayout() {
         return new JPanel(new BorderLayout(2,2));
      }
    
     // Method to determine grid dimensions based on current control settings.
     // Each grid element corresponds to one visualization unit. 
       private Grid createNewGrid() {
         int rows = displayAreaHeightInPixels/unitPixelHeight;
         int columns = displayAreaWidthInPixels/unitPixelWidth;
         return new Grid(rows,columns);
      }
    
     // Given memory address, update color for the corresponding grid element.
       private void updateColorForAddress(MemoryAccessNotice notice) {
         int address = notice.getAddress();
         int value   = notice.getValue();
         int offset = (address – baseAddress)/Memory.WORD_LENGTH_BYTES;
         try {
            theGrid.setElement(offset / theGrid.getColumns(), offset % theGrid.getColumns(), value);
         } 
             catch (IndexOutOfBoundsException e) {
                 // If address is out of range for display, do nothing.  
            }
      }
      
      
      //////////////////////////////////////////////////////////////////////////////////////
      //  Specialized inner classes for modeling and animation.
      //////////////////////////////////////////////////////////////////////////////////////
    
   
    /////////////////////////////////////////////////////////////////////////////
    //  Class that represents the panel for visualizing and animating memory reference
    //  patterns.
       private class GraphicsPanel extends JPanel {
        
          // override default paint method to assure display updated correctly every time
         // the panel is repainted.
          public void paint(Graphics g) {
               paintGrid(g, theGrid);
         }
      
        // Paint the color codes.
          private void paintGrid(Graphics g, Grid grid) {
            int upperLeftX = 0, upperLeftY = 0;
            for (int i=0; i=0 && row<=rows && column>=0 && column<=columns) ? grid[row][column] : null;                      }                // Returns value in given grid element without doing any row/column index checking.         // Is faster than getElement but will throw array index out of bounds exception if         // parameter values are outside the bounds of the grid.                    private Color getElementFast(int row, int column) {             return grid[row][column];                     }                          // Set the grid element.           private void setElement(int row, int column, int color) {             grid[row][column] = new Color(color);          }                  // Set the grid element.           private void setElement(int row, int column, Color color) {             grid[row][column] = color;          }                // Just set all grid elements to black.           private void reset() {             for (int i=0; i();
public void MemoryReferenceVisualization(String, String);
public void MemoryReferenceVisualization();
public static void main(String[]);
public String getName();
protected void addAsObserver();
protected javax.swing.JComponent buildMainDisplayArea();
protected void processMIPSUpdate(java.util.Observable, mars.mips.hardware.AccessNotice);
protected void initializePreGUI();
protected void initializePostGUI();
protected void reset();
protected void updateDisplay();
protected javax.swing.JComponent getHelpComponent();
private javax.swing.JComponent buildOrganizationArea();
private javax.swing.JComponent buildVisualizationArea();
private void initializeDisplayBaseChoices();
private void updateBaseAddress();
private java.awt.Dimension getDisplayAreaDimension();
private void resetCounts();
private int getIntComboBoxSelection(javax.swing.JComboBox);
private javax.swing.JPanel getPanelWithBorderLayout();
private MemoryReferenceVisualization$Grid createNewGrid();
private void incrementReferenceCountForAddress(int);
}

MagnifierImage$2

package mars.tools;
synchronized class MagnifierImage$2 extends java.awt.event.MouseMotionAdapter {
void MagnifierImage$2(MagnifierImage);
public void mouseDragged(java.awt.event.MouseEvent);
}

MemoryReferenceVisualization$CounterColor

package mars.tools;
synchronized class MemoryReferenceVisualization$CounterColor implements Comparable {
private int colorRangeStart;
private java.awt.Color associatedColor;
public void MemoryReferenceVisualization$CounterColor(MemoryReferenceVisualization, int, java.awt.Color);
public int compareTo(Object);
}

MemoryReferenceVisualization$4

package mars.tools;
synchronized class MemoryReferenceVisualization$4 implements java.awt.event.ActionListener {
void MemoryReferenceVisualization$4(MemoryReferenceVisualization);
public void actionPerformed(java.awt.event.ActionEvent);
}

FloatRepresentation$HexDisplayKeystrokeListener

package mars.tools;
synchronized class FloatRepresentation$HexDisplayKeystrokeListener extends java.awt.event.KeyAdapter {
private int digitLength;
public void FloatRepresentation$HexDisplayKeystrokeListener(FloatRepresentation, int);
public void keyTyped(java.awt.event.KeyEvent);
public void keyPressed(java.awt.event.KeyEvent);
private boolean isHexDigit(char);
}

MarsBot$BotRunnable$1

package mars.tools;
synchronized class MarsBot$BotRunnable$1 implements java.awt.event.ActionListener {
void MarsBot$BotRunnable$1(MarsBot$BotRunnable);
public void actionPerformed(java.awt.event.ActionEvent);
}

ScavengerHunt$Location

package mars.tools;
synchronized class ScavengerHunt$Location {
public int X;
public int Y;
private void ScavengerHunt$Location(ScavengerHunt);
}

FloatRepresentation

package mars.tools;
public synchronized class FloatRepresentation extends AbstractMarsToolAndApplication {
private static String version;
private static String heading;
private static final String title = Floating Point Representation, ;
private static final String defaultHex = 00000000;
private static final String defaultDecimal = 0.0;
private static final String defaultBinarySign = 0;
private static final String defaultBinaryExponent = 00000000;
private static final String defaultBinaryFraction = 00000000000000000000000;
private static final int maxLengthHex = 8;
private static final int maxLengthBinarySign = 1;
private static final int maxLengthBinaryExponent = 8;
private static final int maxLengthBinaryFraction = 23;
private static final int maxLengthBinaryTotal = 32;
private static final int maxLengthDecimal = 20;
private static final String denormalizedLabel = significand (denormalized – no ‘hidden bit’);
private static final String normalizedLabel = significand (‘hidden bit’ underlined) ;
private static final java.awt.Font instructionsFont;
private static final java.awt.Font hexDisplayFont;
private static final java.awt.Font binaryDisplayFont;
private static final java.awt.Font decimalDisplayFont;
private static final java.awt.Color hexDisplayColor;
private static final java.awt.Color binaryDisplayColor;
private static final java.awt.Color decimalDisplayColor;
private static final String expansionFontTag = ;
private static final String instructionFontTag = ;
private static final int exponentBias = 127;
private mars.mips.hardware.Register attachedRegister;
private mars.mips.hardware.Register[] fpRegisters;
private FloatRepresentation thisFloatTool;
private javax.swing.JPanel binarySignDecoratedDisplay;
private javax.swing.JPanel binaryExponentDecoratedDisplay;
private javax.swing.JPanel binaryFractionDecoratedDisplay;
private javax.swing.JTextField hexDisplay;
private javax.swing.JTextField decimalDisplay;
private javax.swing.JTextField binarySignDisplay;
private javax.swing.JTextField binaryExponentDisplay;
private javax.swing.JTextField binaryFractionDisplay;
private javax.swing.JLabel expansionDisplay;
private javax.swing.JLabel significandLabel;
private FloatRepresentation$BinaryToDecimalFormulaGraphic binaryToDecimalFormulaGraphic;
private FloatRepresentation$InstructionsPane instructions;
private String defaultInstructions;
private static final String zeroes = 0000000000000000000000000000000000000000000000000000000000000000;
private static final String HTMLspaces =         ;
static void ();
public void FloatRepresentation(String, String);
public void FloatRepresentation();
public static void main(String[]);
public String getName();
protected void addAsObserver();
protected void deleteAsObserver();
protected javax.swing.JComponent buildMainDisplayArea();
public void update(java.util.Observable, Object);
protected void reset();
protected javax.swing.JComponent buildDisplayArea();
private synchronized void updateAnyAttachedRegister(int);
private void updateDisplays(FloatRepresentation$FlavorsOfFloat);
private void updateDisplaysAndRegister(FloatRepresentation$FlavorsOfFloat);
private void updateSignificandLabel(FloatRepresentation$FlavorsOfFloat);
}

Magnifier$3

package mars.tools;
synchronized class Magnifier$3 implements java.awt.event.ActionListener {
void Magnifier$3(Magnifier);
public void actionPerformed(java.awt.event.ActionEvent);
}

TokenList

package mars.assembler;
public synchronized class TokenList implements Cloneable {
private java.util.ArrayList tokenList;
private String processedLine;
public void TokenList();
public void setProcessedLine(String);
public String getProcessedLine();
public Token get(int);
public void set(int, Token);
public int size();
public void add(Token);
public void remove(int);
public boolean isEmpty();
public String toString();
public String toTypeString();
public Object clone();
}

mars/assembler/MacroPool.java
mars/assembler/MacroPool.java   package mars.assembler;

   import java.util.ArrayList;
   import java.util.Stack;

   import mars.ErrorList;
   import mars.MIPSprogram;

/*
Copyright (c) 2013.

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
 
/**
 * Stores information of macros defined by now. 
 * Will be used in first pass of assembling MIPS source code. When reached
 * .macro directive, parser calls
 * {@link MacroPool#BeginMacro(String, int)} and skips source code lines until
 * reaches .end_macro directive. then calls
 * {@link MacroPool#CommitMacro(int)} and the macro information stored in a
 * {@link Macro} instance will be added to {@link #macroList}. 
 * Each {@link MIPSprogram} will have one {@link MacroPool}
 * NOTE: Forward referencing macros (macro expansion before its definition in
 * source code) and Nested macro definition (defining a macro inside other macro
 * definition) are not supported.
 * 
 * @author M.H.Sekhavat < >
 */
    public class MacroPool {
      private MIPSprogram program;
   /**
    * List of macros defined by now
    */
      private ArrayList macroList;
   /**
    * @see #BeginMacro(String, int)
    */
      private Macro current;
      private ArrayList callStack;
      private ArrayList callStackOrigLines;
   /**
    * @see #getNextCounter()
    */
      private int counter;
   
   
   /**
   * Create an empty MacroPool for given program
   * @param mipsProgram  associated MIPS program
   */
       public MacroPool(MIPSprogram mipsProgram) {
         this.program = mipsProgram;
         macroList = new ArrayList();
         callStack=new ArrayList();
         callStackOrigLines=new ArrayList();
         current = null;
         counter = 0;
      }
   
   /**
    * This method will be called by parser when reached .macro
    * directive.
    * Instantiates a new {@link Macro} object and stores it in {@link #current}
    * . {@link #current} will be added to {@link #macroList} by
    * {@link #CommitMacro(int)}
    * 
    * @param nameToken
    *            Token containing name of macro after .macro directive
    */
   
       public void beginMacro(Token nameToken) {
         current = new Macro();
         current.setName(nameToken.getValue());
         current.setFromLine(nameToken.getSourceLine());
         current.setOriginalFromLine(nameToken.getOriginalSourceLine());
         current.setProgram(program);
      }    
   
   /**
    * This method will be called by parser when reached .end_macro
    * directive. 
    * Adds/Replaces {@link #current} macro into the {@link #macroList}.
    * 
    * @param endToken
    *            Token containing .end_macro directive in source code
    */
   
       public void commitMacro(Token endToken) {
         current.setToLine(endToken.getSourceLine());
         current.setOriginalToLine(endToken.getOriginalSourceLine());
         current.readyForCommit();
         macroList.add(current);
         current = null;
      }
            
   /**
    * Will be called by parser when reaches a macro expansion call
    * 
    * @param tokens
    *            tokens passed to macro expansion call
    * @return {@link Macro} object matching the name and argument count of
    *         tokens passed
    */
       public Macro getMatchingMacro(TokenList tokens, int callerLine) {
         if (tokens.size() < 1)             return null;          Macro ret = null;          Token firstToken = tokens.get(0);          for (Macro macro : macroList) {             if (macro.getName().equals(firstToken.getValue())                 && macro.getArgs().size() + 1 == tokens.size()                 && macro.getToLine() < callerLine                 && (ret == null || ret.getFromLine() < macro.getFromLine()))                ret = macro;          }          return ret;       }        /**     * @param value     * @return true if any macros have been defined with name value
    *         by now, not concerning arguments count.
    */
       public boolean matchesAnyMacroName(String value) {
         for (Macro macro : macroList)
            if (macro.getName().equals(value))
               return true;
         return false;
      }
   
   
       public Macro getCurrent() {
         return current;
      }
   
       public void setCurrent(Macro current) {
         this.current = current;
      }
   
   /**
    * {@link #counter} will be set to 0 on construction of this class and will
    * be incremented by each call. parser calls this method once for every
    * expansions. it will be a unique id for each expansion of macro in a file
    * 
    * @return counter value
    */
       public int getNextCounter() {
         return counter++;
      }
   
   
       public ArrayList getCallStack() {
         return callStack;
      }
   
   
       public boolean pushOnCallStack(Token token) { //returns true if detected expansion loop
         int sourceLine = token.getSourceLine();
         int origSourceLine = token.getOriginalSourceLine();
         if (callStack.contains(sourceLine))
            return true;
         callStack.add(sourceLine);
         callStackOrigLines.add(origSourceLine);
         return false;
      }
   
       public void popFromCallStack() {
         callStack.remove(callStack.size()-1);
         callStackOrigLines.remove(callStackOrigLines.size()-1);
      }
   
   
       public String getExpansionHistory() {
         String ret=””;
         for (int i=0; i0)
               ret+=”->”;
            ret+=callStackOrigLines.get(i).toString();
         }
         return ret;
      }
   }

mars/assembler/Directives.java
mars/assembler/Directives.java   package mars.assembler;

   import java.util.ArrayList;

/*
Copyright (c) 2003-2012,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Class representing MIPS assembler directives.  If Java had enumerated types, these
 * would probably be implemented that way.  Each directive is represented by a unique object.
 * The directive name is indicative of the directive it represents.  For example, DATA
 * represents the MIPS .data directive.
 * 
 * @author Pete Sanderson
 * @version August 2003
 **/

    public final class Directives {
   
      private static ArrayList directiveList = new ArrayList();
      public static final Directives DATA   = new Directives(“.data”, “Subsequent items stored in Data segment at next available address”);
      public static final Directives TEXT   = new Directives(“.text”, “Subsequent items (instructions) stored in Text segment at next available address”);
      public static final Directives WORD   = new Directives(“.word”, “Store the listed value(s) as 32 bit words on word boundary”);
      public static final Directives ASCII  = new Directives(“.ascii”, “Store the string in the Data segment but do not add null terminator”);
      public static final Directives ASCIIZ = new Directives(“.asciiz”, “Store the string in the Data segment and add null terminator”);
      public static final Directives BYTE   = new Directives(“.byte”, “Store the listed value(s) as 8 bit bytes”);
      public static final Directives ALIGN  = new Directives(“.align”, “Align next data item on specified byte boundary (0=byte, 1=half, 2=word, 3=double)”); 
      public static final Directives HALF   = new Directives(“.half”, “Store the listed value(s) as 16 bit halfwords on halfword boundary”);
      public static final Directives SPACE  = new Directives(“.space”, “Reserve the next specified number of bytes in Data segment”);
      public static final Directives DOUBLE = new Directives(“.double”, “Store the listed value(s) as double precision floating point”);
      public static final Directives FLOAT  = new Directives(“.float”, “Store the listed value(s) as single precision floating point”);
      public static final Directives EXTERN = new Directives(“.extern”, “Declare the listed label and byte length to be a global data field”);
      public static final Directives KDATA  = new Directives(“.kdata”, “Subsequent items stored in Kernel Data segment at next available address”);
      public static final Directives KTEXT  = new Directives(“.ktext”, “Subsequent items (instructions) stored in Kernel Text segment at next available address”);
      public static final Directives GLOBL  = new Directives(“.globl”, “Declare the listed label(s) as global to enable referencing from other files”);
      public static final Directives SET    = new Directives(“.set”, “Set assembler variables.  Currently ignored but included for SPIM compatability”);
      /*  EQV added by DPS 11 July 2012 */
      public static final Directives EQV    = new Directives(“.eqv”, “Substitute second operand for first. First operand is symbol, second operand is expression (like #define)”);
      /* MACRO and END_MACRO added by Mohammad Sekhavat Oct 2012 */    
      public static final Directives MACRO  = new Directives(“.macro”, “Begin macro definition.  See .end_macro”);
      public static final Directives END_MACRO = new Directives(“.end_macro”, “End macro definition.  See .macro”);
      /*  INCLUDE added by DPS 11 Jan 2013 */
      public static final Directives INCLUDE   = new Directives(“.include”, “Insert the contents of the specified file.  Put filename in quotes.”);
   
   
      private String descriptor;
      private String description; // help text
   
       private Directives() {
      // private ctor assures no objects can be created other than those above.
         this.descriptor  = “generic”;
         this.description = “”;
         directiveList.add(this);
      }
   
       private Directives(String name, String description) {
         this.descriptor  = name;
         this.description = description;
         directiveList.add(this);
      }
   
   /**
    * Find Directive object, if any, which matches the given String.
    * 
    * @param str A String containing candidate directive name (e.g. “.ascii”)
    * @return If match is found, returns matching Directives object, else returns null.
    **/
    
       public static Directives matchDirective(String str) {
         Directives match;
         for (int i=0; inull.
    **/
    
       public static ArrayList prefixMatchDirectives(String str) {
         ArrayList matches = null;
         for (int i=0; i();
private void Directives();
private void Directives(String, String);
public static Directives matchDirective(String);
public static java.util.ArrayList prefixMatchDirectives(String);
public String toString();
public String getName();
public String getDescription();
public static java.util.ArrayList getDirectiveList();
public static boolean isIntegerDirective(Directives);
public static boolean isFloatingDirective(Directives);
}

mars/assembler/TokenTypes.java
mars/assembler/TokenTypes.java   package mars.assembler;
    import mars.*;
    import mars.util.*;
    import mars.mips.hardware.*;
    
    /*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
/**
 * Constants to identify the types of tokens found in MIPS programs.  If Java had
 * enumerated types, that’s how these would probably be implemented.
 * 
 * @author Pete Sanderson
 * @version August 2003
 **/

    public final class TokenTypes {
   
      public static final String TOKEN_DELIMITERS = “\t ,()”;
      public static final TokenTypes COMMENT       = new TokenTypes(“COMMENT”);
      public static final TokenTypes DIRECTIVE     = new TokenTypes(“DIRECTIVE”);
      public static final TokenTypes OPERATOR      = new TokenTypes(“OPERATER”);
      public static final TokenTypes DELIMITER     = new TokenTypes(“DELIMITER”);
   /** note: REGISTER_NAME is token of form $zero whereas REGISTER_NUMBER is token
   *       of form $0.  The former is part of extended assembler, and latter is part
   *       of basic assembler.  
   **/
      public static final TokenTypes REGISTER_NAME = new TokenTypes(“REGISTER_NAME”); // mnemonic
      public static final TokenTypes REGISTER_NUMBER = new TokenTypes(“REGISTER_NUMBER”);
      public static final TokenTypes FP_REGISTER_NAME = new TokenTypes(“FP_REGISTER_NAME”);     
      public static final TokenTypes IDENTIFIER    = new TokenTypes(“IDENTIFIER”);
      public static final TokenTypes LEFT_PAREN    = new TokenTypes(“LEFT_PAREN”);
      public static final TokenTypes RIGHT_PAREN   = new TokenTypes(“RIGHT_PAREN”);
   //public static final TokenTypes INTEGER       = new TokenTypes(“INTEGER”);
      public static final TokenTypes INTEGER_5     = new TokenTypes(“INTEGER_5”);
      public static final TokenTypes INTEGER_16    = new TokenTypes(“INTEGER_16”);
      public static final TokenTypes INTEGER_16U    = new TokenTypes(“INTEGER_16U”);
      public static final TokenTypes INTEGER_32    = new TokenTypes(“INTEGER_32”);
      public static final TokenTypes REAL_NUMBER   = new TokenTypes(“REAL_NUMBER”);
      public static final TokenTypes QUOTED_STRING = new TokenTypes(“QUOTED_STRING”);
      public static final TokenTypes PLUS          = new TokenTypes(“PLUS”);
      public static final TokenTypes MINUS         = new TokenTypes(“MINUS”);
      public static final TokenTypes COLON         = new TokenTypes(“COLON”);
      public static final TokenTypes ERROR         = new TokenTypes(“ERROR”);
      public static final TokenTypes MACRO_PARAMETER = new TokenTypes(“MACRO_PARAMETER”);
   
      private String descriptor;
   
       private TokenTypes() {
      // private ctor assures no objects can be created other than those above.
         descriptor = “generic”;
      }
   
       private TokenTypes(String name) {
         descriptor = name;
      }
   
   /**
    * Produces String equivalent of this token type, which is its name.
    * 
    * @return String containing descriptive name for token type.
    **/
       public String toString() {
         return descriptor;
      }
   
   /**
    * Classifies the given token into one of the MIPS types.
    * 
    * @param value String containing candidate language element, extracted from MIPS program.
    * 
    * @return Returns the corresponding TokenTypes object if the parameter matches a
    * defined MIPS token type, else returns null.
    **/
    
       public static TokenTypes matchTokenType(String value)
      {
      
         TokenTypes type = null;
         // If it starts with single quote (‘), it is a mal-formed character literal
         // because a well-formed character literal was converted to string-ified 
         // integer before getting here…
           if (value.charAt(0) == ‘\”)
               return TokenTypes.ERROR;
                
       // See if it is a comment
         if (value.charAt(0) == ‘#’)
            return TokenTypes.COMMENT;
           
       // See if it is one of the simple tokens 
         if (value.length() == 1) {
            switch (value.charAt(0)) {
               case ‘(‘ : 
                  return TokenTypes.LEFT_PAREN;
               case ‘)’ : 
                  return TokenTypes.RIGHT_PAREN;
               case ‘:’ : 
                  return TokenTypes.COLON;
               case ‘+’ : 
                  return TokenTypes.PLUS;
               case ‘-‘ : 
                  return TokenTypes.MINUS;
            }
         }

       // See if it is a macro parameter  
         if (Macro.tokenIsMacroParameter(value, false))
             return TokenTypes.MACRO_PARAMETER;
                       
       // See if it is a register
         Register reg = RegisterFile.getUserRegister(value);
         if (reg != null) 
            if (reg.getName().equals(value)) 
               return TokenTypes.REGISTER_NAME;
            else
               return TokenTypes.REGISTER_NUMBER;
      
       // See if it is a floating point register
       
         reg = Coprocessor1.getRegister(value);
         if (reg != null)
            return TokenTypes.FP_REGISTER_NAME;
       
       // See if it is an immediate (constant) integer value
       // Classify based on # bits needed to represent in binary
       // This is needed because most immediate operands limited to 16 bits
       // others limited to 5 bits unsigned (shift amounts) others 32 bits.
         try {

            int i = Binary.stringToInt(value);   // KENV 1/6/05
                
        /***************************************************************************
         *  MODIFICATION AND COMMENT, DPS 3-July-2008
         *
         * The modifications of January 2005 documented below are being rescinded.
         * All hexadecimal immediate values are considered 32 bits in length and
         * their classification as INTEGER_5, INTEGER_16, INTEGER_16U (new)
         * or INTEGER_32 depends on their 32 bit value.  So 0xFFFF will be
         * equivalent to 0x0000FFFF instead of 0xFFFFFFFF.  This change, along with
         * the introduction of INTEGER_16U (adopted from Greg Gibeling of Berkeley),
         * required extensive changes to instruction templates especially for
         * pseudo-instructions.
         *
         * This modification also appears inbuildBasicStatementFromBasicInstruction()
         * in mars.ProgramStatement. 
         *               
       *  ///// Begin modification 1/4/05 KENV   ///////////////////////////////////////////
       *  // We have decided to interpret non-signed (no + or -) 16-bit hexadecimal immediate  
       *  // operands as signed values in the range -32768 to 32767. So 0xffff will represent
       *  // -1, not 65535 (bit 15 as sign bit), 0x8000 will represent -32768 not 32768.
       *  // NOTE: 32-bit hexadecimal immediate operands whose values fall into this range
       *  // will be likewise affected, but they are used only in pseudo-instructions.  The
       *  // code in ExtendedInstruction.java to split this number into upper 16 bits for “lui” 
       *  // and lower 16 bits for “ori” works with the original source code token, so it is 
       *  // not affected by this tweak.  32-bit immediates in data segment directives
       *  // are also processed elsewhere so are not affected either.
       *  ////////////////////////////////////////////////////////////////////////////////
       *  
       *     if ( Binary.isHex(value) &&
       *         (i >= 32768) &&
       *         (i <= 65535) )  // Range 0x8000 ... 0xffff        *     {        *          // Subtract the 0xffff bias, because strings in the        *          // range "0x8000" ... "0xffff" are used to represent        *          // 16-bit negative numbers, not positive numbers.        *        i = i - 65536;        *     }        *    // ------------- END    KENV 1/4/05   MODIFICATIONS --------------        *            **************************  END DPS 3-July-2008 COMMENTS *******************************/            // shift operands must be in range 0-31             if (i>=0 && i<=31) {                return TokenTypes.INTEGER_5;             }             if (i>=DataTypes.MIN_UHALF_VALUE && i<=DataTypes.MAX_UHALF_VALUE) {                 return TokenTypes.INTEGER_16U;              }             if (i>=DataTypes.MIN_HALF_VALUE && i<=DataTypes.MAX_HALF_VALUE) {                return TokenTypes.INTEGER_16;             }                          return TokenTypes.INTEGER_32;  // default when no other type is applicable          }              catch(NumberFormatException e)             {             // NO ACTION -- exception suppressed             }               // See if it is a real (fixed or floating point) number.  Note that parseDouble()        // accepts integer values but if it were an integer literal we wouldn't get this far.          try {             Double.parseDouble(value);             return TokenTypes.REAL_NUMBER;          }              catch (NumberFormatException e)             {             // NO ACTION -- exception suppressed             }                  // See if it is an instruction operator          if (Globals.instructionSet.matchOperator(value) != null)             return TokenTypes.OPERATOR;                    // See if it is a directive          if (value.charAt(0) == '.' && Directives.matchDirective(value) != null) {             return TokenTypes.DIRECTIVE;          }                // See if it is a quoted string          if (value.charAt(0) == '"')             return TokenTypes.QUOTED_STRING;               // Test for identifier goes last because I have defined tokens for various         // MIPS constructs (such as operators and directives) that also could fit        // the lexical specifications of an identifier, and those need to be        // recognized first.          if (isValidIdentifier(value))                         return TokenTypes.IDENTIFIER;                   // Matches no MIPS language token.          return TokenTypes.ERROR;       }            /**          *          *  Lets you know if given tokentype is for integers (INTGER_5, INTEGER_16, INTEGER_32).          *          *  @param type the TokenType of interest          *  @return true if type is an integer type, false otherwise.          **/        public static boolean isIntegerTokenType(TokenTypes type) {          return type == TokenTypes.INTEGER_5 || type == TokenTypes.INTEGER_16 ||                 type == TokenTypes.INTEGER_16U || type == TokenTypes.INTEGER_32;       }        /**          *          *  Lets you know if given tokentype is for floating point numbers (REAL_NUMBER).          *          *  @param type the TokenType of interest          *  @return true if type is an floating point type, false otherwise.          **/           public static boolean isFloatingTokenType(TokenTypes type) {          return type == TokenTypes.REAL_NUMBER;       }                 // COD2, A-51:  "Identifiers are a sequence of alphanumeric characters,        //               underbars (_), and dots (.) that do not begin with a number."      // Ideally this would be in a separate Identifier class but I did not see an immediate      // need beyond this method (refactoring effort would probably identify other uses       // related to symbol table).          //          // DPS 14-Jul-2008: added '$' as valid symbol.  Permits labels to include $.          //                  MIPS-target GCC will produce labels that start with $.         public static boolean isValidIdentifier(String value) {          boolean result =                   (Character.isLetter(value.charAt(0)) || value.charAt(0)=='_' || value.charAt(0)=='.' || value.charAt(0)=='$');          int index = 1;          while (result && index < value.length()) {             if (!(Character.isLetterOrDigit(value.charAt(index)) || value.charAt(index)=='_' || value.charAt(index)=='.' || value.charAt(index)=='$'))                result = false;             index++;          }            return result;       }        } TokenTypes package mars.assembler; public final synchronized class TokenTypes { public static final String TOKEN_DELIMITERS = ,(); public static final TokenTypes COMMENT; public static final TokenTypes DIRECTIVE; public static final TokenTypes OPERATOR; public static final TokenTypes DELIMITER; public static final TokenTypes REGISTER_NAME; public static final TokenTypes REGISTER_NUMBER; public static final TokenTypes FP_REGISTER_NAME; public static final TokenTypes IDENTIFIER; public static final TokenTypes LEFT_PAREN; public static final TokenTypes RIGHT_PAREN; public static final TokenTypes INTEGER_5; public static final TokenTypes INTEGER_16; public static final TokenTypes INTEGER_16U; public static final TokenTypes INTEGER_32; public static final TokenTypes REAL_NUMBER; public static final TokenTypes QUOTED_STRING; public static final TokenTypes PLUS; public static final TokenTypes MINUS; public static final TokenTypes COLON; public static final TokenTypes ERROR; public static final TokenTypes MACRO_PARAMETER; private String descriptor; static void ();
private void TokenTypes();
private void TokenTypes(String);
public String toString();
public static TokenTypes matchTokenType(String);
public static boolean isIntegerTokenType(TokenTypes);
public static boolean isFloatingTokenType(TokenTypes);
public static boolean isValidIdentifier(String);
}

TranslationCode

package mars.assembler;
public abstract interface TranslationCode {
public abstract void translate();
}

Tokenizer

package mars.assembler;
public synchronized class Tokenizer {
private mars.ErrorList errors;
private mars.MIPSprogram sourceMIPSprogram;
private java.util.HashMap equivalents;
private static final String escapedCharacters = ‘”\ntbrf0;
private static final String[] escapedCharactersValues;
static void ();
public void Tokenizer();
public void Tokenizer(mars.MIPSprogram);
public java.util.ArrayList tokenize(mars.MIPSprogram) throws mars.ProcessingException;
private java.util.ArrayList processIncludes(mars.MIPSprogram, java.util.Map) throws mars.ProcessingException;
public TokenList tokenizeExampleInstruction(String) throws mars.ProcessingException;
public TokenList tokenizeLine(int, String);
public TokenList tokenizeLine(mars.MIPSprogram, int, String);
private TokenList processEqv(mars.MIPSprogram, int, String, TokenList);
public TokenList tokenizeLine(int, String, mars.ErrorList);
public mars.ErrorList getErrors();
private void processCandidateToken(char[], mars.MIPSprogram, int, String, int, int, TokenList);
private String preprocessCharacterLiteral(String);
}

MacroPool

package mars.assembler;
public synchronized class MacroPool {
private mars.MIPSprogram program;
private java.util.ArrayList macroList;
private Macro current;
private java.util.ArrayList callStack;
private java.util.ArrayList callStackOrigLines;
private int counter;
public void MacroPool(mars.MIPSprogram);
public void beginMacro(Token);
public void commitMacro(Token);
public Macro getMatchingMacro(TokenList, int);
public boolean matchesAnyMacroName(String);
public Macro getCurrent();
public void setCurrent(Macro);
public int getNextCounter();
public java.util.ArrayList getCallStack();
public boolean pushOnCallStack(Token);
public void popFromCallStack();
public String getExpansionHistory();
}

mars/assembler/TokenList.java
mars/assembler/TokenList.javapackage mars.assembler;
import java.util.ArrayList;

/*
Copyright (c) 2003-2013,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Represents the list of tokens in a single line of MIPS code.  It uses, but is not
 * a subclass of, ArrayList.
 * 
 * @author Pete Sanderson 
 * @version August 2003
 */

public class TokenList implements Cloneable {
    
    private ArrayList tokenList;
    private String processedLine;// DPS 03-Jan-2013

    /**
     * Constructor for objects of class TokenList
     */
    public TokenList() {
        tokenList = new ArrayList();
          processedLine = “”; // DPS 03-Jan-2013
    }
    
    /**
     * Use this to record the source line String for this token list 
     * after possible modification (textual substitution) during 
     * assembly preprocessing.  The modified source will be displayed in
     * the Text Segment Display.
     * @param line The source line, possibly modified (possibly not)
     */
   // DPS 03-Jan-2013
   public void setProcessedLine(String line) {
       processedLine = line; 
    }

    /**
     * Retrieve the source line String associated with this
     * token list.  It may or may not have been modified during
     * assembly preprocessing.  
     * @return The source line for this token list.
     */   // DPS 03-Jan-2013/   
    public String getProcessedLine() {
       return processedLine;
    }
    
    /**
     * Returns requested token given position number (starting at 0).
     * 
     * @param  pos   Position in token list.
     * @return     the requested token, or ArrayIndexOutOfBounds exception 
     */
    public Token get(int pos) {
        return (Token) tokenList.get(pos);
    }

    /**
     * Replaces token at position with different one.  Will throw
     * ArrayIndexOutOfBounds exception if position does not exist.
     * 
     * @param  pos   Position in token list.
     * @param  replacement Replacement token
     */
    public void set(int pos, Token replacement) {
        tokenList.set(pos, replacement); 
    }
     
    /**
     * Returns number of tokens in list.
     * 
     * @return  token count. 
     */    
    public int size() {
        return tokenList.size();
    }

    /**
     * Adds a Token object to the end of the list.
     * 
     * @param  token   Token object to be added.
     */    
    public void add(Token token) {
        tokenList.add(token);
    }

    /**
     * Removes Token object at specified list position. Uses ArrayList remove method.
     * 
     * @param  pos   Position in token list.  Subsequent Tokens are shifted one position left.
     * @throws IndexOutOfBoundsException if pos is < 0 or >= size()
     */    
    public void remove(int pos) {
        tokenList.remove(pos);
    }

    /**
     * Returns empty/non-empty status of list.
     * 
     * @return     true if list has no tokens, else false
     */    
    public boolean isEmpty() {
        return tokenList.isEmpty();
    }

    /**
     * Get a String representing the token list.
     * 
     * @return     String version of the token list 
     * (a blank is inserted after each token). 
     */
         
     public String toString() {
        String stringified = “”;
         for (int i=0; itrue if the programmer’s statement matches the MIPS 
    * specification, else returns false.
    */
   
       static boolean tokenOperandMatch(TokenList candidateList, Instruction inst, ErrorList errors) {
         if (!numOperandsCheck(candidateList, inst, errors))
            return false;
         if (!operandTypeCheck(candidateList, inst, errors)) 
            return false;
         return true;
      }
    
   /*
    * If candidate operator token matches more than one instruction mnemonic, then select 
    * first such Instruction that has an exact operand match.  If none match, 
    * return the first Instruction and let client deal with operand mismatches.  
    */
       static Instruction bestOperandMatch(TokenList tokenList, ArrayList instrMatches) {
         if (instrMatches == null)
            return null;
         if (instrMatches.size() == 1)
            return (Instruction) instrMatches.get(0);
         for (int i=0; i=DataTypes.MIN_HALF_VALUE && temp<=DataTypes.MAX_HALF_VALUE)                    continue;                if (specType == TokenTypes.INTEGER_16U && candType == TokenTypes.INTEGER_16 &&                     temp>=DataTypes.MIN_UHALF_VALUE && temp<=DataTypes.MAX_UHALF_VALUE)                    continue;             }             if ((specType == TokenTypes.INTEGER_5 && candType == TokenTypes.INTEGER_16) ||                 (specType == TokenTypes.INTEGER_5 && candType == TokenTypes.INTEGER_16U) ||                 (specType == TokenTypes.INTEGER_5 && candType == TokenTypes.INTEGER_32) ||                 (specType == TokenTypes.INTEGER_16 && candType == TokenTypes.INTEGER_16U) ||                 (specType == TokenTypes.INTEGER_16U && candType == TokenTypes.INTEGER_16) ||                 (specType == TokenTypes.INTEGER_16U && candType == TokenTypes.INTEGER_32) ||                 (specType == TokenTypes.INTEGER_16 && candType == TokenTypes.INTEGER_32)) {                generateMessage(candToken, "operand is out of range", errors);                return false;             }             if (candType != specType) {                generateMessage(candToken, "operand is of incorrect type", errors);                return false;             }          }                /********  nice little debugging code to see which operand format         ********  the operands for this source code instruction matched.         System.out.print("Candidate: ");         for (int i=1; iassemble(), which implements a two-pass assembler. It
 * translates MIPS source code into binary machine code.
 * 
 * @author Pete Sanderson
 * @version August 2003
 **/

    public class Assembler {
      private ArrayList machineList;
      private ErrorList errors;
      private boolean inDataSegment; // status maintained by parser
      private boolean inMacroSegment; // status maintained by parser, true if in
                                // macro definition segment
      private int externAddress;
      private boolean autoAlign;
      private Directives currentDirective;
      private Directives dataDirective;
      private MIPSprogram fileCurrentlyBeingAssembled;
      private TokenList globalDeclarationList;
      private UserKernelAddressSpace textAddress;
      private UserKernelAddressSpace dataAddress;
      private DataSegmentForwardReferences currentFileDataSegmentForwardReferences,
        accumulatedDataSegmentForwardReferences;
   
   /**
    * Parse and generate machine code for the given MIPS program. It must have
    * already been tokenized. Warnings are not considered errors.
    * 
    * @param p
    *            A MIPSprogram object representing the program source.
    * @param extendedAssemblerEnabled
    *            A boolean value that if true permits use of extended (pseudo)
    *            instructions in the source code. If false, these are flagged
    *            as errors.
    * @return An ArrayList representing the assembled program. Each member of
    *         the list is a ProgramStatement object containing the source,
    *         intermediate, and machine binary representations of a program
    *         statement.
    * 
    * @see ProgramStatement
    **/
       public ArrayList assemble(MIPSprogram p, boolean extendedAssemblerEnabled)
        throws ProcessingException {
         return assemble(p, extendedAssemblerEnabled, false);
      }
   
   /**
    * Parse and generate machine code for the given MIPS program. It must have
    * already been tokenized.
    * 
    * @param p
    *            A MIPSprogram object representing the program source.
    * @param extendedAssemblerEnabled
    *            A boolean value that if true permits use of extended (pseudo)
    *            instructions in the source code. If false, these are flagged
    *            as errors.
    * @param warningsAreErrors
    *            A boolean value – true means assembler warnings will be
    *            considered errors and terminate the assemble; false means the
    *            assembler will produce warning message but otherwise ignore
    *            warnings.
    * @return An ArrayList representing the assembled program. Each member of
    *         the list is a ProgramStatement object containing the source,
    *         intermediate, and machine binary representations of a program
    *         statement.
    * 
    * @see ProgramStatement
    **/
       public ArrayList assemble(MIPSprogram p, boolean extendedAssemblerEnabled,
        boolean warningsAreErrors) throws ProcessingException {
         ArrayList programFiles = new ArrayList();
         programFiles.add(p);
         return this.assemble(programFiles, extendedAssemblerEnabled, warningsAreErrors);
      }
   
   /**
    * Get list of assembler errors and warnings
    * 
    * @return ErrorList of any assembler errors and warnings.
    */
       public ErrorList getErrorList() {
         return errors;
      }
   
   /**
    * Parse and generate machine code for the given MIPS program. All source
    * files must have already been tokenized. Warnings will not be considered
    * errors.
    * 
    * @param tokenizedProgramFiles
    *            An ArrayList of MIPSprogram objects, each produced from a
    *            different source code file, representing the program source.
    * @param extendedAssemblerEnabled
    *            A boolean value that if true permits use of extended (pseudo)
    *            instructions in the source code. If false, these are flagged
    *            as errors.
    * @return An ArrayList representing the assembled program. Each member of
    *         the list is a ProgramStatement object containing the source,
    *         intermediate, and machine binary representations of a program
    *         statement. Returns null if incoming array list is null or empty.
    * 
    * @see ProgramStatement
    **/
       public ArrayList assemble(ArrayList tokenizedProgramFiles, boolean extendedAssemblerEnabled)
        throws ProcessingException {
         return assemble(tokenizedProgramFiles, extendedAssemblerEnabled, false);
      }
   
   /**
    * Parse and generate machine code for the given MIPS program. All source
    * files must have already been tokenized.
    * 
    * @param tokenizedProgramFiles
    *            An ArrayList of MIPSprogram objects, each produced from a
    *            different source code file, representing the program source.
    * @param extendedAssemblerEnabled
    *            A boolean value that if true permits use of extended (pseudo)
    *            instructions in the source code. If false, these are flagged
    *            as errors.
    * @param warningsAreErrors
    *            A boolean value – true means assembler warnings will be
    *            considered errors and terminate the assemble; false means the
    *            assembler will produce warning message but otherwise ignore
    *            warnings.
    * @return An ArrayList representing the assembled program. Each member of
    *         the list is a ProgramStatement object containing the source,
    *         intermediate, and machine binary representations of a program
    *         statement. Returns null if incoming array list is null or empty.
    * 
    * @see ProgramStatement
    **/
       public ArrayList assemble(ArrayList tokenizedProgramFiles, boolean extendedAssemblerEnabled,
        boolean warningsAreErrors) throws ProcessingException {
         if (tokenizedProgramFiles == null || tokenizedProgramFiles.size() == 0)
            return null;
         textAddress = new UserKernelAddressSpace(Memory.textBaseAddress,
            Memory.kernelTextBaseAddress);
         dataAddress = new UserKernelAddressSpace(Memory.dataBaseAddress,
            Memory.kernelDataBaseAddress);
         externAddress = Memory.externBaseAddress;
         currentFileDataSegmentForwardReferences = new DataSegmentForwardReferences();
         accumulatedDataSegmentForwardReferences = new DataSegmentForwardReferences();
         Globals.symbolTable.clear();
         Globals.memory.clear();
         this.machineList = new ArrayList();
         this.errors = new ErrorList();
         if (Globals.debug)
            System.out.println(“Assembler first pass begins:”);
      // PROCESS THE FIRST ASSEMBLY PASS FOR ALL SOURCE FILES BEFORE PROCEEDING
      // TO SECOND PASS. THIS ASSURES ALL SYMBOL TABLES ARE CORRECTLY BUILT.
      // THERE IS ONE GLOBAL SYMBOL TABLE (for identifiers declared .globl) PLUS
      // ONE LOCAL SYMBOL TABLE FOR EACH SOURCE FILE.
         for (int fileIndex = 0; fileIndex < tokenizedProgramFiles.size(); fileIndex++) {             if (errors.errorLimitExceeded())                break;             this.fileCurrentlyBeingAssembled = (MIPSprogram) tokenizedProgramFiles.get(fileIndex);           // List of labels declared ".globl". new list for each file assembled             this.globalDeclarationList = new TokenList();          // Parser begins by default in text segment until directed otherwise.             this.inDataSegment = false;          // Macro segment will be started by .macro directive             this.inMacroSegment = false;          // Default is to align data from directives on appropriate boundary (word, half, byte)          // This can be turned off for remainder of current data segment with ".align 0"             this.autoAlign = true;          // Default data directive is .word for 4 byte data items             this.dataDirective = Directives.WORD;          // Clear out (initialize) symbol table related structures.             fileCurrentlyBeingAssembled.getLocalSymbolTable().clear();             currentFileDataSegmentForwardReferences.clear();          // sourceList is an ArrayList of String objects, one per source line.          // tokenList is an ArrayList of TokenList objects, one per source line;          // each ArrayList in tokenList consists of Token objects.             ArrayList sourceLineList = fileCurrentlyBeingAssembled.getSourceLineList();
            ArrayList tokenList = fileCurrentlyBeingAssembled.getTokenList();
            ArrayList parsedList = fileCurrentlyBeingAssembled.createParsedList();
         // each file keeps its own macro definitions
            MacroPool macroPool = fileCurrentlyBeingAssembled.createMacroPool();
         // FIRST PASS OF ASSEMBLER VERIFIES SYNTAX, GENERATES SYMBOL TABLE,
         // INITIALIZES DATA SEGMENT
            ArrayList statements;
            for (int i = 0; i < tokenList.size(); i++) {                if (errors.errorLimitExceeded())                   break;                 for (int z=0; z<((TokenList)tokenList.get(i)).size(); z++) {                    Token t = ((TokenList) tokenList.get(i)).get(z);                 // record this token's original source program and line #. Differs from final, if .include used                   t.setOriginal(sourceLineList.get(i).getMIPSprogram(),sourceLineList.get(i).getLineNumber());                }                            statements = this.parseLine((TokenList) tokenList.get(i),                   sourceLineList.get(i).getSource(),                    sourceLineList.get(i).getLineNumber(),                    extendedAssemblerEnabled);                if (statements != null) {                   parsedList.addAll(statements);                }             }             if (inMacroSegment) {                errors.add(new ErrorMessage(fileCurrentlyBeingAssembled,                   fileCurrentlyBeingAssembled.getLocalMacroPool().getCurrent().getFromLine(),                   0, "Macro started but not ended (no .end_macro directive)"));             }          // move ".globl" symbols from local symtab to global             this.transferGlobals();          // Attempt to resolve forward label references that were discovered in operand fields          // of data segment directives in current file. Those that are not resolved after this          // call are either references to global labels not seen yet, or are undefined.          // Cannot determine which until all files are parsed, so copy unresolved entries          // into accumulated list and clear out this one for re-use with the next source file.             currentFileDataSegmentForwardReferences.resolve(fileCurrentlyBeingAssembled                .getLocalSymbolTable());             accumulatedDataSegmentForwardReferences.add(currentFileDataSegmentForwardReferences);             currentFileDataSegmentForwardReferences.clear();          } // end of first-pass loop for each MIPSprogram                            // Have processed all source files. Attempt to resolve any remaining forward label       // references from global symbol table. Those that remain unresolved are undefined       // and require error message.          accumulatedDataSegmentForwardReferences.resolve(Globals.symbolTable);          accumulatedDataSegmentForwardReferences.generateErrorMessages(errors);              // Throw collection of errors accumulated through the first pass.          if (errors.errorsOccurred()) {             throw new ProcessingException(errors);          }          if (Globals.debug)             System.out.println("Assembler second pass begins");       // SECOND PASS OF ASSEMBLER GENERATES BASIC ASSEMBLER THEN MACHINE CODE.       // Generates basic assembler statements...          for (int fileIndex = 0; fileIndex < tokenizedProgramFiles.size(); fileIndex++) {             if (errors.errorLimitExceeded())                break;             this.fileCurrentlyBeingAssembled = (MIPSprogram) tokenizedProgramFiles.get(fileIndex);             ArrayList parsedList = fileCurrentlyBeingAssembled.getParsedList();             ProgramStatement statement;             for (int i = 0; i < parsedList.size(); i++) {                statement = (ProgramStatement) parsedList.get(i);                statement.buildBasicStatementFromBasicInstruction(errors);                if (errors.errorsOccurred()) {                   throw new ProcessingException(errors);                }                if (statement.getInstruction() instanceof BasicInstruction) {                   this.machineList.add(statement);                }                 else {                // It is a pseudo-instruction:                // 1. Fetch its basic instruction template list                // 2. For each template in the list,                // 2a. substitute operands from source statement                // 2b. tokenize the statement generated by 2a.                // 2d. call parseLine() to generate basic instrction                // 2e. add returned programStatement to the list                // The templates, and the instructions generated by filling                // in the templates, are specified                // in basic format (e.g. mnemonic register reference $zero                // already translated to $0).                // So the values substituted into the templates need to be                // in this format. Since those                // values come from the original source statement, they need                // to be translated before                // substituting. The next method call will perform this                // translation on the original                // source statement. Despite the fact that the original                // statement is a pseudo                // instruction, this method performs the necessary                // translation correctly.                   ExtendedInstruction inst = (ExtendedInstruction) statement.getInstruction();                   String basicAssembly = statement.getBasicAssemblyStatement();                   int sourceLine = statement.getSourceLine();                   TokenList theTokenList = new Tokenizer().tokenizeLine(sourceLine,                      basicAssembly, errors);                                // ////////////////////////////////////////////////////////////////////////////                // If we are using compact memory config and there is a compact expansion, use it                   ArrayList templateList;                   if (compactTranslationCanBeApplied(statement)) {                      templateList = inst.getCompactBasicIntructionTemplateList();                   }                    else {                      templateList = inst.getBasicIntructionTemplateList();                   }                                // subsequent ProgramStatement constructor needs the correct text segment address.                   textAddress.set(statement.getAddress());                // Will generate one basic instruction for each template in the list.                   for (int instrNumber = 0; instrNumber < templateList.size(); instrNumber++) {                      String instruction = ExtendedInstruction.makeTemplateSubstitutions(                         this.fileCurrentlyBeingAssembled,                         (String) templateList.get(instrNumber), theTokenList);                   // 23 Jan 2008 by DPS. Template substitution may result in no instruction.                   // If this is the case, skip remainder of loop iteration. This should only                   // happen if template substitution was for "nop" instruction but delayed branching                   // is disabled so the "nop" is not generated.                      if (instruction == null || instruction == "") {                         continue;                      }                                      // All substitutions have been made so we have generated                   // a valid basic instruction!                      if (Globals.debug)                         System.out.println("PSEUDO generated: " + instruction);                   // For generated instruction: tokenize, build program                   // statement, add to list.                      TokenList newTokenList = new Tokenizer().tokenizeLine(sourceLine,                         instruction, errors);                      ArrayList instrMatches = this.matchInstruction(newTokenList.get(0));                      Instruction instr = OperandFormat.bestOperandMatch(newTokenList,                         instrMatches);                   // Only first generated instruction is linked to original source                      ProgramStatement ps = new ProgramStatement(                         this.fileCurrentlyBeingAssembled,                         (instrNumber == 0) ? statement.getSource() : "", newTokenList,                         newTokenList, instr, textAddress.get(), statement.getSourceLine());                      textAddress.increment(Instruction.INSTRUCTION_LENGTH);                      ps.buildBasicStatementFromBasicInstruction(errors);                      this.machineList.add(ps);                   } // end of FOR loop, repeated for each template in list.                } // end of ELSE part for extended instruction.                              } // end of assembler second pass.          }          if (Globals.debug)             System.out.println("Code generation begins");       ///////////// THIRD MAJOR STEP IS PRODUCE MACHINE CODE FROM ASSEMBLY //////////       // Generates machine code statements from the list of basic assembler statements       // and writes the statement to memory.          ProgramStatement statement;          for (int i = 0; i < this.machineList.size(); i++) {             if (errors.errorLimitExceeded())                break;             statement = (ProgramStatement) this.machineList.get(i);             statement.buildMachineStatementFromBasicStatement(errors);             if (Globals.debug)                System.out.println(statement);             try {                Globals.memory.setStatement(statement.getAddress(), statement);             }                  catch (AddressErrorException e) {                   Token t = statement.getOriginalTokenList().get(0);                   errors.add(new ErrorMessage(t.getSourceMIPSprogram(), t.getSourceLine(), t                      .getStartPos(), "Invalid address for text segment: " + e.getAddress()));                }          }       // Aug. 24, 2005 Ken Vollmar       // Ensure that I/O "file descriptors" are initialized for a new program run          SystemIO.resetFiles();       // DPS 6 Dec 2006:       // We will now sort the ArrayList of ProgramStatements by getAddress() value.       // This is for display purposes, since they have already been stored to Memory.       // Use of .ktext and .text with address operands has two implications:       // (1) the addresses may not be ordered at this point. Requires unsigned int       // sort because kernel addresses are negative. See special Comparator.       // (2) It is possible for two instructions to be placed at the same address.       // Such occurances will be flagged as errors.       // Yes, I would not have to sort here if I used SortedSet rather than ArrayList       // but in case of duplicate I like having both statements handy for error message.          Collections.sort(this.machineList, new ProgramStatementComparator());          catchDuplicateAddresses(this.machineList, errors);          if (errors.errorsOccurred() || errors.warningsOccurred() && warningsAreErrors) {             throw new ProcessingException(errors);          }          return this.machineList;       } // assemble()        // //////////////////////////////////////////////////////////////////////    // Will check for duplicate text addresses, which can happen inadvertantly when using    // operand on .text directive. Will generate error message for each one that occurs.        private void catchDuplicateAddresses(ArrayList instructions, ErrorList errors) {          for (int i = 0; i < instructions.size() - 1; i++) {             ProgramStatement ps1 = (ProgramStatement) instructions.get(i);             ProgramStatement ps2 = (ProgramStatement) instructions.get(i + 1);             if (ps1.getAddress() == ps2.getAddress()) {                errors.add(new ErrorMessage(ps2.getSourceMIPSprogram(), ps2.getSourceLine(), 0,                   "Duplicate text segment address: "                         + mars.venus.NumberDisplayBaseChooser.formatUnsignedInteger(ps2                                 .getAddress(), (Globals.getSettings()                                 .getDisplayAddressesInHex()) ? 16 : 10)                         + " already occupied by " + ps1.getSourceFile() + " line "                         + ps1.getSourceLine() + " (caused by use of "                         + ((Memory.inTextSegment(ps2.getAddress())) ? ".text" : ".ktext")                         + " operand)"));             }          }       }        /**     * This method parses one line of MIPS source code. It works with the list     * of tokens, but original source is also provided. It also carries out     * directives, which includes initializing the data segment. This method is     * invoked in the assembler first pass.     *      * @param tokenList     * @param source     * @param sourceLineNumber     * @param extendedAssemblerEnabled     * @return ArrayList of ProgramStatements because parsing a macro expansion     *         request will return a list of ProgramStatements expanded     */        private ArrayList parseLine(TokenList tokenList, String source,
        int sourceLineNumber, boolean extendedAssemblerEnabled) {
         ArrayList ret = new ArrayList();
      
         ProgramStatement programStatement;
         TokenList tokens = this.stripComment(tokenList);
      
      // Labels should not be processed in macro definition segment.
         MacroPool macroPool = fileCurrentlyBeingAssembled.getLocalMacroPool();
         if (inMacroSegment) {
            detectLabels(tokens, macroPool.getCurrent());
         } 
         else {
            stripLabels(tokens);
         }
         if (tokens.isEmpty())
            return null;
      // Grab first (operator) token…
         Token token = tokens.get(0);
         TokenTypes tokenType = token.getType();
      
      // Let’s handle the directives here…
         if (tokenType == TokenTypes.DIRECTIVE) {
            this.executeDirective(tokens);
            return null;
         }
      
      // don’t parse if in macro segment
         if (inMacroSegment)
            return null;
      
      // SPIM-style macro calling:
         TokenList parenFreeTokens = tokens;
         if (tokens.size() > 2 && tokens.get(1).getType() == TokenTypes.LEFT_PAREN
            && tokens.get(tokens.size() – 1).getType() == TokenTypes.RIGHT_PAREN) {
            parenFreeTokens = (TokenList) tokens.clone();
            parenFreeTokens.remove(tokens.size() – 1);
            parenFreeTokens.remove(1);
         }
         Macro macro = macroPool.getMatchingMacro(parenFreeTokens, parenFreeTokens.get(0).getSourceLine());
      
      // expand macro if this line is a macro expansion call
         if (macro != null) {
            tokens = parenFreeTokens;
         // get unique id for this expansion
            int counter = macroPool.getNextCounter();
            if (macroPool.pushOnCallStack(token)) {
               errors.add(new ErrorMessage(fileCurrentlyBeingAssembled, tokens.get(0)
                  .getSourceLine(), 0, “Detected a macro expansion loop (recursive reference). “));
            } 
            else {
               for (int i = macro.getFromLine() + 1; i < macro.getToLine(); i++) {                   String substituted = macro.getSubstitutedLine(i, tokens, counter, errors);                   TokenList tokenList2 = fileCurrentlyBeingAssembled.getTokenizer().tokenizeLine(                      i, substituted, errors);                   // If token list getProcessedLine() is not empty, then .eqv was performed and it contains the modified source.                 // Put it into the line to be parsed, so it will be displayed properly in text segment display. DPS 23 Jan 2013                   if (tokenList2.getProcessedLine().length() > 0)
                     substituted = tokenList2.getProcessedLine();
                  // recursively parse lines of expanded macro
                  ArrayList statements = parseLine(tokenList2, “<" + (i-macro.getFromLine()+macro.getOriginalFromLine()) + "> ”
                     + substituted.trim(), sourceLineNumber, extendedAssemblerEnabled);
                  if (statements != null)
                     ret.addAll(statements);
               }
               macroPool.popFromCallStack();
            }
            return ret;
         }
      
      // DPS 14-July-2008
      // Yet Another Hack: detect unrecognized directive. MARS recognizes the same directives
      // as SPIM but other MIPS assemblers recognize additional directives. Compilers such
      // as MIPS-directed GCC generate assembly code containing these directives. We’d like
      // the opportunity to ignore them and continue. Tokenizer would categorize an unrecognized
      // directive as an TokenTypes.IDENTIFIER because it would not be matched as a directive and
      // MIPS labels can start with ‘.’ NOTE: this can also be handled by including the
      // ignored directive in the Directives.java list. There is already a mechanism in place
      // for generating a warning there. But I cannot anticipate the names of all directives
      // so this will catch anything, including a misspelling of a valid directive (which is
      // a nice thing to do).
         if (tokenType == TokenTypes.IDENTIFIER && token.getValue().charAt(0) == ‘.’) {
            errors.add(new ErrorMessage(ErrorMessage.WARNING, token.getSourceMIPSprogram(), token
               .getSourceLine(), token.getStartPos(), “MARS does not recognize the ”
               + token.getValue() + ” directive.  Ignored.”));
            return null;
         }
      
      // The directives with lists (.byte, .double, .float, .half, .word, .ascii, .asciiz)
      // should be able to extend the list over several lines. Since this method assembles
      // only one source line, state information must be stored from one invocation to
      // the next, to sense the context of this continuation line. That state information
      // is contained in this.dataDirective (the current data directive).
      //
         if (this.inDataSegment && // 30-Dec-09 DPS Added data segment guard…
            (tokenType == TokenTypes.PLUS
                    || // because invalid instructions were being caught…
                    tokenType == TokenTypes.MINUS
                    || // here and reported as a directive in text segment!
                    tokenType == TokenTypes.QUOTED_STRING || tokenType == TokenTypes.IDENTIFIER
                    || TokenTypes.isIntegerTokenType(tokenType) || TokenTypes
                        .isFloatingTokenType(tokenType))) {
            this.executeDirectiveContinuation(tokens);
            return null;
         }
      
      // If we are in the text segment, the variable “token” must now refer to
      // an OPERATOR
      // token. If not, it is either a syntax error or the specified operator
      // is not
      // yet implemented.
         if (!this.inDataSegment) {
            ArrayList instrMatches = this.matchInstruction(token);
            if (instrMatches == null)
               return ret;
         // OK, we’ve got an operator match, let’s check the operands.
            Instruction inst = OperandFormat.bestOperandMatch(tokens, instrMatches);
         // Here’s the place to flag use of extended (pseudo) instructions
         // when setting disabled.
            if (inst instanceof ExtendedInstruction && !extendedAssemblerEnabled) {
               errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),
                  token.getStartPos(),
                  “Extended (pseudo) instruction or format not permitted.  See Settings.”));
            }
            if (OperandFormat.tokenOperandMatch(tokens, inst, errors)) {
               programStatement = new ProgramStatement(this.fileCurrentlyBeingAssembled, source,
                  tokenList, tokens, inst, textAddress.get(), sourceLineNumber);
            // instruction length is 4 for all basic instruction, varies for extended instruction
            // Modified to permit use of compact expansion if address fits
            // in 15 bits. DPS 4-Aug-2009
               int instLength = inst.getInstructionLength();
               if (compactTranslationCanBeApplied(programStatement)) {
                  instLength = ((ExtendedInstruction) inst).getCompactInstructionLength();
               }
               textAddress.increment(instLength);
               ret.add(programStatement);
               return ret;
            }
         }
         return null;
      } // parseLine()
   
       private void detectLabels(TokenList tokens, Macro current) {
         if (tokenListBeginsWithLabel(tokens))
            current.addLabel(tokens.get(0).getValue());
      }
   
   // Determine whether or not a compact (16-bit) translation from
   // pseudo-instruction to basic instruction can be applied. If
   // the argument is a basic instruction, obviously not. If an
   // extended instruction, we have to be operating under a 16-bit
   // memory model and the instruction has to have defined an
   // alternate compact translation.
       private boolean compactTranslationCanBeApplied(ProgramStatement statement) {
         return (statement.getInstruction() instanceof ExtendedInstruction
            && Globals.memory.usingCompactMemoryConfiguration() && ((ExtendedInstruction) statement
                .getInstruction()).hasCompactTranslation());
      }
   
   // //////////////////////////////////////////////////////////////////////////////////
   // Pre-process the token list for a statement by stripping off any comment.
   // NOTE: the ArrayList parameter is not modified; a new one is cloned and
   // returned.
       private TokenList stripComment(TokenList tokenList) {
         if (tokenList.isEmpty())
            return tokenList;
         TokenList tokens = (TokenList) tokenList.clone();
      // If there is a comment, strip it off.
         int last = tokens.size() – 1;
         if (tokens.get(last).getType() == TokenTypes.COMMENT) {
            tokens.remove(last);
         }
         return tokens;
      } // stripComment()
   
   /**
    * Pre-process the token list for a statement by stripping off any label, if
    * either are present. Any label definition will be recorded in the symbol
    * table. NOTE: the ArrayList parameter will be modified.
    */
       private void stripLabels(TokenList tokens) {
      // If there is a label, handle it here and strip it off.
         boolean thereWasLabel = this.parseAndRecordLabel(tokens);
         if (thereWasLabel) {
            tokens.remove(0); // Remove the IDENTIFIER.
            tokens.remove(0); // Remove the COLON, shifted to 0 by previous remove
         }
      }
   
   // //////////////////////////////////////////////////////////////////////////////////
   // Parse and record label, if there is one. Note the identifier and its colon are
   // two separate tokens, since they may be separated by spaces in source code.
       private boolean parseAndRecordLabel(TokenList tokens) {
         if (tokens.size() < 2) {             return false;          }           else {             Token token = tokens.get(0);             if (tokenListBeginsWithLabel(tokens)) {                if (token.getType() == TokenTypes.OPERATOR) {                   // an instruction name was used as label (e.g. lw:), so change its token type                   token.setType(TokenTypes.IDENTIFIER);                }                fileCurrentlyBeingAssembled.getLocalSymbolTable().addSymbol(token,                   (this.inDataSegment) ? dataAddress.get() : textAddress.get(),                   this.inDataSegment, this.errors);                return true;             }              else {                return false;             }          }       } // parseLabel()            private boolean tokenListBeginsWithLabel(TokenList tokens) {       // 2-July-2010. DPS. Remove prohibition of operator names as labels          if (tokens.size() < 2)             return false;          return (tokens.get(0).getType() == TokenTypes.IDENTIFIER || tokens.get(0).getType() == TokenTypes.OPERATOR)             && tokens.get(1).getType() == TokenTypes.COLON;       }        // //////////////////////////////////////////////////////////////////////////////////    // This source code line is a directive, not a MIPS instruction. Let's carry it out.        private void executeDirective(TokenList tokens) {          Token token = tokens.get(0);          Directives direct = Directives.matchDirective(token.getValue());          if (Globals.debug)             System.out.println("line " + token.getSourceLine() + " is directive " + direct);          if (direct == null) {             errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(), token                .getStartPos(), "\"" + token.getValue()                + "\" directive is invalid or not implemented in MARS"));             return;          }          else if (direct == Directives.EQV) { /* EQV added by DPS 11 July 2012 */             // Do nothing.  This was vetted and processed during tokenizing.          }           else if (direct == Directives.MACRO) {             if (tokens.size() < 2) {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),                   token.getStartPos(), "\"" + token.getValue()                         + "\" directive requires at least one argument."));                return;             }             if (tokens.get(1).getType() != TokenTypes.IDENTIFIER) {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),                   tokens.get(1).getStartPos(), "Invalid Macro name \""                         + tokens.get(1).getValue() + "\""));                return;             }             if (inMacroSegment) {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),                   token.getStartPos(), "Nested macros are not allowed"));                return;             }             inMacroSegment = true;             MacroPool pool = fileCurrentlyBeingAssembled.getLocalMacroPool();             pool.beginMacro(tokens.get(1));             for (int i = 2; i < tokens.size(); i++) {                Token arg = tokens.get(i);                if (arg.getType() == TokenTypes.RIGHT_PAREN                 || arg.getType() == TokenTypes.LEFT_PAREN)                   continue;                if (!Macro.tokenIsMacroParameter(arg.getValue(), true)) {                   errors.add(new ErrorMessage(arg.getSourceMIPSprogram(), arg.getSourceLine(),                      arg.getStartPos(), "Invalid macro argument '" + arg.getValue() + "'"));                   return;                }                pool.getCurrent().addArg(arg.getValue());             }          }           else if (direct == Directives.END_MACRO) {             if (tokens.size() > 1) {
               errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),
                  token.getStartPos(), “invalid text after .END_MACRO”));
               return;
            }
            if (!inMacroSegment) {
               errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),
                  token.getStartPos(), “.END_MACRO without .MACRO”));
               return;
            }
            inMacroSegment = false;
            fileCurrentlyBeingAssembled.getLocalMacroPool().commitMacro(token);
         } 
         else if (inMacroSegment) {
         // should not parse lines even directives in macro segment
            return;
         } 
         else if (direct == Directives.DATA || direct == Directives.KDATA) {
            this.inDataSegment = true;
            this.autoAlign = true;
            this.dataAddress.setAddressSpace((direct == Directives.DATA) ? this.dataAddress.USER
               : this.dataAddress.KERNEL);
            if (tokens.size() > 1 && TokenTypes.isIntegerTokenType(tokens.get(1).getType())) {
               this.dataAddress.set(Binary.stringToInt(tokens.get(1).getValue())); // KENV 1/6/05
            }
         } 
         else if (direct == Directives.TEXT || direct == Directives.KTEXT) {
            this.inDataSegment = false;
            this.textAddress.setAddressSpace((direct == Directives.TEXT) ? this.textAddress.USER
               : this.textAddress.KERNEL);
            if (tokens.size() > 1 && TokenTypes.isIntegerTokenType(tokens.get(1).getType())) {
               this.textAddress.set(Binary.stringToInt(tokens.get(1).getValue())); // KENV 1/6/05
            }
         } 
         else if (direct == Directives.WORD || direct == Directives.HALF
            || direct == Directives.BYTE || direct == Directives.FLOAT
            || direct == Directives.DOUBLE) {
            this.dataDirective = direct;
            if (passesDataSegmentCheck(token) && tokens.size() > 1) { // DPS
                                                                    // 11/20/06, added text segment prohibition
               storeNumeric(tokens, direct, errors);
            }
         } 
         else if (direct == Directives.ASCII || direct == Directives.ASCIIZ) {
            this.dataDirective = direct;
            if (passesDataSegmentCheck(token)) {
               storeStrings(tokens, direct, errors);
            }
         } 
         else if (direct == Directives.ALIGN) {
            if (passesDataSegmentCheck(token)) {
               if (tokens.size() != 2) {
                  errors.add(new ErrorMessage(token.getSourceMIPSprogram(),
                     token.getSourceLine(), token.getStartPos(), “\”” + token.getValue()
                            + “\” requires one operand”));
                  return;
               }
               if (!TokenTypes.isIntegerTokenType(tokens.get(1).getType())
                || Binary.stringToInt(tokens.get(1).getValue()) < 0) {                   errors.add(new ErrorMessage(token.getSourceMIPSprogram(),                      token.getSourceLine(), token.getStartPos(), "\"" + token.getValue()                             + "\" requires a non-negative integer"));                   return;                }                int value = Binary.stringToInt(tokens.get(1).getValue()); // KENV 1/6/05                if (value == 0) {                   this.autoAlign = false;                }                 else {                   this.dataAddress.set(this.alignToBoundary(this.dataAddress.get(),                      (int) Math.pow(2, value)));                }             }          }           else if (direct == Directives.SPACE) {             if (passesDataSegmentCheck(token)) {                if (tokens.size() != 2) {                   errors.add(new ErrorMessage(token.getSourceMIPSprogram(),                      token.getSourceLine(), token.getStartPos(), "\"" + token.getValue()                             + "\" requires one operand"));                   return;                }                if (!TokenTypes.isIntegerTokenType(tokens.get(1).getType())                 || Binary.stringToInt(tokens.get(1).getValue()) < 0) {                   errors.add(new ErrorMessage(token.getSourceMIPSprogram(),                      token.getSourceLine(), token.getStartPos(), "\"" + token.getValue()                             + "\" requires a non-negative integer"));                   return;                }                int value = Binary.stringToInt(tokens.get(1).getValue()); // KENV 1/6/05                this.dataAddress.increment(value);             }          }           else if (direct == Directives.EXTERN) {             if (tokens.size() != 3) {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),                   token.getStartPos(), "\"" + token.getValue()                         + "\" directive requires two operands (label and size)."));                return;             }             if (!TokenTypes.isIntegerTokenType(tokens.get(2).getType())                 || Binary.stringToInt(tokens.get(2).getValue()) < 0) {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),                   token.getStartPos(), "\"" + token.getValue()                         + "\" requires a non-negative integer size"));                return;             }             int size = Binary.stringToInt(tokens.get(2).getValue());          // If label already in global symtab, do nothing. If not, add it right now.             if (Globals.symbolTable.getAddress(tokens.get(1).getValue()) == SymbolTable.NOT_FOUND) {                Globals.symbolTable.addSymbol(tokens.get(1), this.externAddress,                   Symbol.DATA_SYMBOL, errors);                this.externAddress += size;             }          }           else if (direct == Directives.SET) {             errors.add(new ErrorMessage(ErrorMessage.WARNING, token.getSourceMIPSprogram(), token                .getSourceLine(), token.getStartPos(),                "MARS currently ignores the .set directive."));          }           else if (direct == Directives.GLOBL) {             if (tokens.size() < 2) {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),                   token.getStartPos(), "\"" + token.getValue()                         + "\" directive requires at least one argument."));                return;             }          // SPIM limits .globl list to one label, why not extend it to a list?             for (int i = 1; i < tokens.size(); i++) {             // Add it to a list of labels to be processed at the end of the             // pass. At that point, transfer matching symbol definitions from              // local symbol table to global symbol table.                Token label = tokens.get(i);                if (label.getType() != TokenTypes.IDENTIFIER) {                   errors.add(new ErrorMessage(token.getSourceMIPSprogram(),                      token.getSourceLine(), token.getStartPos(), "\"" + token.getValue()                             + "\" directive argument must be label."));                   return;                }                globalDeclarationList.add(label);             }          }           else {             errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(), token                .getStartPos(), "\"" + token.getValue()                + "\" directive recognized but not yet implemented."));             return;          }       } // executeDirective()        // //////////////////////////////////////////////////////////////////////////////    // Process the list of .globl labels, if any, declared and defined in this file.    // We'll just move their symbol table entries from local symbol table to global    // symbol table at the end of the first assembly pass.        private void transferGlobals() {          for (int i = 0; i < globalDeclarationList.size(); i++) {             Token label = globalDeclarationList.get(i);             Symbol symtabEntry = fileCurrentlyBeingAssembled.getLocalSymbolTable().getSymbol(                label.getValue());             if (symtabEntry == null) {                errors.add(new ErrorMessage(fileCurrentlyBeingAssembled, label.getSourceLine(),                   label.getStartPos(), "\"" + label.getValue()                         + "\" declared global label but not defined."));             }              else {                if (Globals.symbolTable.getAddress(label.getValue()) != SymbolTable.NOT_FOUND) {                   errors.add(new ErrorMessage(fileCurrentlyBeingAssembled, label.getSourceLine(),                      label.getStartPos(), "\"" + label.getValue()                             + "\" already defined as global in a different file."));                }                 else {                   fileCurrentlyBeingAssembled.getLocalSymbolTable().removeSymbol(label);                   Globals.symbolTable.addSymbol(label, symtabEntry.getAddress(),                      symtabEntry.getType(), errors);                }             }          }       }        // //////////////////////////////////////////////////////////////////////////////////    // This source code line, if syntactically correct, is a continuation of a    // directive list begun on on previous line.        private void executeDirectiveContinuation(TokenList tokens) {          Directives direct = this.dataDirective;          if (direct == Directives.WORD || direct == Directives.HALF || direct == Directives.BYTE             || direct == Directives.FLOAT || direct == Directives.DOUBLE) {             if (tokens.size() > 0) {
               storeNumeric(tokens, direct, errors);
            }
         } 
         else if (direct == Directives.ASCII || direct == Directives.ASCIIZ) {
            if (passesDataSegmentCheck(tokens.get(0))) {
               storeStrings(tokens, direct, errors);
            }
         }
      } // executeDirectiveContinuation()
   
   // //////////////////////////////////////////////////////////////////////////////////
   // Given token, find the corresponding Instruction object. If token was not
   // recognized as OPERATOR, there is a problem.
       private ArrayList matchInstruction(Token token) {
         if (token.getType() != TokenTypes.OPERATOR) {
            if (token.getSourceMIPSprogram().getLocalMacroPool()
                .matchesAnyMacroName(token.getValue()))
               this.errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token
                  .getSourceLine(), token.getStartPos(), “forward reference or invalid parameters for macro \””
                  + token.getValue() + “\””));
            else
               this.errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token
                  .getSourceLine(), token.getStartPos(), “\”” + token.getValue()
                  + “\” is not a recognized operator”));
            return null;
         }
         ArrayList inst = Globals.instructionSet.matchOperator(token.getValue());
         if (inst == null) { // This should NEVER happen…
            this.errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),
               token.getStartPos(), “Internal Assembler error: \”” + token.getValue()
                    + “\” tokenized OPERATOR then not recognized”));
         }
         return inst;
      } // matchInstruction()
   
   // //////////////////////////////////////////////////////////////////////////////////
   // Processes the .word/.half/.byte/.float/.double directive.
   // Can also handle “directive continuations”, e.g. second or subsequent line
   // of a multiline list, which does not contain the directive token. Just pass the
   // current directive as argument.
       private void storeNumeric(TokenList tokens, Directives directive, ErrorList errors) {
         Token token = tokens.get(0);
      // A double-check; should have already been caught…removed “.word” exemption 11/20/06
         if (!passesDataSegmentCheck(token))
            return;
      // Correctly handles case where this is a “directive continuation” line.
         int tokenStart = 0;
         if (token.getType() == TokenTypes.DIRECTIVE)
            tokenStart = 1;
      
      // Set byte length in memory of each number (e.g. WORD is 4, BYTE is 1, etc)
         int lengthInBytes = DataTypes.getLengthInBytes(directive);
      
      // Handle the “value : n” format, which replicates the value “n” times.
         if (tokens.size() == 4 && tokens.get(2).getType() == TokenTypes.COLON) {
            Token valueToken = tokens.get(1);
            Token repetitionsToken = tokens.get(3);
         // DPS 15-jul-08, allow “:” for repetition for all numeric
         // directives (originally just .word)
         // Conditions for correctly-formed replication:
         // (integer directive AND integer value OR floating directive AND
         // (integer value OR floating value))
         // AND integer repetition value
            if (!(Directives.isIntegerDirective(directive)
                && TokenTypes.isIntegerTokenType(valueToken.getType()) || Directives
                .isFloatingDirective(directive)
                && (TokenTypes.isIntegerTokenType(valueToken.getType()) || TokenTypes
                        .isFloatingTokenType(valueToken.getType())))
                || !TokenTypes.isIntegerTokenType(repetitionsToken.getType())) {
               errors.add(new ErrorMessage(fileCurrentlyBeingAssembled,
                  valueToken.getSourceLine(), valueToken.getStartPos(),
                  “malformed expression”));
               return;
            }
            int repetitions = Binary.stringToInt(repetitionsToken.getValue()); // KENV 1/6/05
            if (repetitions <= 0) {                errors.add(new ErrorMessage(fileCurrentlyBeingAssembled, repetitionsToken                   .getSourceLine(), repetitionsToken.getStartPos(),                   "repetition factor must be positive"));                return;             }             if (this.inDataSegment) {                if (this.autoAlign) {                   this.dataAddress                      .set(this.alignToBoundary(this.dataAddress.get(), lengthInBytes));                }                for (int i = 0; i < repetitions; i++) {                   if (Directives.isIntegerDirective(directive)) {                      storeInteger(valueToken, directive, errors);                   }                    else {                      storeRealNumber(valueToken, directive, errors);                   }                }             } // WHAT ABOUT .KDATA SEGMENT?          /***************************************************************************           * /****** NOTE of 11/20/06. Below will always throw exception b/c           * you cannot use Memory.set() with text segment addresses and the           * "not valid address" produced here is misleading. Added data           * segment check prior to this point, so this "else" will never be           * executed. I'm leaving it in just in case MARS in the future adds           * capability of writing to the text segment (e.g. ability to           * de-assemble a binary value into its corresponding MIPS           * instruction)           *            * else { // not in data segment...which we assume to mean in text           * segment. try { for (int i=0; i < repetitions; i++) {           * Globals.memory.set(this.textAddress.get(),           * Binary.stringToInt(valueToken.getValue()), lengthInBytes);           * this.textAddress.increment(lengthInBytes); } } catch           * (AddressErrorException e) { errors.add(new           * ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),           * token.getStartPos(), "\""+this.textAddress.get()+           * "\" is not a valid text segment address")); } }           ************************************************************************/             return;          }              // if not in ".word w : n" format, must just be list of one or more values.          for (int i = tokenStart; i < tokens.size(); i++) {             token = tokens.get(i);             if (Directives.isIntegerDirective(directive)) {                storeInteger(token, directive, errors);             }             if (Directives.isFloatingDirective(directive)) {                storeRealNumber(token, directive, errors);             }          }          return;       } // storeNumeric()        // //////////////////////////////////////////////////////////////////////////////    // Store integer value given integer (word, half, byte) directive.    // Called by storeNumeric()    // NOTE: The token itself may be a label, in which case the correct action is    // to store the address of that label (into however many bytes specified).        private void storeInteger(Token token, Directives directive, ErrorList errors) {          int lengthInBytes = DataTypes.getLengthInBytes(directive);          if (TokenTypes.isIntegerTokenType(token.getType())) {             int value = Binary.stringToInt(token.getValue());              int fullvalue = value;             // DPS 4-Jan-2013.  Overriding 6-Jan-2005 KENV changes.             // If value is out of range for the directive, will simply truncate             // the leading bits (includes sign bits). This is what SPIM does.               // But will issue a warning (not error) which SPIM does not do.             if (directive == Directives.BYTE) {                value = value & 0x000000FF;              }              else if (directive == Directives.HALF) {                value = value & 0x0000FFFF;              }                        if (DataTypes.outOfRange(directive, fullvalue)) {                errors.add(new ErrorMessage(ErrorMessage.WARNING, token.getSourceMIPSprogram(), token.getSourceLine(),                   token.getStartPos(), "\"" + token.getValue()                         + "\" is out-of-range for a signed value and possibly truncated"));             }             if (this.inDataSegment) {                writeToDataSegment(value, lengthInBytes, token, errors);             }             /******             * NOTE of 11/20/06. "try" below will always throw exception b/c you             * cannot use Memory.set() with text segment addresses and the             * "not valid address" produced here is misleading. Added data             * segment check prior to this point, so this "else" will never be             * executed. I'm leaving it in just in case MARS in the future adds             * capability of writing to the text segment (e.g. ability to             * de-assemble a binary value into its corresponding MIPS             * instruction)             ********/             else {                try {                   Globals.memory.set(this.textAddress.get(), value, lengthInBytes);                }                     catch (AddressErrorException e) {                      errors.add(new ErrorMessage(token.getSourceMIPSprogram(),                         token.getSourceLine(), token.getStartPos(), "\""                             + this.textAddress.get()                             + "\" is not a valid text segment address"));                      return;                   }                this.textAddress.increment(lengthInBytes);             }          } // end of "if integer token type"          else if (token.getType() == TokenTypes.IDENTIFIER) {             if (this.inDataSegment) {                int value = fileCurrentlyBeingAssembled.getLocalSymbolTable()                   .getAddressLocalOrGlobal(token.getValue());                if (value == SymbolTable.NOT_FOUND) {                // Record value 0 for now, then set up backpatch entry                   int dataAddress = writeToDataSegment(0, lengthInBytes, token, errors);                   currentFileDataSegmentForwardReferences.add(dataAddress, lengthInBytes, token);                }                 else { // label already defined, so write its address                   writeToDataSegment(value, lengthInBytes, token, errors);                }             } // Data segment check done previously, so this "else" will not be.             // See 11/20/06 note above.             else {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),                   token.getStartPos(), "\"" + token.getValue()                         + "\" label as directive operand not permitted in text segment"));             }          } // end of "if label"          else {             errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(), token                .getStartPos(), "\"" + token.getValue()                + "\" is not a valid integer constant or label"));          }       }// storeInteger        // //////////////////////////////////////////////////////////////////////////////    // Store real (fixed or floating point) value given floating (float, double) directive.    // Called by storeNumeric()        private void storeRealNumber(Token token, Directives directive, ErrorList errors) {          int lengthInBytes = DataTypes.getLengthInBytes(directive);          double value;                 if (TokenTypes.isIntegerTokenType(token.getType())             || TokenTypes.isFloatingTokenType(token.getType())) {             try {                value = Double.parseDouble(token.getValue());             }                  catch (NumberFormatException nfe) {                   errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),                      token.getStartPos(), "\"" + token.getValue()                         + "\" is not a valid floating point constant"));                   return;                }             if (DataTypes.outOfRange(directive, value)) {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),                   token.getStartPos(), "\"" + token.getValue()                         + "\" is an out-of-range value"));                return;             }          }           else {             errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(), token                .getStartPos(), "\"" + token.getValue()                + "\" is not a valid floating point constant"));             return;          }              // Value has been validated; let's store it.                 if (directive == Directives.FLOAT) {             writeToDataSegment(Float.floatToIntBits((float) value), lengthInBytes, token, errors);          }          if (directive == Directives.DOUBLE) {             writeDoubleToDataSegment(value, token, errors);          }              } // storeRealNumber        // //////////////////////////////////////////////////////////////////////////////////    // Use directive argument to distinguish between ASCII and ASCIIZ. The    // latter stores a terminating null byte. Can handle a list of one or more    // strings on a single line.        private void storeStrings(TokenList tokens, Directives direct, ErrorList errors) {          Token token;       // Correctly handles case where this is a "directive continuation" line.          int tokenStart = 0;          if (tokens.get(0).getType() == TokenTypes.DIRECTIVE) {             tokenStart = 1;          }          for (int i = tokenStart; i < tokens.size(); i++) {             token = tokens.get(i);             if (token.getType() != TokenTypes.QUOTED_STRING) {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(),                   token.getStartPos(), "\"" + token.getValue()                         + "\" is not a valid character string"));             }              else {                String quote = token.getValue();                char theChar;                for (int j = 1; j < quote.length() - 1; j++) {                   theChar = quote.charAt(j);                   if (theChar == '\\') {                      theChar = quote.charAt(++j);                      switch (theChar) {                         case 'n':                            theChar = '\n';                            break;                         case 't':                            theChar = '\t';                            break;                         case 'r':                            theChar = '\r';                            break;                         case '\\':                            theChar = '\\';                            break;                         case '\'':                            theChar = '\'';                            break;                         case '"':                            theChar = '"';                            break;                         case 'b':                            theChar = '\b';                            break;                         case 'f':                            theChar = '\f';                            break;                         case '0':                            theChar = '\0';                            break;                      // Not implemented: \ n = octal character (n is number)                      // \ x n = hex character (n is number)                      // \ u n = unicode character (n is number)                      // There are of course no spaces in these escape                      // codes...                      }                   }                   try {                      Globals.memory.set(this.dataAddress.get(), (int) theChar,                         DataTypes.CHAR_SIZE);                   }                        catch (AddressErrorException e) {                         errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token                            .getSourceLine(), token.getStartPos(), "\""                            + this.dataAddress.get() + "\" is not a valid data segment address"));                      }                   this.dataAddress.increment(DataTypes.CHAR_SIZE);                }                if (direct == Directives.ASCIIZ) {                   try {                      Globals.memory.set(this.dataAddress.get(), 0, DataTypes.CHAR_SIZE);                   }                        catch (AddressErrorException e) {                         errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token                            .getSourceLine(), token.getStartPos(), "\""                            + this.dataAddress.get() + "\" is not a valid data segment address"));                      }                   this.dataAddress.increment(DataTypes.CHAR_SIZE);                }             }          }       } // storeStrings()        // //////////////////////////////////////////////////////////////////////////////////    // Simply check to see if we are in data segment. Generate error if not.        private boolean passesDataSegmentCheck(Token token) {          if (!this.inDataSegment) {             errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(), token                .getStartPos(), "\"" + token.getValue()                + "\" directive cannot appear in text segment"));             return false;          }           else {             return true;          }       }        // //////////////////////////////////////////////////////////////////////////////////    // Writes the given int value into current data segment address. Works for    // all the integer types plus float (caller is responsible for doing floatToIntBits).    // Returns address at which the value was stored.        private int writeToDataSegment(int value, int lengthInBytes, Token token, ErrorList errors) {          if (this.autoAlign) {             this.dataAddress.set(this.alignToBoundary(this.dataAddress.get(), lengthInBytes));          }          try {             Globals.memory.set(this.dataAddress.get(), value, lengthInBytes);          }               catch (AddressErrorException e) {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(), token                   .getStartPos(), "\"" + this.dataAddress.get()                   + "\" is not a valid data segment address"));                return this.dataAddress.get();             }          int address = this.dataAddress.get();          this.dataAddress.increment(lengthInBytes);          return address;       }        // //////////////////////////////////////////////////////////////////////////////////    // Writes the given double value into current data segment address. Works    // only for DOUBLE floating    // point values -- Memory class doesn't have method for writing 8 bytes, so    // use setWord twice.        private void writeDoubleToDataSegment(double value, Token token, ErrorList errors) {          int lengthInBytes = DataTypes.DOUBLE_SIZE;          if (this.autoAlign) {             this.dataAddress.set(this.alignToBoundary(this.dataAddress.get(), lengthInBytes));          }          try {             Globals.memory.setDouble(this.dataAddress.get(), value);          }               catch (AddressErrorException e) {                errors.add(new ErrorMessage(token.getSourceMIPSprogram(), token.getSourceLine(), token                   .getStartPos(), "\"" + this.dataAddress.get()                   + "\" is not a valid data segment address"));                return;             }          this.dataAddress.increment(lengthInBytes);       }        // //////////////////////////////////////////////////////////////////////////////////    // If address is multiple of byte boundary, returns address. Otherwise, returns address    // which is next higher multiple of the byte boundary. Used for aligning data segment.    // For instance if args are 6 and 4, returns 8 (next multiple of 4 higher than 6).    // NOTE: it will fix any symbol table entries for this address too. See else part.        private int alignToBoundary(int address, int byteBoundary) {          int remainder = address % byteBoundary;          if (remainder == 0) {             return address;          }           else {             int alignedAddress = address + byteBoundary - remainder;             fileCurrentlyBeingAssembled.getLocalSymbolTable().fixSymbolTableAddress(address,                alignedAddress);             return alignedAddress;          }       }        // ///////////////////////////////////////////////////////////////////////////////////    // Private class used as Comparator to sort the final ArrayList of    // ProgramStatements.    // Sorting is based on unsigned integer value of    // ProgramStatement.getAddress()        private class ProgramStatementComparator implements Comparator {       // Will be used to sort the collection. Unsigned int compare, because       // all kernel 32-bit       // addresses have 1 in high order bit, which makes the int negative.       // "Unsigned" compare       // is needed when signs of the two operands differ.           public int compare(Object obj1, Object obj2) {             if (obj1 instanceof ProgramStatement && obj2 instanceof ProgramStatement) {                int addr1 = ((ProgramStatement) obj1).getAddress();                int addr2 = ((ProgramStatement) obj2).getAddress();                return (addr1 < 0 && addr2 >= 0 || addr1 >= 0 && addr2 < 0) ? addr2 : addr1 - addr2;             }              else {                throw new ClassCastException();             }          }              // Take a hard line.           public boolean equals(Object obj) {             return this == obj;          }       }        // ///////////////////////////////////////////////////////////////////////////////////    // Private class to simultaneously track addresses in both user and kernel    // address spaces.    // Instantiate one for data segment and one for text segment.        private class UserKernelAddressSpace {          int[] address;          int currentAddressSpace;          private final int USER = 0, KERNEL = 1;              // Initially use user address space, not kernel.           private UserKernelAddressSpace(int userBase, int kernelBase) {             address = new int[2];             address[USER] = userBase;             address[KERNEL] = kernelBase;             currentAddressSpace = USER;          }                  private int get() {             return address[currentAddressSpace];          }                  private void set(int value) {             address[currentAddressSpace] = value;          }                  private void increment(int increment) {             address[currentAddressSpace] += increment;          }                  private void setAddressSpace(int addressSpace) {             if (addressSpace == USER || addressSpace == KERNEL) {                currentAddressSpace = addressSpace;             }              else {                throw new IllegalArgumentException();             }          }       }        // //////////////////////////////////////////////////////////////////////////    // Handy class to handle forward label references appearing as data    // segment operands. This is needed because the data segment is comletely    // processed by the end of the first assembly pass, and its directives may    // contain labels as operands. When this occurs, the label's associated    // address becomes the operand value. If it is a forward reference, we will    // save the necessary information in this object for finding and patching in    // the correct address at the end of the first pass (for this file or for all    // files if more than one).    //    // If such a parsed label refers to a local or global label not defined yet,    // pertinent information is added to this object:    // - memory address that needs the label's address,    // - number of bytes (addresses are 4 bytes but may be used with any of    // the integer directives: .word, .half, .byte)    // - the label's token. Normally need only the name but error message needs more.        private class DataSegmentForwardReferences {          private ArrayList forwardReferenceList;                  private DataSegmentForwardReferences() {             forwardReferenceList = new ArrayList();          }                  private int size() {             return forwardReferenceList.size();          }              // Add a new forward reference entry. Client must supply the following:       // - memory address to receive the label's address once resolved       // - number of address bytes to store (1 for .byte, 2 for .half, 4 for .word)       // - the label's token. All its information will be needed if error message generated.           private void add(int patchAddress, int length, Token token) {             forwardReferenceList.add(new DataSegmentForwardReference(patchAddress, length, token));          }              // Add the entries of another DataSegmentForwardReferences object to this one.       // Can be used at the end of each source file to dump all unresolved references       // into a common list to be processed after all source files parsed.           private void add(DataSegmentForwardReferences another) {             forwardReferenceList.addAll(another.forwardReferenceList);          }              // Clear out the list. Allows you to re-use it.           private void clear() {             forwardReferenceList.clear();          }              // Will traverse the list of forward references, attempting to resolve them.       // For each entry it will first search the provided local symbol table and       // failing that, the global one. If passed the global symbol table, it will       // perform a second, redundant, search. If search is successful, the patch       // is applied and the forward reference removed. If search is not successful,       // the forward reference remains (it is either undefined or a global label       // defined in a file not yet parsed).           private int resolve(SymbolTable localSymtab) {             int count = 0;             int labelAddress;             DataSegmentForwardReference entry;             for (int i = 0; i < forwardReferenceList.size(); i++) {                entry = (DataSegmentForwardReference) forwardReferenceList.get(i);                labelAddress = localSymtab.getAddressLocalOrGlobal(entry.token.getValue());                if (labelAddress != SymbolTable.NOT_FOUND) {                // patch address has to be valid b/c we already stored there...                   try {                      Globals.memory.set(entry.patchAddress, labelAddress, entry.length);                   }                        catch (AddressErrorException aee) {                      }                   forwardReferenceList.remove(i);                   i--; // needed because removal shifted the remaining list indices down                   count++;                }             }             return count;          }              // Call this when you are confident that remaining list entries are to       // undefined labels.           private void generateErrorMessages(ErrorList errors) {             DataSegmentForwardReference entry;             for (int i = 0; i < forwardReferenceList.size(); i++) {                entry = (DataSegmentForwardReference) forwardReferenceList.get(i);                errors.add(new ErrorMessage(entry.token.getSourceMIPSprogram(), entry.token                   .getSourceLine(), entry.token.getStartPos(), "Symbol \""                   + entry.token.getValue() + "\" not found in symbol table."));             }          }              // inner-inner class to hold each entry of the forward reference list.           private class DataSegmentForwardReference {             int patchAddress;             int length;             Token token;                        DataSegmentForwardReference(int patchAddress, int length, Token token) {                this.patchAddress = patchAddress;                this.length = length;                this.token = token;             }          }              }    } SourceLine package mars.assembler; public synchronized class SourceLine { private String source; private String filename; private mars.MIPSprogram mipsProgram; private int lineNumber; public void SourceLine(String, mars.MIPSprogram, int); public String getSource(); public String getFilename(); public int getLineNumber(); public mars.MIPSprogram getMIPSprogram(); } mars/assembler/Tokenizer.java mars/assembler/Tokenizer.java   package mars.assembler;    import mars.*;    import java.util.*;    import java.io.*; /* Copyright (c) 2003-2013,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * A tokenizer is capable of tokenizing a complete MIPS program, or a given line from  * a MIPS program.  Since MIPS is line-oriented, each line defines a complete statement.  * Tokenizing is the process of analyzing the input MIPS program for the purpose of  * recognizing each MIPS language element.  The types of language elements are known as "tokens".  * MIPS tokens are defined in the TokenTypes class.  * Example: 
 * The MIPS statement  here:  lw  $t3, 8($t4)   #load third member of array
 * generates the following token list
 * IDENTIFIER, COLON, OPERATOR, REGISTER_NAME, COMMA, INTEGER_5, LEFT_PAREN, 
 * REGISTER_NAME, RIGHT_PAREN, COMMENT
 * 
 * @author Pete Sanderson
 * @version August 2003
 **/

    public class Tokenizer {
   
      private ErrorList errors;
      private MIPSprogram sourceMIPSprogram;
      private HashMap equivalents; // DPS 11-July-2012
    // The 8 escaped characters are: single quote, double quote, backslash, newline (linefeed),
    // tab, backspace, return, form feed.  The characters and their corresponding decimal codes:
      private static final String escapedCharacters = “‘\”\\ntbrf0”;
      private static final String[] escapedCharactersValues = {“39″,”34″,”92″,”10″,”9″,”8″,”13″,”12″,”0”};
   
   /**
    *  Simple constructor. Initializes empty error list.
    */
    
       public Tokenizer() {
         this(null);
      }
   
   /**
    *  Constructor for use with existing MIPSprogram.  Designed to be used with Macro feature.
    *  @param program A previously-existing MIPSprogram object or null if none.
    */         
       public Tokenizer(MIPSprogram program){
         errors = new ErrorList();
         sourceMIPSprogram = program;
      }
   
   /**
    * Will tokenize a complete MIPS program.  MIPS is line oriented (not free format),
    * so we will be line-oriented too.
    *
    * @param p The MIPSprogram to be tokenized.
    * @return An ArrayList representing the tokenized program.  Each list member is a TokenList
    * that represents a tokenized source statement from the MIPS program.
    **/
   
       public ArrayList tokenize(MIPSprogram p) throws ProcessingException {
         sourceMIPSprogram = p;
         equivalents = new HashMap(); // DPS 11-July-2012
         ArrayList tokenList = new ArrayList();
         //ArrayList source = p.getSourceList();
         ArrayList source = processIncludes(p, new HashMap()); // DPS 9-Jan-2013
         p.setSourceLineList(source);
         TokenList currentLineTokens;
         String sourceLine;
         for (int i=0; i 0 && sourceLine != currentLineTokens.getProcessedLine()) {
               source.set(i,new SourceLine(currentLineTokens.getProcessedLine(),source.get(i).getMIPSprogram(), source.get(i).getLineNumber())); 
            } 
         }
         if (errors.errorsOccurred()) {
            throw new ProcessingException(errors);
         }
         return tokenList;
      }
   
   
     
   // pre-pre-processing pass through source code to process any “.include” directives.
   // When one is encountered, the contents of the included file are inserted at that 
   // point.  If no .include statements, the return value is a new array list but
   // with the same lines of source code.  Uses recursion to correctly process included
   // files that themselves have .include.  Plus it will detect and report recursive
   // includes both direct and indirect.
   // DPS 11-Jan-2013
       private ArrayList processIncludes(MIPSprogram program, Map inclFiles) throws ProcessingException {
         ArrayList source = program.getSourceList();
         ArrayList result = new ArrayList(source.size());
         for (int i=0; i ii+1) 
                      && tl.get(ii+1).getType() == TokenTypes.QUOTED_STRING) {
                  String filename = tl.get(ii+1).getValue();
                  filename = filename.substring(1, filename.length()-1); // get rid of quotes
                  // Handle either absolute or relative pathname for .include file
                  if (!new File(filename).isAbsolute()) {
                     filename = new File(program.getFilename()).getParent()+File.separator+filename;
                  }
                  if (inclFiles.containsKey(filename)) {
                     // This is a recursive include.  Generate error message and return immediately.
                     Token t = tl.get(ii+1);
                     errors.add(new ErrorMessage(program, t.getSourceLine(),t.getStartPos(), 
                        “Recursive include of file “+filename));
                     throw new ProcessingException(errors);
                  }
                  inclFiles.put(filename, filename);
                  MIPSprogram incl = new MIPSprogram();
                  try {
                     incl.readSource(filename);
                  }
                      catch (ProcessingException p) {
                        Token t = tl.get(ii+1);
                        errors.add(new ErrorMessage(program, t.getSourceLine(),t.getStartPos(), 
                           “Error reading include file “+filename));    
                        throw new ProcessingException(errors);
                     }
                  ArrayList allLines = processIncludes(incl, inclFiles);
                  result.addAll(allLines);
                  hasInclude = true;
                  break;                    
               } 
            }
            if (!hasInclude){
               result.add(new SourceLine(line, program, i+1));//line);
            }
         }
         return result;
      }
    
   /**
    * Used only to create a token list for the example provided with each instruction
    * specification.
    *
    * @param example The example MIPS instruction to be tokenized.
    * 
    * @return An TokenList representing the tokenized instruction.  Each list member is a Token
    * that represents one language element.
    * 
    * @throws  ProcessingException This occurs only if the instruction specification itself
    * contains one or more lexical (i.e. token) errors.
    **/
   
       public TokenList tokenizeExampleInstruction(String example) throws ProcessingException {
         TokenList result = new TokenList();
         result = tokenizeLine(0, example);
         if (errors.errorsOccurred()) {
            throw new ProcessingException(errors);
         }
         return result;
      }
   
   
   /**
    * Will tokenize one line of source code.  If lexical errors are discovered,
    * they are noted in an ErrorMessage object which is added to the ErrorList.
    * Will NOT throw an exception yet because we want to persevere beyond first error.
    *
    * @param lineNum  line number from source code (used in error message)
    * @param theLine String containing source code
    * @return the generated token list for that line
    * 
    **/
    /*
    * 
    * Tokenizing is not as easy as it appears at first blush, because the typical 
    * delimiters: space, tab, comma, can all appear inside MIPS quoted ASCII strings!
    * Also, spaces are not as necessary as they seem, the following line is accepted
    * and parsed correctly by SPIM:    label:lw,$t4,simple#comment
    * as is this weird variation:      label  :lw  $t4  ,simple ,  ,  , # comment
    * 
    * as is this line:  stuff:.asciiz”# ,\n\””,”aaaaa”  (interestingly, if you put
    * additional characters after the \”, they are ignored!!)
    * 
    * I also would like to know the starting character position in the line of each
    * token, for error reporting purposes.  StringTokenizer cannot give you this.
    * 
    * Given all the above, it is just as easy to “roll my own” as to use StringTokenizer
    */
   
   // Modified for release 4.3, to preserve existing API.
       public TokenList tokenizeLine(int lineNum, String theLine) {
         return tokenizeLine(sourceMIPSprogram, lineNum, theLine);
      }
    
    // The original version takes on program as additional parameter
       public TokenList tokenizeLine(MIPSprogram program, int lineNum, String theLine) {
         TokenTypes tokenType;
         TokenList result = new TokenList();
         if (theLine.length() == 0)
            return result;
      // will be faster to work with char arrays instead of strings
         char c;
         char[] line = theLine.toCharArray();
         int linePos = 0;
         char[] token = new char[line.length];
         int tokenPos = 0;
         int tokenStartPos = 1;
         boolean insideQuotedString = false;
         if (Globals.debug) 
            System.out.println(“source line —>”+theLine+”<---");       // Each iteration of this loop processes one character in the source line.          while (linePos < line.length) {             c = line[linePos];             if (insideQuotedString) { // everything goes into token                token[tokenPos++] = c;                if (c == '"' && token[tokenPos-2] != '\\') { // If quote not preceded by backslash, this is end                   this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);                   tokenPos = 0;                   insideQuotedString = false;                }              }              else { // not inside a quoted string, so be sensitive to delimiters                switch(c) {                   case '#' :  // # denotes comment that takes remainder of line                      if (tokenPos > 0) {
                        this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
                        tokenPos = 0;
                     }
                     tokenStartPos = linePos+1;
                     tokenPos = line.length-linePos;
                     System.arraycopy(line, linePos, token, 0, tokenPos);
                     this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
                     linePos = line.length;
                     tokenPos = 0;
                     break;
                  case ‘ ‘ :
                  case ‘\t’:
                  case ‘,’ : // space, tab or comma is delimiter
                     if (tokenPos > 0) {
                        this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
                        tokenPos = 0;
                     }
                     break;
                  // These two guys are special.  Will be recognized as unary if and only if two conditions hold:
                  // 1. Immediately followed by a digit (will use look-ahead for this).
                  // 2. Previous token, if any, is _not_ an IDENTIFIER
                  // Otherwise considered binary and thus a separate token.  This is a slight hack but reasonable.
                  case ‘+’ :
                  case ‘-‘ :
                      // Here’s the REAL hack: recognizing signed exponent in E-notation floating point!
                     // (e.g. 1.2e-5) Add the + or – to the token and keep going.  DPS 17 Aug 2005
                     if (tokenPos > 0 && line.length >= linePos+2 && Character.isDigit(line[linePos+1]) &&
                                                       (line[linePos-1]==’e’ || line[linePos-1]==’E’)) {
                        token[tokenPos++] = c;
                        break;
                     }
                     // End of REAL hack.  
                     if (tokenPos > 0) {
                        this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
                        tokenPos = 0;
                     }
                     tokenStartPos = linePos+1;
                     token[tokenPos++] = c;
                     if ( !((result.isEmpty() || ((Token)result.get(result.size()-1)).getType() != TokenTypes.IDENTIFIER) &&
                           (line.length >= linePos+2 && Character.isDigit(line[linePos+1]))) ) {
                           // treat it as binary…..
                        this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
                        tokenPos = 0;
                     }
                     break; 
                  // these are other single-character tokens
                  case ‘:’ : 
                  case ‘(‘ :
                  case ‘)’ :
                     if (tokenPos > 0) {
                        this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
                        tokenPos = 0;
                     }
                     tokenStartPos = linePos+1;
                     token[tokenPos++] = c;
                     this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
                     tokenPos = 0;
                     break; 
                  case ‘”‘ : // we’re not inside a quoted string, so start a new token…
                     if (tokenPos > 0) {
                        this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
                        tokenPos = 0;
                     }
                     tokenStartPos = linePos+1;
                     token[tokenPos++] = c;
                     insideQuotedString = true;
                     break;
                  case ‘\” : // start of character constant (single quote).
                     if (tokenPos > 0) {
                        this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
                        tokenPos = 0;
                     }
                    // Our strategy is to process the whole thing right now…
                     tokenStartPos = linePos+1;
                     token[tokenPos++] = c; // Put the quote in token[0]
                     int lookaheadChars = line.length – linePos – 1;
                    // need minimum 2 more characters, 1 for char and 1 for ending quote
                     if (lookaheadChars < 2)                          break;  // gonna be an error                      c = line[++linePos];                       token[tokenPos++] = c; // grab second character, put it in token[1]                      if (c == '\'')                          break; // gonna be an error: nothing between the quotes                      c = line[++linePos];                        token[tokenPos++] = c; // grab third character, put it in token[2]                      // Process if we've either reached second, non-escaped, quote or end of line.                      if (c == '\'' && token[1] != '\\' || lookaheadChars==2) {                          this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);                         tokenPos = 0;                         tokenStartPos = linePos+1;                         break;                      }                     // At this point, there is at least one more character on this line. If we're                      // still here after seeing a second quote, it was escaped.  Not done yet;                     // we either have an escape code, an octal code (also escaped) or invalid.                      c = line[++linePos];                       token[tokenPos++] = c; // grab fourth character, put it in token[3]                     // Process, if this is ending quote for escaped character or if at end of line                      if (c == '\'' || lookaheadChars==3) {                          this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);                         tokenPos = 0;                         tokenStartPos = linePos+1;                         break;                      }                     // At this point, we've handled all legal possibilities except octal, e.g. '\377'                     // Proceed, if enough characters remain to finish off octal.                      if (lookaheadChars >= 5) {
                        c = line[++linePos]; 
                        token[tokenPos++] = c;  // grab fifth character, put it in token[4]
                        if (c != ‘\”) {
                           // still haven’t reached end, last chance for validity!
                           c = line[++linePos];   
                           token[tokenPos++] = c;  // grab sixth character, put it in token[5]
                        }
                     }
                    // process no matter what…we either have a valid character by now or not
                     this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
                     tokenPos = 0;
                     tokenStartPos = linePos+1;
                     break;                                                                         
                  default :
                     if (tokenPos == 0)
                        tokenStartPos = linePos+1;
                     token[tokenPos++] = c;
                     break; 
               }  // switch
            } // if (insideQuotedString)
            linePos++;
         }  // while
         if (tokenPos > 0) {
            this.processCandidateToken(token, program, lineNum, theLine, tokenPos, tokenStartPos, result);
            tokenPos = 0;
         }
         result = processEqv(program, lineNum, theLine, result); // DPS 11-July-2012
         return result;
      }
   
      // Process the .eqv directive, which needs to be applied prior to tokenizing of subsequent statements.
    // This handles detecting that theLine contains a .eqv directive, in which case it needs
    // to be added to the HashMap of equivalents.  It also handles detecting that theLine
    // contains a symbol that was previously defined in an .eqv directive, in which case
    // the substitution needs to be made.
    // DPS 11-July-2012
       private TokenList processEqv(MIPSprogram program, int lineNum, String theLine, TokenList tokens) {
        // See if it is .eqv directive.  If so, record it…
        // Have to assure it is a well-formed statement right now (can’t wait for assembler).
      
         if (tokens.size()>2 && (tokens.get(0).getType() == TokenTypes.DIRECTIVE || tokens.get(2).getType() == TokenTypes.DIRECTIVE)) {
            // There should not be a label but if there is, the directive is in token position 2 (ident, colon, directive).
            int dirPos = (tokens.get(0).getType() == TokenTypes.DIRECTIVE) ? 0 : 2; 
            if (Directives.matchDirective(tokens.get(dirPos).getValue()) == Directives.EQV) {
               // Get position in token list of last non-comment token
               int tokenPosLastOperand = tokens.size() – ((tokens.get(tokens.size()-1).getType()==TokenTypes.COMMENT)? 2 : 1);
               // There have to be at least two non-comment tokens beyond the directive
               if (tokenPosLastOperand < dirPos+2) {                   errors.add(new ErrorMessage(program, lineNum,tokens.get(dirPos).getStartPos(),                         "Too few operands for "+Directives.EQV.getName()+" directive"));                   return tokens;                }                // Token following the directive has to be IDENTIFIER                if (tokens.get(dirPos+1).getType() != TokenTypes.IDENTIFIER) {                   errors.add(new ErrorMessage(program, lineNum,tokens.get(dirPos).getStartPos(),                         "Malformed "+Directives.EQV.getName()+" directive"));                   return tokens;                }                String symbol = tokens.get(dirPos+1).getValue();                 // Make sure the symbol is not contained in the expression.  Not likely to occur but if left                 // undetected it will result in infinite recursion.  e.g.  .eqv ONE, (ONE)                for (int i=dirPos+2; i 0 && value.charAt(0)==’\”) value = preprocessCharacterLiteral(value);
         TokenTypes type = TokenTypes.matchTokenType(value);
         if (type == TokenTypes.ERROR) {
            errors.add(new ErrorMessage(program, line, tokenStartPos, 
                       theLine+”\nInvalid language element: “+value));
         }
         Token toke = new Token(type, value, program, line, tokenStartPos);
         tokenList.add(toke);
         return;
      }
    
    
    
    // If passed a candidate character literal, attempt to translate it into integer constant.
    // If the translation fails, return original value.
       private String preprocessCharacterLiteral(String value) {
         // must start and end with quote and have something in between
         if (value.length() < 3 || value.charAt(0) != '\'' || value.charAt(value.length()-1) != '\'') {             return value;           }          String quotesRemoved = value.substring(1, value.length()-1);         // if not escaped, then if one character left return its value else return original.           if (quotesRemoved.charAt(0) != '\\') {             return (quotesRemoved.length() == 1) ? Integer.toString((int)quotesRemoved.charAt(0)) : value;          }          // now we know it is escape sequence and have to decode which of the 8: ',",\,n,t,b,r,f          if (quotesRemoved.length() == 2) {             int escapedCharacterIndex = escapedCharacters.indexOf(quotesRemoved.charAt(1));             return (escapedCharacterIndex >= 0) ? escapedCharactersValues[escapedCharacterIndex] : value;  
         }
        // last valid possibility is 3 digit octal code 000 through 377
         if (quotesRemoved.length() == 4) {
            try {
               int intValue = Integer.parseInt(quotesRemoved.substring(1),8);
               if (intValue >= 0 && intValue <= 255) {                    return Integer.toString(intValue);                }             }                  catch (NumberFormatException nfe) { } // if not valid octal, will fall through and reject          }            return value;       }    } mars/assembler/Symbol.java mars/assembler/Symbol.javapackage mars.assembler;  /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */     /**     *  Represents a MIPS program identifier to be stored in the symbol table.     *   @author Jason Bumgarner, Jason Shrewsbury     *   @version June 2003     **/      public class Symbol{       private String name;       private int address;       private boolean data; // boolean true if data symbol false if text symbol.       public static final boolean TEXT_SYMBOL = false;       public static final boolean DATA_SYMBOL = true;        /**      *  Basic constructor, creates a symbol object.      *   @param name The name of the Symbol.      *   @param address The memroy address that the Symbol refers to.      *   @param data The type of Symbol that it is.      **/            public Symbol(String name, int address, boolean data){          this.name    = name;          this.address = address;          this.data    = data;       }         /**       *  Returns the address of the the Symbol.       *   @return The address of the Symbol.       **/            public int getAddress(){          return this.address;       }            /**       *  Returns the label of the the Symbol.       *   @return The label of the Symbol.       **/               public String getName(){          return this.name;       }            /**       *  Finds the type of symbol, text or data.       *   @return The type of the data.       **/               public boolean getType(){          return this.data;       }                  /**       * Sets (replaces) the address of the the Symbol.       *   @param newAddress The revised address of the Symbol.       **/            public void setAddress(int newAddress){            this.address = newAddress;          return;       }    } mars/assembler/DataTypes.java mars/assembler/DataTypes.javapackage mars.assembler; /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Information about MIPS data types.  * @author Pete Sanderson  * @version August 2003  **/   public final class DataTypes { /** Number of bytes occupied by MIPS double is 8. **/     public static final int DOUBLE_SIZE = 8; /** Number of bytes occupied by MIPS float is 4. **/     public static final int FLOAT_SIZE = 4; /** Number of bytes occupied by MIPS word is 4. **/     public static final int WORD_SIZE = 4; /** Number of bytes occupied by MIPS halfword is 2. **/     public static final int HALF_SIZE = 2; /** Number of bytes occupied by MIPS byte is 1. **/     public static final int BYTE_SIZE = 1; /** Number of bytes occupied by MIPS character is 1. **/     public static final int CHAR_SIZE = 1; /** Maximum value that can be stored in a MIPS word is 231-1 **/
    public static final int MAX_WORD_VALUE = Integer.MAX_VALUE;
/** Lowest value that can be stored in a MIPS word is -231 **/
    public static final int MIN_WORD_VALUE = Integer.MIN_VALUE;
/** Maximum value that can be stored in a MIPS halfword is 215-1 **/
    public static final int MAX_HALF_VALUE = 32767; //(int)Math.pow(2,15) – 1;
/** Lowest value that can be stored in a MIPS halfword is -215 **/
    public static final int MIN_HALF_VALUE = -32768; //0 – (int) Math.pow(2,15);
/** Maximum value that can be stored in an unsigned MIPS halfword is 216-1 **/
    public static final int MAX_UHALF_VALUE = 65535; 
/** Lowest value that can be stored in na unsigned MIPS halfword is 0 **/
    public static final int MIN_UHALF_VALUE = 0; 
/** Maximum value that can be stored in a MIPS byte is 27-1 **/
    public static final int MAX_BYTE_VALUE = Byte.MAX_VALUE;
/** Lowest value that can be stored in a MIPS byte is -27 **/
    public static final int MIN_BYTE_VALUE = Byte.MIN_VALUE;
/** Maximum positive finite value that can be stored in a MIPS float is same as Java Float **/
    public static final double MAX_FLOAT_VALUE = Float.MAX_VALUE;
/** Largest magnitude negative value that can be stored in a MIPS float (negative of the max) **/
    public static final double LOW_FLOAT_VALUE = -Float.MAX_VALUE;
/** Maximum positive finite value that can be stored in a MIPS double is same as Java Double  **/
    public static final double MAX_DOUBLE_VALUE = Double.MAX_VALUE;
/** Largest magnitude negative value that can be stored in a MIPS double(negative of the max) **/
    public static final double LOW_DOUBLE_VALUE = -Double.MAX_VALUE;
    
   /**
    * Get length in bytes for numeric MIPS directives.
    * @param direct Directive to be measured.
    * @return Returns length in bytes for values of that type.  If type is not numeric
    * (or not implemented yet), returns 0.
    **/
    
   public static int getLengthInBytes(Directives direct) {
       if (direct == Directives.FLOAT)
           return FLOAT_SIZE;
       else if (direct == Directives.DOUBLE)
           return DOUBLE_SIZE;
       else if (direct == Directives.WORD)
           return WORD_SIZE;
       else if (direct == Directives.HALF)
           return HALF_SIZE;
       else if (direct == Directives.BYTE)
           return BYTE_SIZE;
       else 
           return 0;
   }

    
   /**
    * Determines whether given integer value falls within value range for given directive.
    * @param direct Directive that controls storage allocation for value.
    * @param value The value to be stored.
    * @return Returns true if value can be stored in the number of bytes allowed
    * by the given directive (.word, .half, .byte), false otherwise.
    **/   
   public static boolean outOfRange(Directives direct, int value) {
       if (direct == Directives.HALF && (value < MIN_HALF_VALUE || value > MAX_HALF_VALUE))
           return true;
       else if (direct == Directives.BYTE && (value < MIN_BYTE_VALUE || value > MAX_BYTE_VALUE))
           return true;
       else 
           return false;       
   }
    
   /**
    * Determines whether given floating point value falls within value range for given directive.
     * For float, this refers to range of the data type, not precision.  Example: 1.23456789012345 
     * be stored in a float with loss of precision.  It’s within the range.  But 1.23e500 cannot be 
     * stored in a float because the exponent 500 is too large (float allows 8 bits for exponent).
    * @param direct Directive that controls storage allocation for value.
    * @param value The value to be stored.
    * @return Returns true if value is within range of
    * the given directive (.float, .double), false otherwise.
    **/   
   public static boolean outOfRange(Directives direct, double value) {
       if (direct == Directives.FLOAT && (value < LOW_FLOAT_VALUE || value > MAX_FLOAT_VALUE))
           return true;
       else 
           return false;       
   }
}

Assembler$ProgramStatementComparator

package mars.assembler;
synchronized class Assembler$ProgramStatementComparator implements java.util.Comparator {
private void Assembler$ProgramStatementComparator(Assembler);
public int compare(Object, Object);
public boolean equals(Object);
}

SymbolTable

package mars.assembler;
public synchronized class SymbolTable {
private static String startLabel;
private String filename;
private java.util.ArrayList table;
public static final int NOT_FOUND = -1;
static void ();
public void SymbolTable(String);
public void addSymbol(Token, int, boolean, mars.ErrorList);
public void removeSymbol(Token);
public int getAddress(String);
public int getAddressLocalOrGlobal(String);
public Symbol getSymbol(String);
public Symbol getSymbolGivenAddress(String);
public Symbol getSymbolGivenAddressLocalOrGlobal(String);
public java.util.ArrayList getDataSymbols();
public java.util.ArrayList getTextSymbols();
public java.util.ArrayList getAllSymbols();
public int getSize();
public void clear();
public void fixSymbolTableAddress(int, int);
public static String getStartLabel();
}

mars/assembler/Macro.java
mars/assembler/Macro.java   package mars.assembler;

   import java.util.ArrayList;
   import java.util.Arrays;
   import java.util.Collections;

   import mars.ErrorList;
   import mars.ErrorMessage;
   import mars.MIPSprogram;
   import mars.mips.hardware.RegisterFile;

/*
Copyright (c) 2013.

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Stores information of a macro definition.
 * 
 * @author M.H.Sekhavat < >
 */
    public class Macro {
      private String name;
      private MIPSprogram program;
      private ArrayList labels;
   
   /**
    * first and last line number of macro definition. first line starts with
    * .macro directive and last line is .end_macro directive.
    */
      private int fromLine, toLine;
      private int origFromLine, origToLine;
   /**
    * arguments like %arg will be substituted by macro expansion
    */
      private ArrayList args;
   
       public Macro() {
         name = “”;
         program = null;
         fromLine = toLine = 0;
         origFromLine = origToLine = 0;
         args = new ArrayList();
         labels = new ArrayList();
      }
   
       public String getName() {
         return name;
      }
   
       public void setName(String name) {
         this.name = name;
      }
   
       public MIPSprogram getProgram() {
         return program;
      }
   
       public void setProgram(MIPSprogram program) {
         this.program = program;
      }
   
       public int getFromLine() {
         return fromLine;
      }
    
       public int getOriginalFromLine() {
         return this.origFromLine;
      }
    
       public void setFromLine(int fromLine) {
         this.fromLine = fromLine;
      }
   
       public void setOriginalFromLine(int origFromLine) {
         this.origFromLine = origFromLine;
      }
   
       public int getToLine() {
         return toLine;
      }
    
       public int getOriginalToLine() {
         return this.origToLine;
      }
    
       public void setToLine(int toLine) {
         this.toLine = toLine;
      }
   
       public void setOriginalToLine(int origToLine) {
         this.origToLine = origToLine;
      }
    
       public ArrayList getArgs() {
         return args;
      }
   
       public void setArgs(ArrayList args) {
         this.args = args;
      }
   
   /**
    * @param obj
    *            {@link Macro} object to check if their name and count of
    *            arguments are same
    */
       @Override
       public boolean equals(Object obj) {
         if (obj instanceof Macro) {
            Macro macro = (Macro) obj;
            return macro.getName().equals(name) && (macro.args.size() == args.size());
         }
         return super.equals(obj);
      }
   
       public void addArg(String value) {
         args.add(value);
      }
   
   /**
    * Substitutes macro arguments in a line of source code inside macro
    * definition to be parsed after macro expansion. 
    * Also appends “_M#” to all labels defined inside macro body where # is value of counter
    * 
    * @param line
    *            source line number in macro definition to be substituted
    * @param args
    * @param counter
    *            unique macro expansion id
    * @param errors
    * @return line-th line of source code, with substituted
    *         arguments
    */
   
       public String getSubstitutedLine(int line, TokenList args, long counter, ErrorList errors) {
         String s = program.getSourceLine(line);
         TokenList tokens = (TokenList) program.getTokenList().get(line – 1);
         for (int i = tokens.size() – 1; i >= 0; i–) {
            Token token = tokens.get(i);
            if (tokenIsMacroParameter(token.getValue(), true)) {
               int repl = -1;
               for (int j = 0; j < this.args.size(); j++) {                   if (this.args.get(j).equals(token.getValue())) {                      repl = j;                      break;                   }                }                String substitute = token.getValue();                if (repl != -1)                   substitute = args.get(repl + 1).toString();                else {                   errors.add(new ErrorMessage(program, token.getSourceLine(),                      token.getStartPos(), "Unknown macro parameter"));                }                s = replaceToken(s, token, substitute);             }              else if (tokenIsMacroLabel(token.getValue())){                String substitute = token.getValue()+"_M"+counter;                s=replaceToken(s, token, substitute);             }          }                 return s;       }        /**     * returns true if value is name of a label defined in this macro’s body.
    * @param value
    * @return
    */
       private boolean tokenIsMacroLabel(String value) {
         return (Collections.binarySearch(labels, value)>=0);
      }
   
   /**
    * replaces token tokenToBeReplaced which is occured in source with substitute.
    * @param source
    * @param tokenToBeReplaced
    * @param substitute
    * @return 
    */
       private String replaceToken(String source, Token tokenToBeReplaced, String substitute) {
         return source.substring(0, tokenToBeReplaced.getStartPos() – 1)
            + substitute
            + source.substring(tokenToBeReplaced.getStartPos() – 1
                    + tokenToBeReplaced.getValue().length());
      }
   
   /**
    * returns whether tokenValue is macro parameter or not
    * @param tokenValue
    * @param acceptSpimStyleParameters accepts SPIM-style parameters which begin with ‘$’ if true
    * @return
    */
       public static boolean tokenIsMacroParameter(String tokenValue, boolean acceptSpimStyleParameters) {
         if (acceptSpimStyleParameters) {
            if (RegisterFile.getUserRegister(tokenValue) == null && tokenValue.charAt(0) == ‘$’)
               return true;
         }
         return tokenValue.length() > 1 && tokenValue.charAt(0) == ‘%’;
      }
   
       public void addLabel(String value) {
         labels.add(value);
      }
   
   /**
    * Operations to be done on this macro before it is committed in macro pool.
    */
       public void readyForCommit() {
         Collections.sort(labels);
      }
   
   
   
   }

DataTypes

package mars.assembler;
public final synchronized class DataTypes {
public static final int DOUBLE_SIZE = 8;
public static final int FLOAT_SIZE = 4;
public static final int WORD_SIZE = 4;
public static final int HALF_SIZE = 2;
public static final int BYTE_SIZE = 1;
public static final int CHAR_SIZE = 1;
public static final int MAX_WORD_VALUE = 2147483647;
public static final int MIN_WORD_VALUE = -2147483648;
public static final int MAX_HALF_VALUE = 32767;
public static final int MIN_HALF_VALUE = -32768;
public static final int MAX_UHALF_VALUE = 65535;
public static final int MIN_UHALF_VALUE = 0;
public static final int MAX_BYTE_VALUE = 127;
public static final int MIN_BYTE_VALUE = -128;
public static final double MAX_FLOAT_VALUE = 3.4028234663852886E38;
public static final double LOW_FLOAT_VALUE = -3.4028234663852886E38;
public static final double MAX_DOUBLE_VALUE = 1.7976931348623157E308;
public static final double LOW_DOUBLE_VALUE = -1.7976931348623157E308;
public void DataTypes();
public static int getLengthInBytes(Directives);
public static boolean outOfRange(Directives, int);
public static boolean outOfRange(Directives, double);
}

Token

package mars.assembler;
public synchronized class Token {
private TokenTypes type;
private String value;
private mars.MIPSprogram sourceMIPSprogram;
private int sourceLine;
private int sourcePos;
private mars.MIPSprogram originalMIPSprogram;
private int originalSourceLine;
public void Token(TokenTypes, String, mars.MIPSprogram, int, int);
public void setOriginal(mars.MIPSprogram, int);
public mars.MIPSprogram getOriginalProgram();
public int getOriginalSourceLine();
public TokenTypes getType();
public void setType(TokenTypes);
public String getValue();
public String toString();
public mars.MIPSprogram getSourceMIPSprogram();
public int getSourceLine();
public int getStartPos();
}

Assembler$UserKernelAddressSpace

package mars.assembler;
synchronized class Assembler$UserKernelAddressSpace {
int[] address;
int currentAddressSpace;
private final int USER;
private final int KERNEL;
private void Assembler$UserKernelAddressSpace(Assembler, int, int);
private int get();
private void set(int);
private void increment(int);
private void setAddressSpace(int);
}

mars/assembler/Token.java
mars/assembler/Token.java   package mars.assembler;
   import mars.*;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Represents one token in the input MIPS program.  Each Token carries, along with its
 * type and value, the position (line, column) in which its source appears in the MIPS program.
 * 
 * @author Pete Sanderson
 * @version August 2003
 **/

    public class Token {
   
      private TokenTypes type;
      private String value;
      private MIPSprogram sourceMIPSprogram;
      private int sourceLine, sourcePos;
   // original program and line will differ from the above if token was defined in an included file
      private MIPSprogram originalMIPSprogram;
      private int originalSourceLine;  
   /**
    * Constructor for Token class.
    * 
    * @param type The token type that this token has. (e.g. REGISTER_NAME)
    * @param value The source value for this token (e.g. $t3)
    * @param sourceMIPSprogram The MIPSprogram object containing this token
    * @param line The line number in source program in which this token appears.
    * @param start The starting position in that line number of this token’s source value.
    * @see TokenTypes
    **/
    
       public Token(TokenTypes type, String value, MIPSprogram sourceMIPSprogram, int line, int start) {
         this.type = type;
         this.value = value;
         this.sourceMIPSprogram = sourceMIPSprogram;
         this.sourceLine = line;
         this.sourcePos = start; 
         this.originalMIPSprogram = sourceMIPSprogram;
         this.originalSourceLine = line;
      }

   
   /**
    * Set original program and line number for this token.
     * Line number or both may change during pre-assembly as a result
     * of the “.include” directive, and we need to keep the original
     * for later reference (error messages, text segment display).
    * 
    * @param origProgram MIPS program containing this token.
    * @param origSourceLine Line within that program of this token.
    **/         
       public void setOriginal(MIPSprogram origProgram, int origSourceLine) {
         this.originalMIPSprogram = origProgram;
         this.originalSourceLine = origSourceLine;
      }
        
   /**
    * Produces original program containing this token.
    * 
    * @return MIPSprogram of origin for this token.
    **/
       public MIPSprogram getOriginalProgram() {
         return this.originalMIPSprogram;
      }
        
   /**
    * Produces original line number of this token. It could change as result
     * of “.include”
    * 
    * @return original line number of this token.
    **/   
       public int getOriginalSourceLine() {
         return this.originalSourceLine;
      }
   
   /**
    * Produces token type of this token.
    * 
    * @return TokenType of this token.
    **/
       public TokenTypes getType() {
         return type;
      }
   
   /**
    * Set or modify token type.  Generally used to note that
     * an identifier that matches an instruction name is 
     * actually being used as a label.
    * 
    * @param type new TokenTypes for this token.
    **/   
        public void setType(TokenTypes type) {
           this.type = type;
        }
           
   /**
    * Produces source code of this token.
    * 
    * @return String containing source code of this token.
    **/
    
       public String getValue() {
         return value;
      }
   
   /**
    * Get a String representing the token.  This method is
    * equivalent to getValue().
    * 
    * @return     String version of the token. 
    */   
    
       public String toString() {
         return value;
      }
   
   /**
    * Produces MIPSprogram object associated with this token.
    * 
    * @return  MIPSprogram object associated with this token.
    **/
    
       public MIPSprogram getSourceMIPSprogram() {
         return sourceMIPSprogram;
      }
   
   /**
    * Produces line number of MIPS program of this token.
    * 
    * @return line number in source program of this token.
    **/
    
       public int getSourceLine() {
         return sourceLine;
      }
   
      /**
    * Produces position within source line of this token.
    * 
    * @return first character position within source program line of this token.
    **/
    
       public int getStartPos() {
         return sourcePos;
      }
       
   }

Assembler

package mars.assembler;
public synchronized class Assembler {
private java.util.ArrayList machineList;
private mars.ErrorList errors;
private boolean inDataSegment;
private boolean inMacroSegment;
private int externAddress;
private boolean autoAlign;
private Directives currentDirective;
private Directives dataDirective;
private mars.MIPSprogram fileCurrentlyBeingAssembled;
private TokenList globalDeclarationList;
private Assembler$UserKernelAddressSpace textAddress;
private Assembler$UserKernelAddressSpace dataAddress;
private Assembler$DataSegmentForwardReferences currentFileDataSegmentForwardReferences;
private Assembler$DataSegmentForwardReferences accumulatedDataSegmentForwardReferences;
public void Assembler();
public java.util.ArrayList assemble(mars.MIPSprogram, boolean) throws mars.ProcessingException;
public java.util.ArrayList assemble(mars.MIPSprogram, boolean, boolean) throws mars.ProcessingException;
public mars.ErrorList getErrorList();
public java.util.ArrayList assemble(java.util.ArrayList, boolean) throws mars.ProcessingException;
public java.util.ArrayList assemble(java.util.ArrayList, boolean, boolean) throws mars.ProcessingException;
private void catchDuplicateAddresses(java.util.ArrayList, mars.ErrorList);
private java.util.ArrayList parseLine(TokenList, String, int, boolean);
private void detectLabels(TokenList, Macro);
private boolean compactTranslationCanBeApplied(mars.ProgramStatement);
private TokenList stripComment(TokenList);
private void stripLabels(TokenList);
private boolean parseAndRecordLabel(TokenList);
private boolean tokenListBeginsWithLabel(TokenList);
private void executeDirective(TokenList);
private void transferGlobals();
private void executeDirectiveContinuation(TokenList);
private java.util.ArrayList matchInstruction(Token);
private void storeNumeric(TokenList, Directives, mars.ErrorList);
private void storeInteger(Token, Directives, mars.ErrorList);
private void storeRealNumber(Token, Directives, mars.ErrorList);
private void storeStrings(TokenList, Directives, mars.ErrorList);
private boolean passesDataSegmentCheck(Token);
private int writeToDataSegment(int, int, Token, mars.ErrorList);
private void writeDoubleToDataSegment(double, Token, mars.ErrorList);
private int alignToBoundary(int, int);
}

OperandFormat

package mars.assembler;
public synchronized class OperandFormat {
private void OperandFormat();
static boolean tokenOperandMatch(TokenList, mars.mips.instructions.Instruction, mars.ErrorList);
static mars.mips.instructions.Instruction bestOperandMatch(TokenList, java.util.ArrayList);
private static boolean numOperandsCheck(TokenList, mars.mips.instructions.Instruction, mars.ErrorList);
private static boolean operandTypeCheck(TokenList, mars.mips.instructions.Instruction, mars.ErrorList);
private static void generateMessage(Token, String, mars.ErrorList);
}

Symbol

package mars.assembler;
public synchronized class Symbol {
private String name;
private int address;
private boolean data;
public static final boolean TEXT_SYMBOL = 0;
public static final boolean DATA_SYMBOL = 1;
public void Symbol(String, int, boolean);
public int getAddress();
public String getName();
public boolean getType();
public void setAddress(int);
}

Assembler$DataSegmentForwardReferences$DataSegmentForwardReference

package mars.assembler;
synchronized class Assembler$DataSegmentForwardReferences$DataSegmentForwardReference {
int patchAddress;
int length;
Token token;
void Assembler$DataSegmentForwardReferences$DataSegmentForwardReference(Assembler$DataSegmentForwardReferences, int, int, Token);
}

package mars;
import java.awt.*;
import javax.swing.*;

/*
Copyright (c) 2003-2010, Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
“Software”), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject
to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
*/

/**
* Produces MARS splash screen.

* Adapted from http://www.java-tips.org/content/view/1267/2/

*/

public class MarsSplashScreen extends JWindow {

private int duration;

public MarsSplashScreen(int d) {
duration = d;
}

/**
* A simple little method to show a title screen in the center
* of the screen for the amount of time given in the constructor
*/
public void showSplash() {
ImageBackgroundPanel content = new ImageBackgroundPanel();
this.setContentPane(content);

// Set the window’s bounds, centering the window
// Wee bit of a hack. I’ve hardcoded the image dimensions of
// MarsSurfacePathfinder.jpg, because obtaining them via
// getHeight() and getWidth() is not trival — it is possible
// that at the time of the call the image has not completed
// loading so the Image object doesn’t know how big it is.
// So observers are involved — see the API.
int width = 390;
int height =215;
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screen = tk.getScreenSize();
int x = (screen.width-width)/2;
int y = (screen.height-height)/2;
setBounds(x,y,width,height);

// Build the splash screen
JLabel title = new JLabel(“MARS: Mips Assembler and Runtime Simulator”, JLabel.CENTER);
JLabel copyrt1 = new JLabel
(”

Version “+Globals.version+” Copyright (c) “+Globals.copyrightYears+””, JLabel.CENTER);
JLabel copyrt2 = new JLabel
(”

“+Globals.copyrightHolders+””, JLabel.CENTER);
title.setFont(new Font(“Sans-Serif”, Font.BOLD, 16));
title.setForeground(Color.black);
copyrt1.setFont(new Font(“Sans-Serif”, Font.BOLD, 14));
copyrt2.setFont(new Font(“Sans-Serif”, Font.BOLD, 14));
copyrt1.setForeground(Color.white);
copyrt2.setForeground(Color.white);

content.add(title,BorderLayout.NORTH);
content.add(copyrt1,BorderLayout.CENTER);
content.add(copyrt2,BorderLayout.SOUTH);

// Display it
setVisible(true);
// Wait a little while, maybe while loading resources
try { Thread.sleep(duration); }
catch (Exception e) {}
setVisible(false);
}

class ImageBackgroundPanel extends JPanel
{
Image image;
public ImageBackgroundPanel()
{
try
{
image = new ImageIcon(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(Globals.imagesPath+”MarsSurfacePathfinder.jpg”))).getImage();
}
catch (Exception e) {System.out.println(e); /*handled in paintComponent()*/ }
}

@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
}
}

}
mars/util/Binary.java
mars/util/Binary.java   package mars.util;
    import mars.Globals;
   import java.util.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
/**
 * Some utility methods for working with binary representations.
 * 
 * @author Pete Sanderson, Ken Vollmar, and Jason Bumgarner
 * @version July 2005
 */
    public class Binary {
   
    // Using int value 0-15 as index, yields equivalent hex digit as char.
      private static char[] chars = 
                   {‘0′,’1′,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’a’,’b’,’c’,’d’,’e’,’f’};
    // Use this to produce String equivalent of unsigned int value (add it to int value, result is long)
      private static final long UNSIGNED_BASE = (long)0x7FFFFFFF + (long)0x7FFFFFFF +(long)2; //0xFFFFFFFF+1
   
    /**
     * Translate int value into a String consisting of ‘1’s and ‘0’s.
     * 
     * @param value The int value to convert.
     * @param length The number of bit positions, starting at least significant, to process.
     * @return String consisting of ‘1’ and ‘0’ characters corresponding to the requested binary sequence.
     **/
     
       public static String intToBinaryString(int value, int length) {
         char[] result = new char[length];
         int index = length-1;
         for (int i=0; i= 0) {
               if (value.charAt(position) == ‘1’)
                  result = result + pow;
               pow *= 2;
               position–;
               rep++;
            }
            hexChars[digits-digs+1] = chars[result];
         }
         return new String(hexChars);
      }    
   
    /**
     * Translate String consisting of hexadecimal digits into String consisting of
     * corresponding binary digits (‘1’s and ‘0’s).  No length limit.
     * String position 0 will have most-significant bit, position length-1 has least-significant.
     * 
     * @param value String containing ‘0’, ‘1’, …’f’ 
     * characters which form hexadecimal.  Letters may be either upper or lower case.
     * Works either with or without leading “Ox”.
     * @return String with equivalent value in binary.
     **/    
       public static String hexStringToBinaryString(String value) {
         String result = “”;
         // slice off leading Ox or 0X
         if (value.indexOf(“0x”)==0 || value.indexOf(“0X”)==0) {
            value = value.substring(2);
         }
         for (int digs = 0; digs < value.length(); digs++) {             switch (value.charAt(digs)) {                case '0' : result += "0000";                    break;                case '1' : result += "0001";                    break;                case '2' : result += "0010";                    break;                case '3' : result += "0011";                    break;                case '4' : result += "0100";                    break;                case '5' : result += "0101";                    break;                case '6' : result += "0110";                    break;                case '7' : result += "0111";                    break;                case '8' : result += "1000";                    break;                case '9' : result += "1001";                    break;                case 'a' : case 'A' : result += "1010";                    break;                case 'b' : case 'B' : result += "1011";                    break;                case 'c' : case 'C' : result += "1100";                    break;                case 'd' : case 'D' : result += "1101";                    break;                case 'e' : case 'E' : result += "1110";                    break;                case 'f' : case 'F' : result += "1111";                    break;             }          }          return result;       }           /**      * Translate String consisting of '1's and '0's into char equivalent of the corresponding      * hexadecimal digit.  String limited to length 4.      * String position 0 has most-significant bit, position length-1 has least-significant.      *       * @param value The String value to convert.      * @return char '0', '1', ...'F' which form hexadecimal equivalent of decoded String.      * If string length > 4, returns ‘0’.
     **/   
   
       public static char binaryStringToHexDigit(String value) {
         if (value.length() > 4) 
            return ‘0’;
         int result = 0;
         int pow = 1;
         for (int i=value.length()-1; i>=0; i–) {
            if (value.charAt(i) == ‘1’)
               result = result + pow;
            pow *= 2;
         }
         return chars[result];
      }  
   
    /**
     * Prefix a hexadecimal-indicating string “0x” to the string which is 
     * returned by the method “Integer.toHexString”. Prepend leading zeroes
     * to that string as necessary to make it always eight hexadecimal digits.
     *
     * @param d The int value to convert.
     * @return String containing ‘0’, ‘1’, …’F’ which form hexadecimal equivalent of int.
     */
       public static String intToHexString(int d)
      {
         String leadingZero = new String(“0”);
         String leadingX = new String(“0x”);
         String t = Integer.toHexString(d);
         while (t.length() < 8)             t = leadingZero.concat(t);                       t = leadingX.concat(t);             return t;       }         /**      * Returns a 6 character string representing the 16-bit hexadecimal equivalent of the      * given integer value.  First two characters are "0x".  It assumes value will "fit"       * in 16 bits.  If non-negative, prepend leading zeroes to that string as necessary       * to make it always four hexadecimal digits.  If negative, chop off the first      * four 'f' digits so result is always four hexadecimal digits      *      * @param d The int value to convert.      * @return String containing '0', '1', ...'F' which form hexadecimal equivalent of int.      */        public static String intToHalfHexString(int d)       {          String leadingZero = new String("0");          String leadingX = new String("0x");          String t = Integer.toHexString(d);          if (t.length() > 4) {
            t = t.substring(t.length()-4, t.length());
         }
         while (t.length() < 4)             t = leadingZero.concat(t);                       t = leadingX.concat(t);             return t;       }                 /**      * Prefix a hexadecimal-indicating string "0x" to the string equivalent to the       * hexadecimal value in the long parameter. Prepend leading zeroes      * to that string as necessary to make it always sixteen hexadecimal digits.      *      * @param value The long value to convert.      * @return String containing '0', '1', ...'F' which form hexadecimal equivalent of long.      */            public static String longToHexString(long value) {          return binaryStringToHexString(longToBinaryString(value));       }             /**      * Produce String equivalent of integer value interpreting it as an unsigned integer.      * For instance,  -1 (0xffffffff) produces "4294967295" instead of "-1".      * @param d The int value to interpret.      * @return String which forms unsigned 32 bit equivalent of int.      */        public static String unsignedIntToIntString(int d) {          return (d >= 0) ? Integer.toString(d) : Long.toString(UNSIGNED_BASE+d);
      }
   
    /**
     * Produce ASCII string equivalent of integer value, interpreting it as 4 one-byte
     * characters.  If the value in a given byte does not correspond to a printable
     * character, it will be assigned a default character (defined in config.properties)
     * for a placeholder.
     * 
     * @param d The int value to interpret
     * @return String that represents ASCII equivalent
     */     
       public static String intToAscii(int d) {
         StringBuilder result = new StringBuilder(8);
         for (int i=3; i>=0; i–) {
            int byteValue = getByte(d, i);
            result.append( (byteValue < Globals.ASCII_TABLE.length) ? Globals.ASCII_TABLE[byteValue] : Globals.ASCII_NON_PRINT );          }          return result.toString();       }              /**      * Attempt to validate given string whose characters represent a 32 bit integer.      * Integer.decode() is insufficient because it will not allow incorporation of      * hex two's complement (i.e. 0x80...0 through 0xff...f).  Allows      * optional negative (-) sign but no embedded spaces.      *      * @param s candidate string      * @return returns int value represented by given string      * @throws NumberFormatException if string cannot be translated into an int      */              public static int stringToInt(String s) throws NumberFormatException {          String work = new String(s);          int result = 0;        // First, use Integer.decode().  This will validate most, but it flags        // valid hex two's complement values as exceptions.  We'll catch those and        // do our own validation.          try {             result = Integer.decode(s).intValue();          }               catch (NumberFormatException nfe) {             // Multistep process toward validation of hex two's complement. 3-step test:             //   (1) exactly 10 characters long,             //   (2) starts with Ox or 0X,             //   (3) last 8 characters are valid hex digits.                work = work.toLowerCase();                if (work.length() == 10 && work.startsWith("0x")) {                   String bitString = "";                   int index;                   // while testing characters, build bit string to set up for binaryStringToInt                   for (int i=2; i<10; i++) {                      index = Arrays.binarySearch(chars, work.charAt(i));                      if (index < 0) {                         throw new NumberFormatException();                      }                      bitString = bitString + intToBinaryString(index,4);                   }                   result = binaryStringToInt(bitString);                }                /*  The following "else" composed by Jose Baiocchi Paredes, Oct 2009.  This new code                     will correctly translate a string representing an unsigned decimal (not hex)                   value whose signed value is negative.  This is the decimal equivalent of the                  "then" case just above.  The method was not used in this context until Release 3.6                   when background highlighting of the Data Segment was added.  Caused exceptions                   under certain conditions.                 */                else if (!work.startsWith("0x")) {                   result = 0;                   for (int i=0; i> 32);  // high order 32 bits
      }
    
    
        /**
      *  Returns int representing the bit values of the low order 32 bits of given
      *  64 bit long value.
      *   @param longValue The long value from which to extract bits.
      *   @return int containing low order 32 bits of argument
      **/       
       public static int lowOrderLongToInt(long longValue) {
         return (int) (longValue << 32 >> 32);  // low order 32 bits
      }     
   
        /**
      *  Returns long (64 bit integer) combining the bit values of two given 32 bit
      *  integer values.
      *   @param highOrder Integer to form the high-order 32 bits of result.
      *   @param lowOrder Integer to form the high-order 32 bits of result.
      *   @return long containing concatenated 32 bit int values.
      **/       
       public static long twoIntsToLong(int highOrder, int lowOrder) {
         return (((long)highOrder) << 32) | (((long)lowOrder) & 0xFFFFFFFFL);       }                   /**       *  Returns the bit value of the given bit position of the given int value.       *   @param value The value to read the bit from.       *   @param bit bit position in range 0 (least significant) to 31 (most)       *   @return 0 if the bit position contains 0, and 1 otherwise.       **/               public static int bitValue(int value, int bit) {          return 1 & (value >> bit);
      }
     
    
    /**
      *  Returns the bit value of the given bit position of the given long value.
      *   @param value The value to read the bit from.
      *   @param bit bit position in range 0 (least significant) to 63 (most)
      *   @return 0 if the bit position contains 0, and 1 otherwise.
      **/
      
       public static int bitValue(long value, int bit) {
       
         return (int) (1L & (value >> bit));
      }
     
        /**
      *  Sets the specified bit of the specified value to 1, and returns the result.
      *   @param value The value in which the bit is to be set.
      *   @param bit bit position in range 0 (least significant) to 31 (most)
      *   @return value possibly modified with given bit set to 1.
      **/
      
       public static int setBit(int value, int bit) {
         return value | ( 1 << bit) ;       }                   /**       *  Sets the specified bit of the specified value to 0, and returns the result.       *   @param value The value in which the bit is to be set.       *   @param bit bit position in range 0 (least significant) to 31 (most)       *   @return value possibly modified with given bit set to 0.       **/               public static int clearBit(int value, int bit) {          return value &  ~(1 << bit);       }                 // setByte and getByte added by DPS on 12 July 2006              /**       *  Sets the specified byte of the specified value to the low order 8 bits of        *  specified replacement value, and returns the result.       *   @param value The value in which the byte is to be set.       *   @param bite byte position in range 0 (least significant) to 3 (most)       *   @param replace value to place into that byte position - use low order 8 bits       *   @return value modified value.       **/               public static int setByte(int value, int bite, int replace) {          return value & ~(0xFF << (bite<<3)) | ((replace & 0xFF) << (bite<<3)) ;       }                   /**       *  Gets the specified byte of the specified value.       *   @param value The value in which the byte is to be retrieved.       *   @param bite byte position in range 0 (least significant) to 3 (most)       *   @return zero-extended byte value in low order byte.       **/               public static int getByte(int value, int bite) {          return value << ((3-bite)<<3) >>> 24;
      }
     
           // KENV 1/4/05
   /**
    * Parsing method to see if a string represents a hex number.
    *  As per http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html#decode(java.lang.String),
    *  a string represents a hex number if the string is in the forms:
    *      Signopt 0x HexDigits
    *      Signopt 0X HexDigits
    *      Signopt # HexDigits   <---- Disallow this form since # is MIPS comment     *     *     * @param v String containing numeric digits (could be decimal, octal, or hex)     *     * @return Returns true if string represents a hex number, else returns false.
    **/
       public static boolean isHex(String v)
      {
         try
         {
           // don’t care about return value, just whether it threw exception.
           // If value is EITHER a valid int OR a valid long, continue.
            try {
               Binary.stringToInt(v);
            } 
                catch (NumberFormatException nfe) {
                  try {
                     Binary.stringToLong(v);
                  } 
                      catch (NumberFormatException e) {
                        return false;  // both failed; it is neither valid int nor long
                     }
               }                    
         
            if ((v.charAt(0) == ‘-‘) &&  // sign is optional but if present can only be –
                     (v.charAt(1) == ‘0’) &&
                     (Character.toUpperCase( v.charAt(1) ) == ‘X’) )
               return true;  // Form is Sign 0x…. and the entire string is parseable as a number
            
            else if ((v.charAt(0) == ‘0’) &&
                     (Character.toUpperCase( v.charAt(1) ) == ‘X’) )
               return true;  // Form is 0x…. and the entire string is parseable as a number
         
         }
             catch (StringIndexOutOfBoundsException e)
            {
               return false;
            }
      
         return false; // default
      }
   
   
   
           // KENV 1/4/05
   /**
    * Parsing method to see if a string represents an octal number.
    *  As per http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html#decode(java.lang.String),
    *  a string represents an octal number if the string is in the forms:
    *      Signopt 0 OctalDigits
    *
    * @param v String containing numeric digits (could be decimal, octal, or hex)
    *
    * @return Returns true if string represents an octal number, else returns false.
    **/
       public static boolean isOctal(String v)
      {
               // Don’t mistake “0” or a string that starts “0x” for an octal string
         try
         {
                 // we don’t care what value Binary.stringToInt(v) returns, just whether it threw exception
            int dontCare = Binary.stringToInt(v);
         
            if (isHex(v)) 
               return false; // String starts with “0” but continues “0x”, so not octal
                 
            if ((v.charAt(0) == ‘-‘) &&   // sign is optional but if present can only be –
                     (v.charAt(1) == ‘0’) &&
                     (v.length() > 1) )  // Has to have more digits than the leading zero
               return true;  // Form is Sign 0…. and the entire string is parseable as a number
            
            else if ((v.charAt(0) == ‘0’) &&
                     (v.length() > 1) )  // Has to have more digits than the leading zero
               return true;  // Form is 0…. and the entire string is parseable as a number
         
         }
             catch (StringIndexOutOfBoundsException e)
            {
               return false;
            }
             catch (NumberFormatException e)
            {
               return false;
            }
      
         return false; // default
      }
   
   
   
   }

mars/util/PropertiesFile.java
mars/util/PropertiesFile.java   package mars.util;
   import mars.*;
   import java.util.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
/**
 * Provides means to work with “.properties” files which are used to store
 * various MARS settings.
 *
 * @author Pete Sanderson
 * @version October 2006
  */
    public class PropertiesFile  {
    
    /**
     *  Produce Properties (a Hashtable) object containing key-value pairs
     *  from specified properties file.  This may be used as an alternative
     *  to readPropertiesFile() which uses a different implementation.
     *
     *  @param file Properties filename.  Do NOT include the file extension as
     *  it is assumed to be “.properties” and is added here.
     *  @return Properties (Hashtable) of key-value pairs read from the file.
     */
   
       public static Properties loadPropertiesFromFile(String file) {
         Properties properties = new Properties();
         try {
            InputStream is = PropertiesFile.class.getResourceAsStream(“/”+file+”.properties”);
            properties.load(is);
         } 
             catch (IOException ioe) { } // If it doesn’t work, properties will be empty
             catch (NullPointerException npe) { } 
         return properties;
      }
   }

mars/util/FilenameFinder.java
mars/util/FilenameFinder.java   package mars.util;
   import java.io.File;
   import java.io.IOException;
   import java.net.URI;
   import java.net.URISyntaxException;
   import java.net.URL;
   import java.util.ArrayList;
   import java.util.Enumeration;
   import java.util.StringTokenizer;
   import java.util.zip.ZipEntry;
   import java.util.zip.ZipFile;

   import javax.swing.filechooser.FileFilter;
    
    /*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
/**
 * Utility class to perform necessary file-related search
 * operations.  One is to find file names in JAR file,
 * another is to find names of files in given directory
 * of normal file system.
 *
 * @author Pete Sanderson
 * @version October 2006
  */
    public class FilenameFinder
   {
      private static final String JAR_EXTENSION = “.jar”;
      private static final String FILE_URL = “file:”;
      private static final String JAR_URI_PREFIX = “jar:”;
      private static final boolean NO_DIRECTORIES = false;
      public static String MATCH_ALL_EXTENSIONS = “*”; 
   /**
    * Locate files and return list of file names.  Given a known relative directory path,
    * it will locate it and build list of all names of files in that directory 
    * having the given file extension. If the “known file path” doesn’t work 
    * because MARS is running from an executable JAR file, it will locate the 
    * directory in the JAR file and proceed from there.  NOTE: since this uses
    * the class loader to get the resource, the directory path needs to be 
    * relative to classpath, not absolute.  To work with an arbitrary file system,
    * use the other version of this overloaded method.  Will NOT match directories
    * that happen to have the desired extension.
    * @param classLoader class loader to use
    * @param directoryPath Search will be confined to this directory.  Use “/” as 
    * separator but do NOT include starting or ending “/”  (e.g. mars/tools)
    * @param fileExtension Only files with this extension will be added 
    * to the list.  Do NOT include the “.” in extension.
    * @return array list of matching file names as Strings.  If none, list is empty.
    */
       public static ArrayList getFilenameList(ClassLoader classLoader,
                                              String directoryPath, 
                                              String fileExtension  ) {
         fileExtension = checkFileExtension(fileExtension);
         ArrayList filenameList = new ArrayList();
        // Modified by DPS 10-July-2008 to better handle path containing space
        // character (%20) and to hopefully handle path containing non-ASCII
        // characters.  The “toURI()” approach was suggested by MARS user
        // Felipe Lessa and worked for him when running ‘java Mars’ but it did
        // not work when executing from a jar file ‘java -jar Mars.jar’.  I
        // took it from there and discovered that in the latter situation,
        // “toURI()” created a URI prefixed with “jar:” and the “getPath()” in 
        // that case returns null! If you strip the “jar:” prefix and create a 
        // new URI from the resulting string, it works!  Thanks Felipe!
        //
        // NOTE 5-Sep-2008: “toURI()” was introduced in Java 1.5.  To maintain
        // 1.4 compatibility, I need to change it to call URI constructor with
        // string argument, as documented in Sun API.
         // 
         // Modified by Ingo Kofler 24-Sept-2009 to handle multiple JAR files.
        // This requires use of ClassLoader getResources() instead of 
        // getResource().  The former will look in all JAR files listed in
        // in the java command.
        //
         URI uri;
         try {
            Enumeration urls = classLoader.getResources(directoryPath);
          
            while (urls.hasMoreElements()) {
               uri = new URI(urls.nextElement().toString());
               if (uri.toString().indexOf(JAR_URI_PREFIX)==0) {
                  uri = new URI(uri.toString().substring(JAR_URI_PREFIX.length()));
               }
             
               File f = new File(uri.getPath());
               File[] files = f.listFiles();
               if (files == null) {         
                  if (f.toString().toLowerCase().indexOf(JAR_EXTENSION)>0) {
                       // Must be running from a JAR file. Use ZipFile to find files and create list.
                              // Modified 12/28/09 by DPS to add results to existing filenameList instead of overwriting it.         
                     filenameList.addAll(getListFromJar(extractJarFilename(f.toString()), directoryPath, fileExtension));
                  } 
               }
               else {  // have array of File objects; convert to names and add to list
                  FileFilter filter = getFileFilter(fileExtension, “”, NO_DIRECTORIES);
                  for (int i=0; i0) {
               // Must be running from a JAR file. Use ZipFile to find files and create list.         
               filenameList = getListFromJar(extractJarFilename(f.toString()), directoryPath, fileExtension);
            } 
         }
         else {  // have array of File objects; convert to names and add to list
            FileFilter filter = getFileFilter(fileExtension, “”, NO_DIRECTORIES);
            for (int i=0; i 0 && i < s.length() - 1) {              ext = s.substring(i+1).toLowerCase();           }           return ext;        }          /**      *  Get a FileFilter that will filter files based on the given list of filename extensions.      *  @param extensions ArrayList of Strings, each string is acceptable filename extension.      *  @param description String containing description to be added in parentheses after list of extensions.      *  @param acceptDirectories boolean value true if directories are accepted by the filter, false otherwise.      *  @return a FileFilter object that accepts files with given extensions, and directories if so indicated.      */              public static FileFilter getFileFilter(ArrayList extensions, String description, boolean acceptDirectories) {          return new MarsFileFilter(extensions, description, acceptDirectories);       }           /**      *  Get a FileFilter that will filter files based on the given list of filename extensions.      *  All directories are accepted by the filter.      *  @param extensions ArrayList of Strings, each string is acceptable filename extension      *  @param description String containing description to be added in parentheses after list of extensions.      *  @return a FileFilter object that accepts files with given extensions, and directories if so indicated.      */                    public static FileFilter getFileFilter(ArrayList extensions, String description) {          return getFileFilter(extensions, description, true);       }           /**      *  Get a FileFilter that will filter files based on the given filename extension.      *  @param extension String containing acceptable filename extension.      *  @param description String containing description to be added in parentheses after list of extensions.      *  @param acceptDirectories boolean value true if directories are accepted by the filter, false otherwise.      *  @return a FileFilter object that accepts files with given extensions, and directories if so indicated.      */              public static FileFilter getFileFilter(String extension, String description, boolean acceptDirectories) {          ArrayList extensions = new ArrayList();          extensions.add(extension);          return new MarsFileFilter(extensions, description, acceptDirectories);       }           /**      *  Get a FileFilter that will filter files based on the given filename extension.      *  All directories are accepted by the filter.      *  @param extension String containing acceptable filename extension      *  @param description String containing description to be added in parentheses after list of extensions.      *  @return a FileFilter object that accepts files with given extensions, and directories if so indicated.      */                    public static FileFilter getFileFilter(String extension, String description) {          ArrayList extensions = new ArrayList();          extensions.add(extension);          return getFileFilter(extensions, description, true);       }           /**      *  Determine if given filename ends with given extension.      *  @param name A String containing the file name      *  @param extension A String containing the file extension.  Leading period is optional.      *  @return Returns true if filename ends with given extension, false otherwise.      */      // For assured results, make sure extension starts with "."    (will add it if not there)         public static boolean fileExtensionMatch(String name, String extension) {          return (extension==null || extension.length()==0 || name.endsWith(((extension.startsWith("."))? "" : ".")+extension));       }                // return list of file names in specified folder inside JAR        private static ArrayList getListFromJar(String jarName, String directoryPath, String fileExtension) {          fileExtension = checkFileExtension(fileExtension);          ArrayList nameList = new ArrayList();          if (jarName==null) {             return nameList;          }          try {             ZipFile zf = new ZipFile(new File(jarName));             Enumeration list = zf.entries();             while (list.hasMoreElements()) {                ZipEntry ze = (ZipEntry) list.nextElement();                if (ze.getName().startsWith(directoryPath+"/") &&                     fileExtensionMatch(ze.getName(),fileExtension)) {                   nameList.add(ze.getName().substring(ze.getName().lastIndexOf('/')+1));                }             }          }               catch (Exception e) {                System.out.println("Exception occurred reading MarsTool list from JAR: "+e);             }          return nameList;       }           // Given pathname, extract and return JAR file name (must be only element containing ".jar")      // 5 Dec 2007 DPS: Modified to return file path of JAR file, not just its name.  This was      //                 by request of Zachary Kurmas of Grant Valley State, who got errors trying      //                 to run the Mars.jar file from a different working directory.  He helpfully      //                 pointed out what the error is and where it occurs.  Originally, it would      //                 work only if the JAR file was in the current working directory (as would      //                 be the case if executed from a GUI by double-clicking the jar icon).        private static String extractJarFilename(String path) {          StringTokenizer findTheJar = new StringTokenizer(path,"\\/");          if (path.toLowerCase().startsWith(FILE_URL)) {             path = path.substring(FILE_URL.length());          }          int jarPosition = path.toLowerCase().indexOf(JAR_EXTENSION);          return (jarPosition >= 0) ? path.substring(0,jarPosition+JAR_EXTENSION.length()) : path;
      }
    
    // make sure file extension, if it is real, does not start with ‘.’ — remove it.
       private static String checkFileExtension(String fileExtension) {
         return (fileExtension==null || fileExtension.length()==0 || !fileExtension.startsWith(“.”))
                ? fileExtension
                 : fileExtension.substring(1);
      }
    
    
    ///////////////////////////////////////////////////////////////////////////
    //  FileFilter subclass to be instantiated by the getFileFilter method above.
    //  This extends javax.swing.filechooser.FileFilter
    
       private static class MarsFileFilter extends FileFilter {
      
         private ArrayList extensions;
         private String fullDescription;
         private boolean acceptDirectories;
        
          private MarsFileFilter(ArrayList extensions, String description, boolean acceptDirectories) {
            this.extensions = extensions;
            this.fullDescription = buildFullDescription(description, extensions);
            this.acceptDirectories = acceptDirectories;
         }
        
        // User provides descriptive phrase to be parenthesized.
        // We will attach it to description of the extensions.  For example, if the extensions
        // given are s and asm and the description is “Assembler Programs” the full description
        // generated here will be “Assembler Programs (*.s; *.asm)”
          private String buildFullDescription(String description, ArrayList extensions) {
            String result = (description == null) ? “” : description;
            if (extensions.size() > 0) {
               result += ”  (“;
            }
            for (int i=0; i 0) {
                  result += ((i==0)?””:”; “)+”*”+((extension.charAt(0)==’.’)? “” : “.”)+extension;
               }
            }
            if (extensions.size() > 0) {
               result += “)”;
            }
            return result;
         }
        
        // required by the abstract superclass
          public String getDescription() {
            return this.fullDescription;
         }
        
        // required by the abstract superclass.
          public boolean accept(File file) {
            if (file.isDirectory()) { 
               return acceptDirectories; 
            } 
            String fileExtension = getExtension(file); 
            if (fileExtension != null) { 
               for (int i=0; i();
public void EditorFont();
public static String[] getCommonFamilies();
public static String[] getAllFamilies();
public static String[] getFontStyleStrings();
public static int styleStringToStyleInt(String);
public static String styleIntToStyleString(int);
public static String sizeIntToSizeString(int);
public static int sizeStringToSizeInt(String);
public static java.awt.Font createFontFromStringValues(String, String, String);
public static String substituteSpacesForTabs(String);
public static String substituteSpacesForTabs(String, int);
private static String[] actualCommonFamilies();
}

MemoryDump

package mars.util;
public synchronized class MemoryDump {
public static java.util.ArrayList dumpTriples;
private static final java.util.HashMap segmentBoundMap;
private static final String[] segmentNames;
private static int[] baseAddresses;
private static int[] limitAddresses;
static void ();
public void MemoryDump();
public static Integer[] getSegmentBounds(String);
public static String[] getSegmentNames();
public static int[] getBaseAddresses(String[]);
public static int[] getLimitAddresses(String[]);
public static int getAddressOfFirstNull(int, int) throws mars.mips.hardware.AddressErrorException;
}

mars/util/EditorFont.java
mars/util/EditorFont.java   package mars.util;
   import mars.*;
   import java.awt.*;
   import java.util.*;
   import java.awt.Font;
    
    /*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
/**
 *  Specialized Font class designed to be used by both the
 *  settings menu methods and the Settings class.
 *
 * @author Pete Sanderson
 * @version July 2007
  */
    public class EditorFont  {
    
      // Note: These are parallel arrays so corresponding elements must match up.
      private static final String[] styleStrings = { “Plain”, “Bold”, “Italic”, “Bold + Italic” };
      private static final int[] styleInts = { Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD | Font.ITALIC };
      public static final String DEFAULT_STYLE_STRING = styleStrings[0];
      public static final int DEFAULT_STYLE_INT = styleInts[0];
      public static final int MIN_SIZE = 6;
      public static final int MAX_SIZE = 72;
      public static final int DEFAULT_SIZE = 12;
    /* Fonts in 3 categories that are common to major Java platforms: Win, Mac, Linux.
     *    Monospace: Courier New and Lucida Sans Typewriter
     *    Serif: Georgia, Times New Roman
     *    Sans Serif: Ariel, Verdana
     * This is according to lists published by www.codestyle.org.
     */
      private static final String[] allCommonFamilies =  { “Arial”, “Courier New”, “Georgia”, 
                          “Lucida Sans Typewriter”, “Times New Roman”, “Verdana” };
   
     
    /**
     *  Obtain an array of common font family names.  These are guaranteed to
     *  be available at runtime, as they were checked against the local
     *  GraphicsEnvironment.
     *  @return Array of strings, each is a common and available font family name.
     */
     
       public static String[] getCommonFamilies() {
         return commonFamilies;
      }
   
    /**
     *  Obtain an array of all available font family names.  These are guaranteed to
     *  be available at runtime, as they come from the local GraphicsEnvironment.
     *  @return Array of strings, each is an available font family name.
     */
     
       public static String[] getAllFamilies() {
         return GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
      }
    
    /**
     * Get array containing String values for font style names.
     */
       public static String[] getFontStyleStrings() {
         return styleStrings;
      }
     
    
      /**
     *  Given a string that represents a font style, returns the
     *  corresponding final int defined in Font: PLAIN, BOLD, ITALIC.  It 
     *  is not case-sensitive.
     *  @param style String representing the font style name
     *  @return The int value of the corresponding Font style constant.  If the
     *  string does not match any style name, returns Font.PLAIN.
     */
       public static int styleStringToStyleInt(String style) {
         String styleLower = style.toLowerCase();
         for (int i=0; i < styleStrings.length; i++) {             if (styleLower.equals(styleStrings[i].toLowerCase())) {                return styleInts[i];             }          }          return DEFAULT_STYLE_INT;       }          /**      *  Given an int that represents a font style from the Font class,      *  returns the corresponding String.        *  @param style Must be one of Font.PLAIN, Font.BOLD, Font.ITALIC.      *  @return The String representation of that style.  If the parameter      *  is not one of the above, returns "Plain".      */        public static String styleIntToStyleString(int style) {          for (int i=0; i < styleInts.length; i++) {             if (style == styleInts[i]) {                return styleStrings[i];             }          }          return DEFAULT_STYLE_STRING;       }          /**       *  Given an int representing font size, returns corresponding string.     *  @param size  Int representing size.     *  @return String value of parameter, unless it is less than MIN_SIZE (returns MIN_SIZE     *  as String) or greater than MAX_SIZE (returns MAX_SIZE as String).     */        public static String sizeIntToSizeString(int size) {          int result = (sizeMAX_SIZE) ? MAX_SIZE : size);
         return String.valueOf(result);
      }
   
     /**
      *  Given a String representing font size, returns corresponding int.
    *  @param size  String representing size.
    *  @return int value of parameter, unless it is less than MIN_SIZE (returns 
    *  MIN_SIZE) or greater than MAX_SIZE (returns MAX_SIZE).  If the string
    *  cannot be parsed as a decimal integer, it returns DEFAULT_SIZE.
    */  
       public static int sizeStringToSizeInt(String size) {
         int result = DEFAULT_SIZE;
         try {
            result = Integer.parseInt(size);
         } 
             catch (NumberFormatException e) { }
         return (resultMAX_SIZE) ? MAX_SIZE : result);
      }
    
    /**
     *  Creates a new Font object based on the given String specifications.  This
     *  is different than Font’s constructor, which requires ints for style and size.
     *  It assures that defaults and size limits are applied when necessary.
     *  @param family String containing font family.
     *  @param style String containing font style.  A list of available styles can
     *  be obtained from getFontStyleStrings().  The default of styleStringToStyleInt()
     *  is substituted if necessary.
     *  @param size String containing font size.  The defaults and limits of
     *  sizeStringToSizeInt() are substituted if necessary.
     */
       public static Font createFontFromStringValues(String family, String style, String size) {
         return new Font(family, styleStringToStyleInt(style), sizeStringToSizeInt(size));
      }
    
    /**
     *  Handy utility to produce a string that substitutes spaces for all tab characters 
     *  in the given string.  The number of spaces generated is based on the position of
     *  the tab character and the editor’s current tab size setting.
     *  @param string The original string 
     *  @return New string in which spaces are substituted for tabs
     *  @throws NullPointerException if string is null
     */
      private static final String TAB_STRING = “\t”;
      private static final char TAB_CHAR = ‘\t’;
      private static final String SPACES = ”                                                  “;
     
       public static String substituteSpacesForTabs(String string) {
         return substituteSpacesForTabs(string, Globals.getSettings().getEditorTabSize());
      }

    /**
     *  Handy utility to produce a string that substitutes spaces for all tab characters 
     *  in the given string.  The number of spaces generated is based on the position of
     *  the tab character and the specified tab size.
     *  @param string The original string 
         *  @param tabSize The number of spaces each tab character represents
     *  @return New string in which spaces are substituted for tabs
     *  @throws NullPointerException if string is null
     */      
       public static String substituteSpacesForTabs(String string, int tabSize) {
         if (!string.contains(TAB_STRING)) 
            return string;
         StringBuffer result = new StringBuffer(string);
         for (int i=0; i= 0) {
               result[k++] = allCommonFamilies[i];
            }
         }
        // If not all are found, creat a new array with only the ones that are.
         if (k < allCommonFamilies.length) {             String[] temp = new String[k];             System.arraycopy(result, 0, temp, 0, k);             result = temp;          }          return result;       }    } Binary package mars.util; public synchronized class Binary { private static char[] chars; private static final long UNSIGNED_BASE = 4294967296; static void ();
public void Binary();
public static String intToBinaryString(int, int);
public static String intToBinaryString(int);
public static String longToBinaryString(long, int);
public static String longToBinaryString(long);
public static int binaryStringToInt(String);
public static long binaryStringToLong(String);
public static String binaryStringToHexString(String);
public static String hexStringToBinaryString(String);
public static char binaryStringToHexDigit(String);
public static String intToHexString(int);
public static String intToHalfHexString(int);
public static String longToHexString(long);
public static String unsignedIntToIntString(int);
public static String intToAscii(int);
public static int stringToInt(String) throws NumberFormatException;
public static long stringToLong(String) throws NumberFormatException;
public static int highOrderLongToInt(long);
public static int lowOrderLongToInt(long);
public static long twoIntsToLong(int, int);
public static int bitValue(int, int);
public static int bitValue(long, int);
public static int setBit(int, int);
public static int clearBit(int, int);
public static int setByte(int, int, int);
public static int getByte(int, int);
public static boolean isHex(String);
public static boolean isOctal(String);
}

SystemIO

package mars.util;
public synchronized class SystemIO {
public static final int SYSCALL_BUFSIZE = 128;
public static final int SYSCALL_MAXFILES = 32;
public static String fileErrorString;
private static final int O_RDONLY = 0;
private static final int O_WRONLY = 1;
private static final int O_RDWR = 2;
private static final int O_APPEND = 8;
private static final int O_CREAT = 512;
private static final int O_TRUNC = 1024;
private static final int O_EXCL = 2048;
private static final int STDIN = 0;
private static final int STDOUT = 1;
private static final int STDERR = 2;
private static java.io.BufferedReader inputReader;
static void ();
public void SystemIO();
public static int readInteger(int);
public static float readFloat(int);
public static double readDouble(int);
public static void printString(String);
public static String readString(int, int);
public static int readChar(int);
public static int writeToFile(int, byte[], int);
public static int readFromFile(int, byte[], int);
public static int openFile(String, int);
public static void closeFile(int);
public static void resetFiles();
public static String getFileErrorMessage();
private static java.io.BufferedReader getInputReader();
}

SystemIO$FileIOData

package mars.util;
synchronized class SystemIO$FileIOData {
private static String[] fileNames;
private static int[] fileFlags;
private static Object[] streams;
static void ();
private void SystemIO$FileIOData();
private static void resetFiles();
private static void setupStdio();
private static void setStreamInUse(int, Object);
private static Object getStreamInUse(int);
private static boolean filenameInUse(String);
private static boolean fdInUse(int, int);
private static void close(int);
private static int nowOpening(String, int);
}

FilenameFinder

package mars.util;
public synchronized class FilenameFinder {
private static final String JAR_EXTENSION = .jar;
private static final String FILE_URL = file:;
private static final String JAR_URI_PREFIX = jar:;
private static final boolean NO_DIRECTORIES = 0;
public static String MATCH_ALL_EXTENSIONS;
static void ();
public void FilenameFinder();
public static java.util.ArrayList getFilenameList(ClassLoader, String, String);
public static java.util.ArrayList getFilenameList(ClassLoader, String, java.util.ArrayList);
public static java.util.ArrayList getFilenameList(String, String);
public static java.util.ArrayList getFilenameList(String, java.util.ArrayList);
public static java.util.ArrayList getFilenameList(java.util.ArrayList, String);
public static java.util.ArrayList getFilenameList(java.util.ArrayList, java.util.ArrayList);
public static String getExtension(java.io.File);
public static javax.swing.filechooser.FileFilter getFileFilter(java.util.ArrayList, String, boolean);
public static javax.swing.filechooser.FileFilter getFileFilter(java.util.ArrayList, String);
public static javax.swing.filechooser.FileFilter getFileFilter(String, String, boolean);
public static javax.swing.filechooser.FileFilter getFileFilter(String, String);
public static boolean fileExtensionMatch(String, String);
private static java.util.ArrayList getListFromJar(String, String, String);
private static String extractJarFilename(String);
private static String checkFileExtension(String);
}

mars/util/SystemIO.java
mars/util/SystemIO.java   package mars.util;
   import mars.*;
   import java.io.*;
   import javax.swing.*;
   import java.util.*;
    
    /*
Copyright (c) 2003-2013,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
/**
 * Provides standard i/o services needed to simulate the MIPS syscall
 * routines.  These methods will detect whether the simulator is being
 * run from the command line or through the GUI, then do I/O to
 * System.in and System.out in the former situation, and interact with
 * the GUI in the latter.
 *
 * @author Pete Sanderson and Ken Vollmar
 * @version August 2003-2005
 */
    public class SystemIO
   {
    /** Buffer size for syscalls for file I/O */
      public static final int SYSCALL_BUFSIZE = 128;
    /** Maximum number of files that can be open */
      public static final int SYSCALL_MAXFILES = 32;
    /** String used for description of file error */
      public static String fileErrorString = new String(“File operation OK”);
   
      private static final int O_RDONLY = 0x00000000;
      private static final int O_WRONLY = 0x00000001;
      private static final int O_RDWR   = 0x00000002;
      private static final int O_APPEND = 0x00000008;
      private static final int O_CREAT  = 0x00000200; // 512
      private static final int O_TRUNC  = 0x00000400; // 1024
      private static final int O_EXCL   = 0x00000800; // 2048
    
    // standard I/O channels
      private static final int STDIN  = 0;
      private static final int STDOUT = 1;
      private static final int STDERR = 2;
   
      // Will use one buffered reader for all keyboard/redirected/piped input.
    // Added by DPS 28 Feb 2008.  See getInputReader() below.
      private static BufferedReader inputReader = null;
   
    /**
     * Implements syscall to read an integer value.  
     * Client is responsible for catching NumberFormatException.
     * @param serviceNumber the number assigned to Read Int syscall (default 5)
     * @return int value corresponding to user input
     */
   
       public static int readInteger(int serviceNumber)
      {
         String input = “0”;
         if (Globals.getGui() == null)
         {
            try
            {  
               input = getInputReader().readLine();
            } 
                catch (IOException e)
               {}
         } 
         else
         {
            if (Globals.getSettings().getBooleanSetting(Settings.POPUP_SYSCALL_INPUT)) {
               input = Globals.getGui().getMessagesPane().getInputString(
                    “Enter an integer value (syscall “+serviceNumber+”)”);
            } 
            else {
               input = Globals.getGui().getMessagesPane().getInputString(-1);
            }
         }
      
        // Client is responsible for catching NumberFormatException
         return new Integer(input.trim()).intValue();
      }
    
    
    /**
     * Implements syscall to read a float value.
     * Client is responsible for catching NumberFormatException.
     * @param serviceNumber the number assigned to Read Float syscall (default 6)
     * @return float value corresponding to user input
     * Feb 14 2005 Ken Vollmar
     */
       public static float readFloat(int serviceNumber)
      {
         String input = “0”;
         if (Globals.getGui() == null)
         {
            try
            {
               input = getInputReader().readLine();
            } 
                catch (IOException e)
               {}
         } 
         else
         {
            if (Globals.getSettings().getBooleanSetting(Settings.POPUP_SYSCALL_INPUT)) {
               input = Globals.getGui().getMessagesPane().getInputString(
                    “Enter a float value (syscall “+serviceNumber+”)”);
            } 
            else {
               input = Globals.getGui().getMessagesPane().getInputString(-1);
            }
         }
         return new Float(input.trim()).floatValue();
      
      }
    
    
    /**
     * Implements syscall to read a double value.
     * Client is responsible for catching NumberFormatException.
     * @param serviceNumber the number assigned to Read Double syscall (default 7)
     * @return double value corresponding to user input
     * 1 Aug 2005 DPS, based on Ken Vollmar’s readFloat
     */
       public static double readDouble(int serviceNumber)
      {
         String input = “0”;
         if (Globals.getGui() == null)
         {
            try
            {
               input = getInputReader().readLine();
            } 
                catch (IOException e)
               {}
         } 
         else
         {
            if (Globals.getSettings().getBooleanSetting(Settings.POPUP_SYSCALL_INPUT)) {
               input = Globals.getGui().getMessagesPane().getInputString(
                    “Enter a double value (syscall “+serviceNumber+”)”);
            } 
            else {
               input = Globals.getGui().getMessagesPane().getInputString(-1);
            }
         }
         return new Double(input.trim()).doubleValue();
      
      }
    
    
    /**
     * Implements syscall having 4 in $v0, to print a string.
     */
       public static void printString(String string)
      {
         if (Globals.getGui() == null)
         {
            System.out.print(string);
         } 
         else
         {
            Globals.getGui().getMessagesPane().postRunMessage(string);
         }
      
      }
    
    
    /**
     * Implements syscall to read a string.
     * @param serviceNumber the number assigned to Read String syscall (default 8)
     * @param maxLength the maximum string length
     * @return the entered string, truncated to maximum length if necessary
     */
       public static String readString(int serviceNumber, int maxLength)
      {
         String input = “”;
         if (Globals.getGui() == null)
         {
            try
            {
               input = getInputReader().readLine();
            } 
                catch (IOException e)
               {}
         } 
         else
         {
            if (Globals.getSettings().getBooleanSetting(Settings.POPUP_SYSCALL_INPUT)) {
               input = Globals.getGui().getMessagesPane().getInputString(
                    “Enter a string of maximum length ” + maxLength
                    + ” (syscall “+serviceNumber+”)”);            
            } 
            else {
               input = Globals.getGui().getMessagesPane().getInputString(maxLength);
               if (input.endsWith(“\n”)) {
                  input = input.substring(0, input.length() – 1);
               }
            }
         }
        
         if (input.length() > maxLength) {
            // Modified DPS 13-July-2011.  Originally: return input.substring(0, maxLength);
            return (maxLength <= 0) ? "" : input.substring(0, maxLength);          }           else {             return  input;          }       }             /** Implements syscall having 12 in $v0, to read a char value.      *      * @param serviceNumber the number assigned to Read Char syscall (default 12)      * @return int value with lowest byte corresponding to user input      */        public static int readChar(int serviceNumber)       {          String input = "0";          int returnValue = 0;          if (Globals.getGui() == null)          {             try             {                input = getInputReader().readLine();             }                  catch (IOException e)                {}          }           else          {             if (Globals.getSettings().getBooleanSetting(Settings.POPUP_SYSCALL_INPUT)) {                input = Globals.getGui().getMessagesPane().getInputString(                     "Enter a character value (syscall "+serviceNumber+")");                          }              else {                          input = Globals.getGui().getMessagesPane().getInputString(1);             }          }          // The whole try-catch is not really necessary in this case since I'm         // just propagating the runtime exception (the default behavior), but          // I want to make it explicit.  The client needs to catch it.          try          {             returnValue = (int) (input.charAt(0)); // first character input          }               catch (IndexOutOfBoundsException e) // no chars present             {                throw e;  // was: returnValue = 0;             }                 return returnValue;              }             /** Write bytes to file.      *      * @param fd file descriptor      * @param myBuffer byte array containing characters to write      * @param lengthRequested number of bytes to write      * @return number of bytes written, or -1 on error      */            public static int writeToFile(int fd, byte[] myBuffer, int lengthRequested)       {        /////////////// DPS 8-Jan-2013  ////////////////////////////////////////////////////        /// Write to STDOUT or STDERR file descriptor while using IDE - write to Messages pane.           if ((fd==STDOUT || fd==STDERR) && Globals.getGui() != null) {             String data = new String(myBuffer);             Globals.getGui().getMessagesPane().postRunMessage(data);             return data.length();          }        ///////////////////////////////////////////////////////////////////////////////////        //// When running in command mode, code below works for either regular file or STDOUT/STDERR                 if (!FileIOData.fdInUse(fd, 1)) // Check the existence of the "write" fd          {             fileErrorString = new String(                     "File descriptor " + fd + " is not open for writing");             return -1;          }          // retrieve FileOutputStream from storage          OutputStream outputStream = (OutputStream) FileIOData.getStreamInUse(fd);          try          {             // Oct. 9 2005 Ken Vollmar             // Observation: made a call to outputStream.write(myBuffer, 0, lengthRequested)             //     with myBuffer containing 6(ten) 32-bit-words <---> 24(ten) bytes, where the
            //     words are MIPS integers with values such that many of the bytes are ZEROES.
            //     The effect is apparently that the write stops after encountering a zero-valued
            //     byte. (The method write does not return a value and so this can’t be verified
            //     by the return value.)
            // Writes up to lengthRequested bytes of data to this output stream from an array of bytes.
            // outputStream.write(myBuffer, 0, lengthRequested); // write is a void method — no verification value returned
            
            // Oct. 9 2005 Ken Vollmar  Force the write statement to write exactly
            // the number of bytes requested, even though those bytes include many ZERO values.
            for (int ii = 0; ii < lengthRequested; ii++)             {                outputStream.write(myBuffer[ii]);              }             outputStream.flush();// DPS 7-Jan-2013          }               catch (IOException e)             {                fileErrorString = new String(                     "IO Exception on write of file with fd " + fd);                return -1;             }               catch (IndexOutOfBoundsException e)             {                fileErrorString = new String(                     "IndexOutOfBoundsException on write of file with fd" + fd);                return -1;             }                 return lengthRequested;              } // end writeToFile              /** Read bytes from file.      *      * @param fd file descriptor      * @param myBuffer byte array to contain bytes read      * @param lengthRequested number of bytes to read      * @return number of bytes read, 0 on EOF, or -1 on error      */        public static int readFromFile(int fd, byte[] myBuffer, int lengthRequested)       {          int retValue = -1;          /////////////// DPS 8-Jan-2013  //////////////////////////////////////////////////        /// Read from STDIN file descriptor while using IDE - get input from Messages pane.           if (fd==STDIN && Globals.getGui() != null) {             String input = Globals.getGui().getMessagesPane().getInputString(lengthRequested);             byte[] bytesRead = input.getBytes();;             for (int i=0; i < myBuffer.length; i++) {                myBuffer[i] = (i < bytesRead.length) ? bytesRead[i] : 0 ;             }             return Math.min(myBuffer.length, bytesRead.length);          }        ////////////////////////////////////////////////////////////////////////////////////        //// When running in command mode, code below works for either regular file or STDIN                  if (!FileIOData.fdInUse(fd, 0)) // Check the existence of the "read" fd          {             fileErrorString = new String(                     "File descriptor " + fd + " is not open for reading");             return -1;          }         // retrieve FileInputStream from storage          InputStream InputStream = (InputStream) FileIOData.getStreamInUse(fd);          try          {             // Reads up to lengthRequested bytes of data from this Input stream into an array of bytes.             retValue = InputStream.read(myBuffer, 0, lengthRequested);             // This method will return -1 upon EOF, but our spec says that negative             // value represents an error, so we return 0 for EOF.  DPS 10-July-2008.             if (retValue == -1) {                retValue = 0;             }          }               catch (IOException e)             {                fileErrorString = new String(                     "IO Exception on read of file with fd " + fd);                return -1;             }               catch (IndexOutOfBoundsException e)             {                fileErrorString = new String(                     "IndexOutOfBoundsException on read of file with fd" + fd);                return -1;             }          return retValue;              } // end readFromFile            /**     * Open a file for either reading or writing. Note that read/write flag is NOT     * IMPLEMENTED.  Also note that file permission modes are also NOT IMPLEMENTED.      *     * @param filename string containing filename     * @param flag 0 for read, 1 for write     * @return file descriptor in the range 0 to SYSCALL_MAXFILES-1, or -1 if error     * @author Ken Vollmar     */        public static int openFile(String filename, int flags)       {         // Internally, a "file descriptor" is an index into a table         // of the filename, flag, and the File???putStream associated with         // that file descriptor.                 int retValue = -1;          char ch[] = { ' '}; // Need an array to convert to String          FileInputStream inputStream;          FileOutputStream outputStream;          int fdToUse;                // Check internal plausibility of opening this file          fdToUse = FileIOData.nowOpening(filename, flags);          retValue = fdToUse; // return value is the fd          if (fdToUse < 0)          {              return -1;          }   // fileErrorString would have been set                             if (flags == O_RDONLY) // Open for reading only          {             try             {                 // Set up input stream from disk file                inputStream = new FileInputStream(filename);                FileIOData.setStreamInUse(fdToUse, inputStream); // Save stream for later use             }                  catch (FileNotFoundException e)                {                   fileErrorString = new String(                         "File " + filename + " not found, open for input.");                   retValue = -1;                }          }           else if ( (flags & O_WRONLY) != 0 ) // Open for writing only          {             // Set up output stream to disk file             try             {                 outputStream = new FileOutputStream(filename, ((flags & O_APPEND) != 0) );                FileIOData.setStreamInUse(fdToUse, outputStream); // Save stream for later use             }                  catch (FileNotFoundException e)                {                   fileErrorString = new String(                         "File " + filename + " not found, open for output.");                   retValue = -1;                }          }          return retValue; // return the "file descriptor"              }         /** Close the file with specified file descriptor       *      * @param fd the file descriptor of an open file      */        public static void closeFile(int fd)       {          FileIOData.close(fd);       }         /**       * Reset all files -- clears out the file descriptor table.      */        public static void resetFiles()       {          FileIOData.resetFiles();       }          /**       *  Retrieve file operation or error message     *     *  @return string containing message     */        public static String getFileErrorMessage()       {          return fileErrorString;       }           ///////////////////////////////////////////////////////////////////////       // Private method to simply return the BufferedReader used for     // keyboard input, redirected input, or piped input.     // These are all equivalent in the eyes of the program because they are      // transparent to it.  Lazy instantiation.  DPS.  28 Feb 2008             private static BufferedReader getInputReader() {          if (inputReader == null) {             inputReader = new BufferedReader(new InputStreamReader(System.in));            }          return inputReader;       }               // //////////////////////////////////////////////////////////////////////////////     // Maintain information on files in use. The index to the arrays is the "file descriptor."     // Ken Vollmar, August 2005             private static class FileIOData       {          private static String[] fileNames = new String[ SYSCALL_MAXFILES ]; // The filenames in use. Null if file descriptor i is not in use.          private static int[] fileFlags = new int[ SYSCALL_MAXFILES ]; // The flags of this file, 0=READ, 1=WRITE. Invalid if this file descriptor is not in use.          private static Object[] streams = new Object[SYSCALL_MAXFILES]; // The streams in use, associated with the filenames                // Reset all file information. Closes any open files and resets the arrays           private static void resetFiles()          {             for (int i = 0; i < SYSCALL_MAXFILES; i++)             {                close(i);             }             setupStdio();          }         // DPS 8-Jan-2013           private static void setupStdio() {             fileNames[STDIN]  = "STDIN";             fileNames[STDOUT] = "STDOUT";             fileNames[STDERR] = "STDERR";             fileFlags[STDIN]  = SystemIO.O_RDONLY;             fileFlags[STDOUT] = SystemIO.O_WRONLY;             fileFlags[STDERR] = SystemIO.O_WRONLY;             streams[STDIN]  = System.in;             streams[STDOUT] = System.out;             streams[STDERR] = System.err;             System.out.flush();             System.err.flush();          }                // Preserve a stream that is in use           private static void setStreamInUse(int fd, Object s)          {             streams[fd] = s;                    }                // Retrieve a stream for use           private static Object getStreamInUse(int fd)          {             return streams[fd];                    }                // Determine whether a given filename is already in use.           private static boolean filenameInUse(String requestedFilename)          {             for (int i = 0; i < SYSCALL_MAXFILES; i++)             {                if (fileNames[i] != null                         && fileNames[i].equals(requestedFilename))                {                     // System.out.println("Mars.SystemIO.FileIOData.filenameInUse: rtng TRUE for " + requestedFilename);                   return true;                }             }                       // System.out.println("Mars.SystemIO.FileIOData.filenameInUse: rtng TRUE for " + requestedFilename);             return false;                    }                // Determine whether a given fd is already in use with the given flag.           private static boolean fdInUse(int fd, int flag)          {             if (fd < 0 || fd >= SYSCALL_MAXFILES)
            {
               return false;
            } 
            else if (fileNames[fd] != null && fileFlags[fd] == 0 && flag == 0)
            {  // O_RDONLY read-only
               return true;
            }
            else if (fileNames[fd] != null && ((fileFlags[fd] & flag & O_WRONLY) == O_WRONLY) )
            {  // O_WRONLY write-only
               return true;
            }         
            return false;
         
         }
      
        // Close the file with file descriptor fd. No errors are recoverable — if the user’s
        // made an error in the call, it will come back to him.
          private static void close(int fd)
         {
            // Can’t close STDIN, STDOUT, STDERR, or invalid fd
            if (fd <= STDERR || fd >= SYSCALL_MAXFILES) 
               return;
               
            fileNames[fd] = null;
            // All this code will be executed only if the descriptor is open.
            if (streams[fd] != null)
            {
               int keepFlag = fileFlags[fd];
               Object keepStream = streams[fd];
               fileFlags[fd] = -1;
               streams[fd] = null;
               try {
                  if (keepFlag == O_RDONLY)
                     ((FileInputStream)keepStream).close();
                  else
                     ((FileOutputStream)keepStream).close();
               } 
                   catch (IOException ioe) {
                  // not concerned with this exception
                  }
            } 
            else {
               fileFlags[fd] = -1; // just to be sure… streams[fd] known to be null
            }
         }
      
        // Attempt to open a new file with the given flag, using the lowest available file descriptor.
        // Check that filename is not in use, flag is reasonable, and there is an available file descriptor.
        // Return: file descriptor in 0…(SYSCALL_MAXFILES-1), or -1 if error
          private static int nowOpening(String filename, int flag)
         {
            int i = 0;
            if (filenameInUse(filename))
            {
               fileErrorString = new String(
                        “File name ” + filename + ” is already open.”);
               return -1;
            }
         
            if (flag != O_RDONLY && flag != O_WRONLY && flag != (O_WRONLY | O_APPEND) ) // Only read and write are implemented
            {
               fileErrorString = new String(
                        “File name ” + filename
                        + ” has unknown requested opening flag”);
               return -1;
            }
         
            while (fileNames[i] != null && i < SYSCALL_MAXFILES)             {                i++;             } // Attempt to find available file descriptor                       if (i >= SYSCALL_MAXFILES) // no available file descriptors
            {
               fileErrorString = new String(
                        “File name ” + filename
                        + ” exceeds maximum open file limit of ”
                        + SYSCALL_MAXFILES);
               return -1;
            }    
         
            // Must be OK — put filename in table
            fileNames[i] = new String(filename); // our table has its own copy of filename
            fileFlags[i] = flag;
            fileErrorString = new String(“File operation OK”);
            return i;
         
         }
      
      } // end private class FileIOData
    ////////////////////////////////////////////////////////////////////////////////
   
   
   }

FilenameFinder$MarsFileFilter

package mars.util;
synchronized class FilenameFinder$MarsFileFilter extends javax.swing.filechooser.FileFilter {
private java.util.ArrayList extensions;
private String fullDescription;
private boolean acceptDirectories;
private void FilenameFinder$MarsFileFilter(java.util.ArrayList, String, boolean);
private String buildFullDescription(String, java.util.ArrayList);
public String getDescription();
public boolean accept(java.io.File);
}

mars/util/MemoryDump.java
mars/util/MemoryDump.java   package mars.util;

   import mars.Globals;
   import mars.mips.hardware.*;
   import java.io.File;
   import java.io.FileNotFoundException;
   import java.io.FileOutputStream;
   import java.io.IOException;
   import java.io.PrintStream;
   import java.util.*;

    /*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

    public class MemoryDump {
   
      /** A list of segmentname/dumpformat/filename triples which should be dumped */
      public static ArrayList dumpTriples = null;
      
      /** A mapping from segments names (like “.text”) to the base and limit for that segment. */
      private static final HashMap segmentBoundMap = new HashMap();
      
      private static final String[] segmentNames = { “.text”, “.data” };
      private static int[] baseAddresses = new int[2];
      private static int[] limitAddresses = new int[2];
   
   
      /**
     * Return array with segment address bounds for specified segment.
     * @param segment String with segment name (initially “.text” and “.data”)
     * @return array of two Integer, the base and limit address for that segment.  Null if parameter
     * name does not match a known segment name.
     */
     
       public static Integer[] getSegmentBounds(String segment) {
         for (int i=0; i< segmentNames.length; i++) {             if (segmentNames[i].equals(segment)) {                Integer[] bounds = new Integer[2];                bounds[0] = new Integer(getBaseAddresses(segmentNames)[i]);                bounds[1] = new Integer(getLimitAddresses(segmentNames)[i]);                return bounds;             }          }          return null;       }                 /**      * Get the names of segments available for memory dump.      * @return array of Strings, each string is segment name (e.g. ".text", ".data")      */            public static String[] getSegmentNames() {          return segmentNames;       }                           /**          * Get the MIPS memory base address(es) of the specified segment name(s).          * If invalid segment name is provided, will throw NullPointerException, so          * I recommend getting segment names from getSegmentNames().          *          * @param segments Array of Strings containing segment names (".text", ".data")          * @return Array of int containing corresponding base addresses.          */        public static int[] getBaseAddresses(String[] segments) {          baseAddresses[0] = Memory.textBaseAddress;          baseAddresses[1] = Memory.dataBaseAddress;          return baseAddresses;       }                   /**          * Get the MIPS memory limit address(es) of the specified segment name(s).          * If invalid segment name is provided, will throw NullPointerException, so          * I recommend getting segment names from getSegmentNames().          *          * @param segments Array of Strings containing segment names (".text", ".data")          * @return Array of int containing corresponding limit addresses.          */           public static int[] getLimitAddresses(String[] segments) {          limitAddresses[0] = Memory.textLimitAddress;          limitAddresses[1] = Memory.dataSegmentLimitAddress;          return limitAddresses;       }                                                 /**       *  Look for first "null" memory value in an address range.  For text segment (binary code), this     *  represents a word that does not contain an instruction.  Normally use this to find the end of      *  the program.  For data segment, this represents the first block of simulated memory (block length     *  currently 4K words) that has not been referenced by an assembled/executing program.     *     *  @param baseAddress lowest MIPS address to be searched; the starting point     *  @param limitAddress highest MIPS address to be searched     *  @return lowest address within specified range that contains "null" value as described above.     *  @throws AddressErrorException if the base address is not on a word boundary     */        public static int getAddressOfFirstNull(int baseAddress, int limitAddress) throws AddressErrorException {          int address = baseAddress;          for (; address < limitAddress; address += Memory.WORD_LENGTH_BYTES) {             if (Globals.memory.getRawWordOrNull(address) == null) {                break;             }           }          return address;       }        } MarsSplashScreen package mars; public synchronized class MarsSplashScreen extends javax.swing.JWindow { private int duration; public void MarsSplashScreen(int); public void showSplash(); } SettingsMemoryConfigurationAction$MemoryConfigurationDialog package mars.venus; synchronized class SettingsMemoryConfigurationAction$MemoryConfigurationDialog extends javax.swing.JDialog implements java.awt.event.ActionListener { javax.swing.JTextField[] addressDisplay; javax.swing.JLabel[] nameDisplay; SettingsMemoryConfigurationAction$ConfigurationButton selectedConfigurationButton; SettingsMemoryConfigurationAction$ConfigurationButton initialConfigurationButton; public void SettingsMemoryConfigurationAction$MemoryConfigurationDialog(SettingsMemoryConfigurationAction, java.awt.Frame, String, boolean); private javax.swing.JPanel buildDialogPanel(); private java.awt.Component buildConfigChooser(); private java.awt.Component buildConfigDisplay(); public void actionPerformed(java.awt.event.ActionEvent); private java.awt.Component buildControlPanel(); private void performApply(); private void performClose(); private void performReset(); private void setConfigDisplay(mars.mips.hardware.MemoryConfiguration); } mars/venus/FileStatus.java mars/venus/FileStatus.java   package mars.venus;    import mars.*;    import java.io.*; /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */    /**       *  Used to store and return information on the status of the current ASM file that       *  is being edited in the program.       *   @author Team JSpim       **/            public class FileStatus{       /** initial state or after close */       public static final int NO_FILE = 0;       /** New edit window with no edits */       public static final int NEW_NOT_EDITED = 1;      /** New edit window with unsaved edits */       public static final int NEW_EDITED = 2;       /** open/saved edit window with no edits */       public static final int NOT_EDITED = 3;      /** open/saved edit window with unsaved edits */       public static final int EDITED = 4;       /** successful assembly */       public static final int RUNNABLE = 5;      /** execution is under way */       public static final int RUNNING = 6;      /** execution terminated */       public static final int TERMINATED = 7;          /** file is being opened.  DPS 9-Aug-2011 */         public static final int OPENING = 8;              ///////////////////////////////////////////////////////////////////      //                                                               //      //  The static part.  Legacy code from original student team's   //      //  2003 Practicum project through MARS 3.8, when the editor     //      //  was limited to one file.  The status of that file became     //      //  the de facto status of the system.  Should have used a       //      //  singleton class but in 2003 did not know what that was!      //      //  My plan is to phase out all statics but the constants        //      //  in MARS 4.0 but will keep it in place while at the same time //      //  defining non-static members for use by individual files      //      //  currently opened in the editor.  DPS, 9 April 2010.          //      //                                                               //      ///////////////////////////////////////////////////////////////////             private static int systemStatus; // set to one of the above       private static boolean systemAssembled;       private static boolean systemSaved;       private static boolean systemEdited;       private static String systemName;       private static File systemFile;          /**      * Set file status.  Also updates menu state accordingly.      *       * @param newStatus  New status: EDITED, RUNNABLE, etc, see list above.      */        public static void set(int newStatus) {          systemStatus = newStatus;          Globals.getGui().setMenuState(systemStatus);       }           /**      * Get file status      *       * @return file status EDITED, RUNNABLE, etc, see list above      */             public static int get() {          return systemStatus;       }              /**       *  Changes the value of assenbked to the parameter given.       *   @param b boolean variable that tells what to set assembled to.       */        public static void setAssembled(boolean b){          systemAssembled= b;       }            /**       *  Changes the value of saved to the parameter given.       *   @param b boolean variable that tells what to set saved to .       */        public static void setSaved(boolean b){          systemSaved= b;       }           /**       *  Changes the value of edited to the parameter given.       *   @param b boolean variable that tells what to set edited to.       */        public static void setEdited(boolean b){          systemEdited= b;       }             /**       *  Changes the value of name to the parameter given.       *   @param s string variable tells what to set the name of the file to .       */        public static void setName(String s){           systemName = s;        }            /**       *  Sets the file to the ASM file passed.       *   @param f file object variable that stores the ASM file.       */        public static void setFile(File f){          systemFile = f;       }              /**       *  Returns the ASM file.       *   @return The ASM file.       */            public static File getFile(){          return systemFile;       }            /**       *  Returns the name of the file.       *   @return The name of the ASM file.       */        public static String getName(){          return systemName;       }            /**       *  Tells whether the file has been assembled.       *   @return Boolean value that is true if the ASM file has been assembled.       */        public static boolean isAssembled(){          return systemAssembled;       }            /**       *  Tells whether the file has been saved.       *   @return Boolean variable that is true if the ASM file has been saved       */        public static boolean isSaved(){          return systemSaved;       }            /**       *  Tells whether the file has been edited since it has been saved.       *   @return Boolean value that returns true if the ASM file has been edited.       */        public static boolean isEdited(){          return systemEdited;       }            /**       *  Resets all the values in FileStatus       */        public static void reset(){           systemStatus = NO_FILE;          systemName= "";          systemAssembled= false;          systemSaved= false;          systemEdited= false;          systemFile= null;       }           /////////////////////  END OF STATIC PART   ///////////////////////      ///////////////////////////////////////////////////////////////////                // Remaining members are of instantiable class that can be used by      // every file that is currently open in the editor.                    private int status;       private File file;            /**      *  Create a FileStatus object with FileStatis.NO_FILE for status and null for file getters.      */        public FileStatus() {          this(FileStatus.NO_FILE,null);       }            /**      *  Create a FileStatus object with given status and file pathname.      *      *  @param status Initial file status.  See FileStatus static constants.      *  @param pathname Full file pathname. See setPathname(String newPath) below.      */           public FileStatus(int status, String pathname) {          this.status = status;          if (pathname==null) {             this.file = null;          }           else {             setPathname(pathname);          }       }          /**      *  Set editing status of this file.  See FileStatus static constants.      *      *  @param newStatus the new status      */        public void setFileStatus(int newStatus) {          this.status = newStatus;       }          /**      *  Get editing status of this file.       *      *  @return current editing status.  See FileStatus static constants.      */             public int getFileStatus() {          return this.status;       }          /**      *  Determine if file is "new", which means created using New but not yet saved.      *  If created using Open, it is not new.      *      *  @return true if file was created using New and has not yet been saved, false otherwise.      */        public boolean isNew() {          return status == FileStatus.NEW_NOT_EDITED || status == FileStatus.NEW_EDITED;       }          /**      *  Determine if file has been modified since last save or, if not yet saved, since       *  being created using New or Open.      *      *  @return true if file has been modified since save or creation, false otherwise.      */             public boolean hasUnsavedEdits() {          return status == FileStatus.NEW_EDITED || status == FileStatus.EDITED;       }         /**      *  Set full file pathname. See java.io.File(String pathname) for parameter specs.      *      *  @param newPath the new pathname. If no directory path, getParent() will return null.      */             public void setPathname(String newPath) {          this.file = new File(newPath);       }         /**      *  Set full file pathname. See java.io.File(String parent, String child) for parameter specs.      *      *  @param parent the parent directory of the file.  If null, getParent() will return null.      *  @param name the name of the file (no directory path)       */                 public void setPathname(String parent, String name) {          this.file = new File(parent,name);       }            /**       *  Get full file pathname.  See java.io.File.getPath()        *       *  @return full pathname as a String.  Null if        */        public String getPathname() {          return (this.file==null) ? null : this.file.getPath();       }          /**       *  Get file name with no path information.  See java.io.File.getName()        *       *  @return filename as a String       */           public String getFilename() {                  return (this.file==null) ? null : this.file.getName();       }          /**       *  Get file parent pathname.  See java.io.File.getParent()        *       *  @return parent full pathname as a String       */                public String getParent()  {          return (this.file==null) ? null : this.file.getParent();       }                   /**       *  Update static FileStatus fields with values from this FileStatus object       *  To support legacy code that depends on the static.       */               public void updateStaticFileStatus() {          systemStatus = this.status;          systemName= this.file.getPath();          systemAssembled= false;          systemSaved= (status==NOT_EDITED || status==RUNNABLE || status==RUNNING || status==TERMINATED);          systemEdited= (status==NEW_EDITED || status==EDITED);          systemFile= this.file;                 }         } HelpHelpAction$1 package mars.venus; synchronized class HelpHelpAction$1 extends java.awt.event.WindowAdapter { void HelpHelpAction$1(HelpHelpAction, javax.swing.JDialog); public void windowClosing(java.awt.event.WindowEvent); } EditFindReplaceAction$FindReplaceDialog$2 package mars.venus; synchronized class EditFindReplaceAction$FindReplaceDialog$2 implements java.awt.event.ActionListener { void EditFindReplaceAction$FindReplaceDialog$2(EditFindReplaceAction$FindReplaceDialog); public void actionPerformed(java.awt.event.ActionEvent); } mars/venus/FilePrintAction.java mars/venus/FilePrintAction.java   package mars.venus;    import mars.*;    import java.awt.*;    import java.awt.event.*;    import javax.swing.*;    import java.io.*;    import java.awt.print.*;    import java.util.*;    /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */       /**     * Action  for the File -> Print menu item
    */              
    public class FilePrintAction extends GuiAction {
     
       public FilePrintAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
   
    /** Uses the HardcopyWriter class developed by David Flanagan for the book
     * “Java Examples in a Nutshell”.  It will do basic printing of multipage
     * text documents.  It displays a print dialog but does not act on any
     * changes the user may have specified there, such as number of copies.
     *
     * @param e component triggering this call
     */
   
       public void actionPerformed(ActionEvent e) {
           EditPane editPane = mainUI.getMainPane().getEditPane();
            if (editPane == null) return;
         int fontsize = 10;  // fixed at 10 point
         double margins = .5; // all margins (left,right,top,bottom) fixed at .5″
         HardcopyWriter out;
         try {
            out = new HardcopyWriter(mainUI,editPane.getFilename(),
                                         fontsize, margins, margins, margins, margins);
         }
             catch (HardcopyWriter.PrintCanceledException pce) {
               return;
            }
         BufferedReader in = new BufferedReader(new StringReader(editPane.getSource()));
         int lineNumberDigits = new Integer(editPane.getSourceLineCount()).toString().length();      
         String line;
            String lineNumberString = “”;
         int lineNumber = 0;
         int numchars;
         try {
            line = in.readLine();
            while(line != null) {
               if (editPane.showingLineNumbers()) {
                  lineNumber++;
                  lineNumberString = new Integer(lineNumber).toString() + “: “;
                  while (lineNumberString.length() < lineNumberDigits) {                      lineNumberString = lineNumberString + " ";                   }                }                     line = lineNumberString + line + "\n";                out.write(line.toCharArray(), 0, line.length());                line = in.readLine();             }             in.close( );             out.close( );          }              catch (IOException ioe) {             }           return;       }     }       SettingsHighlightingAction$BackgroundChanger package mars.venus; synchronized class SettingsHighlightingAction$BackgroundChanger implements java.awt.event.ActionListener { private int position; public void SettingsHighlightingAction$BackgroundChanger(SettingsHighlightingAction, int); public void actionPerformed(java.awt.event.ActionEvent); } mars/venus/SettingsAssembleAllAction.java mars/venus/SettingsAssembleAllAction.java   package mars.venus;    import mars.simulator.*;     import mars.*;    import java.util.*;    import java.awt.*;    import java.awt.event.*;    import javax.swing.*;    import java.io.*;          /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */         /**     * Action class for the Settings menu item to determine whether assemble operation applies      * only to current file or to all files in its directory.     */     public class SettingsAssembleAllAction extends GuiAction  {                 public SettingsAssembleAllAction(String name, Icon icon, String descrip,                              Integer mnemonic, KeyStroke accel, VenusUI gui) {          super(name, icon, descrip, mnemonic, accel, gui);       }                  public void actionPerformed(ActionEvent e) {            Globals.getSettings().setAssembleAllEnabled(                ((JCheckBoxMenuItem) e.getSource()).isSelected());       }             } mars/venus/RunToggleBreakpointsAction.java mars/venus/RunToggleBreakpointsAction.java   package mars.venus;    import mars.*;    import java.awt.event.*;    import javax.swing.*;    import javax.swing.event.*;          /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */         /**     * Action class for the Run menu item to clear execution breakpoints that have been set.      * It is a listener and is notified whenever a breakpoint is added or removed, thus will      * set its enabled status true or false depending on whether breakpoints remain after that action.      */     public class RunToggleBreakpointsAction extends GuiAction  {             /**           * Create the object and register with text segment window as a listener on its table model.           * The table model has not been created yet, so text segment window will hang onto this           * registration info and transfer it to the table model upon creation (which happens with           * each successful assembly).           */        public RunToggleBreakpointsAction(String name, Icon icon, String descrip,                              Integer mnemonic, KeyStroke accel, VenusUI gui) {          super(name, icon, descrip, mnemonic, accel, gui);                }      /**           *  When this option is selected, tell text segment window to clear breakpoints in its table model.           */        public void actionPerformed(ActionEvent e) {          Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().toggleBreakpoints();                   }             } MessagesPane$Asker$1$1 package mars.venus; synchronized class MessagesPane$Asker$1$1 implements Runnable { void MessagesPane$Asker$1$1(MessagesPane$Asker$1, javax.swing.event.DocumentEvent); public void run(); } SettingsHighlightingAction$2 package mars.venus; synchronized class SettingsHighlightingAction$2 extends javax.swing.JCheckBox { void SettingsHighlightingAction$2(SettingsHighlightingAction); protected void processMouseEvent(java.awt.event.MouseEvent); protected void processKeyEvent(java.awt.event.KeyEvent); } EditPane$2 package mars.venus; synchronized class EditPane$2 implements java.awt.event.ItemListener { void EditPane$2(EditPane); public void itemStateChanged(java.awt.event.ItemEvent); } SettingsEditorAction$EditorFontDialog$8 package mars.venus; synchronized class SettingsEditorAction$EditorFontDialog$8 implements javax.swing.event.ChangeListener { void SettingsEditorAction$EditorFontDialog$8(SettingsEditorAction$EditorFontDialog); public void stateChanged(javax.swing.event.ChangeEvent); } SettingsWarningsAreErrorsAction package mars.venus; public synchronized class SettingsWarningsAreErrorsAction extends GuiAction { public void SettingsWarningsAreErrorsAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI); public void actionPerformed(java.awt.event.ActionEvent); } MessagesPane$Asker package mars.venus; synchronized class MessagesPane$Asker implements Runnable { java.util.concurrent.ArrayBlockingQueue resultQueue; int initialPos; int maxLen; final javax.swing.event.DocumentListener listener; final javax.swing.text.NavigationFilter navigationFilter; final mars.simulator.Simulator$StopListener stopListener; void MessagesPane$Asker(MessagesPane, int); public void run(); void cleanup(); void returnResponse(); String response(); } MonoRightCellRenderer package mars.venus; synchronized class MonoRightCellRenderer extends javax.swing.table.DefaultTableCellRenderer { public static final java.awt.Font MONOSPACED_PLAIN_12POINT; static void ();
void MonoRightCellRenderer();
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable, Object, boolean, boolean, int, int);
}

GuiAction

package mars.venus;
public synchronized class GuiAction extends javax.swing.AbstractAction {
protected VenusUI mainUI;
protected void GuiAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

FileExitAction

package mars.venus;
public synchronized class FileExitAction extends GuiAction {
public void FileExitAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/FileExitAction.java
mars/venus/FileExitAction.java   package mars.venus;
   import mars.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the File -> Exit menu item
    */              
    public class FileExitAction extends GuiAction {
     
       public FileExitAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
    /**
         * Exit MARS, unless one or more files have unsaved edits and user cancels.
         */   
       public void actionPerformed(ActionEvent e){
            if (mainUI.editor.closeAll()) {
             System.exit(0);
             }
      }
   }   

mars/venus/EditSelectAllAction.java
mars/venus/EditSelectAllAction.java   package mars.venus;
   import mars.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the Edit -> Copy menu item
    */              
    public class EditSelectAllAction extends GuiAction {
     
       public EditSelectAllAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
          
       public void actionPerformed(ActionEvent e){
            mainUI.getMainPane().getEditPane().selectAllText();
      }
   }

SettingsAssembleAllAction

package mars.venus;
public synchronized class SettingsAssembleAllAction extends GuiAction {
public void SettingsAssembleAllAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

Coprocessor1Window$MyTippedJTable$1

package mars.venus;
synchronized class Coprocessor1Window$MyTippedJTable$1 extends javax.swing.table.JTableHeader {
void Coprocessor1Window$MyTippedJTable$1(Coprocessor1Window$MyTippedJTable, javax.swing.table.TableColumnModel);
public String getToolTipText(java.awt.event.MouseEvent);
}

FileDumpMemoryAction$DumpFormatComboBoxRenderer

package mars.venus;
synchronized class FileDumpMemoryAction$DumpFormatComboBoxRenderer extends javax.swing.plaf.basic.BasicComboBoxRenderer {
private javax.swing.JComboBox myMaster;
public void FileDumpMemoryAction$DumpFormatComboBoxRenderer(FileDumpMemoryAction, javax.swing.JComboBox);
public java.awt.Component getListCellRendererComponent(javax.swing.JList, Object, int, boolean, boolean);
}

mars/venus/HelpAboutAction.java
mars/venus/HelpAboutAction.java   package mars.venus;
   import mars.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the Help -> About menu item
    */              
    public class HelpAboutAction extends GuiAction {
       public  HelpAboutAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
          
       public void actionPerformed(ActionEvent e){
          JOptionPane.showMessageDialog(mainUI,
                          “MARS “+Globals.version+”    Copyright “+Globals.copyrightYears+”\n”+
                              Globals.copyrightHolders+”\n”+
                              “MARS is the Mips Assembler and Runtime Simulator.\n\n”+
                              “Mars image courtesy of NASA/JPL.\n”+
                              “Toolbar and menu icons are from:\n”+
                              ”  *  Tango Desktop Project (tango.freedesktop.org),\n”+
                              ”  *  glyFX (www.glyfx.com) Common Toolbar Set,\n”+
                              ”  *  KDE-Look (www.kde-look.org) crystalline-blue-0.1,\n”+
                              ”  *  Icon-King (www.icon-king.com) Nuvola 1.0.\n”+
                              “Print feature adapted from HardcopyWriter class in David Flanagan’s\n”+
                              “Java Examples in a Nutshell 3rd Edition, O’Reilly, ISBN 0-596-00620-9.”,
                              “About Mars”,
                              JOptionPane.INFORMATION_MESSAGE,
                              new ImageIcon(“images/RedMars50.gif”));
      }
   }

FileStatus

package mars.venus;
public synchronized class FileStatus {
public static final int NO_FILE = 0;
public static final int NEW_NOT_EDITED = 1;
public static final int NEW_EDITED = 2;
public static final int NOT_EDITED = 3;
public static final int EDITED = 4;
public static final int RUNNABLE = 5;
public static final int RUNNING = 6;
public static final int TERMINATED = 7;
public static final int OPENING = 8;
private static int systemStatus;
private static boolean systemAssembled;
private static boolean systemSaved;
private static boolean systemEdited;
private static String systemName;
private static java.io.File systemFile;
private int status;
private java.io.File file;
public static void set(int);
public static int get();
public static void setAssembled(boolean);
public static void setSaved(boolean);
public static void setEdited(boolean);
public static void setName(String);
public static void setFile(java.io.File);
public static java.io.File getFile();
public static String getName();
public static boolean isAssembled();
public static boolean isSaved();
public static boolean isEdited();
public static void reset();
public void FileStatus();
public void FileStatus(int, String);
public void setFileStatus(int);
public int getFileStatus();
public boolean isNew();
public boolean hasUnsavedEdits();
public void setPathname(String);
public void setPathname(String, String);
public String getPathname();
public String getFilename();
public String getParent();
public void updateStaticFileStatus();
}

SettingsHighlightingAction$ForegroundChanger

package mars.venus;
synchronized class SettingsHighlightingAction$ForegroundChanger implements java.awt.event.ActionListener {
private int position;
public void SettingsHighlightingAction$ForegroundChanger(SettingsHighlightingAction, int);
public void actionPerformed(java.awt.event.ActionEvent);
}

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

/*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

  /**
    *  Sets up a window to display Coprocessor 1 registers in the Registers pane of the UI.
     *   @author Pete Sanderson 2005
     **/
    
    public class Coprocessor1Window extends JPanel implements ActionListener, Observer { 
      private static JTable table;
      private static Register [] registers;
      private Object[][] tableData;
      private boolean highlighting;
      private int highlightRow;
      private ExecutePane executePane;
      private JCheckBox[] conditionFlagCheckBox;
      private static final int NAME_COLUMN = 0;
      private static final int FLOAT_COLUMN = 1;
      private static final int DOUBLE_COLUMN = 2;
        private static Settings settings;
   
   /**
     *  Constructor which sets up a fresh window with a table that contains the register values.
     **/
   
       public Coprocessor1Window() {
         Simulator.getInstance().addObserver(this);
           settings = Globals.getSettings();
         // Display registers in table contained in scroll pane.
         this.setLayout(new BorderLayout()); // table display will occupy entire width if widened
         table = new MyTippedJTable(new RegTableModel(setupWindow()));
         table.getColumnModel().getColumn(NAME_COLUMN).setPreferredWidth(20);
         table.getColumnModel().getColumn(FLOAT_COLUMN).setPreferredWidth(70);
         table.getColumnModel().getColumn(DOUBLE_COLUMN).setPreferredWidth(130);
        // 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(FLOAT_COLUMN).setCellRenderer(new RegisterCellRenderer(MonoRightCellRenderer.MONOSPACED_PLAIN_12POINT, SwingConstants.RIGHT));
         table.getColumnModel().getColumn(DOUBLE_COLUMN).setCellRenderer(new RegisterCellRenderer(MonoRightCellRenderer.MONOSPACED_PLAIN_12POINT, SwingConstants.RIGHT));
         this.add(new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
        // Display condition flags in panel below the registers
         JPanel flagsPane = new JPanel(new BorderLayout());
         flagsPane.setToolTipText(
                   “flags are used by certain floating point instructions, default flag is 0”);
         flagsPane.add(new JLabel(“Condition Flags”,JLabel.CENTER),BorderLayout.NORTH);
         int numFlags = Coprocessor1.getConditionFlagCount();
         conditionFlagCheckBox = new JCheckBox[numFlags];
         JPanel checksPane = new JPanel(new GridLayout(2,numFlags/2));
        // Tried to get interior of checkboxes to be white while its label and 
        // remaining background stays same background color.  Found example 
        // like the following on the web, but does not appear to have any 
        // affect.  Might be worth further study but for now I’ll just set
        // background to white.  I want white so the checkbox appears
        // “responsive” to user clicking on it (it is responsive anyway but looks
        // dead when drawn in gray.
        //Object saveBG = UIManager.getColor(“CheckBox.interiorBackground”);
        //UIManager.put(“CheckBox.interiorBackground”, Color.WHITE);
         for (int i=0; i < numFlags; i++) {             conditionFlagCheckBox[i] = new JCheckBox(Integer.toString(i));             conditionFlagCheckBox[i].addActionListener(this);             conditionFlagCheckBox[i].setBackground(Color.WHITE);             conditionFlagCheckBox[i].setToolTipText("checked == 1, unchecked == 0");             checksPane.add(conditionFlagCheckBox[i]);          }               //UIManager.put("CheckBox.interiorBackground", saveBG);           flagsPane.add(checksPane,BorderLayout.CENTER);          this.add(flagsPane, BorderLayout.SOUTH);       }             /** Called when user clicks on a condition flag checkbox.       * Updates both the display and the underlying Coprocessor 1 flag.       * @param e component that triggered this call       */        public void actionPerformed(ActionEvent e) {           JCheckBox checkBox = (JCheckBox)e.getSource();           int i = Integer.parseInt(checkBox.getText());          if(checkBox.isSelected()) {              checkBox.setSelected(true);             Coprocessor1.setConditionFlag(i);           }           else {              checkBox.setSelected(false);              Coprocessor1.clearConditionFlag(i);          }        }           /**       *  Sets up the data for the window.     *   @return The array object with the data for the window.     **/               public Object[][] setupWindow(){          registers = Coprocessor1.getRegisters();          this.highlighting = false;          tableData = new Object[registers.length][3];          for(int i=0; i< registers.length; i++){             tableData[i][0]= registers[i].getName();             tableData[i][1]= NumberDisplayBaseChooser.formatFloatNumber(registers[i].getValue(),NumberDisplayBaseChooser.getBase(settings.getDisplayValuesInHex()));//formatNumber(floatValue,NumberDisplayBaseChooser.getBase(settings.getDisplayValuesInHex()));             if (i%2 == 0) { // even numbered double registers                long longValue = 0;                try {                   longValue = Coprocessor1.getLongFromRegisterPair(registers[i].getName());                }                     catch (InvalidRegisterAccessException e) {} // cannot happen since i must be even                tableData[i][2]= NumberDisplayBaseChooser.formatDoubleNumber(longValue,NumberDisplayBaseChooser.getBase(settings.getDisplayValuesInHex()));             }              else {                tableData[i][2] = "";             }          }          return tableData;       }            /**      *  Reset and redisplay registers.      */        public void clearWindow() {          this.clearHighlighting();          Coprocessor1.resetRegisters();          this.updateRegisters(Globals.getGui().getMainPane().getExecutePane().getValueDisplayBase());          Coprocessor1.clearConditionFlags();          this.updateConditionFlagDisplay();       }          /**      * Clear highlight background color from any row 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()));          }       }                  /**      * Redisplay registers using current display number base (10 or 16)      */        public void updateRegisters() {          updateRegisters(Globals.getGui().getMainPane().getExecutePane().getValueDisplayBase());       }          /**      * Redisplay registers using specified display number base (10 or 16)      * @param base number base for display (10 or 16)      */             public void updateRegisters(int base) {          registers = Coprocessor1.getRegisters();          for(int i=0; i< registers.length; i++){             updateFloatRegisterValue(registers[i].getNumber(), registers[i].getValue(), base);             if (i%2 ==0) {                updateDoubleRegisterValue(i, base);             }          }          updateConditionFlagDisplay();       }             private void updateConditionFlagDisplay() {          for (int i=0; i Go menu item (and toolbar icon)
    */
    public class RunGoAction extends GuiAction  {
    
      public static int defaultMaxSteps = -1; // “forever”, formerly 10000000; // 10 million
      public static int maxSteps = defaultMaxSteps;  
      private String name;
      private ExecutePane executePane;
    
       public RunGoAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
         /**
          * Action to take when GO is selected — run the MIPS program!
          */
       public void actionPerformed(ActionEvent e) {
         name = this.getValue(Action.NAME).toString();
         executePane = mainUI.getMainPane().getExecutePane();
         if(FileStatus.isAssembled()){
               if (!mainUI.getStarted()) {
               processProgramArgumentsIfAny();  // DPS 17-July-2008
            }           
            if(mainUI.getReset()|| mainUI.getStarted()){
            
               mainUI.setStarted(true);  // added 8/27/05
                
               mainUI.messagesPane.postMarsMessage(
                       name+”: running “+FileStatus.getFile().getName()+”\n\n”);
               mainUI.getMessagesPane().selectRunMessageTab();
               executePane.getTextSegmentWindow().setCodeHighlighting(false);
               executePane.getTextSegmentWindow().unhighlightAllSteps();
                //FileStatus.set(FileStatus.RUNNING);
               mainUI.setMenuState(FileStatus.RUNNING);
               try {
                  int[] breakPoints = executePane.getTextSegmentWindow().getSortedBreakPointsArray();
                  boolean done = Globals.program.simulateFromPC(breakPoints,maxSteps,this);
               } 
                   catch (ProcessingException pe) {
                  }
            }            
            else{
               // This should never occur because at termination the Go and Step buttons are disabled.
               JOptionPane.showMessageDialog(mainUI,”reset “+mainUI.getReset()+” started “+mainUI.getStarted());//”You must reset before you can execute the program again.”);                 
            }
         }
         else{
            // note: this should never occur since “Go” is only enabled after successful assembly.
            JOptionPane.showMessageDialog(mainUI,”The program must be assembled before it can be run.”);
         }      
      }
      
    /**
     *  Method to be called when Pause is selected through menu/toolbar/shortcut.  This should only
     *  happen when MIPS program is running (FileStatus.RUNNING).  See VenusUI.java for enabled
     *  status of menu items based on FileStatus.  Set GUI as if at breakpoint or executing
     *  step by step.
     */
      
       public void paused(boolean done, int pauseReason, ProcessingException pe) {
        // I doubt this can happen (pause when execution finished), but if so treat it as stopped.
         if (done) {
            stopped(pe,Simulator.NORMAL_TERMINATION);
            return;
         }
         if (pauseReason == Simulator.BREAKPOINT) {
            mainUI.messagesPane.postMarsMessage(
                       name+”: execution paused at breakpoint: “+FileStatus.getFile().getName()+”\n\n”);
         } 
         else {
            mainUI.messagesPane.postMarsMessage(
                       name+”: execution paused by user: “+FileStatus.getFile().getName()+”\n\n”);          
         }
         mainUI.getMessagesPane().selectMarsMessageTab();
         executePane.getTextSegmentWindow().setCodeHighlighting(true);
         executePane.getTextSegmentWindow().highlightStepAtPC();
         executePane.getRegistersWindow().updateRegisters();
         executePane.getCoprocessor1Window().updateRegisters();
         executePane.getCoprocessor0Window().updateRegisters();
         executePane.getDataSegmentWindow().updateValues();
         FileStatus.set(FileStatus.RUNNABLE);
         mainUI.setReset(false);
      }
   
    /**
     *  Method to be called when Stop is selected through menu/toolbar/shortcut.  This should only
     *  happen when MIPS program is running (FileStatus.RUNNING).  See VenusUI.java for enabled
     *  status of menu items based on FileStatus.  Display finalized values as if execution
     *  terminated due to completion or exception.
     */       
      
       public void stopped(ProcessingException pe, int reason) {
         // show final register and data segment values.
         executePane.getRegistersWindow().updateRegisters();
         executePane.getCoprocessor1Window().updateRegisters();
         executePane.getCoprocessor0Window().updateRegisters();
         executePane.getDataSegmentWindow().updateValues();
         FileStatus.set(FileStatus.TERMINATED);
         SystemIO.resetFiles(); // close any files opened in MIPS program
        // Bring coprocessor 0 to the front if terminated due to exception.
         if (pe != null) {
            mainUI.getRegistersPane().setSelectedComponent(executePane.getCoprocessor0Window());
            executePane.getTextSegmentWindow().setCodeHighlighting(true);
            executePane.getTextSegmentWindow().unhighlightAllSteps();
            executePane.getTextSegmentWindow().highlightStepAtAddress(RegisterFile.getProgramCounter()-4);
         }
         switch (reason) {
            case Simulator.NORMAL_TERMINATION : 
               mainUI.getMessagesPane().postMarsMessage(
                             “\n”+name+”: execution completed successfully.\n\n”);
               mainUI.getMessagesPane().postRunMessage(
                             “\n– program is finished running –\n\n”);
               mainUI.getMessagesPane().selectRunMessageTab();
               break;
            case Simulator.CLIFF_TERMINATION : 
               mainUI.getMessagesPane().postMarsMessage(
                             “\n”+name+”: execution terminated by null instruction.\n\n”);
               mainUI.getMessagesPane().postRunMessage(
                             “\n– program is finished running (dropped off bottom) –\n\n”);
               mainUI.getMessagesPane().selectRunMessageTab();
               break;
            case Simulator.EXCEPTION :
               mainUI.getMessagesPane().postMarsMessage(
                                pe.errors().generateErrorReport());
               mainUI.getMessagesPane().postMarsMessage(
                                “\n”+name+”: execution terminated with errors.\n\n”);
               break;
            case Simulator.PAUSE_OR_STOP :
               mainUI.getMessagesPane().postMarsMessage(
                             “\n”+name+”: execution terminated by user.\n\n”);
               mainUI.getMessagesPane().selectMarsMessageTab();
               break;
            case Simulator.MAX_STEPS :
               mainUI.getMessagesPane().postMarsMessage(
                             “\n”+name+”: execution step limit of “+maxSteps+” exceeded.\n\n”);
               mainUI.getMessagesPane().selectMarsMessageTab();
               break;
            case Simulator.BREAKPOINT : // should never get here
               break;
         }
         RunGoAction.resetMaxSteps();
         mainUI.setReset(false);
      }
    
    /**
     * Reset max steps limit to default value at termination of a simulated execution.
     */
     
       public static void resetMaxSteps() {
         maxSteps = defaultMaxSteps;
      }
    
        ////////////////////////////////////////////////////////////////////////////////////
        // Method to store any program arguments into MIPS memory and registers before
        // execution begins. Arguments go into the gap between $sp and kernel memory.  
        // Argument pointers and count go into runtime stack and $sp is adjusted accordingly.
        // $a0 gets argument count (argc), $a1 gets stack address of first arg pointer (argv).
       private void processProgramArgumentsIfAny() {
         String programArguments = executePane.getTextSegmentWindow().getProgramArguments();
         if (programArguments == null || programArguments.length() == 0 ||
                !Globals.getSettings().getProgramArguments()) {
            return;
         }
            new ProgramArgumentList(programArguments).storeProgramArguments();
      }
        
    
   }

NumberDisplayBaseChooser

package mars.venus;
public synchronized class NumberDisplayBaseChooser extends javax.swing.JCheckBox {
public static final int DECIMAL = 10;
public static final int HEXADECIMAL = 16;
public static final int ASCII = 0;
private int base;
private javax.swing.JCheckBoxMenuItem settingMenuItem;
public void NumberDisplayBaseChooser(String, boolean);
public int getBase();
public void setBase(int);
public static String formatUnsignedInteger(int, int);
public static String formatNumber(int, int);
public static String formatNumber(float, int);
public static String formatNumber(double, int);
public String formatNumber(int);
public String formatUnsignedInteger(int);
public static String formatFloatNumber(int, int);
public static String formatDoubleNumber(long, int);
public void setSettingsMenuItem(javax.swing.JCheckBoxMenuItem);
public static int getBase(boolean);
}

EditFindReplaceAction

package mars.venus;
public synchronized class EditFindReplaceAction extends GuiAction {
private static String searchString;
private static boolean caseSensitivity;
private static final String DIALOG_TITLE = Find and Replace;
javax.swing.JDialog findReplaceDialog;
static void ();
public void EditFindReplaceAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/TextSegmentWindow.java
mars/venus/TextSegmentWindow.java   package mars.venus;
    
   import mars.*;
   import mars.mips.hardware.*;
   import mars.mips.instructions.*;
   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.util.*;   
   import javax.swing.table.*;
   import javax.swing.event.*;
    
    /*
Copyright (c) 2003-2007,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

  /**
    *  Creates the Text Segment window in the Execute tab of the UI
     *   @author Team JSpim
     **/  
     
    public class TextSegmentWindow extends JInternalFrame {
      private  JPanel programArgumentsPanel;  // DPS 17-July-2008
      private  JTextField programArgumentsTextField; // DPS 17-July-2008
      private static final int PROGRAM_ARGUMENT_TEXTFIELD_COLUMNS = 40;
      private  JTable table;
      private  JScrollPane tableScroller;
      private  Object[][] data;
    /* Maintain an int array of code addresses in parallel with ADDRESS_COLUMN,
     * to speed model-row -> text-address mapping.  Maintain a Hashtable of
     * (text-address, model-row) pairs to speed text-address -> model-row mapping.
     * The former is used for breakpoints and changing display base (e.g. base 10 
     * to 16); the latter is used for highlighting.  Both structures will remain
     * consistent once set up, since address column is not editable.
     */
      private  int[] intAddresses;      // index is table model row, value is text address
      private  Hashtable addressRows;   // key is text address, value is table model row
      private  Container contentPane;
      private  TextTableModel tableModel;
      private Font tableCellFont = new Font(“Monospaced”,Font.PLAIN,12);
      private  boolean codeHighlighting;
      private boolean breakpointsEnabled;  // Added 31 Dec 2009
      private int highlightAddress;
      private TableModelListener tableModelListener;
      private boolean inDelaySlot; // Added 25 June 2007
    
      private static String[] columnNames = {“Bkpt”, “Address”, “Code”, “Basic”, “Source”};
      private static final int BREAK_COLUMN = 0;
      private static final int ADDRESS_COLUMN = 1;
      private static final int CODE_COLUMN = 2;
      private static final int BASIC_COLUMN = 3;
      private static final int SOURCE_COLUMN = 4;
    
      private static final Font monospacedPlain12Point = new Font(“Monospaced”,Font.PLAIN,12); 
         
    /**
      *  Constructor, sets up a new JInternalFrame.
      **/
    
       public TextSegmentWindow(){
         super(“Text Segment”, true, false, true, true);
         contentPane = this.getContentPane();
         codeHighlighting = true;
         breakpointsEnabled = true;
         programArgumentsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
         programArgumentsPanel.add(new JLabel(“Program Arguments: “));
         programArgumentsTextField = new JTextField(PROGRAM_ARGUMENT_TEXTFIELD_COLUMNS);
         programArgumentsTextField.setToolTipText(“Arguments provided to program at runtime via $a0 (argc) and $a1 (argv)”);
         programArgumentsPanel.add(programArgumentsTextField);
      }
   
     
    /**
      *  Method to be called once the user compiles the program.  
      *  Should convert the lines of code over to the table rows and columns.
      **/
       public  void setupTable(){
         int addressBase = Globals.getGui().getMainPane().getExecutePane().getAddressDisplayBase();
         codeHighlighting = true;
         breakpointsEnabled = true;
         ArrayList sourceStatementList = Globals.program.getMachineList();
         data = new Object[sourceStatementList.size()][columnNames.length];
         intAddresses = new int[data.length];
         addressRows = new Hashtable(data.length);
        // Get highest source line number to determine #leading spaces so line numbers will vertically align
        // In multi-file situation, this will not necessarily be the last line b/c sourceStatementList contains
        // source lines from all files.  DPS 3-Oct-10
         int maxSourceLineNumber = 0;
         for (int i=sourceStatementList.size()-1; i>=0; i–) {
            ProgramStatement statement = (ProgramStatement) sourceStatementList.get(i);
            if (statement.getSourceLine() > maxSourceLineNumber) {
               maxSourceLineNumber = statement.getSourceLine();
            }
         }
         int sourceLineDigits = (“”+maxSourceLineNumber).length();
         int leadingSpaces = 0;
         int lastLine = -1;
         for (int i = 0; i < sourceStatementList.size(); i++) {             ProgramStatement statement = (ProgramStatement) sourceStatementList.get(i);             intAddresses[i] = statement.getAddress();             addressRows.put(new Integer(intAddresses[i]), new Integer(i));             data[i][BREAK_COLUMN] = Boolean.FALSE;             data[i][ADDRESS_COLUMN] = NumberDisplayBaseChooser.formatUnsignedInteger(statement.getAddress(), addressBase);             data[i][CODE_COLUMN] = NumberDisplayBaseChooser.formatNumber(statement.getBinaryStatement(), 16);             data[i][BASIC_COLUMN] = statement.getPrintableBasicAssemblyStatement();             String sourceString = "";             if (!statement.getSource().equals("")) {                leadingSpaces = sourceLineDigits - ("" + statement.getSourceLine()).length();                String lineNumber = "          ".substring(0, leadingSpaces)                   + statement.getSourceLine()+ ": ";                if (statement.getSourceLine()==lastLine)                   lineNumber="          ".substring(0, sourceLineDigits)+"  ";                sourceString = lineNumber                    + mars.util.EditorFont.substituteSpacesForTabs(statement.getSource());                     }             data[i][SOURCE_COLUMN] = sourceString;             lastLine=statement.getSourceLine();          }          contentPane.removeAll();          tableModel = new TextTableModel(data);          if (tableModelListener!=null) {             tableModel.addTableModelListener(tableModelListener);             tableModel.fireTableDataChanged();// initialize listener          }          table= new MyTippedJTable(tableModel);                // prevents cells in row from being highlighted when user clicks on breakpoint checkbox          table.setRowSelectionAllowed(false);                   table.getColumnModel().getColumn(BREAK_COLUMN).setMinWidth(40);           table.getColumnModel().getColumn(ADDRESS_COLUMN).setMinWidth(80);           table.getColumnModel().getColumn(CODE_COLUMN).setMinWidth(80);                   table.getColumnModel().getColumn(BREAK_COLUMN).setMaxWidth(50);           table.getColumnModel().getColumn(ADDRESS_COLUMN).setMaxWidth(90);           table.getColumnModel().getColumn(CODE_COLUMN).setMaxWidth(90);          table.getColumnModel().getColumn(BASIC_COLUMN).setMaxWidth(200);                        table.getColumnModel().getColumn(BREAK_COLUMN).setPreferredWidth(40);           table.getColumnModel().getColumn(ADDRESS_COLUMN).setPreferredWidth(80);           table.getColumnModel().getColumn(CODE_COLUMN).setPreferredWidth(80);          table.getColumnModel().getColumn(BASIC_COLUMN).setPreferredWidth(160);          table.getColumnModel().getColumn(SOURCE_COLUMN).setPreferredWidth(280);                   CodeCellRenderer codeStepHighlighter = new CodeCellRenderer();           table.getColumnModel().getColumn(BASIC_COLUMN).setCellRenderer(codeStepHighlighter);          table.getColumnModel().getColumn(SOURCE_COLUMN).setCellRenderer(codeStepHighlighter);         // to render String right-justified in mono font          table.getColumnModel().getColumn(ADDRESS_COLUMN).setCellRenderer(new MonoRightCellRenderer());          table.getColumnModel().getColumn(CODE_COLUMN).setCellRenderer(new MachineCodeCellRenderer());          table.getColumnModel().getColumn(BREAK_COLUMN).setCellRenderer(new CheckBoxTableCellRenderer());          reorderColumns(); // Re-order columns according to current preference...          // Add listener to catch column re-ordering for updating settings.          table.getColumnModel().addColumnModelListener(new MyTableColumnMovingListener());                 tableScroller = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,                           ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);          contentPane.add(tableScroller);          if (Globals.getSettings().getProgramArguments()) {             addProgramArgumentsPanel();            }           }          ////////////  Support for program arguments added DPS 17-July-2008 //////////////     /**      *  Get program arguments from text field in south border of text segment window.      *      *  @return String containing program arguments      */        public String getProgramArguments() {          return programArgumentsTextField.getText();       }             public void addProgramArgumentsPanel() {          // Don't add it if text segment window blank (file closed or no assemble yet)          if (contentPane != null && contentPane.getComponentCount() > 0) {
            contentPane.add(programArgumentsPanel, BorderLayout.NORTH);   
            contentPane.validate();  
         } 
      }
    
       public void removeProgramArgumentsPanel() {
         if (contentPane != null) {
            contentPane.remove(programArgumentsPanel);
            contentPane.validate();
         }
      }
    //
    ///////////////////////// end program arguments section  ////////////////////////
    
    /**
     * remove all components
     */
       public void clearWindow() {
         contentPane.removeAll();
      }
   
    
    /**
     * Assign listener to Table model.  Used for breakpoints, since that is the only editable
     * column in the table.  Since table model objects are transient (get a new one with each 
     * successful assemble), this method will simply keep the identity of the listener then
     * add it as a listener each time a new table model object is created.  Limit 1 listener.
     */
       public void registerTableModelListener(TableModelListener tml) {
         tableModelListener = tml;
      } 
    
        /**
     *  Redisplay the addresses.  This should only be done when address display base is
     *  modified (e.g. between base 16 hex and base 10 dec).
     */
       public void updateCodeAddresses() {
         if (contentPane.getComponentCount() == 0) 
            return; // ignore if no content to change
         int addressBase = Globals.getGui().getMainPane().getExecutePane().getAddressDisplayBase();
         int address;
         String formattedAddress;
         for (int i=0; i=0 && thisDistance < shortDistance) {             shortDistance = thisDistance;             desiredComboBoxIndex = EXTERN_BASE_ADDRESS_INDEX;          }         // Check distance from global pointer; can be either side of it...          thisDistance = Math.abs(address - RegisterFile.getValue(RegisterFile.GLOBAL_POINTER_REGISTER)); // distance from global pointer          if (thisDistance < shortDistance) {             shortDistance = thisDistance;             desiredComboBoxIndex = GLOBAL_POINTER_ADDRESS_INDEX;          }         // Check distance from .data base.  Cannot be below it          thisDistance = address - Memory.dataBaseAddress;          if (thisDistance >=0 && thisDistance < shortDistance) {             shortDistance = thisDistance;             desiredComboBoxIndex = DATA_BASE_ADDRESS_INDEX;          }         // Check distance from heap base.  Cannot be below it          thisDistance = address - Memory.heapBaseAddress;          if (thisDistance >=0 && thisDistance < shortDistance) {             shortDistance = thisDistance;             desiredComboBoxIndex = HEAP_BASE_ADDRESS_INDEX;          }                   // Check distance from stack pointer.  Can be on either side of it...          thisDistance = Math.abs(address - RegisterFile.getValue(RegisterFile.STACK_POINTER_REGISTER));          if (thisDistance < shortDistance) {             shortDistance = thisDistance;             desiredComboBoxIndex = STACK_POINTER_BASE_ADDRESS_INDEX;          }                   /*          if (address >= Memory.externBaseAddress) {
            if (address < Memory.globalPointer) {                desiredComboBoxIndex = EXTERN_BASE_ADDRESS_INDEX;             }             else if (address < Memory.dataBaseAddress) {                desiredComboBoxIndex = GLOBAL_POINTER_ADDRESS_INDEX;             }              else if (address < Memory.heapBaseAddress) {                desiredComboBoxIndex = DATA_BASE_ADDRESS_INDEX;             }              else if (Math.abs(address-Memory.heapBaseAddress) < Math.abs(address-Memory.stackPointer)) {                desiredComboBoxIndex = HEAP_BASE_ADDRESS_INDEX;             }              else {                desiredComboBoxIndex = STACK_POINTER_BASE_ADDRESS_INDEX;             }          }           else if (Memory.inKernelDataSegment(address)) {             desiredComboBoxIndex = KERNEL_DATA_BASE_ADDRESS_INDEX;          }           else if (Memory.inMemoryMapSegment(address)) {             desiredComboBoxIndex = MMIO_BASE_ADDRESS_INDEX;          }         */          return desiredComboBoxIndex;       }              ////////////////////////////////////////////////////////////////////////////////     //  Generates the Address/Data part of the Data Segment window.     //   Returns the JScrollPane for the Address/Data part of the Data Segment window.        private JScrollPane generateDataPanel(){          dataData = new Object[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];          int valueBase = Globals.getGui().getMainPane().getExecutePane().getValueDisplayBase();          int addressBase = Globals.getGui().getMainPane().getExecutePane().getAddressDisplayBase();          int address = this.homeAddress;          for(int row=0; row=0.  DPS 23 jan 2009
         addressColumn = -1; 
      }
   
       
       private int getValueDisplayFormat() {
         return (asciiDisplay) ? NumberDisplayBaseChooser.ASCII : 
            Globals.getGui().getMainPane().getExecutePane().getValueDisplayBase();
      }
    
    /**
     * Update table model with contents of new memory “chunk”.  Mars supports megabytes of
     * data segment space so we only plug a “chunk” at a time into the table.
     * @param firstAddr the first address in the memory range to be placed in the model.
     */
     
       public void updateModelForMemoryRange(int firstAddr) {
         if (tablePanel.getComponentCount() == 0) 
            return; // ignore if no content to change
         int valueBase = getValueDisplayFormat();
         int addressBase = Globals.getGui().getMainPane().getExecutePane().getAddressDisplayBase();
         int address = firstAddr;
         TableModel dataModel = dataTable.getModel();
         for (int row=0; row=MEMORY_CHUNK_SIZE) { // out of range
            return;
         }
         int row = offset/BYTES_PER_ROW;
         int column = (offset % BYTES_PER_ROW)/BYTES_PER_VALUE + 1; // column 0 reserved for address
         int valueBase = Globals.getGui().getMainPane().getExecutePane().getValueDisplayBase();
         ((DataTableModel)dataTable.getModel()).setDisplayAndModelValueAt(NumberDisplayBaseChooser.formatNumber(value, valueBase),
                    row,column);
      }
    
    /**
     *  Redisplay the addresses.  This should only be done when address display base is
     *  modified (e.g. between base 16, hex, and base 10, dec).
     */
       public void updateDataAddresses() {
         if (tablePanel.getComponentCount() == 0) 
            return; // ignore if no content to change
         int addressBase = Globals.getGui().getMainPane().getExecutePane().getAddressDisplayBase();
         int address = this.firstAddress;
         String formattedAddress;
         for(int i=0; i= highLimit – MEMORY_CHUNK_SIZE) {
            lowAddress = highLimit – MEMORY_CHUNK_SIZE + 1;
            nextButton.setEnabled(false);
         } 
         else {
            nextButton.setEnabled(true);
         }
         return lowAddress;
      }
   
    
        /** 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 delegate of the Memory object, which lets us know of memory operations
     * The Simulator keeps us informed of when simulated MIPS execution is active.
     * This is the only time we care about memory 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) {
                  Memory.getInstance().addObserver(this);
                  addressHighlighting = true;
               }
            } 
            else {
               // Simulated MIPS execution stops.  Stop responding.
               Memory.getInstance().deleteObserver(this);
            }
         } 
         else if (obj instanceof MemoryAccessNotice) { 
            // NOTE: observable != Memory.getInstance() because Memory class delegates notification duty.
            MemoryAccessNotice access = (MemoryAccessNotice) obj;
            if (access.getAccessType()==AccessNotice.WRITE) {
               int address = access.getAddress();
                // Use the same highlighting technique as for Text Segment — see
                // AddressCellRenderer class below.
               this.highlightCellForAddress(address);
            }
         }
      }
    
    
   ///////////////////////////////////////////////////////////////////////////////     
   // Class defined to address apparent Javax.swing.JComboBox bug: when selection is
   // is set programmatically using setSelectedIndex() rather than by user-initiated 
   // event (such as mouse click), the text displayed in the JComboBox is not always 
   // updated correctly. Sometimes it is, sometimes updated to incorrect value.  
   // No pattern that I can detect.  Google search yielded many forums addressing
   // this problem. One suggested solution, a JComboBox superclass overriding 
   // setSelectedIndex to also call selectedItemChanged() did not help.  Only this 
   // solution to extend the model class to call the protected 
   // “fireContentsChanged()” method worked. DPS 25-Jan-2009
       private class CustomComboBoxModel extends DefaultComboBoxModel {
          public CustomComboBoxModel(Object[] list) {
            super(list);
         }
          private void forceComboBoxUpdate(int index) {
            super.fireContentsChanged(this,index,index);
         }
      }
      
    
    
    ////////////////////////////////////////////////////////////////////////
    // Class representing memory data table data
    
       class DataTableModel extends AbstractTableModel {
         String[] columnNames;
         Object[][] data;         
        
          public DataTableModel(Object[][] d, String [] n){
            data=d;
            columnNames= n;
         }
      
          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];
         }
      
        /*
         * The cells in the Address column are not editable.  
        * Value cells are editable except when displayed 
        * in ASCII view – don’t want to give the impression
        * that ASCII text can be entered directly because
        * it can’t.  It is possible but not worth the
        * effort to implement.
         */
          public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col != ADDRESS_COLUMN && !asciiDisplay) { 
               return true;
            } 
            else {
               return false;
            }
         }
      
      
      
        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  
         */
          public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
         }
      
      
        /*
         * 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 memory is updated.
         */
          public void setValueAt(Object value, int row, int col) {
            int val=0;
            int address=0;
            try {
               val = Binary.stringToInt((String) value);
            }
                catch (NumberFormatException nfe) {
                  data[row][col] = “INVALID”;
                  fireTableCellUpdated(row, col);
                  return;
               }
         
               // calculate address from row and column
            try {
               address = Binary.stringToInt((String)data[row][ADDRESS_COLUMN]) + (col-1)*BYTES_PER_VALUE;  // KENV 1/6/05
            }
                catch (NumberFormatException nfe) {
                  //  can’t really happen since memory addresses are completely under
                  // the control of my software.
               }
            //  Assures that if changed during MIPS program execution, the update will
            //  occur only between MIPS instructions.
            synchronized (Globals.memoryAndRegistersLock) {
               try {
                  Globals.memory.setRawWord(address,val);
               } 
                // somehow, user was able to display out-of-range address.  Most likely to occur between
                // stack base and Kernel.
                   catch (AddressErrorException aee) {
                     val = 0;
                  }
            }// end synchronized block
            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 memory.
         */
          private void setDisplayAndModelValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
         }
      
          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("--------------------------");          }       }                   // Special renderer capable of highlighting cells by changing background color.     // Will set background to highlight color if certain conditions met.             class AddressCellRenderer extends DefaultTableCellRenderer {                    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.setHorizontalAlignment(SwingConstants.RIGHT);             int rowFirstAddress = Binary.stringToInt(table.getValueAt(row,ADDRESS_COLUMN).toString());             if (settings.getDataSegmentHighlighting() && addressHighlighting  && rowFirstAddress==addressRowFirstAddress && column==addressColumn) {                cell.setBackground( settings.getColorSettingByPosition(Settings.DATASEGMENT_HIGHLIGHT_BACKGROUND) );                cell.setForeground( settings.getColorSettingByPosition(Settings.DATASEGMENT_HIGHLIGHT_FOREGROUND) );                cell.setFont( settings.getFontByPosition(Settings.DATASEGMENT_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;          }                }        ///////////////////////////////////////////////////////////////////      //      // JTable subclass to provide custom tool tips for each of the      // text table column headers. From Sun's JTable tutorial.      // http://java.sun.com/docs/books/tutorial/uiswing/components/table.html      //        private class MyTippedJTable extends JTable {           MyTippedJTable(DataTableModel m) {             super(m);          }                           private String[] columnToolTips = {                /* address  */ "Base MIPS memory address for this row of the table.",                /* value +0 */ "32-bit value stored at base address for its row.",                 /* value +n */ "32-bit value stored ",                 /* value +n */ " bytes beyond base address for its row."                };                        //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 (realIndex < 2) ?  columnToolTips[realIndex]                                         : columnToolTips[2]+((realIndex-1)*4)+columnToolTips[3];                   }                };          }       }          ///////////////////////////////////////////////////////////////////////     //     //  The Prev button (left arrow) scrolls downward through the     //  selected address range.  It is a RepeatButton, which means     //  if the mouse is held down on the button, it will repeatedly     //  fire after an initial delay.  Allows rapid scrolling.     //  DPS 20 July 2008        private class PrevButton extends RepeatButton {           public PrevButton(Icon ico) {             super(ico);             this.setInitialDelay(500);  // 500 milliseconds hold-down before firing             this.setDelay(60);          // every 60 milliseconds after that             this.addActionListener(this);          }         // This one will respond when either timer goes off or button lifted.           public void actionPerformed(ActionEvent ae) {             firstAddress -= PREV_NEXT_CHUNK_SIZE;             firstAddress = setFirstAddressAndPrevNextButtonEnableStatus(firstAddress);             updateModelForMemoryRange(firstAddress);          }       }//////////////////////////////////////////////////////////////////////          ///////////////////////////////////////////////////////////////////////     //     //  The Next button (right arrow) scrolls upward through the     //  selected address range.  It is a RepeatButton, which means     //  if the mouse is held down on the button, it will repeatedly     //  fire after an initial delay.  Allows rapid scrolling.     //  DPS 20 July 2008                private class NextButton extends RepeatButton {           public NextButton(Icon ico) {             super(ico);             this.setInitialDelay(500);  // 500 milliseconds hold-down before firing             this.setDelay(60);          // every 60 milliseconds after that             this.addActionListener(this);          }         // This one will respond when either timer goes off or button lifted.           public void actionPerformed(ActionEvent ae) {             firstAddress += PREV_NEXT_CHUNK_SIZE;             firstAddress = setFirstAddressAndPrevNextButtonEnableStatus(firstAddress);             updateModelForMemoryRange(firstAddress);          }       }//////////////////////////////////////////////////////////////////////         } SettingsHighlightingAction$DefaultChanger package mars.venus; synchronized class SettingsHighlightingAction$DefaultChanger implements java.awt.event.ItemListener { private int position; public void SettingsHighlightingAction$DefaultChanger(SettingsHighlightingAction, int); public void itemStateChanged(java.awt.event.ItemEvent); } mars/venus/RunAssembleAction.java mars/venus/RunAssembleAction.java   package mars.venus;    import mars.*;    import mars.util.*;    import mars.mips.hardware.*;    import java.util.*;    import java.io.*;    import java.awt.*;    import java.awt.event.*;    import javax.swing.*;    /* Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */      /**     * Action class for the Run -> Assemble menu item (and toolbar icon)
    */
    public class RunAssembleAction extends GuiAction {
     
      private static ArrayList MIPSprogramsToAssemble;
      private static boolean extendedAssemblerEnabled;
      private static boolean warningsAreErrors;
    // Threshold for adding filename to printed message of files being assembled.
      private static final int LINE_LENGTH_LIMIT = 60;
     
       public RunAssembleAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
       
   // These are both used by RunResetAction to re-assemble under identical conditions.
       static ArrayList getMIPSprogramsToAssemble() {
         return MIPSprogramsToAssemble;
      }
       static boolean getExtendedAssemblerEnabled() {
         return extendedAssemblerEnabled;
      }
    
       static boolean getWarningsAreErrors() {
         return warningsAreErrors;
      }
        
       public void actionPerformed(ActionEvent e) {
         String name = this.getValue(Action.NAME).toString();
         Component editPane = mainUI.getMainPane().getEditPane();
         ExecutePane executePane = mainUI.getMainPane().getExecutePane();
         RegistersPane registersPane = mainUI.getRegistersPane();
         extendedAssemblerEnabled = Globals.getSettings().getExtendedAssemblerEnabled();
         warningsAreErrors = Globals.getSettings().getWarningsAreErrors();
         if(FileStatus.getFile()!= null){  
            if (FileStatus.get() == FileStatus.EDITED) {
               mainUI.editor.save();
            }
            try{
               Globals.program = new MIPSprogram();
               ArrayList filesToAssemble;
               if (Globals.getSettings().getAssembleAllEnabled()) {// setting calls for multiple file assembly 
                  filesToAssemble = FilenameFinder.getFilenameList(
                               new File(FileStatus.getName()).getParent(), Globals.fileExtensions);
               } 
               else {
                  filesToAssemble = new ArrayList();
                  filesToAssemble.add(FileStatus.getName());  
               }
               String exceptionHandler = null;
               if (Globals.getSettings().getExceptionHandlerEnabled() &&
                   Globals.getSettings().getExceptionHandler() != null &&
                   Globals.getSettings().getExceptionHandler().length() > 0) {
                  exceptionHandler = Globals.getSettings().getExceptionHandler();
               }
               MIPSprogramsToAssemble = Globals.program.prepareFilesForAssembly(filesToAssemble, FileStatus.getFile().getPath(), exceptionHandler);                 
               mainUI.messagesPane.postMarsMessage(buildFileNameList(name+”: assembling “, MIPSprogramsToAssemble));
               // added logic to receive any warnings and output them…. DPS 11/28/06
               ErrorList warnings = Globals.program.assemble(MIPSprogramsToAssemble, extendedAssemblerEnabled,
                                                             warningsAreErrors);
               if (warnings.warningsOccurred()) {
                  mainUI.messagesPane.postMarsMessage(warnings.generateWarningReport());
               }
               mainUI.messagesPane.postMarsMessage(
                          name+”: operation completed successfully.\n\n”);
               FileStatus.setAssembled(true);
               FileStatus.set(FileStatus.RUNNABLE);
               RegisterFile.resetRegisters();
               Coprocessor1.resetRegisters();
               Coprocessor0.resetRegisters();
               executePane.getTextSegmentWindow().setupTable();
               executePane.getDataSegmentWindow().setupTable();
               executePane.getDataSegmentWindow().highlightCellForAddress(Memory.dataBaseAddress); 
               executePane.getDataSegmentWindow().clearHighlighting();
               executePane.getLabelsWindow().setupTable();
               executePane.getTextSegmentWindow().setCodeHighlighting(true);
               executePane.getTextSegmentWindow().highlightStepAtPC();
               registersPane.getRegistersWindow().clearWindow();
               registersPane.getCoprocessor1Window().clearWindow();
               registersPane.getCoprocessor0Window().clearWindow();
               mainUI.setReset(true);
               mainUI.setStarted(false);
               mainUI.getMainPane().setSelectedComponent(executePane);
                
            // Aug. 24, 2005 Ken Vollmar
               SystemIO.resetFiles( );  // Ensure that I/O “file descriptors” are initialized for a new program run
            
            }
                catch (ProcessingException pe) {
                  String errorReport = pe.errors().generateErrorAndWarningReport();
                  mainUI.messagesPane.postMarsMessage(errorReport);
                  mainUI.messagesPane.postMarsMessage(
                             name+”: operation completed with errors.\n\n”);
                  // Select editor line containing first error, and corresponding error message.
                  ArrayList errorMessages = pe.errors().getErrorMessages();
                  for (int i=0; i LINE_LENGTH_LIMIT) {
               result += “\n”;
               lineLength = 0;
            }
         }
         return result + ((lineLength==0)?””:”\n”) + “\n”;
      }
   }        

Coprocessor1Window$MyTippedJTable

package mars.venus;
synchronized class Coprocessor1Window$MyTippedJTable extends javax.swing.JTable {
private String[] regToolTips;
private String[] columnToolTips;
void Coprocessor1Window$MyTippedJTable(Coprocessor1Window, Coprocessor1Window$RegTableModel);
public String getToolTipText(java.awt.event.MouseEvent);
protected javax.swing.table.JTableHeader createDefaultTableHeader();
}

mars/venus/FileNewAction.java
mars/venus/FileNewAction.java   package mars.venus;
   import mars.mips.hardware.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the File -> New menu item
    */              
    public class FileNewAction extends GuiAction {
     
       public FileNewAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
    
    /**
     * Code to create a new document.  It clears the source code window.
     *
     * @param e component triggering this call
     */
       public void actionPerformed(ActionEvent e) {
           mainUI.editor.newFile();
      }
   }
    

EditFindReplaceAction$FindReplaceDialog$4

package mars.venus;
synchronized class EditFindReplaceAction$FindReplaceDialog$4 implements java.awt.event.ActionListener {
void EditFindReplaceAction$FindReplaceDialog$4(EditFindReplaceAction$FindReplaceDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

FileCloseAction

package mars.venus;
public synchronized class FileCloseAction extends GuiAction {
public void FileCloseAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

AbstractFontSettingDialog$ComboBoxRenderer

package mars.venus;
synchronized class AbstractFontSettingDialog$ComboBoxRenderer extends javax.swing.JLabel implements javax.swing.ListCellRenderer {
javax.swing.JSeparator separator;
public void AbstractFontSettingDialog$ComboBoxRenderer(AbstractFontSettingDialog);
public java.awt.Component getListCellRendererComponent(javax.swing.JList, Object, int, boolean, boolean);
}

mars/venus/SettingsStartAtMainAction.java
mars/venus/SettingsStartAtMainAction.java   package mars.venus;
   import mars.simulator.*;
    import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item to control whether or not
     * assembler warnings are considered errors.  If so, a program generating
     * warnings but not errors will not assemble.
    */
    public class SettingsStartAtMainAction extends GuiAction  {
    
   
       public SettingsStartAtMainAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
           Globals.getSettings().setStartAtMain(((JCheckBoxMenuItem)e.getSource()).isSelected());
      }
        
   }

SettingsEditorAction$EditorFontDialog$ForegroundChanger

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog$ForegroundChanger implements java.awt.event.ActionListener {
private int row;
public void SettingsEditorAction$EditorFontDialog$ForegroundChanger(SettingsEditorAction$EditorFontDialog, int);
public void actionPerformed(java.awt.event.ActionEvent);
}

RunStepAction

package mars.venus;
public synchronized class RunStepAction extends GuiAction {
String name;
ExecutePane executePane;
public void RunStepAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
public void stepped(boolean, int, mars.ProcessingException);
private void processProgramArgumentsIfAny();
}

SettingsEditorAction$EditorFontDialog$BoldItalicChanger

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog$BoldItalicChanger implements java.awt.event.ActionListener {
private int row;
public void SettingsEditorAction$EditorFontDialog$BoldItalicChanger(SettingsEditorAction$EditorFontDialog, int);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/EditRedoAction.java
mars/venus/EditRedoAction.java   package mars.venus;
   import mars.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.undo.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the Edit -> Redo menu item
    */              
    public class EditRedoAction extends GuiAction {
     
       public EditRedoAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
         setEnabled(false);
      }
      /**
       * Adapted from TextComponentDemo.java in the
       * Java Tutorial “Text Component Features”
        */
       public void actionPerformed(ActionEvent e) {
         EditPane editPane = mainUI.getMainPane().getEditPane();
         if (editPane != null) {
            editPane.redo();
            updateRedoState();
            mainUI.editUndoAction.updateUndoState();
         }
      }
   
       void updateRedoState() {
         EditPane editPane = mainUI.getMainPane().getEditPane();
         setEnabled(editPane != null && editPane.getUndoManager().canRedo());
      }
   }
    

VenusUI$2

package mars.venus;
synchronized class VenusUI$2 extends java.awt.event.WindowAdapter {
void VenusUI$2(VenusUI);
public void windowClosing(java.awt.event.WindowEvent);
}

SettingsHighlightingAction$4

package mars.venus;
synchronized class SettingsHighlightingAction$4 implements java.awt.event.ActionListener {
void SettingsHighlightingAction$4(SettingsHighlightingAction);
public void actionPerformed(java.awt.event.ActionEvent);
}

PopupListener

package mars.venus;
public synchronized class PopupListener extends java.awt.event.MouseAdapter {
private javax.swing.JPopupMenu popup;
public void PopupListener(javax.swing.JPopupMenu);
public void mousePressed(java.awt.event.MouseEvent);
public void mouseReleased(java.awt.event.MouseEvent);
private void maybeShowPopup(java.awt.event.MouseEvent);
}

DataSegmentWindow$8

package mars.venus;
synchronized class DataSegmentWindow$8 implements java.awt.event.ActionListener {
void DataSegmentWindow$8(DataSegmentWindow);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/EditTabbedPane.java
mars/venus/EditTabbedPane.java   package mars.venus;
   import mars.mips.hardware.*;
   import mars.util.*;
   import mars.*;
   import javax.swing.*;
   import javax.swing.event.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.undo.*;
   import java.text.*;
   import java.util.*;
   import java.io.*;
   import java.beans.PropertyChangeListener;
   import javax.swing.filechooser.FileFilter;
        
    /*
Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

    /**
      *  Tabbed pane for the editor.  Each of its tabs represents an open file.
      *   @author Sanderson
      **/

    public class EditTabbedPane extends JTabbedPane{
      EditPane editTab;
      MainPane mainPane;
    
      private VenusUI mainUI;
      private Editor editor;
      private FileOpener fileOpener;
   
    /**
      *  Constructor for the EditTabbedPane class. 
    **/
    
       public EditTabbedPane(VenusUI appFrame, Editor editor, MainPane mainPane){
         super();
         this.mainUI = appFrame;
         this.editor = editor;
         this.fileOpener = new FileOpener(editor);
         this.mainPane = mainPane;
         this.editor.setEditTabbedPane(this);
         this.addChangeListener(
                new ChangeListener() {
                   public void stateChanged(ChangeEvent e) {
                     EditPane editPane = (EditPane) getSelectedComponent();
                     if (editPane != null) {
                        // New IF statement to permit free traversal of edit panes w/o invalidating
                        // assembly if assemble-all is selected.  DPS 9-Aug-2011
                        if (Globals.getSettings().getBooleanSetting(mars.Settings.ASSEMBLE_ALL_ENABLED)) { 
                           EditTabbedPane.this.updateTitles(editPane); 
                        } 
                        else {
                           EditTabbedPane.this.updateTitlesAndMenuState(editPane); 
                           EditTabbedPane.this.mainPane.getExecutePane().clearPane();
                        }
                        editPane.tellEditingComponentToRequestFocusInWindow();
                     }
                  }
               });  
      }
    
    /**
     * The current EditPane representing a file.  Returns null if
     * no files open.
     *
     * @return the current editor pane
     */
       public EditPane getCurrentEditTab() {
         return (EditPane)this.getSelectedComponent();
      }
   
      /**
     * Select the specified EditPane to be the current tab.
     *
     * @param editPane The EditPane tab to become current.
     */     
       public void setCurrentEditTab(EditPane editPane) {
         this.setSelectedComponent(editPane);
      }
   
     /**
      *  If the given file is open in the tabbed pane, make it the
    *  current tab.  If not opened, open it in a new tab and make
    *  it the current tab.  If file is unable to be opened, 
    *  leave current tab as is.
    *  @param file File object for the desired file.
    *  @return EditPane for the specified file, or null if file is unable to be opened in an EditPane
    */
       public EditPane getCurrentEditTabForFile(File file) {
         EditPane result = null;
         EditPane tab = getEditPaneForFile(file.getPath());
         if (tab != null) {
            if (tab != getCurrentEditTab()) {
               setCurrentEditTab(tab);
            }
            return tab;         
         }
        // If no return yet, then file is not open.  Try to open it.
         if (openFile(file)) {
            result = getCurrentEditTab();
         }
         return result;
      } 
    
   /**
    *  Carries out all necessary operations to implement
    *  the New operation from the File menu.
    */  
       public void newFile() {
         EditPane editPane = new EditPane(this.mainUI);
         editPane.setSourceCode(“”, true);
         editPane.setShowLineNumbersEnabled(true);
         editPane.setFileStatus(FileStatus.NEW_NOT_EDITED);
         String name = editor.getNextDefaultFilename();
         editPane.setPathname(name);
         this.addTab(name, editPane);
        
         FileStatus.reset();
         FileStatus.setName(name);
         FileStatus.set(FileStatus.NEW_NOT_EDITED);
      
         RegisterFile.resetRegisters(); 
         mainUI.setReset(true);
         mainPane.getExecutePane().clearPane();
         mainPane.setSelectedComponent(this);
         editPane.displayCaretPosition(new Point(1,1));
         this.setSelectedComponent(editPane);
         updateTitlesAndMenuState(editPane);
         editPane.tellEditingComponentToRequestFocusInWindow();
      }
    
    
   /**
    *  Carries out all necessary operations to implement
    *  the Open operation from the File menu.  This
    *  begins with an Open File dialog.
    *  @return true if file was opened, false otherwise.
    */      
       public boolean openFile() {
         return fileOpener.openFile();
      }
   
    /**
     * Carries out all necessary operations to open the
     * specified file in the editor.
     *  @return true if file was opened, false otherwise.
     */
       public boolean openFile(File file) {
         return fileOpener.openFile(file);
      }
   
    
   /**
    *  Carries out all necessary operations to implement
    *  the Close operation from the File menu.  May return
    *  false, for instance when file has unsaved changes
    *  and user selects Cancel from the warning dialog.
    *  @return true if file was closed, false otherwise.
    */
       public boolean closeCurrentFile() {
         EditPane editPane = getCurrentEditTab();
         if (editPane != null) {
            if (editsSavedOrAbandoned()) {
               this.remove(editPane);
               mainPane.getExecutePane().clearPane();
               mainPane.setSelectedComponent(this);
            } 
            else {
               return false;
            }
         } 
         return true;
      }
        
   /**
    *  Carries out all necessary operations to implement
    *  the Close All operation from the File menu.
    *  @return true if files closed, false otherwise.
    */      
       public boolean closeAllFiles() {
         boolean result = true;
         boolean unsavedChanges = false;
         int tabCount = getTabCount();
         if (tabCount > 0) {
            mainPane.getExecutePane().clearPane();
            mainPane.setSelectedComponent(this);
            EditPane[] tabs = new EditPane[tabCount];
            for (int i=0; i < tabCount; i++) {                tabs[i] = (EditPane)getComponentAt(i);                if ( tabs[i].hasUnsavedEdits() ) {                   unsavedChanges = true;                }             }             if (unsavedChanges) {                switch (confirm("one or more files")) {                   case JOptionPane.YES_OPTION :                      boolean removedAll = true;                      for (int i=0; i < tabCount; i++) {                         if ( tabs[i].hasUnsavedEdits() ) {                            setSelectedComponent(tabs[i]);                            boolean saved = saveCurrentFile();                            if (saved) {                               this.remove(tabs[i]);                            }                             else {                               removedAll = false;                            }                         }                          else {                            this.remove(tabs[i]);                         }                      }                      return removedAll;                   case JOptionPane.NO_OPTION :                      for (int i=0; i < tabCount; i++) {                          this.remove(tabs[i]);                       }                      return true;                   case JOptionPane.CANCEL_OPTION :                      return false;                   default : // should never occur                      return false;                }             }              else {                for (int i=0; i < tabCount; i++) {                    this.remove(tabs[i]);                 }                 }          }          return result;       }          /**      * Saves file under existing name.  If no name, will invoke Save As.       * @return true if the file was actually saved.      */             public boolean saveCurrentFile() {          EditPane editPane = getCurrentEditTab();          if (saveFile(editPane)) {             FileStatus.setSaved(true);             FileStatus.setEdited(false);             FileStatus.set(FileStatus.NOT_EDITED);             editPane.setFileStatus(FileStatus.NOT_EDITED);             updateTitlesAndMenuState(editPane);             return true;          }          return false;       }            // Save file associatd with specified edit pane.      // Returns true if save operation worked, else false.        private boolean saveFile(EditPane editPane) {          if (editPane != null) {             if (editPane.isNew()) {                File theFile = saveAsFile(editPane);                if (theFile != null) {                   editPane.setPathname(theFile.getPath());                }                return (theFile != null);             }             File theFile = new File(editPane.getPathname());             try {                BufferedWriter outFileStream = new BufferedWriter(new FileWriter(theFile));                          outFileStream.write(editPane.getSource(), 0, editPane.getSource().length());                outFileStream.close();             }                  catch(java.io.IOException c) {                   JOptionPane.showMessageDialog(null,"Save operation could not be completed due to an error:\n"+c,                      "Save Operation Failed", JOptionPane.ERROR_MESSAGE);                   return false;                }             return true;          }          return false;       }                    /**      * Pops up a dialog box to do "Save As" operation.  If necessary      * an additional overwrite dialog is performed.      * @return true if the file was actually saved.      */        public boolean saveAsCurrentFile() {          EditPane editPane = getCurrentEditTab();          File theFile = saveAsFile(editPane);          if (theFile != null) {             FileStatus.setFile(theFile);             FileStatus.setName(theFile.getPath());             FileStatus.setSaved(true);             FileStatus.setEdited(false);             FileStatus.set(FileStatus.NOT_EDITED);             editor.setCurrentSaveDirectory(theFile.getParent());             editPane.setPathname(theFile.getPath());             editPane.setFileStatus(FileStatus.NOT_EDITED);             updateTitlesAndMenuState(editPane);             return true;           }           return false;            }           // perform Save As for selected edit pane.  If the save is performed,     // return its File object.  Otherwise return null.        private File saveAsFile(EditPane editPane) {          File theFile = null;          if (editPane != null) {             JFileChooser saveDialog = null;             boolean operationOK = false;             while (!operationOK) {                // Set Save As dialog directory in a logical way.  If file in                 // edit pane had been previously saved, default to its directory.                   // If a new file (mipsN.asm), default to current save directory.                 // DPS 13-July-2011                if (editPane.isNew()) {                   saveDialog = new JFileChooser(editor.getCurrentSaveDirectory());                }                 else {                   File f = new File(editPane.getPathname());                   if (f != null) {                      saveDialog = new JFileChooser(f.getParent());                   }                    else {                      saveDialog = new JFileChooser(editor.getCurrentSaveDirectory());                   }                }                String paneFile = editPane.getFilename();                if (paneFile != null) saveDialog.setSelectedFile(new File(paneFile));                // end of 13-July-2011 code.                saveDialog.setDialogTitle("Save As");                             int decision = saveDialog.showSaveDialog(mainUI);                if (decision != JFileChooser.APPROVE_OPTION) {                   return null;                }                theFile = saveDialog.getSelectedFile();                operationOK = true;                if (theFile.exists()) {                   int overwrite = JOptionPane.showConfirmDialog(mainUI,                      "File "+theFile.getName()+" already exists.  Do you wish to overwrite it?",                      "Overwrite existing file?",                      JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);                   switch (overwrite) {                      case JOptionPane.YES_OPTION :                         operationOK = true;                         break;                      case JOptionPane.NO_OPTION :                         operationOK = false;                         break;                      case JOptionPane.CANCEL_OPTION :                         return null;                      default : // should never occur                         return null;                   }                }             }             // Either file with selected name does not exist or user wants to              // overwrite it, so go for it!             try {                BufferedWriter outFileStream = new BufferedWriter(new FileWriter(theFile));                          outFileStream.write(editPane.getSource(), 0, editPane.getSource().length());                outFileStream.close();             }                  catch(java.io.IOException c) {                   JOptionPane.showMessageDialog(null,"Save As operation could not be completed due to an error:\n"+c,                      "Save As Operation Failed", JOptionPane.ERROR_MESSAGE);                   return null;                }           }                return theFile;       }                       /**      * Saves all files currently open in the editor.      *       * @return true if operation succeeded otherwise false.      */             public boolean saveAllFiles() {          boolean result = false;          int tabCount = getTabCount();          if (tabCount > 0) {
           
            result = true;
            EditPane[] tabs = new EditPane[tabCount];
            EditPane savedPane = getCurrentEditTab();
            for (int i=0; i < tabCount; i++) {                tabs[i] = (EditPane)getComponentAt(i);                if ( tabs[i].hasUnsavedEdits() ) {                   setCurrentEditTab(tabs[i]);                   if (saveFile(tabs[i])) {                      tabs[i].setFileStatus(FileStatus.NOT_EDITED);                      editor.setTitle(tabs[i].getPathname(), tabs[i].getFilename(), tabs[i].getFileStatus());                   }                    else {                      result = false;                   }                }             }             setCurrentEditTab(savedPane);             if (result) {                EditPane editPane = getCurrentEditTab();                FileStatus.setSaved(true);                FileStatus.setEdited(false);                FileStatus.set(FileStatus.NOT_EDITED);                editPane.setFileStatus(FileStatus.NOT_EDITED);                updateTitlesAndMenuState(editPane);                       }             }          return result;       }                    /**      * Remove the pane and update menu status      */        public void remove(EditPane editPane) {          super.remove(editPane);          editPane = getCurrentEditTab(); // is now next tab or null          if (editPane == null) {             FileStatus.set(FileStatus.NO_FILE);             this.editor.setTitle("","",FileStatus.NO_FILE);             Globals.getGui().setMenuState(FileStatus.NO_FILE);          }           else {             FileStatus.set(editPane.getFileStatus());             updateTitlesAndMenuState(editPane);          }         // When last file is closed, menu is unable to respond to mnemonics         // and accelerators.  Let's have it request focus so it may do so.          if (getTabCount()==0) mainUI.haveMenuRequestFocus();       }              // Handy little utility to update the title on the current tab and the frame title bar      // and also to update the MARS menu state (controls which actions are enabled).        private void updateTitlesAndMenuState(EditPane editPane) {          editor.setTitle(editPane.getPathname(), editPane.getFilename(), editPane.getFileStatus());          editPane.updateStaticFileStatus(); //  for legacy code that depends on the static FileStatus (pre 4.0)          Globals.getGui().setMenuState(editPane.getFileStatus());          }          // Handy little utility to update the title on the current tab and the frame title bar      // and also to update the MARS menu state (controls which actions are enabled).      // DPS 9-Aug-2011        private void updateTitles(EditPane editPane) {          editor.setTitle(editPane.getPathname(), editPane.getFilename(), editPane.getFileStatus());          boolean assembled = FileStatus.isAssembled();           editPane.updateStaticFileStatus(); //  for legacy code that depends on the static FileStatus (pre 4.0)          FileStatus.setAssembled(assembled);       }              /**       * If there is an EditPane for the given file pathname, return it else return null.       *        * @param pathname Pathname for desired file       * @return the EditPane for this file if it is open in the editor, or null if not.       */        public EditPane getEditPaneForFile(String pathname) {          EditPane openPane = null;          for (int i=0; iAssemble’s
                // actionPerformed() method.
               if (theFile.canRead() && Globals.getSettings().getAssembleOnOpenEnabled()) {
                  mainUI.getRunAssembleAction().actionPerformed(null);
               }
            }
            return true;  
         } 
      
       /*
        * Open the specified file.  Return true if file opened, false otherwise
        */
      
          private boolean openFile(File theFile) {
            try {
               theFile = theFile.getCanonicalFile();
            } 
                catch (IOException ioe) {
                  // nothing to do, theFile will keep current value
               }
            String currentFilePath = theFile.getPath();
               // If this file is currently already open, then simply select its tab
            EditPane editPane = getEditPaneForFile(currentFilePath);
            if (editPane != null) {
               setSelectedComponent(editPane);
               //updateTitlesAndMenuState(editPane); 
               updateTitles(editPane);
               return false;
            } 
            else {
               editPane = new EditPane(mainUI);
            }
            editPane.setPathname(currentFilePath);
            //FileStatus.reset();
            FileStatus.setName(currentFilePath);
            FileStatus.setFile(theFile);
            FileStatus.set(FileStatus.OPENING);// DPS 9-Aug-2011
            if (theFile.canRead()) {
               Globals.program = new MIPSprogram();
               try {
                  Globals.program.readSource(currentFilePath);
               } 
                   catch (ProcessingException pe) {
                  }
               // DPS 1 Nov 2006.  Defined a StringBuffer to receive all file contents, 
               // one line at a time, before adding to the Edit pane with one setText.
               // StringBuffer is preallocated to full filelength to eliminate dynamic
               // expansion as lines are added to it. Previously, each line was appended 
               // to the Edit pane as it was read, way slower due to dynamic string alloc.  
               StringBuffer fileContents = new StringBuffer((int)theFile.length());
               int lineNumber = 1;
               String line = Globals.program.getSourceLine(lineNumber++);
               while (line != null) {
                  fileContents.append(line+”\n”);
                  line = Globals.program.getSourceLine(lineNumber++);
               }
               editPane.setSourceCode(fileContents.toString(), true);
                // The above operation generates an undoable edit, setting the initial
                // text area contents, that should not be seen as undoable by the Undo
                // action.  Let’s get rid of it.
               editPane.discardAllUndoableEdits();
               editPane.setShowLineNumbersEnabled(true);
               editPane.setFileStatus(FileStatus.NOT_EDITED);
               
               addTab(editPane.getFilename(), editPane);
               setToolTipTextAt(indexOfComponent(editPane), editPane.getPathname());
               setSelectedComponent(editPane);
               FileStatus.setSaved(true);
               FileStatus.setEdited(false);
               FileStatus.set(FileStatus.NOT_EDITED);
               
               // If assemble-all, then allow opening of any file w/o invalidating assembly.
                // DPS 9-Aug-2011
               if (Globals.getSettings().getBooleanSetting(mars.Settings.ASSEMBLE_ALL_ENABLED)) {
                  updateTitles(editPane);
               } 
               else {// this was the original code…
                  updateTitlesAndMenuState(editPane);
                  mainPane.getExecutePane().clearPane();  
               }
            
               mainPane.setSelectedComponent(EditTabbedPane.this);
               editPane.tellEditingComponentToRequestFocusInWindow();
               mostRecentlyOpenedFile = theFile;
            }
            return true;
         }
        
      // Private method to generate the file chooser’s list of choosable file filters.
      // It is called when the file chooser is created, and called again each time the Open
      // dialog is activated.  We do this because the user may have added a new filter 
      // during the previous dialog.  This can be done by entering e.g. *.txt in the file
      // name text field.  Java is funny, however, in that if the user does this then
      // cancels the dialog, the new filter will remain in the list BUT if the user does
      // this then ACCEPTS the dialog, the new filter will NOT remain in the list.  However
      // the act of entering it causes a property change event to occur, and we have a
      // handler that will add the new filter to our internal filter list and “restore” it
      // the next time this method is called.  Strangely, if the user then similarly
      // adds yet another new filter, the new one becomes simply a description change
      // to the previous one, the previous object is modified AND NO PROPERTY CHANGE EVENT 
      // IS FIRED!  I could obviously deal with this situation if I wanted to, but enough
      // is enough.  The limit will be one alternative filter at a time.
      // DPS… 9 July 2008
      
          private void setChoosableFileFilters() {
         // See if a new filter has been added to the master list.  If so,
         // regenerate the fileChooser list from the master list.
            if (fileFilterCount < fileFilterList.size() ||               fileFilterList.size() != fileChooser.getChoosableFileFilters().length) {                fileFilterCount = fileFilterList.size();             // First, "deactivate" the listener, because our addChoosableFileFilter             // calls would otherwise activate it!  We want it to be triggered only             // by MARS user action.                boolean activeListener = false;                if (fileChooser.getPropertyChangeListeners().length > 0) {
                  fileChooser.removePropertyChangeListener(listenForUserAddedFileFilter);
                  activeListener = true;  // we’ll note this, for re-activation later
               }
            // clear out the list and populate from our own ArrayList.
            // Last one added becomes the default.
               fileChooser.resetChoosableFileFilters();
               for (int i=0; i < fileFilterList.size(); i++) {                   fileChooser.addChoosableFileFilter((FileFilter)fileFilterList.get(i));                }             // Restore listener.                if (activeListener) {                   fileChooser.addPropertyChangeListener(listenForUserAddedFileFilter);                }             }          }//////////////////////////////////////////////////////////////////////////////////       //  Private inner class for special property change listener.  DPS 9 July 2008.       //  If user adds a file filter, e.g. by typing *.txt into the file text field then pressing       //  Enter, then it is automatically added to the array of choosable file filters.  BUT, unless you       //  Cancel out of the Open dialog, it is then REMOVED from the list automatically also. Here       //  we will achieve a sort of persistence at least through the current activation of MARS.                  private class ChoosableFileFilterChangeListener implements PropertyChangeListener {              public void propertyChange(java.beans.PropertyChangeEvent e) {                if (e.getPropertyName()==JFileChooser.CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY) {                   FileFilter[] newFilters = (FileFilter[]) e.getNewValue();                   FileFilter[] oldFilters = (FileFilter[]) e.getOldValue();                   if (newFilters.length > fileFilterList.size()) {
                  // new filter added, so add to end of master list.
                     fileFilterList.add(newFilters[newFilters.length-1]);
                  }
               }
            }       
         }
      
      
      }
   
   }

EditPasteAction

package mars.venus;
public synchronized class EditPasteAction extends GuiAction {
public void EditPasteAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

FilePrintAction

package mars.venus;
public synchronized class FilePrintAction extends GuiAction {
public void FilePrintAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

SettingsEditorAction

package mars.venus;
public synchronized class SettingsEditorAction extends GuiAction {
javax.swing.JDialog editorDialog;
javax.swing.JComboBox fontFamilySelector;
javax.swing.JComboBox fontStyleSelector;
javax.swing.JSlider tabSizeSelector;
javax.swing.JTextField fontSizeDisplay;
String initialFontFamily;
String initialFontStyle;
String initialFontSize;
private static final int gridVGap = 2;
private static final int gridHGap = 2;
private static final javax.swing.border.Border ColorSelectButtonEnabledBorder;
private static final javax.swing.border.Border ColorSelectButtonDisabledBorder;
private static final String GENERIC_TOOL_TIP_TEXT = Use generic editor (original MARS editor, similar to Notepad) instead of language-aware styled editor;
private static final String SAMPLE_TOOL_TIP_TEXT = Current setting; modify using buttons to the right;
private static final String FOREGROUND_TOOL_TIP_TEXT = Click, to select text color;
private static final String BOLD_TOOL_TIP_TEXT = Toggle text bold style;
private static final String ITALIC_TOOL_TIP_TEXT = Toggle text italic style;
private static final String DEFAULT_TOOL_TIP_TEXT = Check, to select defaults (disables buttons);
private static final String BOLD_BUTTON_TOOL_TIP_TEXT = B;
private static final String ITALIC_BUTTON_TOOL_TIP_TEXT = I;
private static final String TAB_SIZE_TOOL_TIP_TEXT = Current tab size in characters;
private static final String BLINK_SPINNER_TOOL_TIP_TEXT = Current blinking rate in milliseconds;
private static final String BLINK_SAMPLE_TOOL_TIP_TEXT = Displays current blinking rate;
private static final String CURRENT_LINE_HIGHLIGHT_TOOL_TIP_TEXT = Check, to highlight line currently being edited;
private static final String AUTO_INDENT_TOOL_TIP_TEXT = Check, to enable auto-indent to previous line when Enter key is pressed;
private static final String[] POPUP_GUIDANCE_TOOL_TIP_TEXT;
static void ();
public void SettingsEditorAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

EditFindReplaceAction$FindReplaceDialog$1

package mars.venus;
synchronized class EditFindReplaceAction$FindReplaceDialog$1 extends java.awt.event.WindowAdapter {
void EditFindReplaceAction$FindReplaceDialog$1(EditFindReplaceAction$FindReplaceDialog);
public void windowClosing(java.awt.event.WindowEvent);
}

LabelsWindow$LabelsForSymbolTable

package mars.venus;
synchronized class LabelsWindow$LabelsForSymbolTable {
private mars.MIPSprogram myMIPSprogram;
private Object[][] labelData;
private javax.swing.JTable labelTable;
private java.util.ArrayList symbols;
private mars.assembler.SymbolTable symbolTable;
private String tableName;
public void LabelsWindow$LabelsForSymbolTable(LabelsWindow, mars.MIPSprogram);
public String getSymbolTableName();
public boolean hasSymbols();
private javax.swing.JTable generateLabelTable();
public void updateLabelAddresses();
}

TextSegmentWindow$MyTableColumnMovingListener

package mars.venus;
synchronized class TextSegmentWindow$MyTableColumnMovingListener implements javax.swing.event.TableColumnModelListener {
private void TextSegmentWindow$MyTableColumnMovingListener(TextSegmentWindow);
public void columnAdded(javax.swing.event.TableColumnModelEvent);
public void columnRemoved(javax.swing.event.TableColumnModelEvent);
public void columnMarginChanged(javax.swing.event.ChangeEvent);
public void columnSelectionChanged(javax.swing.event.ListSelectionEvent);
public void columnMoved(javax.swing.event.TableColumnModelEvent);
}

mars/venus/SettingsEditorAction.java
mars/venus/SettingsEditorAction.java   package mars.venus;
   import mars.simulator.*;
   import mars.*;
   import mars.util.*;
   import mars.venus.editors.jeditsyntax.*;
   import mars.venus.editors.jeditsyntax.tokenmarker.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.text.*;
   import javax.swing.border.*;
   import javax.swing.event.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2011,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item for text editor settings.
    */
    public class SettingsEditorAction extends GuiAction  {
    
      JDialog editorDialog;
      JComboBox fontFamilySelector, fontStyleSelector;
      JSlider tabSizeSelector;
      JTextField fontSizeDisplay;
    
    // Used to determine upon OK, whether or not anything has changed.
      String initialFontFamily, initialFontStyle, initialFontSize; 
      
      /**
       *  Create a new SettingsEditorAction.  Has all the GuiAction parameters.
        */
       public SettingsEditorAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
     
     /**
      *  When this action is triggered, launch a dialog to view and modify
      *  editor settings.
      */
       public void actionPerformed(ActionEvent e) {
         editorDialog = new EditorFontDialog(Globals.getGui(), “Text Editor Settings”, true, Globals.getSettings().getEditorFont() );
         editorDialog.setVisible(true);
      
      }
    
      private static final int gridVGap = 2;
      private static final int gridHGap = 2;
      private static final Border ColorSelectButtonEnabledBorder = new BevelBorder(BevelBorder.RAISED, Color.WHITE, Color.GRAY);
      private static final Border ColorSelectButtonDisabledBorder = new LineBorder(Color.GRAY, 2); 
   
      private static final String GENERIC_TOOL_TIP_TEXT = “Use generic editor (original MARS editor, similar to Notepad) instead of language-aware styled editor”;
   
      private static final String SAMPLE_TOOL_TIP_TEXT = “Current setting; modify using buttons to the right”;
      private static final String FOREGROUND_TOOL_TIP_TEXT = “Click, to select text color”;
      private static final String BOLD_TOOL_TIP_TEXT = “Toggle text bold style”;
      private static final String ITALIC_TOOL_TIP_TEXT = “Toggle text italic style”;
      private static final String DEFAULT_TOOL_TIP_TEXT = “Check, to select defaults (disables buttons)”;
      private static final String BOLD_BUTTON_TOOL_TIP_TEXT = “B”;
      private static final String ITALIC_BUTTON_TOOL_TIP_TEXT = “I”;
    
      private static final String TAB_SIZE_TOOL_TIP_TEXT = “Current tab size in characters”;
      private static final String BLINK_SPINNER_TOOL_TIP_TEXT = “Current blinking rate in milliseconds”;
      private static final String BLINK_SAMPLE_TOOL_TIP_TEXT = “Displays current blinking rate”;
      private static final String CURRENT_LINE_HIGHLIGHT_TOOL_TIP_TEXT = “Check, to highlight line currently being edited”;
      private static final String AUTO_INDENT_TOOL_TIP_TEXT = “Check, to enable auto-indent to previous line when Enter key is pressed”;
      private static final String[] POPUP_GUIDANCE_TOOL_TIP_TEXT = { “Turns off instruction and directive guide popup while typing”,
                                                                     “Generates instruction guide popup after first letter of potential instruction is typed”,
                                                                                        “Generates instruction guide popup after second letter of potential instruction is typed”
                                                                                        };
    
    // Concrete font chooser class. 
       private class EditorFontDialog extends AbstractFontSettingDialog {
       
         private JButton[] foregroundButtons;
         private JLabel[] samples;
         private JToggleButton[] bold, italic;
         private JCheckBox[] useDefault;
        
         private int[] syntaxStyleIndex;
         private SyntaxStyle[] defaultStyles,initialStyles, currentStyles;
         private Font previewFont;
        
         private JPanel dialogPanel,syntaxStylePanel,otherSettingsPanel; /////4 Aug 2010
        
         private JSlider tabSizeSelector;
         private JSpinner tabSizeSpinSelector, blinkRateSpinSelector, popupPrefixLengthSpinSelector;
         private JCheckBox lineHighlightCheck, genericEditorCheck, autoIndentCheck;
         private Caret blinkCaret;
         private JTextField blinkSample;
         private ButtonGroup popupGuidanceButtons;
         private JRadioButton[] popupGuidanceOptions;
        // Flag to indicate whether any syntax style buttons have been clicked
        // since dialog created or most recent “apply”.
         private boolean syntaxStylesAction = false; 
         
         private int initialEditorTabSize, initialCaretBlinkRate, initialPopupGuidance;
         private boolean initialLineHighlighting, initialGenericTextEditor, initialAutoIndent;
          
          public EditorFontDialog(Frame owner, String title, boolean modality, Font font) {
            super(owner, title, modality, font);
            if (Globals.getSettings().getBooleanSetting(Settings.GENERIC_TEXT_EDITOR)) {
               syntaxStylePanel.setVisible(false);
               otherSettingsPanel.setVisible(false); 
            }
         }
         
         // build the dialog here
          protected JPanel buildDialogPanel() {
            JPanel dialog = new JPanel(new BorderLayout());
            JPanel fontDialogPanel = super.buildDialogPanel();
            JPanel syntaxStylePanel = buildSyntaxStylePanel();
            JPanel otherSettingsPanel = buildOtherSettingsPanel();
            fontDialogPanel.setBorder(BorderFactory.createTitledBorder(“Editor Font”));
            syntaxStylePanel.setBorder(BorderFactory.createTitledBorder(“Syntax Styling”));
            otherSettingsPanel.setBorder(BorderFactory.createTitledBorder(“Other Editor Settings”));
            dialog.add(fontDialogPanel, BorderLayout.WEST);
            dialog.add(syntaxStylePanel, BorderLayout.CENTER);
            dialog.add(otherSettingsPanel, BorderLayout.SOUTH);
            this.dialogPanel = dialog; /////4 Aug 2010
            this.syntaxStylePanel = syntaxStylePanel; /////4 Aug 2010
            this.otherSettingsPanel = otherSettingsPanel; /////4 Aug 2010
            return dialog;
         }
      
          // Row of control buttons to be placed along the button of the dialog
          protected Component buildControlPanel() {
            Box controlPanel = Box.createHorizontalBox();
            JButton okButton = new JButton(“Apply and Close”);
            okButton.setToolTipText(SettingsHighlightingAction.CLOSE_TOOL_TIP_TEXT);
            okButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        performApply();
                        closeDialog();
                     }
                  });
            JButton applyButton = new JButton(“Apply”);
            applyButton.setToolTipText(SettingsHighlightingAction.APPLY_TOOL_TIP_TEXT);
            applyButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        performApply();
                     }
                  });
            JButton cancelButton = new JButton(“Cancel”);
            cancelButton.setToolTipText(SettingsHighlightingAction.CANCEL_TOOL_TIP_TEXT);
            cancelButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) { 
                        closeDialog();
                     }
                  });   
            JButton resetButton = new JButton(“Reset”);
            resetButton.setToolTipText(SettingsHighlightingAction.RESET_TOOL_TIP_TEXT);
            resetButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        reset();
                     }
                  });
            initialGenericTextEditor = Globals.getSettings().getBooleanSetting(Settings.GENERIC_TEXT_EDITOR);
            genericEditorCheck = new JCheckBox(“Use Generic Editor”, initialGenericTextEditor);
            genericEditorCheck.setToolTipText(GENERIC_TOOL_TIP_TEXT);
            genericEditorCheck.addItemListener(
                   new ItemListener() {
                      public void itemStateChanged(ItemEvent e) { 
                        if (e.getStateChange()==ItemEvent.SELECTED) {
                           syntaxStylePanel.setVisible(false);
                           otherSettingsPanel.setVisible(false);
                        } 
                        else {
                           syntaxStylePanel.setVisible(true);
                           otherSettingsPanel.setVisible(true);     
                        }
                     }
                  });
            
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(okButton);
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(applyButton);
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(cancelButton);
            controlPanel.add(Box.createHorizontalGlue());        
            controlPanel.add(resetButton);
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(genericEditorCheck);
            controlPanel.add(Box.createHorizontalGlue());
            return controlPanel;
         }
      
      // User has clicked “Apply” or “Apply and Close” button.  Required method, is 
      // abstract in superclass.
          protected void apply(Font font) {
            Globals.getSettings().setBooleanSetting(Settings.GENERIC_TEXT_EDITOR, genericEditorCheck.isSelected());
            Globals.getSettings().setBooleanSetting(Settings.EDITOR_CURRENT_LINE_HIGHLIGHTING, lineHighlightCheck.isSelected());
            Globals.getSettings().setBooleanSetting(Settings.AUTO_INDENT, autoIndentCheck.isSelected());
            Globals.getSettings().setCaretBlinkRate(((Integer)blinkRateSpinSelector.getValue()).intValue());
            Globals.getSettings().setEditorTabSize(tabSizeSelector.getValue());
            if (syntaxStylesAction) { 
               for (int i=0; i= chars_per_line) {
                  newline( );
               // Also start a new page, if necessary
                  if (page == null) newpage( );
               }
            // Now print the character:
            // If it is a space, skip one space, without output.
            // If it is a tab, skip the necessary number of spaces.
            // Otherwise, print the character.
            // It is inefficient to draw only one character at a time, but
            // because our FontMetrics don’t match up exactly to what the
            // printer uses, we need to position each character individually
               if (Character.isSpaceChar(buffer[i])) charnum++;
               else if (buffer[i] == ‘\t’) charnum += chars_per_tab – (charnum % chars_per_tab);
               else {
                  page.drawChars(buffer, i, 1,
                     x0 + charnum * charwidth,
                     y0 + (linenum*lineheight) + lineascent);
                  charnum++;
               }
            }
         }
      }
   /**
   * This is the flush( ) method that all Writer subclasses must implement.
   * There is no way to flush a PrintJob without prematurely printing the
   * page, so we don’t do anything.
   **/
       public void flush( ) { /* do nothing */ }
   /**
   * This is the close( ) method that all Writer subclasses must implement.
   * Print the pending page (if any) and terminate the PrintJob.
   */
       public void close( ) {
         synchronized(this.lock) {
            if (page != null) page.dispose( ); // Send page to the printer
            job.end( ); // Terminate the job
         }
      }
   /**
   * Set the font style. The argument should be one of the font style
   * constants defined by the java.awt.Font class. All subsequent output
   * will be in that style. This method relies on all styles of the
   * Monospaced font having the same metrics.
   **/
       public void setFontStyle(int style) {
         synchronized (this.lock) {
         // Try to set a new font, but restore current one if it fails
            Font current = font;
            try { font = new Font(“Monospaced”, style, fontsize); }
                catch (Exception e) { font = current; }
         // If a page is pending, set the new font. Otherwise newpage( ) will
            if (page != null) page.setFont(font);
         }
      }
   /** End the current page. Subsequent output will be on a new page. */
       public void pageBreak( ) { 
         synchronized(this.lock) { newpage( ); } }
   /** Return the number of columns of characters that fit on the page */
       public int getCharactersPerLine( ) { 
         return this.chars_per_line; }
   /** Return the number of lines that fit on a page */
       public int getLinesPerPage( ) { 
         return this.lines_per_page; }
   /** This internal method begins a new line */
       protected void newline( ) {
         charnum = 0; // Reset character number to 0
         linenum++; // Increment line number
         if (linenum >= lines_per_page) { // If we’ve reached the end of page
            page.dispose( ); // send page to printer
            page = null; // but don’t start a new page yet.
         }
      }
   /** This internal method begins a new page and prints the header. */
       protected void newpage( ) {
         page = job.getGraphics( ); // Begin the new page
         linenum = 0; charnum = 0; // Reset line and char number
         pagenum++; // Increment page number
         page.setFont(headerfont); // Set the header font.
         page.drawString(jobname, x0, headery); // Print job name left justified
         String s = “- ” + pagenum + ” -“; // Print the page # centered.
         int w = headermetrics.stringWidth(s);
         page.drawString(s, x0 + (this.width – w)/2, headery);
         w = headermetrics.stringWidth(time); // Print date right justified
         page.drawString(time, x0 + width – w, headery);
      // Draw a line beneath the header
         int y = headery + headermetrics.getDescent( ) + 1;
         page.drawLine(x0, y, x0+width, y);
      // Set the basic monospaced font for the rest of the page.
         page.setFont(font);
      }
   /**
   * This is the exception class that the HardcopyWriter constructor
   * throws when the user clicks “Cancel” in the print dialog box.
   **/
       public static class PrintCanceledException extends Exception {
          public PrintCanceledException(String msg) { super(msg); }
      }
    
    
   /**
   * A program that prints the specified file using HardcopyWriter
   **/
   
       public static void main(String[ ] args) {
         try {
            if (args.length != 1)
               throw new IllegalArgumentException(“Wrong # of arguments”);
            FileReader in = new FileReader(args[0]);
            HardcopyWriter out = null;
            Frame f = new Frame(“PrintFile: ” + args[0]);
            f.setSize(200, 50);
            f.setVisible(true);
            try {
               out = new HardcopyWriter(f, args[0], 10, .5, .5, .5, .5);
            }
                catch (HardcopyWriter.PrintCanceledException e) {
                  System.exit(0);
               }
            f.setVisible(false);
            char[ ] buffer = new char[4096];
            int numchars;
            while((numchars = in.read(buffer)) != -1)
               out.write(buffer, 0, numchars);
            in.close( );
            out.close( );
         }
             catch (Exception e) {
               System.err.println(e);
               System.err.println(“Usage: ” +
                     “java HardcopyWriter$PrintFile “);
               System.exit(1);
            }
         System.exit(0);
      }
   }

LabelsWindow$LabelDisplayMouseListener

package mars.venus;
synchronized class LabelsWindow$LabelDisplayMouseListener extends java.awt.event.MouseAdapter {
private void LabelsWindow$LabelDisplayMouseListener(LabelsWindow);
public void mouseClicked(java.awt.event.MouseEvent);
}

DataSegmentWindow$MyTippedJTable$1

package mars.venus;
synchronized class DataSegmentWindow$MyTippedJTable$1 extends javax.swing.table.JTableHeader {
void DataSegmentWindow$MyTippedJTable$1(DataSegmentWindow$MyTippedJTable, javax.swing.table.TableColumnModel);
public String getToolTipText(java.awt.event.MouseEvent);
}

mars/venus/FileOpenAction.java
mars/venus/FileOpenAction.java   package mars.venus;
   import mars.*;
   import mars.util.*;
   import java.util.ArrayList;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.filechooser.FileFilter;
   import java.io.*;
   import java.beans.*;
    
    /*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
 
    /**
    * Action  for the File -> Open menu item
    */              
    public class FileOpenAction extends GuiAction {
    
      private File mostRecentlyOpenedFile;
      private JFileChooser fileChooser;
      private int fileFilterCount;
      private ArrayList fileFilterList;
      private PropertyChangeListener listenForUserAddedFileFilter;
     
       public FileOpenAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
     
       /**
      * Launch a file chooser for name of file to open
      *
      * @param e component triggering this call
      */
       public void actionPerformed(ActionEvent e) {
         mainUI.editor.open();
      }
   
   }      

RunStopAction

package mars.venus;
public synchronized class RunStopAction extends GuiAction {
public void RunStopAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/MonoRightCellRenderer.java
mars/venus/MonoRightCellRenderer.java   package mars.venus;
   import mars.*;
   import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/*
 * Use this to render Monospaced and right-aligned data in JTables.
 * I am using it to render integer addresses and values that are stored as
 * Strings containing either the decimal or hexidecimal version
 * of the integer value.
 */
    class MonoRightCellRenderer extends DefaultTableCellRenderer { 
      public static final Font MONOSPACED_PLAIN_12POINT = new Font(“Monospaced”,Font.PLAIN,12); 
       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(MONOSPACED_PLAIN_12POINT);
         cell.setHorizontalAlignment(SwingConstants.RIGHT);
         return cell;
      }  
   }

mars/venus/SettingsAddressDisplayBaseAction.java
mars/venus/SettingsAddressDisplayBaseAction.java   package mars.venus;
   import mars.simulator.*;
    import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item to control number base (10 or 16) of memory addresses.
    */
    public class SettingsAddressDisplayBaseAction extends GuiAction  {
    
   
       public SettingsAddressDisplayBaseAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
         public void actionPerformed(ActionEvent e) {
           boolean isHex = ((JCheckBoxMenuItem) e.getSource()).isSelected(); 
           Globals.getGui().getMainPane().getExecutePane().getAddressDisplayBaseChooser().setSelected(isHex);
            Globals.getSettings().setDisplayAddressesInHex(isHex);
      }
        
   }

HelpHelpAction$2

package mars.venus;
synchronized class HelpHelpAction$2 implements java.awt.event.ActionListener {
void HelpHelpAction$2(HelpHelpAction, javax.swing.JDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/RunResetAction.java
mars/venus/RunResetAction.java   package mars.venus;
   import mars.*;
   import mars.util.*;
   import mars.mips.hardware.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action  for the Run -> Reset menu item
    */   
    public class RunResetAction extends GuiAction {
     
       public RunResetAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
   
   /**
    * reset GUI components and MIPS resources
    */
       public void actionPerformed(ActionEvent e){
         RunGoAction.resetMaxSteps();
         String name = this.getValue(Action.NAME).toString();
         ExecutePane executePane = mainUI.getMainPane().getExecutePane();
         // The difficult part here is resetting the data segment.  Two approaches are:
        // 1. After each assembly, get a deep copy of the Globals.memory array 
        //    containing data segment.  Then replace it upon reset.
        // 2. Simply re-assemble the program upon reset, and the assembler will 
        //    build a new data segment.  Reset can only be done after a successful
        //    assembly, so there is “no” chance of assembler error.
        // I am choosing the second approach although it will slow down the reset
        // operation.  The first approach requires additional Memory class methods.
         try {
            Globals.program.assemble(RunAssembleAction.getMIPSprogramsToAssemble(),
                                         RunAssembleAction.getExtendedAssemblerEnabled(),
                                                 RunAssembleAction.getWarningsAreErrors());
         } 
             catch (ProcessingException pe) {
                 mainUI.getMessagesPane().postMarsMessage(
                   //pe.errors().generateErrorReport());
               “Unable to reset.  Please close file then re-open and re-assemble.\n”);
               return;
            }
         RegisterFile.resetRegisters();
         Coprocessor1.resetRegisters();
         Coprocessor0.resetRegisters();
            executePane.getRegistersWindow().clearHighlighting();
         executePane.getRegistersWindow().updateRegisters();
            executePane.getCoprocessor1Window().clearHighlighting();
         executePane.getCoprocessor1Window().updateRegisters();
         executePane.getCoprocessor0Window().clearHighlighting();
            executePane.getCoprocessor0Window().updateRegisters();
            executePane.getDataSegmentWindow().highlightCellForAddress(Memory.dataBaseAddress); 
         executePane.getDataSegmentWindow().clearHighlighting();
         executePane.getTextSegmentWindow().setCodeHighlighting(true);
         executePane.getTextSegmentWindow().highlightStepAtPC();
         mainUI.getRegistersPane().setSelectedComponent(executePane.getRegistersWindow());
         FileStatus.set(FileStatus.RUNNABLE);
         mainUI.setReset(true);
         mainUI.setStarted(false);
      
         // Aug. 24, 2005 Ken Vollmar
         SystemIO.resetFiles( );  // Ensure that I/O “file descriptors” are initialized for a new program run
      
         mainUI.getMessagesPane().postRunMessage(
                             “\n”+name+”: reset completed.\n\n”);
      }
   }

Coprocessor0Window$RegisterCellRenderer

package mars.venus;
synchronized class Coprocessor0Window$RegisterCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
private java.awt.Font font;
private int alignment;
public void Coprocessor0Window$RegisterCellRenderer(Coprocessor0Window, java.awt.Font, int);
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable, Object, boolean, boolean, int, int);
}

mars/venus/SettingsMemoryConfigurationAction.java
mars/venus/SettingsMemoryConfigurationAction.java   package mars.venus;
   import mars.simulator.*;
   import mars.*;
   import mars.util.*;
   import mars.mips.hardware.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.text.*;
   import javax.swing.border.*;
   import javax.swing.event.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item for text editor settings.
    */
    public class SettingsMemoryConfigurationAction extends GuiAction  {
    
      JDialog configDialog;
      JComboBox fontFamilySelector, fontStyleSelector;
      JSlider fontSizeSelector;
      JTextField fontSizeDisplay;
      SettingsMemoryConfigurationAction thisAction;
    
    // Used to determine upon OK, whether or not anything has changed.
      String initialFontFamily, initialFontStyle, initialFontSize; 
      
      /**
       *  Create a new SettingsEditorAction.  Has all the GuiAction parameters.
        */
       public SettingsMemoryConfigurationAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
         thisAction = this;
      }
     
     /**
      *  When this action is triggered, launch a dialog to view and modify
      *  editor settings.
      */
       public void actionPerformed(ActionEvent e) {
         configDialog = new MemoryConfigurationDialog(Globals.getGui(), “MIPS Memory Configuration”, true );
         configDialog.setVisible(true);
      }
    
     //////////////////////////////////////////////////////////////////////////////
     //
     //   Private class to do all the work!
     //
       private class MemoryConfigurationDialog extends JDialog implements ActionListener {
         JTextField[] addressDisplay;
         JLabel[] nameDisplay;
         ConfigurationButton selectedConfigurationButton, initialConfigurationButton;
         
          public MemoryConfigurationDialog(Frame owner, String title, boolean modality) {
            super(owner, title, modality);
            this.setContentPane(buildDialogPanel());
            this.setDefaultCloseOperation(
                        JDialog.DO_NOTHING_ON_CLOSE);
            this.addWindowListener(
                   new WindowAdapter() {
                      public void windowClosing(WindowEvent we) {
                        performClose();
                     }
                  });
            this.pack();
            this.setLocationRelativeTo(owner);
         }
      
          private JPanel buildDialogPanel() {
            JPanel dialogPanel = new JPanel(new BorderLayout());
            dialogPanel.setBorder(new EmptyBorder(10,10,10,10));
         
            JPanel configInfo = new JPanel(new FlowLayout());
            MemoryConfigurations.buildConfigurationCollection();
            configInfo.add(buildConfigChooser());
            configInfo.add(buildConfigDisplay());
            dialogPanel.add(configInfo);
            dialogPanel.add(buildControlPanel(),BorderLayout.SOUTH);                
            return dialogPanel;
         }
        
          private Component buildConfigChooser() {
            JPanel chooserPanel = new JPanel(new GridLayout(4,1));
            ButtonGroup choices = new ButtonGroup();
            Iterator configurationsIterator = MemoryConfigurations.getConfigurationsIterator();
            while (configurationsIterator.hasNext()) {
               MemoryConfiguration config = (MemoryConfiguration) configurationsIterator.next();
               ConfigurationButton button = new ConfigurationButton(config);
               button.addActionListener(this);
               if (button.isSelected()) {
                  this.selectedConfigurationButton = button;
                  this.initialConfigurationButton = button;
               }
               choices.add(button);
               chooserPanel.add(button);
            }
            chooserPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK)
                                    , “Configuration”));
            return chooserPanel;
         }
      
        
        
          private Component buildConfigDisplay() {
            JPanel displayPanel = new JPanel();
            MemoryConfiguration config = MemoryConfigurations.getCurrentConfiguration();
            String[] configurationItemNames = config.getConfigurationItemNames();
            int numItems = configurationItemNames.length;
            JPanel namesPanel = new JPanel(new GridLayout(numItems,1));
            JPanel valuesPanel = new JPanel(new GridLayout(numItems,1));
            Font monospaced = new Font(“Monospaced”,Font.PLAIN,12);
            nameDisplay = new JLabel[numItems];
         //   for (int i=numItems-1; i >= 0; i–) {
         //      namesPanel.add(new JLabel(configurationItemNames[i]));
         //   }
            addressDisplay = new JTextField[numItems];
            for (int i=0; i= 0; i–) {
               namesPanel.add(nameDisplay[i]);
               valuesPanel.add(addressDisplay[i]);
            }
            setConfigDisplay(config);
            Box columns = Box.createHorizontalBox();
            columns.add(valuesPanel);
            columns.add(Box.createHorizontalStrut(6));
            columns.add(namesPanel);
            displayPanel.add(columns);
            return displayPanel;  
         }
      
        
        // Carry out action for the radio buttons.
          public void actionPerformed(ActionEvent e) {
            MemoryConfiguration config = ((ConfigurationButton) e.getSource()).getConfiguration();
            setConfigDisplay(config);
            this.selectedConfigurationButton = (ConfigurationButton) e.getSource();
         }
        
        
       // Row of control buttons to be placed along the button of the dialog
          private Component buildControlPanel() {
            Box controlPanel = Box.createHorizontalBox();
            JButton okButton = new JButton(“Apply and Close”);
            okButton.setToolTipText(SettingsHighlightingAction.CLOSE_TOOL_TIP_TEXT);
            okButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        performApply();
                        performClose();
                     }
                  });
            JButton applyButton = new JButton(“Apply”);
            applyButton.setToolTipText(SettingsHighlightingAction.APPLY_TOOL_TIP_TEXT);
            applyButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        performApply();
                     }
                  });
            JButton cancelButton = new JButton(“Cancel”);
            cancelButton.setToolTipText(SettingsHighlightingAction.CANCEL_TOOL_TIP_TEXT);
            cancelButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) { 
                        performClose();
                     }
                  });   
            JButton resetButton = new JButton(“Reset”);
            resetButton.setToolTipText(SettingsHighlightingAction.RESET_TOOL_TIP_TEXT);
            resetButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        performReset();
                     }
                  });
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(okButton);
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(applyButton);
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(cancelButton);
            controlPanel.add(Box.createHorizontalGlue());        
            controlPanel.add(resetButton);
            controlPanel.add(Box.createHorizontalGlue());
            return controlPanel;
         }
      
          private void performApply() {
            if (MemoryConfigurations.setCurrentConfiguration(this.selectedConfigurationButton.getConfiguration())) {
               Globals.getSettings().setMemoryConfiguration(this.selectedConfigurationButton.getConfiguration().getConfigurationIdentifier());
               Globals.getGui().getRegistersPane().getRegistersWindow().clearHighlighting();
               Globals.getGui().getRegistersPane().getRegistersWindow().updateRegisters();
               Globals.getGui().getMainPane().getExecutePane().getDataSegmentWindow().updateBaseAddressComboBox();
                   // 21 July 2009 Re-assemble if the situation demands it to maintain consistency.
               if (FileStatus.get() == FileStatus.RUNNABLE ||
                   FileStatus.get() == FileStatus.RUNNING ||
                   FileStatus.get() == FileStatus.TERMINATED)  {
                   // Stop execution if executing — should NEVER happen because this 
                   // Action’s widget is disabled during MIPS execution.
                  if (FileStatus.get() == FileStatus.RUNNING) {
                     Simulator.getInstance().stopExecution(thisAction);
                  }
                  Globals.getGui().getRunAssembleAction().actionPerformed(null);
               }
            }
         }
      
          private void performClose() {
            this.setVisible(false);
            this.dispose();
         }
      
          private void performReset() {
            this.selectedConfigurationButton = this.initialConfigurationButton;
            this.selectedConfigurationButton.setSelected(true);
            setConfigDisplay(this.selectedConfigurationButton.getConfiguration());
         }
      
                
        // Set name values in JLabels and address values in the JTextFields
          private void setConfigDisplay(MemoryConfiguration config) {
            String[] configurationItemNames = config.getConfigurationItemNames();
            int[] configurationItemValues = config.getConfigurationItemValues();
            // Will use TreeMap to extract list of address-name pairs sorted by 
            // hex-stringified address. This will correctly handle kernel addresses,
            // whose int values are negative and thus normal sorting yields incorrect
            // results.  There can be duplicate addresses, so I concatenate the name
            // onto the address to make each key unique.  Then slice off the name upon
            // extraction. 
            TreeMap treeSortedByAddress = new TreeMap();
            for (int i=0; i Paste menu item
    */              
    public class EditPasteAction extends GuiAction {
     
       public EditPasteAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
          
       public void actionPerformed(ActionEvent e){
            mainUI.getMainPane().getEditPane().pasteText();
      }
   }

RunToggleBreakpointsAction

package mars.venus;
public synchronized class RunToggleBreakpointsAction extends GuiAction {
public void RunToggleBreakpointsAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

LabelsWindow$LabelItemListener

package mars.venus;
synchronized class LabelsWindow$LabelItemListener implements java.awt.event.ItemListener {
private void LabelsWindow$LabelItemListener(LabelsWindow);
public void itemStateChanged(java.awt.event.ItemEvent);
}

SettingsProgramArgumentsAction

package mars.venus;
public synchronized class SettingsProgramArgumentsAction extends GuiAction {
public void SettingsProgramArgumentsAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

ColorSelectButton

package mars.venus;
synchronized class ColorSelectButton extends javax.swing.JButton {
public static final javax.swing.border.Border ColorSelectButtonEnabledBorder;
public static final javax.swing.border.Border ColorSelectButtonDisabledBorder;
static void ();
void ColorSelectButton();
public void setEnabled(boolean);
}

mars/venus/RunPauseAction.java
mars/venus/RunPauseAction.java   package mars.venus;
   import mars.simulator.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Run -> Pause menu item (and toolbar icon)
    */
    public class RunPauseAction extends GuiAction  {
    
       public RunPauseAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
         Simulator.getInstance().stopExecution(this);
         // RunGoAction’s “paused” method will do the cleanup.
      }
        
   }

FileNewAction

package mars.venus;
public synchronized class FileNewAction extends GuiAction {
public void FileNewAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

EditCutAction

package mars.venus;
public synchronized class EditCutAction extends GuiAction {
public void EditCutAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$insert_tab

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$insert_tab implements java.awt.event.ActionListener {
public void InputHandler$insert_tab();
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/editors/jeditsyntax/TextAreaPainter.java
mars/venus/editors/jeditsyntax/TextAreaPainter.java/*
 * TextAreaPainter.java – Paints the text area
 * Copyright (C) 1999 Slava Pestov
 *
 * 08/05/2002   Cursor (caret) rendering fixed for JDK 1.4 (Anonymous)
 *
 * You may use and modify this package for any purpose. Redistribution is
 * permitted, in both source and binary form, provided that this notice
 * remains intact in all source distributions of this package.
 */

   package mars.venus.editors.jeditsyntax;

   import mars.venus.editors.jeditsyntax.tokenmarker.*;
   import javax.swing.ToolTipManager;
   import javax.swing.text.*;
   import javax.swing.JComponent;
   import java.awt.event.MouseEvent;
   import java.awt.*;

/**
 * The text area repaint manager. It performs double buffering and paints
 * lines of text.
 * @author Slava Pestov
 * @version $Id: TextAreaPainter.java,v 1.24 1999/12/13 03:40:30 sp Exp $
 */
    public class TextAreaPainter extends JComponent implements TabExpander
   {
   /**
    * Creates a new repaint manager. This should be not be called
    * directly.
    */
       public TextAreaPainter(JEditTextArea textArea, TextAreaDefaults defaults)
      {
         this.textArea = textArea;
      
         setAutoscrolls(true);
         setDoubleBuffered(true);
         setOpaque(true);
      
      
      
         ToolTipManager.sharedInstance().registerComponent(this);
      
         currentLine = new Segment();
         currentLineIndex = -1;
      
         setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
      
         setFont(new Font(“Courier New” /*”Monospaced”*/,Font.PLAIN,14));
         setForeground(Color.black);
         setBackground(Color.white);
      
         tabSizeChars = defaults.tabSize;
         blockCaret = defaults.blockCaret;
         styles = defaults.styles;
         cols = defaults.cols;
         rows = defaults.rows;
         caretColor = defaults.caretColor;
         selectionColor = defaults.selectionColor;
         lineHighlightColor = defaults.lineHighlightColor;
         lineHighlight = defaults.lineHighlight;
         bracketHighlightColor = defaults.bracketHighlightColor;
         bracketHighlight = defaults.bracketHighlight;
         paintInvalid = defaults.paintInvalid;
         eolMarkerColor = defaults.eolMarkerColor;
         eolMarkers = defaults.eolMarkers;
      }
   
   /**
    * Returns if this component can be traversed by pressing the
    * Tab key. This returns false. 
    *
    * NOTE: as of Java 1.4 this method is deprecated and no longer 
    * has the desired effect because the focus subsystem does not 
    * call it.  I’ve implemented a KeyEventDispatcher in JEditTextArea
    * to handle Tabs. DPS 12-May-2010
    */
       public final boolean isManagingFocus()
      {
         return false;
      }
   
   /**
    * Fetch the tab size in characters.  DPS 12-May-2010.
    * @return int tab size in characters
    */
       public int getTabSize() {
         return tabSizeChars;
      }
   
   /**
    * Set the tab size in characters. DPS 12-May-2010.
    * Originally it was fixed at PlainDocument property
    * value (8).
    * @param size tab size in characters
    */
       public void setTabSize(int size) {
         tabSizeChars = size;
      }
   
   /**
    * Returns the syntax styles used to paint colorized text. Entry n
    * will be used to paint tokens with id = n.
    * @see org.syntax.jedit.Token
    */
       public final SyntaxStyle[] getStyles()
      {
         return styles;
      }
   
   /**
    * Sets the syntax styles used to paint colorized text. Entry n
    * will be used to paint tokens with id = n.
    * @param styles The syntax styles
    * @see org.syntax.jedit.Token
    */
       public final void setStyles(SyntaxStyle[] styles)
      {
         this.styles = styles;
         repaint();
      }
   
   /**
    * Returns the caret color.
    */
       public final Color getCaretColor()
      {
         return caretColor;
      }
   
   /**
    * Sets the caret color.
    * @param caretColor The caret color
    */
       public final void setCaretColor(Color caretColor)
      {
         this.caretColor = caretColor;
         invalidateSelectedLines();
      }
   
   /**
    * Returns the selection color.
    */
       public final Color getSelectionColor()
      {
         return selectionColor;
      }
   
   /**
    * Sets the selection color.
    * @param selectionColor The selection color
    */
       public final void setSelectionColor(Color selectionColor)
      {
         this.selectionColor = selectionColor;
         invalidateSelectedLines();
      }
   
   /**
    * Returns the line highlight color.
    */
       public final Color getLineHighlightColor()
      {
         return lineHighlightColor;
      }
   
   /**
    * Sets the line highlight color.
    * @param lineHighlightColor The line highlight color
    */
       public final void setLineHighlightColor(Color lineHighlightColor)
      {
         this.lineHighlightColor = lineHighlightColor;
         invalidateSelectedLines();
      }
   
   /**
    * Returns true if line highlight is enabled, false otherwise.
    */
       public final boolean isLineHighlightEnabled()
      {
         return lineHighlight;
      }
   
   /**
    * Enables or disables current line highlighting.
    * @param lineHighlight True if current line highlight should be enabled,
    * false otherwise
    */
       public final void setLineHighlightEnabled(boolean lineHighlight)
      { 
         this.lineHighlight = lineHighlight;
         invalidateSelectedLines();
      }
   
   /**
    * Returns the bracket highlight color.
    */
       public final Color getBracketHighlightColor()
      {
         return bracketHighlightColor;
      }
   
   /**
    * Sets the bracket highlight color.
    * @param bracketHighlightColor The bracket highlight color
    */
       public final void setBracketHighlightColor(Color bracketHighlightColor)
      {
         this.bracketHighlightColor = bracketHighlightColor;
         invalidateLine(textArea.getBracketLine());
      }
   
   /**
    * Returns true if bracket highlighting is enabled, false otherwise.
    * When bracket highlighting is enabled, the bracket matching the
    * one before the caret (if any) is highlighted.
    */
       public final boolean isBracketHighlightEnabled()
      {
         return bracketHighlight;
      }
   
   /**
    * Enables or disables bracket highlighting.
    * When bracket highlighting is enabled, the bracket matching the
    * one before the caret (if any) is highlighted.
    * @param bracketHighlight True if bracket highlighting should be
    * enabled, false otherwise
    */
       public final void setBracketHighlightEnabled(boolean bracketHighlight)
      {
         this.bracketHighlight = bracketHighlight;
         invalidateLine(textArea.getBracketLine());
      }
   
   /**
    * Returns true if the caret should be drawn as a block, false otherwise.
    */
       public final boolean isBlockCaretEnabled()
      {
         return blockCaret;
      }
   
   /**
    * Sets if the caret should be drawn as a block, false otherwise.
    * @param blockCaret True if the caret should be drawn as a block,
    * false otherwise.
    */
       public final void setBlockCaretEnabled(boolean blockCaret)
      {
         this.blockCaret = blockCaret;
         invalidateSelectedLines();
      }
   
   /**
    * Returns the EOL marker color.
    */
       public final Color getEOLMarkerColor()
      {
         return eolMarkerColor;
      }
   
   /**
    * Sets the EOL marker color.
    * @param eolMarkerColor The EOL marker color
    */
       public final void setEOLMarkerColor(Color eolMarkerColor)
      {
         this.eolMarkerColor = eolMarkerColor;
         repaint();
      }
   
   /**
    * Returns true if EOL markers are drawn, false otherwise.
    */
       public final boolean getEOLMarkersPainted()
      {
         return eolMarkers;
      }
   
   /**
    * Sets if EOL markers are to be drawn.
    * @param eolMarkers True if EOL markers should be drawn, false otherwise
    */
       public final void setEOLMarkersPainted(boolean eolMarkers)
      {
         this.eolMarkers = eolMarkers;
         repaint();
      }
   
   /**
    * Returns true if invalid lines are painted as red tildes (~),
    * false otherwise.
    */
       public boolean getInvalidLinesPainted()
      {
         return paintInvalid;
      }
   
   /**
    * Sets if invalid lines are to be painted as red tildes.
    * @param paintInvalid True if invalid lines should be drawn, false otherwise
    */
       public void setInvalidLinesPainted(boolean paintInvalid)
      {
         this.paintInvalid = paintInvalid;
      }
   
   /**
    * Adds a custom highlight painter.
    * @param highlight The highlight
    */
       public void addCustomHighlight(Highlight highlight)
      {
         highlight.init(textArea,highlights);
         highlights = highlight;
      }
   
   /**
    * Highlight interface.
    */
       public interface Highlight
      {
      /**
       * Called after the highlight painter has been added.
       * @param textArea The text area
       * @param next The painter this one should delegate to
       */
          void init(JEditTextArea textArea, Highlight next);
      
      /**
       * This should paint the highlight and delgate to the
       * next highlight painter.
       * @param gfx The graphics context
       * @param line The line number
       * @param y The y co-ordinate of the line
       */
          void paintHighlight(Graphics gfx, int line, int y);
      
      /**
       * Returns the tool tip to display at the specified
       * location. If this highlighter doesn’t know what to
       * display, it should delegate to the next highlight
       * painter.
       * @param evt The mouse event
       */
          String getToolTipText(MouseEvent evt);
      }
   
   /**
    * Returns the tool tip to display at the specified location.
    * @param evt The mouse event
    */
       public String getToolTipText(MouseEvent evt)
      { 
      //          if(highlights != null)
      //             return highlights.getToolTipText(evt);
      //          else
      //             return null;
         if (highlights != null)
            return highlights.getToolTipText(evt);
         else if (this.textArea.getTokenMarker()==null) 
            return null; 
         else 
            return this.textArea.getSyntaxSensitiveToolTipText(evt.getX(),evt.getY());
      //           int line = yToLine(evt.getY());
      //  int offset = xToOffset(line,evt.getX());
      //          {
      //             if (evt instanceof InstructionMouseEvent) {
      //                System.out.println(“get Tool Tip Text for InstructionMouseEvent”);
      //                return “Instruction: “+ ((InstructionMouseEvent)evt).getLine().toString();
      //             } 
      //             else {
      //                return “Not a fake?”;//null;
      //             }
      //          }
      }
   /**
    * Returns the font metrics used by this component.
    */
       public FontMetrics getFontMetrics()
      {
         return fm;
      }
   
   /**
    * Sets the font for this component. This is overridden to update the
    * cached font metrics and to recalculate which lines are visible.
    * @param font The font
    */
       public void setFont(Font font)
      {
         super.setFont(font);
         fm = Toolkit.getDefaultToolkit().getFontMetrics(font); 
         textArea.recalculateVisibleLines();
      }
   
   
   
   /**
    * Repaints the text.
    * @param gfx The graphics context
    */
       public void paint(Graphics gfx)
      {
      
      // Added 4/6/10 DPS to set antialiasing for text rendering – smoother letters
      // Second one says choose algorithm for quality over speed
         ((Graphics2D)gfx).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); 
         ((Graphics2D)gfx).setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
      
      
         tabSize = fm.charWidth(‘ ‘) * tabSizeChars; // was: ((Integer)textArea.getDocument().getProperty(PlainDocument.tabSizeAttribute)).intValue();
      
         Rectangle clipRect = gfx.getClipBounds();
      
         gfx.setColor(getBackground());
         gfx.fillRect(clipRect.x,clipRect.y,clipRect.width,clipRect.height);
      
      // We don’t use yToLine() here because that method doesn’t
      // return lines past the end of the document
         int height = fm.getHeight();
         int firstLine = textArea.getFirstLine();
         int firstInvalid = firstLine + clipRect.y / height;
      // Because the clipRect’s height is usually an even multiple
      // of the font height, we subtract 1 from it, otherwise one
      // too many lines will always be painted.
         int lastInvalid = firstLine + (clipRect.y + clipRect.height – 1) / height;
      
         try
         {
            TokenMarker tokenMarker = ((SyntaxDocument)textArea.getDocument())
               .getTokenMarker();
            int x = textArea.getHorizontalOffset();
         
            for(int line = firstInvalid; line <= lastInvalid; line++)             {                paintLine(gfx,tokenMarker,line,x);             }                       if(tokenMarker != null && tokenMarker.isNextLineRequested())             {                int h = clipRect.y + clipRect.height;                repaint(0,h,getWidth(),getHeight() - h);             }          }              catch(Exception e)             {                System.err.println("Error repainting line"                   + " range {" + firstInvalid + ","                   + lastInvalid + "}:");                e.printStackTrace();             }       }        /**     * Marks a line as needing a repaint.     * @param line The line to invalidate     */        public final void invalidateLine(int line)       {          repaint(0,textArea.lineToY(line) + fm.getMaxDescent() + fm.getLeading(),             getWidth(),fm.getHeight());       }        /**     * Marks a range of lines as needing a repaint.     * @param firstLine The first line to invalidate     * @param lastLine The last line to invalidate     */        public final void invalidateLineRange(int firstLine, int lastLine)       {          repaint(0,textArea.lineToY(firstLine) + fm.getMaxDescent() + fm.getLeading(),             getWidth(),(lastLine - firstLine + 1) * fm.getHeight());       }        /**     * Repaints the lines containing the selection.     */        public final void invalidateSelectedLines()       {          invalidateLineRange(textArea.getSelectionStartLine(),             textArea.getSelectionEndLine());       }        /**     * Implementation of TabExpander interface. Returns next tab stop after     * a specified point.     * @param x The x co-ordinate     * @param tabOffset Ignored     * @return The next tab stop after x
    */
       public float nextTabStop(float x, int tabOffset)
      {
         int offset = textArea.getHorizontalOffset();
         int ntabs = ((int)x – offset) / tabSize;
         return (ntabs + 1) * tabSize + offset;
      }
   
   /**
    * Returns the painter’s preferred size.
    */
       public Dimension getPreferredSize()
      {
         Dimension dim = new Dimension();
         dim.width = fm.charWidth(‘w’) * cols;
         dim.height = fm.getHeight() * rows;
         return dim;
      }
   
   
   /**
    * Returns the painter’s minimum size.
    */
       public Dimension getMinimumSize()
      {
         return getPreferredSize();
      }
   
   // package-private members
      int currentLineIndex;
      Token currentLineTokens;
      Segment currentLine;
   
   // protected members
      protected JEditTextArea textArea;
   
      protected SyntaxStyle[] styles;
      protected Color caretColor;
      protected Color selectionColor;
      protected Color lineHighlightColor;
      protected Color bracketHighlightColor;
      protected Color eolMarkerColor;
   
      protected boolean blockCaret;
      protected boolean lineHighlight;
      protected boolean bracketHighlight;
      protected boolean paintInvalid;
      protected boolean eolMarkers;
      protected int cols;
      protected int rows;
   
      protected int tabSize, tabSizeChars;
      protected FontMetrics fm;
   
      protected Highlight highlights;
   
       protected void paintLine(Graphics gfx, TokenMarker tokenMarker,
       int line, int x)
      {//System.out.println(“paintLine “+ (++count));
         Font defaultFont = getFont();
         Color defaultColor = getForeground();
      
         currentLineIndex = line;
         int y = textArea.lineToY(line);
      
         if(line < 0 || line >= textArea.getLineCount())
         {
            if(paintInvalid)
            {
               paintHighlight(gfx,line,y);
               styles[Token.INVALID].setGraphicsFlags(gfx,defaultFont);
               gfx.drawString(“~”,0,y + fm.getHeight());
            }
         }
         else if(tokenMarker == null)
         {
            paintPlainLine(gfx,line,defaultFont,defaultColor,x,y);
         }
         else
         {
            paintSyntaxLine(gfx,tokenMarker,line,defaultFont,
               defaultColor,x,y);
         }
      }
   
       protected void paintPlainLine(Graphics gfx, int line, Font defaultFont,
       Color defaultColor, int x, int y)
      {
         paintHighlight(gfx,line,y);
         textArea.getLineText(line,currentLine);
      
         gfx.setFont(defaultFont);
         gfx.setColor(defaultColor);
      
         y += fm.getHeight();
         x = Utilities.drawTabbedText(currentLine,x,y,gfx,this,0);
      
         if(eolMarkers)
         {
            gfx.setColor(eolMarkerColor);
            gfx.drawString(“.”,x,y);
         }
      }
   //      private int count=0;
       protected void paintSyntaxLine(Graphics gfx, TokenMarker tokenMarker,
       int line, Font defaultFont, Color defaultColor, int x, int y)
      {//System.out.println(“paintSyntaxLine line “+ line);
         textArea.getLineText(currentLineIndex,currentLine);
         currentLineTokens = tokenMarker.markTokens(currentLine,
            currentLineIndex);
      
         paintHighlight(gfx,line,y);
      
         gfx.setFont(defaultFont);
         gfx.setColor(defaultColor);
         y += fm.getHeight();
         x = SyntaxUtilities.paintSyntaxLine(currentLine,
            currentLineTokens,styles,this,gfx,x,y);
      //          count++;
      //          if (count % 100 == 10) {
      //             textArea.setToolTipText(“Setting Text at Count of “+count); System.out.println(“set tool tip”);
      //          }
      //          if (count % 100 == 60) {
      //             textArea.setToolTipText(null);System.out.println(“reset tool tip”);
      //          }
      //System.out.println(“SyntaxUtilities.paintSyntaxLine “+ (++count));
         if(eolMarkers)
         {
            gfx.setColor(eolMarkerColor);
            gfx.drawString(“.”,x,y);
         }
      }
   
       protected void paintHighlight(Graphics gfx, int line, int y)
      {//System.out.println(“paintHighlight “+ (++count));
         if(line >= textArea.getSelectionStartLine()
         && line <= textArea.getSelectionEndLine())             paintLineHighlight(gfx,line,y);                 if(highlights != null)             highlights.paintHighlight(gfx,line,y);                 if(bracketHighlight && line == textArea.getBracketLine())             paintBracketHighlight(gfx,line,y);                 if(line == textArea.getCaretLine())             paintCaret(gfx,line,y);       }            protected void paintLineHighlight(Graphics gfx, int line, int y)       {//System.out.println("paintLineHighlight "+ (++count));          int height = fm.getHeight();          y += fm.getLeading() + fm.getMaxDescent();                 int selectionStart = textArea.getSelectionStart();          int selectionEnd = textArea.getSelectionEnd();                 if(selectionStart == selectionEnd)          {             if(lineHighlight)             {                gfx.setColor(lineHighlightColor);                gfx.fillRect(0,y,getWidth(),height);             }          }          else          {             gfx.setColor(selectionColor);                       int selectionStartLine = textArea.getSelectionStartLine();             int selectionEndLine = textArea.getSelectionEndLine();             int lineStart = textArea.getLineStartOffset(line);                       int x1, x2;             if(textArea.isSelectionRectangular())             {                int lineLen = textArea.getLineLength(line);                x1 = textArea._offsetToX(line,Math.min(lineLen,                   selectionStart - textArea.getLineStartOffset(                   selectionStartLine)));                x2 = textArea._offsetToX(line,Math.min(lineLen,                   selectionEnd - textArea.getLineStartOffset(                   selectionEndLine)));                if(x1 == x2)                   x2++;             }             else if(selectionStartLine == selectionEndLine)             {                x1 = textArea._offsetToX(line,                   selectionStart - lineStart);                x2 = textArea._offsetToX(line,                   selectionEnd - lineStart);             }             else if(line == selectionStartLine)             {                x1 = textArea._offsetToX(line,                   selectionStart - lineStart);                x2 = getWidth();             }             else if(line == selectionEndLine)             {                x1 = 0;                x2 = textArea._offsetToX(line,                   selectionEnd - lineStart);             }             else             {                x1 = 0;                x2 = getWidth();             }                    // "inlined" min/max()             gfx.fillRect(x1 > x2 ? x2 : x1,y,x1 > x2 ?
               (x1 – x2) : (x2 – x1),height);
         }
      
      }
   
       protected void paintBracketHighlight(Graphics gfx, int line, int y)
      {
         int position = textArea.getBracketPosition();
         if(position == -1)
            return;
         y += fm.getLeading() + fm.getMaxDescent();
         int x = textArea._offsetToX(line,position);
         gfx.setColor(bracketHighlightColor);
      // Hack!!! Since there is no fast way to get the character
      // from the bracket matching routine, we use ( since all
      // brackets probably have the same width anyway
         gfx.drawRect(x,y,fm.charWidth(‘(‘) – 1,
            fm.getHeight() – 1);
      }
   
       protected void paintCaret(Graphics gfx, int line, int y)
      {
         if(textArea.isCaretVisible())
         {
            int offset = textArea.getCaretPosition() 
               – textArea.getLineStartOffset(line);
            int caretX = textArea._offsetToX(line,offset);
            int caretWidth = ((blockCaret ||
               textArea.isOverwriteEnabled()) ?
               fm.charWidth(‘w’) : 1);
            y += fm.getLeading() + fm.getMaxDescent();
            int height = fm.getHeight();
         
            gfx.setColor(caretColor);
         
            if(textArea.isOverwriteEnabled())
            {
               gfx.fillRect(caretX,y + height – 1,
                  caretWidth,1);
            }
            else
            {
               gfx.drawRect(caretX,y,caretWidth, height – 1);
            }
         }
      }
   }

KeywordMap

package mars.venus.editors.jeditsyntax;
public synchronized class KeywordMap {
protected int mapLength;
private KeywordMap$Keyword[] map;
private boolean ignoreCase;
public void KeywordMap(boolean);
public void KeywordMap(boolean, int);
public byte lookup(javax.swing.text.Segment, int, int);
public void add(String, byte);
public boolean getIgnoreCase();
public void setIgnoreCase(boolean);
protected int getStringMapKey(String);
protected int getSegmentMapKey(javax.swing.text.Segment, int, int);
}

InputHandler$backspace_word

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$backspace_word implements java.awt.event.ActionListener {
public void InputHandler$backspace_word();
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$MacroRecorder

package mars.venus.editors.jeditsyntax;
public abstract interface InputHandler$MacroRecorder {
public abstract void actionPerformed(java.awt.event.ActionListener, String);
}

InputHandler

package mars.venus.editors.jeditsyntax;
public abstract synchronized class InputHandler extends java.awt.event.KeyAdapter {
public static final String SMART_HOME_END_PROPERTY = InputHandler.homeEnd;
public static final java.awt.event.ActionListener BACKSPACE;
public static final java.awt.event.ActionListener BACKSPACE_WORD;
public static final java.awt.event.ActionListener DELETE;
public static final java.awt.event.ActionListener DELETE_WORD;
public static final java.awt.event.ActionListener END;
public static final java.awt.event.ActionListener DOCUMENT_END;
public static final java.awt.event.ActionListener SELECT_ALL;
public static final java.awt.event.ActionListener SELECT_END;
public static final java.awt.event.ActionListener SELECT_DOC_END;
public static final java.awt.event.ActionListener INSERT_BREAK;
public static final java.awt.event.ActionListener INSERT_TAB;
public static final java.awt.event.ActionListener HOME;
public static final java.awt.event.ActionListener DOCUMENT_HOME;
public static final java.awt.event.ActionListener SELECT_HOME;
public static final java.awt.event.ActionListener SELECT_DOC_HOME;
public static final java.awt.event.ActionListener NEXT_CHAR;
public static final java.awt.event.ActionListener NEXT_LINE;
public static final java.awt.event.ActionListener NEXT_PAGE;
public static final java.awt.event.ActionListener NEXT_WORD;
public static final java.awt.event.ActionListener SELECT_NEXT_CHAR;
public static final java.awt.event.ActionListener SELECT_NEXT_LINE;
public static final java.awt.event.ActionListener SELECT_NEXT_PAGE;
public static final java.awt.event.ActionListener SELECT_NEXT_WORD;
public static final java.awt.event.ActionListener OVERWRITE;
public static final java.awt.event.ActionListener PREV_CHAR;
public static final java.awt.event.ActionListener PREV_LINE;
public static final java.awt.event.ActionListener PREV_PAGE;
public static final java.awt.event.ActionListener PREV_WORD;
public static final java.awt.event.ActionListener SELECT_PREV_CHAR;
public static final java.awt.event.ActionListener SELECT_PREV_LINE;
public static final java.awt.event.ActionListener SELECT_PREV_PAGE;
public static final java.awt.event.ActionListener SELECT_PREV_WORD;
public static final java.awt.event.ActionListener REPEAT;
public static final java.awt.event.ActionListener TOGGLE_RECT;
public static final java.awt.event.ActionListener CLIP_COPY;
public static final java.awt.event.ActionListener CLIP_PASTE;
public static final java.awt.event.ActionListener CLIP_CUT;
public static final java.awt.event.ActionListener INSERT_CHAR;
private static java.util.Hashtable actions;
protected java.awt.event.ActionListener grabAction;
protected boolean repeat;
protected int repeatCount;
protected InputHandler$MacroRecorder recorder;
static void ();
public void InputHandler();
public static java.awt.event.ActionListener getAction(String);
public static String getActionName(java.awt.event.ActionListener);
public static java.util.Enumeration getActions();
public abstract void addDefaultKeyBindings();
public abstract void addKeyBinding(String, java.awt.event.ActionListener);
public abstract void removeKeyBinding(String);
public abstract void removeAllKeyBindings();
public void grabNextKeyStroke(java.awt.event.ActionListener);
public boolean isRepeatEnabled();
public void setRepeatEnabled(boolean);
public int getRepeatCount();
public void setRepeatCount(int);
public InputHandler$MacroRecorder getMacroRecorder();
public void setMacroRecorder(InputHandler$MacroRecorder);
public abstract InputHandler copy();
public void executeAction(java.awt.event.ActionListener, Object, String);
public static JEditTextArea getTextArea(java.util.EventObject);
protected void handleGrabAction(java.awt.event.KeyEvent);
}

InputHandler$repeat

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$repeat implements java.awt.event.ActionListener, InputHandler$NonRecordable {
public void InputHandler$repeat();
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$delete_word

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$delete_word implements java.awt.event.ActionListener {
public void InputHandler$delete_word();
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$insert_break

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$insert_break implements java.awt.event.ActionListener {
public void InputHandler$insert_break();
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$prev_word

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$prev_word implements java.awt.event.ActionListener {
private boolean select;
public void InputHandler$prev_word(boolean);
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$backspace

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$backspace implements java.awt.event.ActionListener {
public void InputHandler$backspace();
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$insert_char

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$insert_char implements java.awt.event.ActionListener, InputHandler$NonRepeatable {
public void InputHandler$insert_char();
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/editors/jeditsyntax/SyntaxDocument.java
mars/venus/editors/jeditsyntax/SyntaxDocument.java/*
 * SyntaxDocument.java – Document that can be tokenized
 * Copyright (C) 1999 Slava Pestov
 *
 * You may use and modify this package for any purpose. Redistribution is
 * permitted, in both source and binary form, provided that this notice
 * remains intact in all source distributions of this package.
 */

package mars.venus.editors.jeditsyntax;

import  mars.venus.editors.jeditsyntax.tokenmarker.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.UndoableEdit;

/**
 * A document implementation that can be tokenized by the syntax highlighting
 * system.
 *
 * @author Slava Pestov
 * @version $Id: SyntaxDocument.java,v 1.14 1999/12/13 03:40:30 sp Exp $
 */
public class SyntaxDocument extends PlainDocument
{
    /**
     * Returns the token marker that is to be used to split lines
     * of this document up into tokens. May return null if this
     * document is not to be colorized.
     */
    public TokenMarker getTokenMarker()
    {
        return tokenMarker;
    }

    /**
     * Sets the token marker that is to be used to split lines of
     * this document up into tokens. May throw an exception if
     * this is not supported for this type of document.
     * @param tm The new token marker
     */
    public void setTokenMarker(TokenMarker tm)
    {
        tokenMarker = tm;
        if(tm == null)
            return;
        tokenMarker.insertLines(0,getDefaultRootElement()
            .getElementCount());
        tokenizeLines();
    }

    /**
     * Reparses the document, by passing all lines to the token
     * marker. This should be called after the document is first
     * loaded.
     */
    public void tokenizeLines()
    {
        tokenizeLines(0,getDefaultRootElement().getElementCount());
    }

    /**
     * Reparses the document, by passing the specified lines to the
     * token marker. This should be called after a large quantity of
     * text is first inserted.
     * @param start The first line to parse
     * @param len The number of lines, after the first one to parse
     */
    public void tokenizeLines(int start, int len)
    {
        if(tokenMarker == null || !tokenMarker.supportsMultilineTokens())
            return;

        Segment lineSegment = new Segment();
        Element map = getDefaultRootElement();

        len += start;

        try
        {
            for(int i = start; i < len; i++)             {                 Element lineElement = map.getElement(i);                 int lineStart = lineElement.getStartOffset();                 getText(lineStart,lineElement.getEndOffset()                     - lineStart - 1,lineSegment);                 tokenMarker.markTokens(lineSegment,i);             }         }         catch(BadLocationException bl)         {             bl.printStackTrace();         }     }     /**      * Starts a compound edit that can be undone in one operation.      * Subclasses that implement undo should override this method;      * this class has no undo functionality so this method is      * empty.      */     public void beginCompoundEdit() {}     /**      * Ends a compound edit that can be undone in one operation.      * Subclasses that implement undo should override this method;      * this class has no undo functionality so this method is      * empty.      */     public void endCompoundEdit() {}     /**      * Adds an undoable edit to this document's undo list. The edit      * should be ignored if something is currently being undone.      * @param edit The undoable edit      *      * @since jEdit 2.2pre1      */     public void addUndoableEdit(UndoableEdit edit) {}     // protected members     protected TokenMarker tokenMarker;     /**      * We overwrite this method to update the token marker      * state immediately so that any event listeners get a      * consistent token marker.      */     protected void fireInsertUpdate(DocumentEvent evt)     {         if(tokenMarker != null)         {             DocumentEvent.ElementChange ch = evt.getChange(                 getDefaultRootElement());             if(ch != null)             {                 tokenMarker.insertLines(ch.getIndex() + 1,                     ch.getChildrenAdded().length -                     ch.getChildrenRemoved().length);             }         }         super.fireInsertUpdate(evt);     }          /**      * We overwrite this method to update the token marker      * state immediately so that any event listeners get a      * consistent token marker.      */     protected void fireRemoveUpdate(DocumentEvent evt)     {         if(tokenMarker != null)         {             DocumentEvent.ElementChange ch = evt.getChange(                 getDefaultRootElement());             if(ch != null)             {                 tokenMarker.deleteLines(ch.getIndex() + 1,                     ch.getChildrenRemoved().length -                     ch.getChildrenAdded().length);             }         }         super.fireRemoveUpdate(evt);     } } PopupHelpItem package mars.venus.editors.jeditsyntax; public synchronized class PopupHelpItem { private String tokenText; private String example; private String description; private boolean exact; private int exampleLength; private static final String spaces = ; public void PopupHelpItem(String, String, String, boolean); public void PopupHelpItem(String, String, String); public String getTokenText(); public String getExample(); public String getDescription(); public boolean getExact(); public int getExampleLength(); public String getExamplePaddedToLength(int); public void setExample(String); public void setDescription(String); public static int maxExampleLength(java.util.ArrayList); } JEditTextArea$AdjustHandler package mars.venus.editors.jeditsyntax; synchronized class JEditTextArea$AdjustHandler implements java.awt.event.AdjustmentListener { void JEditTextArea$AdjustHandler(JEditTextArea); public void adjustmentValueChanged(java.awt.event.AdjustmentEvent); } JEditTextArea$ScrollLayout package mars.venus.editors.jeditsyntax; synchronized class JEditTextArea$ScrollLayout implements java.awt.LayoutManager { private java.awt.Component center; private java.awt.Component right; private java.awt.Component bottom; private java.util.Vector leftOfScrollBar; void JEditTextArea$ScrollLayout(JEditTextArea); public void addLayoutComponent(String, java.awt.Component); public void removeLayoutComponent(java.awt.Component); public java.awt.Dimension preferredLayoutSize(java.awt.Container); public java.awt.Dimension minimumLayoutSize(java.awt.Container); public void layoutContainer(java.awt.Container); } SyntaxUtilities package mars.venus.editors.jeditsyntax; public synchronized class SyntaxUtilities { public static boolean popupShowing; public static javax.swing.Popup popup; static void ();
public static boolean regionMatches(boolean, javax.swing.text.Segment, int, String);
public static boolean regionMatches(boolean, javax.swing.text.Segment, int, char[]);
public static SyntaxStyle[] getDefaultSyntaxStyles();
public static SyntaxStyle[] getCurrentSyntaxStyles();
public static int paintSyntaxLine(javax.swing.text.Segment, tokenmarker.Token, SyntaxStyle[], javax.swing.text.TabExpander, java.awt.Graphics, int, int);
private void SyntaxUtilities();
}

InputHandler$clip_copy

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$clip_copy implements java.awt.event.ActionListener {
public void InputHandler$clip_copy();
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$NonRepeatable

package mars.venus.editors.jeditsyntax;
public abstract interface InputHandler$NonRepeatable {
}

InputHandler$end

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$end implements java.awt.event.ActionListener {
private boolean select;
public void InputHandler$end(boolean);
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$prev_page

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$prev_page implements java.awt.event.ActionListener {
private boolean select;
public void InputHandler$prev_page(boolean);
public void actionPerformed(java.awt.event.ActionEvent);
}

JEditTextArea

package mars.venus.editors.jeditsyntax;
public synchronized class JEditTextArea extends javax.swing.JComponent {
public static String LEFT_OF_SCROLLBAR;
private static final int VERTICAL_SCROLLBAR_UNIT_INCREMENT_IN_LINES = 1;
private static final int LINES_PER_MOUSE_WHEEL_NOTCH = 3;
private javax.swing.JScrollBar lineNumbersVertical;
javax.swing.JPopupMenu popupMenu;
protected static String CENTER;
protected static String RIGHT;
protected static String BOTTOM;
protected static JEditTextArea focusedComponent;
protected static javax.swing.Timer caretTimer;
protected TextAreaPainter painter;
protected javax.swing.JPopupMenu popup;
protected javax.swing.event.EventListenerList listenerList;
protected JEditTextArea$MutableCaretEvent caretEvent;
protected boolean caretBlinks;
protected boolean caretVisible;
protected boolean blink;
protected boolean editable;
protected int caretBlinkRate;
protected int firstLine;
protected int visibleLines;
protected int electricScroll;
protected int horizontalOffset;
protected javax.swing.JScrollBar vertical;
protected javax.swing.JScrollBar horizontal;
protected boolean scrollBarsInitialized;
protected InputHandler inputHandler;
protected SyntaxDocument document;
protected JEditTextArea$DocumentHandler documentHandler;
protected javax.swing.text.Segment lineSegment;
protected int selectionStart;
protected int selectionStartLine;
protected int selectionEnd;
protected int selectionEndLine;
protected boolean biasLeft;
protected int bracketPosition;
protected int bracketLine;
protected int magicCaret;
protected boolean overwrite;
protected boolean rectSelect;
protected boolean unredoing;
static void ();
public void JEditTextArea(javax.swing.JComponent);
public void JEditTextArea(TextAreaDefaults, javax.swing.JComponent);
public final TextAreaPainter getPainter();
public final InputHandler getInputHandler();
public void setInputHandler(InputHandler);
public final boolean isCaretBlinkEnabled();
public void setCaretBlinkEnabled(boolean);
public final boolean isCaretVisible();
public void setCaretVisible(boolean);
public final void blinkCaret();
public final int getElectricScroll();
public final void setElectricScroll(int);
public void updateScrollBars();
public final int getFirstLine();
public void setFirstLine(int);
public final int getVisibleLines();
public final void recalculateVisibleLines();
public final int getHorizontalOffset();
public void setHorizontalOffset(int);
public boolean setOrigin(int, int);
public boolean scrollToCaret();
public boolean scrollTo(int, int);
public int lineToY(int);
public int yToLine(int);
public final int offsetToX(int, int);
public int _offsetToX(int, int);
public int xToOffset(int, int);
public int xyToOffset(int, int);
public final javax.swing.text.Document getDocument();
public void setDocument(SyntaxDocument);
public final tokenmarker.TokenMarker getTokenMarker();
public final void setTokenMarker(tokenmarker.TokenMarker);
public final int getDocumentLength();
public final int getLineCount();
public final int getLineOfOffset(int);
public int getLineStartOffset(int);
public int getLineEndOffset(int);
public int getLineLength(int);
public String getText();
public void setText(String);
public final String getText(int, int);
public final void getText(int, int, javax.swing.text.Segment);
public final String getLineText(int);
public final void getLineText(int, javax.swing.text.Segment);
public final int getSelectionStart();
public int getSelectionStart(int);
public final int getSelectionStartLine();
public final void setSelectionStart(int);
public final int getSelectionEnd();
public int getSelectionEnd(int);
public final int getSelectionEndLine();
public final void setSelectionEnd(int);
public final int getCaretPosition();
public final int getCaretLine();
public final int getMarkPosition();
public final int getMarkLine();
public final void setCaretPosition(int);
public final void selectAll();
public final void selectNone();
public void select(int, int);
public final String getSelectedText();
public void setSelectedText(String);
public final boolean isEditable();
public final void setEditable(boolean);
public final javax.swing.JPopupMenu getRightClickPopup();
public final void setRightClickPopup(javax.swing.JPopupMenu);
public final int getMagicCaretPosition();
public final void setMagicCaretPosition(int);
public void overwriteSetSelectedText(String);
public final boolean isOverwriteEnabled();
public final void setOverwriteEnabled(boolean);
public final boolean isSelectionRectangular();
public final void setSelectionRectangular(boolean);
public final int getBracketPosition();
public final int getBracketLine();
public final void addCaretListener(javax.swing.event.CaretListener);
public final void removeCaretListener(javax.swing.event.CaretListener);
public void cut();
public void copy();
public void paste();
public void removeNotify();
public void processKeyEvent(java.awt.event.KeyEvent);
protected void fireCaretEvent();
protected void updateBracketHighlight(int);
protected void documentChanged(javax.swing.event.DocumentEvent);
public String getSyntaxSensitiveToolTipText(int, int);
public String getAutoIndent();
public String getLeadingWhiteSpace();
private java.util.ArrayList getSyntaxSensitiveHelpAtLineOffset(int, int, boolean);
private void applySyntaxSensitiveHelp();
private void checkAutoIndent(java.awt.event.KeyEvent);
private void checkPopupMenu(java.awt.event.KeyEvent);
private boolean checkPopupCompletion(java.awt.event.KeyEvent);
}

mars/venus/editors/jeditsyntax/JEditTextArea.java
mars/venus/editors/jeditsyntax/JEditTextArea.java/*
 * JEditTextArea.java – jEdit’s text component
 * Copyright (C) 1999 Slava Pestov
 *
 * You may use and modify this package for any purpose. Redistribution is
 * permitted, in both source and binary form, provided that this notice
 * remains intact in all source distributions of this package.
 */

   package mars.venus.editors.jeditsyntax;

   import mars.Globals;
   import mars.Settings;
   import mars.venus.editors.jeditsyntax.tokenmarker.*; 
   import javax.swing.event.*;
   import javax.swing.text.*;
   import javax.swing.undo.*;
   import javax.swing.*;
   import java.awt.datatransfer.*;
   import java.awt.event.*;
   import java.awt.*;
   import java.util.Enumeration;
   import java.util.Vector;
   import java.util.ArrayList;

/**
 * jEdit’s text area component. It is more suited for editing program
 * source code than JEditorPane, because it drops the unnecessary features
 * (images, variable-width lines, and so on) and adds a whole bunch of
 * useful goodies such as:
 * 

     * 

  • More flexible key binding scheme
     * 

  • Supports macro recorders
     * 

  • Rectangular selection
     * 

  • Bracket highlighting
     * 

  • Syntax highlighting
     * 

  • Command repetition
     * 

  • Block caret can be enabled
     * 

 * It is also faster and doesn’t have as many problems. It can be used
 * in other applications; the only other part of jEdit it depends on is
 * the syntax package.

 *
 * To use it in your app, treat it like any other component, for example:
 * 

JEditTextArea ta = new JEditTextArea();
 * ta.setTokenMarker(new JavaTokenMarker());
 * ta.setText("public class Test {\n"
 *     + "    public static void main(String[] args) {\n"
 *     + "        System.out.println(\"Hello World\");\n"
 *     + "    }\n"
 *     + "}");

 *
 * @author Slava Pestov
 * @version $Id: JEditTextArea.java,v 1.36 1999/12/13 03:40:30 sp Exp $
 */
    public class JEditTextArea extends JComponent 
   {
   /**
    * Adding components with this name to the text area will place
    * them left of the horizontal scroll bar. In jEdit, the status
    * bar is added this way.
    */
      public static String LEFT_OF_SCROLLBAR = “los”;
    
    // Number of text lines moved for each click of the vertical scrollbar buttons.
      private static final int VERTICAL_SCROLLBAR_UNIT_INCREMENT_IN_LINES = 1;
    // Number of text lines moved for each “notch” of the mouse wheel scroller.
      private static final int LINES_PER_MOUSE_WHEEL_NOTCH = 3;
   
   /**
    * Creates a new JEditTextArea with the default settings.
    */
       public JEditTextArea(JComponent lineNumbers)
      {
         this(TextAreaDefaults.getDefaults(), lineNumbers);
      }
   
   /**
    * Creates a new JEditTextArea with the specified settings.
    * @param defaults The default settings
    */
    
      private JScrollBar lineNumbersVertical;//************************************
   
   
       public JEditTextArea(TextAreaDefaults defaults, JComponent lineNumbers)
      {
      // Enable the necessary events
         enableEvents(AWTEvent.KEY_EVENT_MASK);
      
      // Initialize some misc. stuff
         painter = new TextAreaPainter(this,defaults);
         documentHandler = new DocumentHandler();
         listenerList = new EventListenerList();
         caretEvent = new MutableCaretEvent();
         lineSegment = new Segment();
         bracketLine = bracketPosition = -1;
         blink = true;
         unredoing = false;
      
         JScrollPane lineNumberScroller = new JScrollPane(lineNumbers,
                       ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, 
                       ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
         lineNumberScroller.setBorder(new javax.swing.border.EmptyBorder(1,1,1,1));
         lineNumbersVertical = lineNumberScroller.getVerticalScrollBar();
                    
      // Initialize the GUI
         JPanel lineNumbersPlusPainter = new JPanel(new BorderLayout());
         lineNumbersPlusPainter.add(painter, BorderLayout.CENTER);
         lineNumbersPlusPainter.add(lineNumberScroller, BorderLayout.WEST);
         setLayout(new ScrollLayout());
         add(CENTER, lineNumbersPlusPainter); //was: painter
         add(RIGHT,vertical = new JScrollBar(JScrollBar.VERTICAL));
         add(BOTTOM,horizontal = new JScrollBar(JScrollBar.HORIZONTAL));
      
      
      // Add some event listeners
         vertical.addAdjustmentListener(new AdjustHandler());
         horizontal.addAdjustmentListener(new AdjustHandler());
         painter.addComponentListener(new ComponentHandler());
         painter.addMouseListener(new MouseHandler());
         painter.addMouseMotionListener(new DragHandler());
         painter.addMouseWheelListener(new MouseWheelHandler()); // DPS 5-5-10
         addFocusListener(new FocusHandler());
      
      // Load the defaults
         setInputHandler(defaults.inputHandler);
         setDocument(defaults.document);
         editable = defaults.editable;
         caretVisible = defaults.caretVisible;
         caretBlinks = defaults.caretBlinks;
         caretBlinkRate = defaults.caretBlinkRate;
         electricScroll = defaults.electricScroll;
      
         popup = defaults.popup; 
      
         caretTimer.setDelay(caretBlinkRate);
        
        // Intercept keystrokes before focus manager gets them.  If in editing window,
        // pass TAB keystrokes on to the key processor instead of letting focus
        // manager use them for focus traversal.  
        // One can also accomplish this using: setFocusTraversalKeysEnabled(false);
        // but that seems heavy-handed.
        // DPS 12May2010
         KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( 
                new KeyEventDispatcher() {
                   public boolean dispatchKeyEvent(KeyEvent e) {
                     if (JEditTextArea.this.isFocusOwner() && e.getKeyCode()==KeyEvent.VK_TAB &&  e.getModifiers()==0) {
                        processKeyEvent(e);
                        return true;
                     } 
                     else {
                        return false;
                     }
                  }
               });
            
      // We don’t seem to get the initial focus event?
         focusedComponent = this;
      }
   
   
    
   /**
    * Returns if this component can be traversed by pressing
    * the Tab key. This returns false.
    */
   //        public final boolean isManagingFocus()
   //       {
   //          return true;
   //       }
   
   /**
    * Returns the object responsible for painting this text area.
    */
       public final TextAreaPainter getPainter()
      {
         return painter;
      }
   
   /**
    * Returns the input handler.
    */
       public final InputHandler getInputHandler()
      {
         return inputHandler;
      }
   
   /**
    * Sets the input handler.
    * @param inputHandler The new input handler
    */
       public void setInputHandler(InputHandler inputHandler)
      {
         this.inputHandler = inputHandler;
      }
   
   /**
    * Returns true if the caret is blinking, false otherwise.
    */
       public final boolean isCaretBlinkEnabled()
      {
         return caretBlinks;
      }
   
   /**
    * Toggles caret blinking.
    * @param caretBlinks True if the caret should blink, false otherwise
    */
       public void setCaretBlinkEnabled(boolean caretBlinks)
      {
         this.caretBlinks = caretBlinks;
         if(!caretBlinks)
            blink = false;
      
         painter.invalidateSelectedLines();
      }
   
   /**
    * Returns true if the caret is visible, false otherwise.
    */
       public final boolean isCaretVisible()
      {
         return (!caretBlinks || blink) && caretVisible;
      }
   
   /**
    * Sets if the caret should be visible.
    * @param caretVisible True if the caret should be visible, false
    * otherwise
    */
       public void setCaretVisible(boolean caretVisible)
      {
         this.caretVisible = caretVisible;
         blink = true;
      
         painter.invalidateSelectedLines();
      }
   
   /**
    * Blinks the caret.
    */
       public final void blinkCaret()
      {
         if(caretBlinks)
         {
            blink = !blink;
            painter.invalidateSelectedLines();
         }
         else
            blink = true;
      }
   
   /**
    * Returns the number of lines from the top and button of the
    * text area that are always visible.
    */
       public final int getElectricScroll()
      {
         return electricScroll;
      }
   
   /**
    * Sets the number of lines from the top and bottom of the text
    * area that are always visible
    * @param electricScroll The number of lines always visible from
    * the top or bottom
    */
       public final void setElectricScroll(int electricScroll)
      {
         this.electricScroll = electricScroll;
      }
   
   /**
    * Updates the state of the scroll bars. This should be called
    * if the number of lines in the document changes, or when the
    * size of the text are changes.
    */
       public void updateScrollBars()
      {
         if(vertical != null && visibleLines != 0)
         {
            vertical.setValues(firstLine,visibleLines,0,getLineCount());
            vertical.setUnitIncrement(VERTICAL_SCROLLBAR_UNIT_INCREMENT_IN_LINES);
            vertical.setBlockIncrement(visibleLines);
            
            // Editing area scrollbar has custom model that increments by number of text lines instead of
            // number of pixels. The line number display uses a standard (but invisible) scrollbar based
            // on pixels, so I need to adjust accordingly to keep it in synch with the editing area scrollbar.
            // DPS 4-May-2010
            int height = painter.getFontMetrics(painter.getFont()).getHeight();
            lineNumbersVertical.setValues(firstLine*height, visibleLines*height,0,getLineCount()*height);
            lineNumbersVertical.setUnitIncrement(VERTICAL_SCROLLBAR_UNIT_INCREMENT_IN_LINES*height);
            lineNumbersVertical.setBlockIncrement(visibleLines*height);
         }
      
         int width = painter.getWidth();
         if(horizontal != null && width != 0)
         {
            horizontal.setValues(-horizontalOffset,width,0,width * 5);
            horizontal.setUnitIncrement(painter.getFontMetrics()
               .charWidth(‘w’));
            horizontal.setBlockIncrement(width / 2);
         }
      }
   
   /**
    * Returns the line displayed at the text area’s origin.
    */
       public final int getFirstLine()
      {
         return firstLine;
      }
   
   /**
    * Sets the line displayed at the text area’s origin and
    * updates the scroll bars.
    */
       public void setFirstLine(int firstLine)
      {
         if(firstLine == this.firstLine)
            return;
         int oldFirstLine = this.firstLine;
         this.firstLine = firstLine;
         updateScrollBars();
         painter.repaint();
      }
   
   /**
    * Returns the number of lines visible in this text area.
    */
       public final int getVisibleLines()
      {
         return visibleLines;
      }
   
   /**
    * Recalculates the number of visible lines. This should not
    * be called directly.
    */
       public final void recalculateVisibleLines()
      {
         if(painter == null)
            return;
         int height = painter.getHeight();
         int lineHeight = painter.getFontMetrics().getHeight();
         int oldVisibleLines = visibleLines;
         visibleLines = height / lineHeight;
         updateScrollBars();
      }
   
   /**
    * Returns the horizontal offset of drawn lines.
    */
       public final int getHorizontalOffset()
      {
         return horizontalOffset;
      }
   
   /**
    * Sets the horizontal offset of drawn lines. This can be used to
    * implement horizontal scrolling.
    * @param horizontalOffset offset The new horizontal offset
    */
       public void setHorizontalOffset(int horizontalOffset)
      {
         if(horizontalOffset == this.horizontalOffset)
            return;
         this.horizontalOffset = horizontalOffset;
         if(horizontalOffset != horizontal.getValue())
            updateScrollBars();
         painter.repaint();
      }
   
   /**
    * A fast way of changing both the first line and horizontal
    * offset.
    * @param firstLine The new first line
    * @param horizontalOffset The new horizontal offset
    * @return True if any of the values were changed, false otherwise
    */
       public boolean setOrigin(int firstLine, int horizontalOffset)
      {
         boolean changed = false;
         int oldFirstLine = this.firstLine;
      
         if(horizontalOffset != this.horizontalOffset)
         {
            this.horizontalOffset = horizontalOffset;
            changed = true;
         }
      
         if(firstLine != this.firstLine)
         {
            this.firstLine = firstLine;
            changed = true;
         }
      
         if(changed)
         {
            updateScrollBars();
            painter.repaint();
         }
      
         return changed;
      }
   
   /**
    * Ensures that the caret is visible by scrolling the text area if
    * necessary.
    * @return True if scrolling was actually performed, false if the
    * caret was already visible
    */
       public boolean scrollToCaret()
      {
         int line = getCaretLine();
         int lineStart = getLineStartOffset(line);
         int offset = Math.max(0,Math.min(getLineLength(line) – 1,
            getCaretPosition() – lineStart));
      
         return scrollTo(line,offset);
      }
   
   /**
    * Ensures that the specified line and offset is visible by scrolling
    * the text area if necessary.
    * @param line The line to scroll to
    * @param offset The offset in the line to scroll to
    * @return True if scrolling was actually performed, false if the
    * line and offset was already visible
    */
       public boolean scrollTo(int line, int offset)
      {
      // visibleLines == 0 before the component is realized
      // we can’t do any proper scrolling then, so we have
      // this hack…
         if(visibleLines == 0)
         { 
            setFirstLine(Math.max(0,line – electricScroll));
            return true;
         }
      
         int newFirstLine = firstLine;
         int newHorizontalOffset = horizontalOffset;
      
         if(line < firstLine + electricScroll)          {             newFirstLine = Math.max(0,line - electricScroll);          }          else if(line + electricScroll >= firstLine + visibleLines)
         {
            newFirstLine = (line – visibleLines) + electricScroll + 1;
            if(newFirstLine + visibleLines >= getLineCount())
               newFirstLine = getLineCount() – visibleLines;
            if(newFirstLine < 0)                newFirstLine = 0;          }                 int x = _offsetToX(line,offset);          int width = painter.getFontMetrics().charWidth('w');                 if(x < 0)          {             newHorizontalOffset = Math.min(0,horizontalOffset                - x + width + 5);          }          else if(x + width >= painter.getWidth())
         {
            newHorizontalOffset = horizontalOffset +
               (painter.getWidth() – x) – width – 5;
         }
      
         return setOrigin(newFirstLine,newHorizontalOffset);
      }
   
   /**
    * Converts a line index to a y co-ordinate.
    * @param line The line
    */
       public int lineToY(int line)
      {
         FontMetrics fm = painter.getFontMetrics();
         return (line – firstLine) * fm.getHeight()
            – (fm.getLeading() + fm.getMaxDescent());
      }
   
   /**
    * Converts a y co-ordinate to a line index.
    * @param y The y co-ordinate
    */
       public int yToLine(int y)
      {
         FontMetrics fm = painter.getFontMetrics();
         int height = fm.getHeight();
         return Math.max(0,Math.min(getLineCount() – 1,
            y / height + firstLine));
      }
   
   /**
    * Converts an offset in a line into an x co-ordinate. This is a
    * slow version that can be used any time.
    * @param line The line
    * @param offset The offset, from the start of the line
    */
       public final int offsetToX(int line, int offset)
      {
      // don’t use cached tokens
         painter.currentLineTokens = null;
         return _offsetToX(line,offset);
      }
   
   /**
    * Converts an offset in a line into an x co-ordinate. This is a
    * fast version that should only be used if no changes were made
    * to the text since the last repaint.
    * @param line The line
    * @param offset The offset, from the start of the line
    */
       public int _offsetToX(int line, int offset)
      {
         TokenMarker tokenMarker = getTokenMarker();
      
      /* Use painter’s cached info for speed */
         FontMetrics fm = painter.getFontMetrics();
      
         getLineText(line,lineSegment);
      
         int segmentOffset = lineSegment.offset;
         int x = horizontalOffset;
      
      /* If syntax coloring is disabled, do simple translation */
         if(tokenMarker == null)
         {
            lineSegment.count = offset;
            return x + Utilities.getTabbedTextWidth(lineSegment,
               fm,x,painter,0);
         }
         /* If syntax coloring is enabled, we have to do this because
         * tokens can vary in width */
         else
         {
            Token tokens;
            if(painter.currentLineIndex == line
            && painter.currentLineTokens != null)
               tokens = painter.currentLineTokens;
            else
            {
               painter.currentLineIndex = line;
               tokens = painter.currentLineTokens
                  = tokenMarker.markTokens(lineSegment,line);
            }
         
            Toolkit toolkit = painter.getToolkit();
            Font defaultFont = painter.getFont();
            SyntaxStyle[] styles = painter.getStyles();
         
            for(;;)
            {
               byte id = tokens.id;
               if(id == Token.END)
               {
                  return x;
               }
            
               if(id == Token.NULL)
                  fm = painter.getFontMetrics();
               else
                  fm = styles[id].getFontMetrics(defaultFont);
            
               int length = tokens.length;
            
               if(offset + segmentOffset < lineSegment.offset + length)                {                   lineSegment.count = offset - (lineSegment.offset - segmentOffset);                   return x + Utilities.getTabbedTextWidth(                      lineSegment,fm,x,painter,0);                }                else                {                   lineSegment.count = length;                   x += Utilities.getTabbedTextWidth(                      lineSegment,fm,x,painter,0);                   lineSegment.offset += length;                }                tokens = tokens.next;             }          }       }        /**     * Converts an x co-ordinate to an offset within a line.     * @param line The line     * @param x The x co-ordinate     */        public int xToOffset(int line, int x)       {          TokenMarker tokenMarker = getTokenMarker();              /* Use painter's cached info for speed */          FontMetrics fm = painter.getFontMetrics();                 getLineText(line,lineSegment);                 char[] segmentArray = lineSegment.array;          int segmentOffset = lineSegment.offset;          int segmentCount = lineSegment.count;                 int width = horizontalOffset;                 if(tokenMarker == null)          {             for(int i = 0; i < segmentCount; i++)             {                char c = segmentArray[i + segmentOffset];                int charWidth;                if(c == '\t')                   charWidth = (int)painter.nextTabStop(width,i)                      - width;                else                   charWidth = fm.charWidth(c);                             if(painter.isBlockCaretEnabled())                {                   if(x - charWidth <= width)                      return i;                }                else                {                   if(x - charWidth / 2 <= width)                      return i;                }                             width += charWidth;             }                       return segmentCount;          }          else          {             Token tokens;             if(painter.currentLineIndex == line && painter             .currentLineTokens != null)                tokens = painter.currentLineTokens;             else             {                painter.currentLineIndex = line;                tokens = painter.currentLineTokens                   = tokenMarker.markTokens(lineSegment,line);             }                       int offset = 0;             Toolkit toolkit = painter.getToolkit();             Font defaultFont = painter.getFont();             SyntaxStyle[] styles = painter.getStyles();                       for(;;)             {                byte id = tokens.id;                if(id == Token.END)                   return offset;                             if(id == Token.NULL)                   fm = painter.getFontMetrics();                else                   fm = styles[id].getFontMetrics(defaultFont);                             int length = tokens.length;                             for(int i = 0; i < length; i++)                {                   char c = segmentArray[segmentOffset + offset + i];                   int charWidth;                   if(c == '\t')                      charWidth = (int)painter.nextTabStop(width,offset + i)                         - width;                   else                      charWidth = fm.charWidth(c);                                   if(painter.isBlockCaretEnabled())                   {                      if(x - charWidth <= width)                         return offset + i;                   }                   else                   {                      if(x - charWidth / 2 <= width)                         return offset + i;                   }                                   width += charWidth;                }                             offset += length;                tokens = tokens.next;             }          }       }        /**     * Converts a point to an offset, from the start of the text.     * @param x The x co-ordinate of the point     * @param y The y co-ordinate of the point     */        public int xyToOffset(int x, int y)       {          int line = yToLine(y);          int start = getLineStartOffset(line);          return start + xToOffset(line,x);       }        /**     * Returns the document this text area is editing.     */        public final Document getDocument()       {          return document;       }        /**     * Sets the document this text area is editing.     * @param document The document     */        public void setDocument(SyntaxDocument document)       {          if(this.document == document)             return;          if(this.document != null)             this.document.removeDocumentListener(documentHandler);          this.document = document;                 document.addDocumentListener(documentHandler);                 select(0,0);          updateScrollBars();          painter.repaint();       }        /**     * Returns the document's token marker. Equivalent to calling     * getDocument().getTokenMarker().
    */
       public final TokenMarker getTokenMarker()
      {
         return document.getTokenMarker();
      }
   
   /**
    * Sets the document’s token marker. Equivalent to caling
    * getDocument().setTokenMarker().
    * @param tokenMarker The token marker
    */
       public final void setTokenMarker(TokenMarker tokenMarker)
      {
         document.setTokenMarker(tokenMarker);
      }
   
   /**
    * Returns the length of the document. Equivalent to calling
    * getDocument().getLength().
    */
       public final int getDocumentLength()
      {
         return document.getLength();
      }
   
   /**
    * Returns the number of lines in the document.
    */
       public final int getLineCount()
      {
         return document.getDefaultRootElement().getElementCount();
      }
   
   /**
    * Returns the line containing the specified offset.
    * @param offset The offset
    */
       public final int getLineOfOffset(int offset)
      {
         return document.getDefaultRootElement().getElementIndex(offset);
      }
   
   /**
    * Returns the start offset of the specified line.
    * @param line The line
    * @return The start offset of the specified line, or -1 if the line is
    * invalid
    */
       public int getLineStartOffset(int line)
      {
         Element lineElement = document.getDefaultRootElement()
            .getElement(line);
         if(lineElement == null)
            return -1;
         else
            return lineElement.getStartOffset();
      }
   
   /**
    * Returns the end offset of the specified line.
    * @param line The line
    * @return The end offset of the specified line, or -1 if the line is
    * invalid.
    */
       public int getLineEndOffset(int line)
      {
         Element lineElement = document.getDefaultRootElement()
            .getElement(line);
         if(lineElement == null)
            return -1;
         else
            return lineElement.getEndOffset();
      }
   
   /**
    * Returns the length of the specified line.
    * @param line The line
    */
       public int getLineLength(int line)
      {
         Element lineElement = document.getDefaultRootElement()
            .getElement(line);
         if(lineElement == null)
            return -1;
         else
            return lineElement.getEndOffset()
               – lineElement.getStartOffset() – 1;
      }
   
   /**
    * Returns the entire text of this text area.
    */
       public String getText()
      {
         try
         {
            return document.getText(0,document.getLength());
         }
             catch(BadLocationException bl)
            {
               bl.printStackTrace();
               return null;
            }
      }
   
   /**
    * Sets the entire text of this text area.
    */
       public void setText(String text)
      {
         try
         {
            document.beginCompoundEdit();
            document.remove(0,document.getLength());
            document.insertString(0,text,null);
         }
             catch(BadLocationException bl)
            {
               bl.printStackTrace();
            }
         finally
         {
            document.endCompoundEdit();
         }
      }
   
   /**
    * Returns the specified substring of the document.
    * @param start The start offset
    * @param len The length of the substring
    * @return The substring, or null if the offsets are invalid
    */
       public final String getText(int start, int len)
      {
         try
         {
            return document.getText(start,len);
         }
             catch(BadLocationException bl)
            {
               bl.printStackTrace();
               return null;
            }
      }
   
   /**
    * Copies the specified substring of the document into a segment.
    * If the offsets are invalid, the segment will contain a null string.
    * @param start The start offset
    * @param len The length of the substring
    * @param segment The segment
    */
       public final void getText(int start, int len, Segment segment)
      {
         try
         {
            document.getText(start,len,segment);
         }
             catch(BadLocationException bl)
            {
               bl.printStackTrace();
               segment.offset = segment.count = 0;
            }
      }
   
   /**
    * Returns the text on the specified line.
    * @param lineIndex The line
    * @return The text, or null if the line is invalid
    */
       public final String getLineText(int lineIndex)
      {
         int start = getLineStartOffset(lineIndex);
         return getText(start,getLineEndOffset(lineIndex) – start – 1);
      }
   
   /**
    * Copies the text on the specified line into a segment. If the line
    * is invalid, the segment will contain a null string.
    * @param lineIndex The line
    */
       public final void getLineText(int lineIndex, Segment segment)
      {
         int start = getLineStartOffset(lineIndex);
         getText(start,getLineEndOffset(lineIndex) – start – 1,segment);
      }
   
   /**
    * Returns the selection start offset.
    */
       public final int getSelectionStart()
      {
         return selectionStart;
      }
   
   /**
    * Returns the offset where the selection starts on the specified
    * line.
    */
       public int getSelectionStart(int line)
      {
         if(line == selectionStartLine)
            return selectionStart;
         else if(rectSelect)
         {
            Element map = document.getDefaultRootElement();
            int start = selectionStart – map.getElement(selectionStartLine)
               .getStartOffset();
         
            Element lineElement = map.getElement(line);
            int lineStart = lineElement.getStartOffset();
            int lineEnd = lineElement.getEndOffset() – 1;
            return Math.min(lineEnd,lineStart + start);
         }
         else
            return getLineStartOffset(line);
      }
   
   /**
    * Returns the selection start line.
    */
       public final int getSelectionStartLine()
      {
         return selectionStartLine;
      }
   
   /**
    * Sets the selection start. The new selection will be the new
    * selection start and the old selection end.
    * @param selectionStart The selection start
    * @see #select(int,int)
    */
       public final void setSelectionStart(int selectionStart)
      {
         select(selectionStart,selectionEnd);
      }
   
   /**
    * Returns the selection end offset.
    */
       public final int getSelectionEnd()
      {
         return selectionEnd;
      }
   
   /**
    * Returns the offset where the selection ends on the specified
    * line.
    */
       public int getSelectionEnd(int line)
      {
         if(line == selectionEndLine)
            return selectionEnd;
         else if(rectSelect)
         {
            Element map = document.getDefaultRootElement();
            int end = selectionEnd – map.getElement(selectionEndLine)
               .getStartOffset();
         
            Element lineElement = map.getElement(line);
            int lineStart = lineElement.getStartOffset();
            int lineEnd = lineElement.getEndOffset() – 1;
            return Math.min(lineEnd,lineStart + end);
         }
         else
            return getLineEndOffset(line) – 1;
      }
   
   /**
    * Returns the selection end line.
    */
       public final int getSelectionEndLine()
      {
         return selectionEndLine;
      }
   
   /**
    * Sets the selection end. The new selection will be the old
    * selection start and the new selection end.
    * @param selectionEnd The selection end
    * @see #select(int,int)
    */
       public final void setSelectionEnd(int selectionEnd)
      {
         select(selectionStart,selectionEnd);
      }
   
   /**
    * Returns the caret position. This will either be the selection
    * start or the selection end, depending on which direction the
    * selection was made in.
    */
       public final int getCaretPosition()
      {
         return (biasLeft ? selectionStart : selectionEnd);
      }
   
   /**
    * Returns the caret line.
    */
       public final int getCaretLine()
      {
         return (biasLeft ? selectionStartLine : selectionEndLine);
      }
   
   /**
    * Returns the mark position. This will be the opposite selection
    * bound to the caret position.
    * @see #getCaretPosition()
    */
       public final int getMarkPosition()
      {
         return (biasLeft ? selectionEnd : selectionStart);
      }
   
   /**
    * Returns the mark line.
    */
       public final int getMarkLine()
      {
         return (biasLeft ? selectionEndLine : selectionStartLine);
      }
   
   /**
    * Sets the caret position. The new selection will consist of the
    * caret position only (hence no text will be selected)
    * @param caret The caret position
    * @see #select(int,int)
    */
       public final void setCaretPosition(int caret)
      {
         select(caret,caret);
      }
   
   /**
    * Selects all text in the document.
    */
       public final void selectAll()
      {
         select(0,getDocumentLength());
      }
   
   /**
    * Moves the mark to the caret position.
    */
       public final void selectNone()
      {
         select(getCaretPosition(),getCaretPosition());
      }
   
   /**
    * Selects from the start offset to the end offset. This is the
    * general selection method used by all other selecting methods.
    * The caret position will be start if start < end, and end
    * if end > start.
    * @param start The start offset
    * @param end The end offset
    */
       public void select(int start, int end)
      {
         int newStart, newEnd;
         boolean newBias;
         if(start <= end)          {             newStart = start;             newEnd = end;             newBias = false;          }          else          {             newStart = end;             newEnd = start;             newBias = true;          }                 if(newStart < 0 || newEnd > getDocumentLength())
         {
            throw new IllegalArgumentException(“Bounds out of”
               + ” range: ” + newStart + “,” +
               newEnd);
         }
      
      // If the new position is the same as the old, we don’t
      // do all this crap, however we still do the stuff at
      // the end (clearing magic position, scrolling)
         if(newStart != selectionStart || newEnd != selectionEnd
         || newBias != biasLeft)
         {
            int newStartLine = getLineOfOffset(newStart);
            int newEndLine = getLineOfOffset(newEnd);
         
            if(painter.isBracketHighlightEnabled())
            {
               if(bracketLine != -1)
                  painter.invalidateLine(bracketLine);
               updateBracketHighlight(end);
               if(bracketLine != -1)
                  painter.invalidateLine(bracketLine);
            }
         
            painter.invalidateLineRange(selectionStartLine,selectionEndLine);
            painter.invalidateLineRange(newStartLine,newEndLine);
         
            document.addUndoableEdit(new CaretUndo(
               selectionStart,selectionEnd));
         
            selectionStart = newStart;
            selectionEnd = newEnd;
            selectionStartLine = newStartLine;
            selectionEndLine = newEndLine;
            biasLeft = newBias;
         
            fireCaretEvent();
         }
      
      // When the user is typing, etc, we don’t want the caret
      // to blink
         blink = true;
         caretTimer.restart();
      
      // Disable rectangle select if selection start = selection end
         if(selectionStart == selectionEnd)
            rectSelect = false;
      
      // Clear the `magic’ caret position used by up/down
         magicCaret = -1;      
         scrollToCaret();
      }
   
   /**
    * Returns the selected text, or null if no selection is active.
    */
       public final String getSelectedText()
      {
         if(selectionStart == selectionEnd)
            return null;
      
         if(rectSelect)
         {
         // Return each row of the selection on a new line
         
            Element map = document.getDefaultRootElement();
         
            int start = selectionStart – map.getElement(selectionStartLine)
               .getStartOffset();
            int end = selectionEnd – map.getElement(selectionEndLine)
               .getStartOffset();
         
         // Certain rectangles satisfy this condition…
            if(end < start)             {                int tmp = end;                end = start;                start = tmp;             }                       StringBuffer buf = new StringBuffer();             Segment seg = new Segment();                       for(int i = selectionStartLine; i <= selectionEndLine; i++)             {                Element lineElement = map.getElement(i);                int lineStart = lineElement.getStartOffset();                int lineEnd = lineElement.getEndOffset() - 1;                int lineLen = lineEnd - lineStart;                             lineStart = Math.min(lineStart + start,lineEnd);                lineLen = Math.min(end - start,lineEnd - lineStart);                             getText(lineStart,lineLen,seg);                buf.append(seg.array,seg.offset,seg.count);                             if(i != selectionEndLine)                   buf.append('\n');             }                       return buf.toString();          }          else          {             return getText(selectionStart,                selectionEnd - selectionStart);          }       }                 /**     * Replaces the selection with the specified text.     * @param selectedText The replacement text for the selection     */        public void setSelectedText(String selectedText)       {          if(!editable)          {             throw new InternalError("Text component"                + " read only");          }                 document.beginCompoundEdit();                 try          {             if(rectSelect)             {                Element map = document.getDefaultRootElement();                             int start = selectionStart - map.getElement(selectionStartLine)                   .getStartOffset();                int end = selectionEnd - map.getElement(selectionEndLine)                   .getStartOffset();                          // Certain rectangles satisfy this condition...                if(end < start)                {                   int tmp = end;                   end = start;                   start = tmp;                }                             int lastNewline = 0;                int currNewline = 0;                             for(int i = selectionStartLine; i <= selectionEndLine; i++)                {                   Element lineElement = map.getElement(i);                   int lineStart = lineElement.getStartOffset();                   int lineEnd = lineElement.getEndOffset() - 1;                   int rectStart = Math.min(lineEnd,lineStart + start);                                   document.remove(rectStart,Math.min(lineEnd - rectStart,                      end - start));                                   if(selectedText == null)                      continue;                                   currNewline = selectedText.indexOf('\n',lastNewline);                   if(currNewline == -1)                      currNewline = selectedText.length();                                   document.insertString(rectStart,selectedText                      .substring(lastNewline,currNewline),null);                                   lastNewline = Math.min(selectedText.length(),                      currNewline + 1);                }                             if(selectedText != null &&                currNewline != selectedText.length())                {                   int offset = map.getElement(selectionEndLine)                      .getEndOffset() - 1;                   document.insertString(offset,"\n",null);                   document.insertString(offset + 1,selectedText                      .substring(currNewline + 1),null);                }             }             else             {                document.remove(selectionStart,                   selectionEnd - selectionStart);                if(selectedText != null)                {                   document.insertString(selectionStart,                      selectedText,null);                }             }          }              catch(BadLocationException bl)             {                bl.printStackTrace();                throw new InternalError("Cannot replace"                   + " selection");             }          // No matter what happends... stops us from leaving document          // in a bad state          finally          {             document.endCompoundEdit();          }                 setCaretPosition(selectionEnd);       }        /**     * Returns true if this text area is editable, false otherwise.     */        public final boolean isEditable()       {          return editable;       }        /**     * Sets if this component is editable.     * @param editable True if this text area should be editable,     * false otherwise     */        public final void setEditable(boolean editable)       {          this.editable = editable;       }        /**     * Returns the right click popup menu.     */        public final JPopupMenu getRightClickPopup()       {          return popup;       }        /**     * Sets the right click popup menu.     * @param popup The popup     */        public final void setRightClickPopup(JPopupMenu popup)       {          this.popup = popup;       }        /**     * Returns the `magic' caret position. This can be used to preserve     * the column position when moving up and down lines.     */        public final int getMagicCaretPosition()       {          return magicCaret;       }        /**     * Sets the `magic' caret position. This can be used to preserve     * the column position when moving up and down lines.     * @param magicCaret The magic caret position     */        public final void setMagicCaretPosition(int magicCaret)       {          this.magicCaret = magicCaret;       }        /**     * Similar to setSelectedText(), but overstrikes the
    * appropriate number of characters if overwrite mode is enabled.
    * @param str The string
    * @see #setSelectedText(String)
    * @see #isOverwriteEnabled()
    */
       public void overwriteSetSelectedText(String str)
      {
      // Don’t overstrike if there is a selection
         if(!overwrite || selectionStart != selectionEnd)
         {
            setSelectedText(str);
            applySyntaxSensitiveHelp();
            return;
         }
      
      // Don’t overstrike if we’re on the end of
      // the line
         int caret = getCaretPosition();
         int caretLineEnd = getLineEndOffset(getCaretLine());
         if(caretLineEnd – caret <= str.length())          {             setSelectedText(str);             applySyntaxSensitiveHelp();             return;          }                 document.beginCompoundEdit();                 try          {             document.remove(caret,str.length());             document.insertString(caret,str,null);          }              catch(BadLocationException bl)             {                bl.printStackTrace();             }          finally          {             document.endCompoundEdit();          }          applySyntaxSensitiveHelp();                }           JPopupMenu popupMenu;                /**     * Returns true if overwrite mode is enabled, false otherwise.     */        public final boolean isOverwriteEnabled()       {          return overwrite;       }        /**     * Sets if overwrite mode should be enabled.     * @param overwrite True if overwrite mode should be enabled,     * false otherwise.     */        public final void setOverwriteEnabled(boolean overwrite)       {          this.overwrite = overwrite;          painter.invalidateSelectedLines();       }        /**     * Returns true if the selection is rectangular, false otherwise.     */        public final boolean isSelectionRectangular()       {          return rectSelect;       }        /**     * Sets if the selection should be rectangular.     * @param overwrite True if the selection should be rectangular,     * false otherwise.     */        public final void setSelectionRectangular(boolean rectSelect)       {          this.rectSelect = rectSelect;          painter.invalidateSelectedLines();       }        /**     * Returns the position of the highlighted bracket (the bracket     * matching the one before the caret)     */        public final int getBracketPosition()       {          return bracketPosition;       }        /**     * Returns the line of the highlighted bracket (the bracket     * matching the one before the caret)     */        public final int getBracketLine()       {          return bracketLine;       }        /**     * Adds a caret change listener to this text area.     * @param listener The listener     */        public final void addCaretListener(CaretListener listener)       {          listenerList.add(CaretListener.class,listener);       }        /**     * Removes a caret change listener from this text area.     * @param listener The listener     */        public final void removeCaretListener(CaretListener listener)       {          listenerList.remove(CaretListener.class,listener);       }        /**     * Deletes the selected text from the text area and places it     * into the clipboard.     */        public void cut()       {          if(editable)          {             copy();             setSelectedText("");          }       }        /**     * Places the selected text into the clipboard.     */        public void copy()       {          if(selectionStart != selectionEnd)          {             Clipboard clipboard = getToolkit().getSystemClipboard();                       String selection = getSelectedText();                       int repeatCount = inputHandler.getRepeatCount();             StringBuffer buf = new StringBuffer();             for(int i = 0; i < repeatCount; i++)                buf.append(selection);                       clipboard.setContents(new StringSelection(buf.toString()),null);          }       }        /**     * Inserts the clipboard contents into the text.     */        public void paste()       {          if(editable)          {             Clipboard clipboard = getToolkit().getSystemClipboard();             try             {             // The MacOS MRJ doesn't convert \r to \n,             // so do it here                String selection = ((String)clipboard                   .getContents(this).getTransferData(                   DataFlavor.stringFlavor))                   .replace('\r','\n');                             int repeatCount = inputHandler.getRepeatCount();                StringBuffer buf = new StringBuffer();                for(int i = 0; i < repeatCount; i++)                   buf.append(selection);                selection = buf.toString();                setSelectedText(selection);             }                 catch(Exception e)                {                   getToolkit().beep();                   System.err.println("Clipboard does not"                      + " contain a string");                }          }       }        /**     * Called by the AWT when this component is removed from it's parent.     * This stops clears the currently focused component.     */        public void removeNotify()       {          super.removeNotify();          if(focusedComponent == this)             focusedComponent = null;       }        /**     * Forwards key events directly to the input handler.     * This is slightly faster than using a KeyListener     * because some Swing overhead is avoided.     */        public void processKeyEvent(KeyEvent evt)       {           if(inputHandler == null)             return;          switch(evt.getID())          {             case KeyEvent.KEY_TYPED:                inputHandler.keyTyped(evt);                break;             case KeyEvent.KEY_PRESSED:                if (!checkPopupCompletion(evt)) {                   inputHandler.keyPressed(evt);                }                checkPopupMenu(evt);                break;             case KeyEvent.KEY_RELEASED:                inputHandler.keyReleased(evt);                break;          }       }        // protected members       protected static String CENTER = "center";       protected static String RIGHT = "right";       protected static String BOTTOM = "bottom";           protected static JEditTextArea focusedComponent;       protected static Timer caretTimer;           protected TextAreaPainter painter;           protected JPopupMenu popup;           protected EventListenerList listenerList;       protected MutableCaretEvent caretEvent;           protected boolean caretBlinks;       protected boolean caretVisible;       protected boolean blink;           protected boolean editable;           protected int caretBlinkRate;       protected int firstLine;       protected int visibleLines;       protected int electricScroll;           protected int horizontalOffset;           protected JScrollBar vertical;       protected JScrollBar horizontal;       protected boolean scrollBarsInitialized;           protected InputHandler inputHandler;       protected SyntaxDocument document;       protected DocumentHandler documentHandler;           protected Segment lineSegment;           protected int selectionStart;       protected int selectionStartLine;       protected int selectionEnd;       protected int selectionEndLine;       protected boolean biasLeft;           protected int bracketPosition;       protected int bracketLine;           protected int magicCaret;       protected boolean overwrite;       protected boolean rectSelect;       // "unredoing" is mode used by DocumentHandler's insertUpdate() and removeUpdate()       // to pleasingly select the text and location of the undo.   DPS 3-May-2010       protected boolean unredoing = false;                 protected void fireCaretEvent()       {          Object[] listeners = listenerList.getListenerList();          for(int i = listeners.length - 2; i >= 0; i–)
         {
            if(listeners[i] == CaretListener.class)
            {
               ((CaretListener)listeners[i+1]).caretUpdate(caretEvent);
            }
         }
      }
   
       protected void updateBracketHighlight(int newCaretPosition)
      {
         if(newCaretPosition == 0)
         {
            bracketPosition = bracketLine = -1;
            return;
         }
      
         try
         {
            int offset = TextUtilities.findMatchingBracket(
               document,newCaretPosition – 1);
            if(offset != -1)
            {
               bracketLine = getLineOfOffset(offset);
               bracketPosition = offset – getLineStartOffset(bracketLine);
               return;
            }
         }
             catch(BadLocationException bl)
            {
               bl.printStackTrace();
            }
      
         bracketLine = bracketPosition = -1;
      }
   
       protected void documentChanged(DocumentEvent evt)
      {
         DocumentEvent.ElementChange ch = evt.getChange(
            document.getDefaultRootElement());
      
         int count;
         if(ch == null)
            count = 0;
         else
            count = ch.getChildrenAdded().length –
               ch.getChildrenRemoved().length;
      
         int line = getLineOfOffset(evt.getOffset());
         if(count == 0)
         {
            painter.invalidateLine(line);
         }
         // do magic stuff
         else if(line < firstLine)          {             setFirstLine(firstLine + count);          }          // end of magic stuff          else          {             painter.invalidateLineRange(line,firstLine + visibleLines);             updateScrollBars();          }       }            class ScrollLayout implements LayoutManager       {           public void addLayoutComponent(String name, Component comp)          {             if(name.equals(CENTER))                center = comp;             else if(name.equals(RIGHT))                right = comp;             else if(name.equals(BOTTOM))                bottom = comp;             else if(name.equals(LEFT_OF_SCROLLBAR))                leftOfScrollBar.addElement(comp);          }                  public void removeLayoutComponent(Component comp)          {             if(center == comp)                center = null;             if(right == comp)                right = null;             if(bottom == comp)                bottom = null;             else                leftOfScrollBar.removeElement(comp);          }                  public Dimension preferredLayoutSize(Container parent)          {             Dimension dim = new Dimension();             Insets insets = getInsets();             dim.width = insets.left + insets.right;             dim.height = insets.top + insets.bottom;                       Dimension centerPref = center.getPreferredSize();             dim.width += centerPref.width;             dim.height += centerPref.height;             Dimension rightPref = right.getPreferredSize();             dim.width += rightPref.width;             Dimension bottomPref = bottom.getPreferredSize();             dim.height += bottomPref.height;                       return dim;          }                  public Dimension minimumLayoutSize(Container parent)          {             Dimension dim = new Dimension();             Insets insets = getInsets();             dim.width = insets.left + insets.right;             dim.height = insets.top + insets.bottom;                       Dimension centerPref = center.getMinimumSize();             dim.width += centerPref.width;              dim.height += centerPref.height;             Dimension rightPref = right.getMinimumSize();             dim.width += rightPref.width;             Dimension bottomPref = bottom.getMinimumSize();             dim.height += bottomPref.height;                       return dim;          }                  public void layoutContainer(Container parent)          {             Dimension size = parent.getSize();             Insets insets = parent.getInsets();             int itop = insets.top;             int ileft = insets.left;             int ibottom = insets.bottom;             int iright = insets.right;                       int rightWidth = right.getPreferredSize().width;             int bottomHeight = bottom.getPreferredSize().height;             int centerWidth = size.width - rightWidth - ileft - iright;             int centerHeight = size.height - bottomHeight - itop - ibottom;                       center.setBounds(                ileft,                itop,                centerWidth,                centerHeight);                       right.setBounds(                ileft + centerWidth,                itop,                rightWidth,                centerHeight);                    // Lay out all status components, in order             Enumeration status = leftOfScrollBar.elements();             while(status.hasMoreElements())             {                Component comp = (Component)status.nextElement();                Dimension dim = comp.getPreferredSize();                comp.setBounds(ileft,                   itop + centerHeight,                   dim.width,                   bottomHeight);                ileft += dim.width;             }                       bottom.setBounds(                ileft,                itop + centerHeight,                size.width - rightWidth - ileft - iright,                bottomHeight);          }              // private members          private Component center;          private Component right;          private Component bottom;          private Vector leftOfScrollBar = new Vector();       }            static class CaretBlinker implements ActionListener       {           public void actionPerformed(ActionEvent evt)          {             if(focusedComponent != null             && focusedComponent.hasFocus())                focusedComponent.blinkCaret();          }       }            class MutableCaretEvent extends CaretEvent       {           MutableCaretEvent()          {             super(JEditTextArea.this);          }                  public int getDot()          {             return getCaretPosition();          }                  public int getMark()          {             return getMarkPosition();          }       }            class AdjustHandler implements AdjustmentListener       {           public void adjustmentValueChanged(final AdjustmentEvent evt)          {             if(!scrollBarsInitialized)                return;                    // If this is not done, mousePressed events accumulate          // and the result is that scrolling doesn't stop after          // the mouse is released             SwingUtilities.invokeLater(                    new Runnable() {                       public void run()                      {                         if(evt.getAdjustable() == vertical)                            setFirstLine(vertical.getValue());                         else                            setHorizontalOffset(-horizontal.getValue());                      }                   });          }       }            class ComponentHandler extends ComponentAdapter       {           public void componentResized(ComponentEvent evt)          {               recalculateVisibleLines();             scrollBarsInitialized = true;          }       }                    class DocumentHandler implements DocumentListener       {           public void insertUpdate(DocumentEvent evt)          {             documentChanged(evt);                       int offset = evt.getOffset();             int length = evt.getLength();                       // If event fired because of undo or redo, select inserted text. DPS 3-May-2010             if (unredoing) {                 select(offset,offset+length);                 return;             }                       int newStart;             int newEnd;                       if(selectionStart > offset || (selectionStart 
            == selectionEnd && selectionStart == offset))
               newStart = selectionStart + length;
            else
               newStart = selectionStart;
         
            if(selectionEnd >= offset)
               newEnd = selectionEnd + length;
            else
               newEnd = selectionEnd;
            select(newStart,newEnd);
         }
      
          public void removeUpdate(DocumentEvent evt)
         {
            documentChanged(evt);
         
            int offset = evt.getOffset();
            int length = evt.getLength();
         
            // If event fired because of undo or redo, move caret to position of removal. DPS 3-May-2010
            if (unredoing) {
               select(offset,offset);
               setCaretPosition(offset);
               return;
            }
         
            int newStart;
            int newEnd;
         
            if(selectionStart > offset)
            {
               if(selectionStart > offset + length)
                  newStart = selectionStart – length;
               else
                  newStart = offset;
            }
            else
               newStart = selectionStart;
         
            if(selectionEnd > offset)
            {
               if(selectionEnd > offset + length)
                  newEnd = selectionEnd – length;
               else
                  newEnd = offset;
            }
            else
               newEnd = selectionEnd;
            select(newStart,newEnd);
         }
      
          public void changedUpdate(DocumentEvent evt)
         {
         }
      }
   
       class DragHandler implements MouseMotionListener
      {
          public void mouseDragged(MouseEvent evt)
         {
            if(popup != null && popup.isVisible())
               return;
         
            setSelectionRectangular((evt.getModifiers()
               & InputEvent.CTRL_MASK) != 0);
            select(getMarkPosition(),xyToOffset(evt.getX(),evt.getY()));
         }
      
          public void mouseMoved(MouseEvent evt) {}
      }
   
       class FocusHandler implements FocusListener
      {
          public void focusGained(FocusEvent evt)
         {
            setCaretVisible(true);
            focusedComponent = JEditTextArea.this;
         }
      
          public void focusLost(FocusEvent evt)
         {
            setCaretVisible(false);
            focusedComponent = null;
         }
      }
   
       // Added by DPS, 5-5-2010. Allows use of mouse wheel to scroll.
     // Scrolling as fast as I could, the most notches I could get in
     // one MouseWheelEvent was 3.  Normally it will be 1.  Nonetheless,
     // this will scroll up to the number in the event, subject to
     // scrollability of the text in its viewport. 
       class MouseWheelHandler implements MouseWheelListener
      {
          public void mouseWheelMoved(MouseWheelEvent e) { 
            int maxMotion = Math.abs(e.getWheelRotation()) * LINES_PER_MOUSE_WHEEL_NOTCH;
            if (e.getWheelRotation() < 0) {                 setFirstLine( getFirstLine() - Math.min(maxMotion, getFirstLine()) );              }              else {                setFirstLine( getFirstLine() + (Math.min(maxMotion, Math.max(0,getLineCount()-(getFirstLine()+visibleLines)))));             }           }       }                class MouseHandler extends MouseAdapter       {           public void mousePressed(MouseEvent evt)          {             requestFocus();                    // Focus events not fired sometimes?             setCaretVisible(true);             focusedComponent = JEditTextArea.this;                       if((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0             && popup != null)             {                popup.show(painter,evt.getX(),evt.getY());                return;             }                       int line = yToLine(evt.getY());             int offset = xToOffset(line,evt.getX());             int dot = getLineStartOffset(line) + offset;                       switch(evt.getClickCount())             {                case 1:                   doSingleClick(evt,line,offset,dot);                   break;                case 2:                // It uses the bracket matching stuff, so                // it can throw a BLE                   try                   {                      doDoubleClick(evt,line,offset,dot);                   }                       catch(BadLocationException bl)                      {                         bl.printStackTrace();                      }                   break;                case 3:                   doTripleClick(evt,line,offset,dot);                   break;             }          }                  private void doSingleClick(MouseEvent evt, int line,            int offset, int dot)          {             if((evt.getModifiers() & InputEvent.SHIFT_MASK) != 0)             {                rectSelect = (evt.getModifiers() & InputEvent.CTRL_MASK) != 0;                select(getMarkPosition(),dot);             }             else                setCaretPosition(dot);          }                  private void doDoubleClick(MouseEvent evt, int line,           int offset, int dot) throws BadLocationException          {          // Ignore empty lines             if(getLineLength(line) == 0)                return;                       try             {                int bracket = TextUtilities.findMatchingBracket(                   document,Math.max(0,dot - 1));                if(bracket != -1)                {                   int mark = getMarkPosition();                // Hack                   if(bracket > mark)
                  {
                     bracket++;
                     mark–;
                  }
                  select(mark,bracket);
                  return;
               }
            }
                catch(BadLocationException bl)
               {
                  bl.printStackTrace();
               }
         
         // Ok, it’s not a bracket… select the word
            String lineText = getLineText(line);
            char ch = lineText.charAt(Math.max(0,offset – 1));
         
            String noWordSep = (String)document.getProperty(“noWordSep”);
            if(noWordSep == null)
               noWordSep = “”;
         
         // If the user clicked on a non-letter char,
         // we select the surrounding non-letters
            boolean selectNoLetter = (!Character
               .isLetterOrDigit(ch)
               && noWordSep.indexOf(ch) == -1);
         
            int wordStart = 0;
         
            for(int i = offset – 1; i >= 0; i–)
            {
               ch = lineText.charAt(i);
               if(selectNoLetter ^ (!Character
               .isLetterOrDigit(ch) &&
               noWordSep.indexOf(ch) == -1))
               {
                  wordStart = i + 1;
                  break;
               }
            }
         
            int wordEnd = lineText.length();
            for(int i = offset; i < lineText.length(); i++)             {                ch = lineText.charAt(i);                if(selectNoLetter ^ (!Character                .isLetterOrDigit(ch) &&                noWordSep.indexOf(ch) == -1))                {                   wordEnd = i;                   break;                }             }                       int lineStart = getLineStartOffset(line);             select(lineStart + wordStart,lineStart + wordEnd);          }                  private void doTripleClick(MouseEvent evt, int line,           int offset, int dot)          {             select(getLineStartOffset(line),getLineEndOffset(line)-1);          }       }            class CaretUndo extends AbstractUndoableEdit       {          private int start;          private int end;                  CaretUndo(int start, int end)          {             this.start = start;             this.end = end;          }                  public boolean isSignificant()          {             return false;          }                  public String getPresentationName()          {             return "caret move";          }                  public void undo() throws CannotUndoException          {             super.undo();                       select(start,end);          }                  public void redo() throws CannotRedoException          {             super.redo();                       select(start,end);          }                  public boolean addEdit(UndoableEdit edit)          {             if(edit instanceof CaretUndo)             {                CaretUndo cedit = (CaretUndo)edit;                start = cedit.start;                end = cedit.end;                cedit.die();                             return true;             }             else                return false;          }       }               /**      *  Return any relevant tool tip text for token at specified position. Keyword match      *  must be exact.  DPS 24-May-2010         *  @param x x-coordinate of current position      *  @param y y-coordinate of current position      *  @return String containing appropriate tool tip text.  Possibly HTML-encoded.      */      // Is used for tool tip only (not popup menu)        public String getSyntaxSensitiveToolTipText(int x, int y) {          String result = null;          int line = this.yToLine(y);          ArrayList matches = getSyntaxSensitiveHelpAtLineOffset(line, this.xToOffset(line,x), true);          if (matches == null) {              return null;          }          int length = PopupHelpItem.maxExampleLength(matches) + 2;          result = "“;
         for (int i=0; i“) + “" + match.getExamplePaddedToLength(length).replaceAll(" "," ") + "” + match.getDescription();
         }
         return result + ““;
      }
   
   
       /**
        * Constructs string for auto-indent feature.  Returns empty string
      * if auto-intent is disabled or if line has no leading white space. 
      * Uses getLeadingWhiteSpace(). Is used by InputHandler when processing
      * key press for Enter key.   DPS 31-Dec-2010
      * @return String containing auto-indent characters to be inserted into text
      */    
       public String getAutoIndent() {
         return (Globals.getSettings().getBooleanSetting(Settings.AUTO_INDENT)) ? getLeadingWhiteSpace() : “”;
      }
   
       /**
        * Makes a copy of leading white space (tab or space) from the current line and  
      * returns it.    DPS 31-Dec-2010
      * @return String containing leading white space of current line.  Empty string if none.
      */    
       public String getLeadingWhiteSpace() {
         int line = getCaretLine();
         int lineLength = getLineLength(line);
         String indent = “”;
         if (lineLength > 0) {
            String text = getText(getLineStartOffset(line), lineLength);
            for (int position = 0; position < text.length(); position++) {                char character = text.charAt(position);                if (character == '\t' || character == ' ') {                   indent += character;                }                 else {                   break;                }             }          }          return indent;       }           //////////////////////////////////////////////////////////////////////////////////          // Get relevant help information at specified position.  Returns ArrayList of     // PopupHelpItem with one per match, or null if no matches.     // The "exact" parameter is set depending on whether the match has to be     // exact or whether a prefix match will do.  The token "s" will not match     // any instruction names if exact is true, but will match "sw", "sh", etc     // if exact is false.  The former is helpful for mouse-movement-based tool     // tips (this is what you have).  The latter is helpful for caret-based tool     // tips (this is what you can do).        private ArrayList getSyntaxSensitiveHelpAtLineOffset(int line, int offset, boolean exact) {          ArrayList matches = null;          TokenMarker tokenMarker = this.getTokenMarker();          if (tokenMarker != null) {             Segment lineSegment = new Segment();             this.getLineText(line,lineSegment); // fill segment with info from this line             Token tokens = tokenMarker.markTokens(lineSegment,line);             Token tokenList = tokens;             int tokenOffset = 0;             Token tokenAtOffset = null;             // cool for following the tokens...             //System.out.print("(JEditTextArea.java) Token Stream:");             Token toke = tokens;             for (;;) {                //System.out.print(" "+toke.id+"("+toke.length+")");                if (toke.id == Token.END)                    break;                toke = toke.next;             }             //System.out.println();                       for (;;) {                byte id = tokens.id;                if(id == Token.END)                   break;                int length = tokens.length;                if (offset > tokenOffset && offset <= tokenOffset+length) {                   tokenAtOffset = tokens;                   break;                }                tokenOffset += length;                tokens = tokens.next;             }             if (tokenAtOffset != null) {                String tokenText = lineSegment.toString().substring(tokenOffset, tokenOffset+tokenAtOffset.length);                if (exact) {                   matches = tokenMarker.getTokenExactMatchHelp(tokenAtOffset, tokenText);                 }                 else {                   matches = tokenMarker.getTokenPrefixMatchHelp(lineSegment.toString(), tokenList, tokenAtOffset, tokenText);                }             }          }          return matches;       }                ////////////////////////////////////////////////////////////////////////////////////        // Compose and display syntax-sensitive help. Typically invoked upon typing a key.      // Results in popup menu.  Is not used for creating tool tips.        private void applySyntaxSensitiveHelp() {          if (!mars.Globals.getSettings().getBooleanSetting(mars.Settings.POPUP_INSTRUCTION_GUIDANCE)) {             return;          }          int line = getCaretLine();           int lineStart = getLineStartOffset(line);          int offset = Math.max(1,Math.min(getLineLength(line),             getCaretPosition() - lineStart));           ArrayList helpItems = getSyntaxSensitiveHelpAtLineOffset(line,offset,false);          if (helpItems == null && popupMenu != null) {             popupMenu.setVisible(false);             popupMenu = null;          }          if (helpItems != null) {             popupMenu = new JPopupMenu();              int length = PopupHelpItem.maxExampleLength(helpItems) + 2;                  for (int i=0; i"+item.getExamplePaddedToLength(length).replaceAll(" "," ")+"“+item.getDescription()+”“);
               if (item.getExact()) {
                  // The instruction name is completed so the role of the popup changes
                // to that of floating help to assist in operand specification. 
                  menuItem.setSelected(false);
                  menuItem.setEnabled(false); 
               } 
               else {
                  // Typing of instruction/directive name is still in progress; the action listener 
                // will complete it when its menu item is selected.
                  menuItem.addActionListener(new PopupHelpActionListener(item.getTokenText(), item.getExample()));
               }
               popupMenu.add(menuItem);
            }
            popupMenu.pack();
            int y = lineToY(line);
            int x = offsetToX(line, offset);
            int height = painter.getFontMetrics(painter.getFont()).getHeight();
            int width = painter.getFontMetrics(painter.getFont()).charWidth(‘w’);
            int menuXLoc = x+width+width+width;
            int menuYLoc = y+height+height; // display below;
            // Modified to always display popup BELOW the current line.
            // This was done in response to negative student feedback about
            // the popup blocking information they needed to (e.g. operands from
            // previous instructions).  Note that if menu is long enough and
            // current cursor position is low enough, the menu will bottom out at the
            // bottom of the screen and extend above the current line. DPS 23-Dec-2010
            popupMenu.show(this, menuXLoc, menuYLoc); 
            this.requestFocusInWindow(); // get cursor back from the menu
         }
      }
   
   
       // Carries out the instruction/directive completion when popup menu
     // item is selected. 
       private class PopupHelpActionListener implements ActionListener {
         private String tokenText, text;
          public PopupHelpActionListener(String tokenText, String text) {
            this.tokenText = tokenText;
            this.text = text.split(” “)[0];
         }
        // Completion action will insert either a tab or space character following the
        // completed instruction mnemonic.  Inserts a tab if tab key was pressed;
        // space otherwise.  Get this information from the ActionEvent.
          public void actionPerformed(ActionEvent e) {
            String insert = (e.getActionCommand().charAt(0)==’\t’) ? “\t” : ” “;
            if (this.tokenText.length() >= this.text.length()) {
               overwriteSetSelectedText(insert);
            } 
            else {
               overwriteSetSelectedText(this.text.substring(this.tokenText.length())+insert);            
            }
         }
      }
   
       private void checkAutoIndent(KeyEvent evt) {
         if (evt.getKeyCode()==KeyEvent.VK_ENTER) {
            int line = getCaretLine();
            if (line <= 0)                 return;             int previousLine = line - 1 ;             int previousLineLength = getLineLength(previousLine);             if (previousLineLength <= 0)                 return;             String previous = getText(getLineStartOffset(previousLine), previousLineLength);             String indent = "";             for (int position = 0; position < previous.length(); position++) {                char character = previous.charAt(position);                if (character == '\t' || character == ' ') {                   indent += character;                }                 else {                   break;                }             }             overwriteSetSelectedText(indent);          }       }                    ////////////////////////////////////////////////////////////////////////////////////        // Called after processing a Key Pressed event. Will make popup menu disappear if      // Enter or Escape keys pressed.  Will update if Backspace or Delete pressed.      // Not really concerned with modifiers here.        private void checkPopupMenu(KeyEvent evt) {          if ( evt.getKeyCode()==KeyEvent.VK_BACK_SPACE || evt.getKeyCode()==KeyEvent.VK_DELETE)             applySyntaxSensitiveHelp();          if ( (evt.getKeyCode()== KeyEvent.VK_ENTER || evt.getKeyCode() == KeyEvent.VK_ESCAPE)                     && popupMenu != null && popupMenu.isVisible() )              popupMenu.setVisible(false);       }                    ////////////////////////////////////////////////////////////////////////////////////        // Called before processing Key Pressed event. If popup menu is visible, will process      // tab and enter keys to select from the menu, and arrow keys to traverse the menu.        private boolean checkPopupCompletion(KeyEvent evt) {          if ((evt.getKeyCode()==KeyEvent.VK_UP || evt.getKeyCode()==KeyEvent.VK_DOWN)               && popupMenu != null && popupMenu.isVisible() && popupMenu.getComponentCount() > 0)
         {
            MenuElement[] path = MenuSelectionManager.defaultManager().getSelectedPath();
            if (path.length < 1 || !(path[path.length-1] instanceof AbstractButton))                 return false;             AbstractButton item = (AbstractButton) path[path.length-1].getComponent();             if (item.isEnabled()) {                int index = popupMenu.getComponentIndex(item);                if (index < 0)                    return false;                if (evt.getKeyCode() == KeyEvent.VK_UP) {                   index = (index==0) ? popupMenu.getComponentCount()-1 : index-1;                }                 else {                   index = (index==popupMenu.getComponentCount()-1) ? 0 : index+1;                }                 // Neither popupMenu.setSelected() nor popupMenu.getSelectionModel().setSelectedIndex()                 // have the desired effect (changing the menu item selected).  Found references to                  // this in a Sun forum.  http://forums.sun.com/thread.jspa?forumID=57&threadID=641745                 // The solution, as shown here, is to use invokeLater.                final MenuElement[] newPath = new MenuElement[2];                newPath[0] = path[0];                newPath[1] = (MenuElement) popupMenu.getComponentAtIndex(index);                SwingUtilities.invokeLater(                       new Runnable() {                          public void run() {                            MenuSelectionManager.defaultManager().setSelectedPath(newPath);                         }                      });                return true;             }              else {                return false;                }                }          if ((evt.getKeyCode()==KeyEvent.VK_TAB || evt.getKeyCode()==KeyEvent.VK_ENTER)              && popupMenu != null && popupMenu.isVisible() && popupMenu.getComponentCount() > 0) 
         {  
            MenuElement[] path = MenuSelectionManager.defaultManager().getSelectedPath();
            if (path.length < 1 || !(path[path.length-1] instanceof AbstractButton))                 return false;             AbstractButton item = (AbstractButton) path[path.length-1].getComponent();             if (item.isEnabled()) {                ActionListener[] listeners = item.getActionListeners();                if (listeners.length > 0) {
                  listeners[0].actionPerformed(new ActionEvent(item, ActionEvent.ACTION_FIRST,
                     (evt.getKeyCode()==KeyEvent.VK_TAB) ? “\t” : ” “));
                  return true;
               }
            }
         }
         return false;
      }
        
            
      static
      {
         caretTimer = new Timer(500,new CaretBlinker());
         caretTimer.setInitialDelay(500);
         caretTimer.start();
      }
   }
   
    

SyntaxDocument

package mars.venus.editors.jeditsyntax;
public synchronized class SyntaxDocument extends javax.swing.text.PlainDocument {
protected tokenmarker.TokenMarker tokenMarker;
public void SyntaxDocument();
public tokenmarker.TokenMarker getTokenMarker();
public void setTokenMarker(tokenmarker.TokenMarker);
public void tokenizeLines();
public void tokenizeLines(int, int);
public void beginCompoundEdit();
public void endCompoundEdit();
public void addUndoableEdit(javax.swing.undo.UndoableEdit);
protected void fireInsertUpdate(javax.swing.event.DocumentEvent);
protected void fireRemoveUpdate(javax.swing.event.DocumentEvent);
}

InputHandler$home

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$home implements java.awt.event.ActionListener {
private boolean select;
public void InputHandler$home(boolean);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/editors/jeditsyntax/KeywordMap.java
mars/venus/editors/jeditsyntax/KeywordMap.java/*
 * KeywordMap.java – Fast keyword->id map
 * Copyright (C) 1998, 1999 Slava Pestov
 * Copyright (C) 1999 Mike Dillon
 *
 * You may use and modify this package for any purpose. Redistribution is
 * permitted, in both source and binary form, provided that this notice
 * remains intact in all source distributions of this package.
 */

   package mars.venus.editors.jeditsyntax;

   import mars.venus.editors.jeditsyntax.tokenmarker.*;
   import javax.swing.text.Segment;

/**
 * A KeywordMap is similar to a hashtable in that it maps keys
 * to values. However, the `keys’ are Swing segments. This allows lookups of
 * text substrings without the overhead of creating a new string object.
 * 

 * This class is used by CTokenMarker to map keywords to ids.
 *
 * @author Slava Pestov, Mike Dillon
 * @version $Id: KeywordMap.java,v 1.16 1999/12/13 03:40:30 sp Exp $
 */
    public class KeywordMap
   {
   /**
    * Creates a new KeywordMap.
    * @param ignoreCase True if keys are case insensitive
    */
       public KeywordMap(boolean ignoreCase)
      {
         this(ignoreCase, 52);
         this.ignoreCase = ignoreCase;
      }
   
   /**
    * Creates a new KeywordMap.
    * @param ignoreCase True if the keys are case insensitive
    * @param mapLength The number of `buckets’ to create.
    * A value of 52 will give good performance for most maps.
    */
       public KeywordMap(boolean ignoreCase, int mapLength)
      {
         this.mapLength = mapLength;
         this.ignoreCase = ignoreCase;
         map = new Keyword[mapLength];
      }
   
   /**
    * Looks up a key.
    * @param text The text segment
    * @param offset The offset of the substring within the text segment
    * @param length The length of the substring
    */
       public byte lookup(Segment text, int offset, int length)
      {
         if(length == 0)
            return Token.NULL;
         if (text.array[offset]==’%’)
            return Token.MACRO_ARG;  // added 12/12 M. Sekhavat
         Keyword k = map[getSegmentMapKey(text, offset, length)];
         while(k != null)
         {
            if(length != k.keyword.length)
            {
               k = k.next;
               continue;
            }
            if(SyntaxUtilities.regionMatches(ignoreCase,text,offset,
            k.keyword))
               return k.id;
            k = k.next;
         }
         return Token.NULL;
      }
   
   /**
    * Adds a key-value mapping.
    * @param keyword The key
    * @Param id The value
    */
       public void add(String keyword, byte id)
      {
         int key = getStringMapKey(keyword);
         map[key] = new Keyword(keyword.toCharArray(),id,map[key]);
      }
   
   /**
    * Returns true if the keyword map is set to be case insensitive,
    * false otherwise.
    */
       public boolean getIgnoreCase()
      {
         return ignoreCase;
      }
   
   /**
    * Sets if the keyword map should be case insensitive.
    * @param ignoreCase True if the keyword map should be case
    * insensitive, false otherwise
    */
       public void setIgnoreCase(boolean ignoreCase)
      {
         this.ignoreCase = ignoreCase;
      }
   
   // protected members
      protected int mapLength;
   
       protected int getStringMapKey(String s)
      {
         return (Character.toUpperCase(s.charAt(0)) +
            Character.toUpperCase(s.charAt(s.length()-1)))
            % mapLength;
      }
   
       protected int getSegmentMapKey(Segment s, int off, int len)
      {
         return (Character.toUpperCase(s.array[off]) +
            Character.toUpperCase(s.array[off + len – 1]))
            % mapLength;
      }
   
   // private members
       class Keyword
      {
          public Keyword(char[] keyword, byte id, Keyword next)
         {
            this.keyword = keyword;
            this.id = id;
            this.next = next;
         }
      
         public char[] keyword;
         public byte id;
         public Keyword next;
      }
   
      private Keyword[] map;
      private boolean ignoreCase;
   }

KeywordMap$Keyword

package mars.venus.editors.jeditsyntax;
synchronized class KeywordMap$Keyword {
public char[] keyword;
public byte id;
public KeywordMap$Keyword next;
public void KeywordMap$Keyword(KeywordMap, char[], byte, KeywordMap$Keyword);
}

JEditTextArea$FocusHandler

package mars.venus.editors.jeditsyntax;
synchronized class JEditTextArea$FocusHandler implements java.awt.event.FocusListener {
void JEditTextArea$FocusHandler(JEditTextArea);
public void focusGained(java.awt.event.FocusEvent);
public void focusLost(java.awt.event.FocusEvent);
}

InputHandler$next_char

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$next_char implements java.awt.event.ActionListener {
private boolean select;
public void InputHandler$next_char(boolean);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/editors/jeditsyntax/PopupHelpItem.java
mars/venus/editors/jeditsyntax/PopupHelpItem.java
/*
Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

   package mars.venus.editors.jeditsyntax;
    
     /**
      *  Handly little class to contain help information for a popupMenu or 
      *  tool tip item.
      */
    public class PopupHelpItem {
      private String tokenText;
      private String example;
      private String description;
      private boolean exact;        // from exact match?
      private int exampleLength;
      private static final String spaces = ”                                        “; // 40 spaces

    /**
     * Create popup help item.  This is created as result of either an exact-match or
     * prefix-match search.  Note that prefix-match search includes exact as well as partial matches.
     * @param tokenText The document text that matched
     * @param example An example instruction
     * @param description A textual description of the instruction
     * @param exact True if match occurred as result of exact-match search, false otherwise.
     */
       public PopupHelpItem(String tokenText, String example, String description, boolean exact) {
         this.tokenText = tokenText;
         this.example = example;
            if (exact) {
              this.description = description;
            } else {
              int detailPosition = description.indexOf(mars.venus.HelpHelpAction.descriptionDetailSeparator);
              this.description = (detailPosition == -1) ? description : description.substring(0,detailPosition);
            }
         this.exampleLength = this.example.length();
         this.exact = exact;
      }
   
    /**
     * Create popup help item, where match is result of an exact-match search.
     * @param tokenText The document text that matched
     * @param example An example instruction
     * @param description A textual description of the instruction
     */
       public PopupHelpItem(String tokenText, String example, String description) {
         this(tokenText, example, description, true);
      
      } 
        
     /** The document text that mached this item */
       public String getTokenText() {
         return this.tokenText;
      }
    
       public String getExample() {
         return this.example;
      }
   
       public String getDescription() {
         return this.description;
      }
      
    /** Determines whether match occurred in an exact-match or prefix-match search.
     * Note this can return false even if the match is exact because prefix-match also
     * includes exact match results.  E.g. prefix match on “lw” will match both “lwl” and “lw”.
     * @return True if exact-match search, false otherwise.
     */
    public boolean getExact() {
       return this.exact;
    }
    
       public int getExampleLength() {
         return this.exampleLength;
      }
    
     // for performance purposes, length limited to example length + 40
       public String getExamplePaddedToLength(int length) {
         String result = null;
         if (length > this.exampleLength) {
            int numSpaces = length – this.exampleLength;
            if (numSpaces > spaces.length()) {
               numSpaces = spaces.length();
            }
            result = this.example + spaces.substring(0,numSpaces);
         } 
         else if (length == this.exampleLength) {
            result = this.example;
         } 
         else {
            result = this.example.substring(0,length);
         }
         return result;
      }
    
       public void setExample(String example) {
         this.example = example;
         this.exampleLength = example.length();
      }
   
       public void setDescription(String description) {
         this.description = description;
      }
    
    // Utility method.  Traverse ArrayList of PopupHelpItem objects
    // and return String length of longest example.
       public static int maxExampleLength(java.util.ArrayList matches) {
         int length = 0;
         if (matches != null) {
            for (int i=0; i[modifiers+]key where modifier is C for Control, A for Alt,
    * or S for Shift, and key is either a character (a-z) or a field
    * name in the KeyEvent class prefixed with VK_ (e.g., BACK_SPACE)
    * @param keyBinding The key binding
    * @param action The action
    */
       public void addKeyBinding(String keyBinding, ActionListener action)
      {
         Hashtable current = bindings;
      
         StringTokenizer st = new StringTokenizer(keyBinding);
         while(st.hasMoreTokens())
         {
            KeyStroke keyStroke = parseKeyStroke(st.nextToken());
            if(keyStroke == null)
               return;
         
            if(st.hasMoreTokens())
            {
               Object o = current.get(keyStroke);
               if(o instanceof Hashtable)
                  current = (Hashtable)o;
               else
               {
                  o = new Hashtable();
                  current.put(keyStroke,o);
                  current = (Hashtable)o;
               }
            }
            else
               current.put(keyStroke,action);
         }
      }
   
   /**
    * Removes a key binding from this input handler. This is not yet
    * implemented.
    * @param keyBinding The key binding
    */
       public void removeKeyBinding(String keyBinding)
      {
         throw new InternalError(“Not yet implemented”);
      }
   
   /**
    * Removes all key bindings from this input handler.
    */
       public void removeAllKeyBindings()
      {
         bindings.clear();
      }
   
   /**
    * Returns a copy of this input handler that shares the same
    * key bindings. Setting key bindings in the copy will also
    * set them in the original.
    */
       public InputHandler copy()
      {
         return new DefaultInputHandler(this);
      }
   
   /**
    * Handle a key pressed event. This will look up the binding for
    * the key stroke and execute it.
    */
       public void keyPressed(KeyEvent evt)
      { 
         int keyCode = evt.getKeyCode();
         int modifiers = evt.getModifiers();
         if(keyCode == KeyEvent.VK_CONTROL ||
         keyCode == KeyEvent.VK_SHIFT ||
         keyCode == KeyEvent.VK_ALT ||
         keyCode == KeyEvent.VK_META)
            return;
      
         if((modifiers & ~KeyEvent.SHIFT_MASK) != 0
         || evt.isActionKey()
         || keyCode == KeyEvent.VK_BACK_SPACE
         || keyCode == KeyEvent.VK_DELETE
         || keyCode == KeyEvent.VK_ENTER
         || keyCode == KeyEvent.VK_TAB
         || keyCode == KeyEvent.VK_ESCAPE)
         {
            if(grabAction != null)
            {
               handleGrabAction(evt); 
               return;
            }
         
            KeyStroke keyStroke = KeyStroke.getKeyStroke(keyCode, modifiers); 
            Object o = currentBindings.get(keyStroke);
            
            if(o == null)
            {
            // Don’t beep if the user presses some
            // key we don’t know about unless a
            // prefix is active. Otherwise it will
            // beep when caps lock is pressed, etc.
               if(currentBindings != bindings)
               { 
                  Toolkit.getDefaultToolkit().beep();
               // F10 should be passed on, but C+e F10
               // shouldn’t
                  repeatCount = 0;
                  repeat = false;
                  evt.consume();
               }
               currentBindings = bindings;
               // No binding for this keyStroke, pass it to menu 
               // (mnemonic, accelerator).  DPS 4-may-2010
               mars.Globals.getGui().dispatchEventToMenu(evt);
               evt.consume();
               return;
            }
            else if(o instanceof ActionListener)
            {  
               currentBindings = bindings;
               executeAction(((ActionListener)o),
                  evt.getSource(),null);
            
               evt.consume();
               return;
            }
            else if(o instanceof Hashtable)
            {  
               currentBindings = (Hashtable)o;
               evt.consume();
               return;
            }
         }
      }
   
   /**
    * Handle a key typed event. This inserts the key into the text area.
    */
       public void keyTyped(KeyEvent evt)
      { 
         int modifiers = evt.getModifiers();
         char c = evt.getKeyChar();
         // This IF statement needed to prevent Macintosh shortcut keyChar from 
         // being echoed to the text area.  E.g. Command-s, for Save, will echo
         // the ‘s’ character unless filtered out here.  Command modifier 
         // matches KeyEvent.META_MASK.   DPS 30-Nov-2010
         if ((modifiers & KeyEvent.META_MASK) != 0) 
            return;
      // DPS 9-Jan-2013.  Umberto Villano from Italy describes Alt combinations
      // not working on Italian Mac keyboards, where # requires Alt (Option).
        // This is preventing him from writing comments.  Similar complaint from
        // Joachim Parrow in Sweden, only for the $ character.  Villano pointed
        // me to this method.  Plus a Google search on “jeditsyntax alt key”
        // (without quotes) took me to
        // http://compgroups.net/comp.lang.java.programmer/option-key-in-jedit-syntax-package/1068227
        // which says to comment out the second condition in this IF statement:
      // if(c != KeyEvent.CHAR_UNDEFINED && (modifiers & KeyEvent.ALT_MASK) == 0)
        // So let’s give it a try!
        // (…later) Bummer, it results in keystroke echoed into editing area when I use Alt
        // combination for shortcut menu access (e.g. Alt+f to open the File menu).
         if(c != KeyEvent.CHAR_UNDEFINED && (modifiers & KeyEvent.ALT_MASK) == 0)
         {
            if(c >= 0x20 && c != 0x7f)
            { 
               KeyStroke keyStroke = KeyStroke.getKeyStroke(
                  Character.toUpperCase(c));
               Object o = currentBindings.get(keyStroke);
            
               if(o instanceof Hashtable)
               {
                  currentBindings = (Hashtable)o;
                  return;
               }
               else if(o instanceof ActionListener)
               {
                  currentBindings = bindings;
                  executeAction((ActionListener)o,
                     evt.getSource(),
                     String.valueOf(c));
                  return;
               }
            
               currentBindings = bindings;
            
               if(grabAction != null)
               {
                  handleGrabAction(evt);
                  return;
               }
            
            // 0-9 adds another ‘digit’ to the repeat number
               if(repeat && Character.isDigit(c))
               {
                  repeatCount *= 10;
                  repeatCount += (c – ‘0’);
                  return;
               } 
               executeAction(INSERT_CHAR,evt.getSource(),
                  String.valueOf(evt.getKeyChar()));
               repeatCount = 0;
               repeat = false;
            }
         }
      }
   
   /**
    * Converts a string to a keystroke. The string should be of the
    * form modifiers+shortcut where modifiers
    * is any combination of A for Alt, C for Control, S for Shift
    * or M for Meta, and shortcut is either a single character,
    * or a keycode name from the KeyEvent class, without
    * the VK_ prefix.
    * @param keyStroke A string description of the key stroke
    */
       public static KeyStroke parseKeyStroke(String keyStroke)
      {
         if(keyStroke == null)
            return null;
         int modifiers = 0;
         int index = keyStroke.indexOf(‘+’);
         if(index != -1)
         {
            for(int i = 0; i < index; i++)             {                switch(Character.toUpperCase(keyStroke                .charAt(i)))                {                   case 'A':                      modifiers |= InputEvent.ALT_MASK;                      break;                   case 'C':                      modifiers |= InputEvent.CTRL_MASK;                      break;                   case 'M':                      modifiers |= InputEvent.META_MASK;                      break;                   case 'S':                      modifiers |= InputEvent.SHIFT_MASK;                      break;                }             }          }          String key = keyStroke.substring(index + 1);          if(key.length() == 1)          {             char ch = Character.toUpperCase(key.charAt(0));             if(modifiers == 0)                return KeyStroke.getKeyStroke(ch);             else                return KeyStroke.getKeyStroke(ch,modifiers);          }          else if(key.length() == 0)          {             System.err.println("Invalid key stroke: " + keyStroke);             return null;          }          else          {             int ch;                       try             {                ch = KeyEvent.class.getField("VK_".concat(key))                   .getInt(null);             }                 catch(Exception e)                {                   System.err.println("Invalid key stroke: "                      + keyStroke);                   return null;                }                       return KeyStroke.getKeyStroke(ch,modifiers);          }       }        // private members       private Hashtable bindings;       private Hashtable currentBindings;            private DefaultInputHandler(DefaultInputHandler copy)       {          bindings = currentBindings = copy.bindings;       }    } mars/venus/editors/jeditsyntax/JEditBasedTextArea.java mars/venus/editors/jeditsyntax/JEditBasedTextArea.java   package mars.venus.editors.jeditsyntax;    import mars.venus.editors.jeditsyntax.tokenmarker.*;     import mars.venus.editors.MARSTextEditingArea;     import mars.venus.EditPane;    import mars.*;    import java.awt.*;    import javax.swing.event.*;    import javax.swing.text.*;    import javax.swing.undo.*;    import javax.swing.*;    /**      *  Adaptor subclass for JEditTextArea      *      *  Provides those methods required by the MARSTextEditingArea interface      *  that are not defined by JEditTextArea.  This permits JEditTextArea      *  to be used within MARS largely without modification.  DPS 4-20-2010      *      *  @since 4.0      *  @author Pete Sanderson      */           public class JEditBasedTextArea extends JEditTextArea implements MARSTextEditingArea, CaretListener {             private EditPane editPane;       private UndoManager undoManager;       private UndoableEditListener undoableEditListener;       private boolean isCompoundEdit = false;       private CompoundEdit compoundEdit;       private JEditBasedTextArea sourceCode;                                 public JEditBasedTextArea(EditPane editPain, JComponent lineNumbers) {          super(lineNumbers);          this.editPane = editPain;          this.undoManager = new UndoManager();          this.compoundEdit = new CompoundEdit();          this.sourceCode = this;                   // Needed to support unlimited undo/redo capability          undoableEditListener =               new UndoableEditListener() {                 public void undoableEditHappened(UndoableEditEvent e) {                   //Remember the edit and update the menus.                   if (isCompoundEdit) {                      compoundEdit.addEdit(e.getEdit());                   }                    else {                       undoManager.addEdit(e.getEdit());                      editPane.updateUndoState();                      editPane.updateRedoState();                   }                }             };          this.getDocument().addUndoableEditListener(undoableEditListener);           this.setFont(Globals.getSettings().getEditorFont());          this.setTokenMarker(new MIPSTokenMarker());                   addCaretListener(this);       }                 public void setFont(Font f) {          getPainter().setFont(f);       }                  public Font getFont() {          return getPainter().getFont();       }                   //      public void repaint() {      getPainter().repaint();         } //       public Dimension getSize() { return painter.getSize(); } //       public void setSize(Dimension d) { painter.setSize(d);}              /**       *  Use for highlighting the line currently being edited.     *  @param highlight true to enable line highlighting, false to disable.     */        public void setLineHighlightEnabled(boolean highlight) {          getPainter().setLineHighlightEnabled(highlight);       }          /**       *  Set the caret blinking rate in milliseconds.  If rate is 0     *  will disable blinking.  If negative, do nothing.     *  @param rate blinking rate in milliseconds     */        public void setCaretBlinkRate(int rate) {          if (rate == 0) {             caretBlinks = false;          }          if (rate > 0) {
            caretBlinks = true;
            caretBlinkRate = rate;
            caretTimer.setDelay(rate);
            caretTimer.setInitialDelay(rate);
            caretTimer.restart();
         }
      }
   
   
      /**
     *  Set the number of characters a tab will expand to.
     *  @param chars number of characters
     */
       public void setTabSize(int chars) {
         painter.setTabSize(chars);
      }
   
      /**
     * Update the syntax style table, which is obtained from
     * SyntaxUtilities.
     */
       public void updateSyntaxStyles() {
         painter.setStyles(SyntaxUtilities.getCurrentSyntaxStyles());
      }
   
            
       public Component getOuterComponent() {
         return this;
      }
    
    /**
     *  Get rid of any accumulated undoable edits.  It is useful to call
     *  this method after opening a file into the text area.  The 
     *  act of setting its text content upon reading the file will generate 
     *  an undoable edit.  Normally you don’t want a freshly-opened file
     *  to appear with its Undo action enabled.  But it will unless you
     *  call this after setting the text.
     */ 
       public void discardAllUndoableEdits() {
         this.undoManager.discardAllEdits();
      }
    
    /**
     * Display caret position on the edit pane.
     * @param e  A CaretEvent
     */
    
       public void caretUpdate(CaretEvent e) {
         editPane.displayCaretPosition(((MutableCaretEvent)e).getDot());
      }
   
    
     /**
      *  Same as setSelectedText but named for compatibility with
    *  JTextComponent method replaceSelection.
    *  DPS, 14 Apr 2010
    *  @param replacementText The replacement text for the selection
    */
       public void replaceSelection(String replacementText) {
         setSelectedText(replacementText);
      }
     //
     // 
       public void setSelectionVisible(boolean vis) {
      
      }
    
     //
     //
       public void setSourceCode(String s, boolean editable) {       
         this.setText(s);
         this.setBackground( (editable)? Color.WHITE : Color.GRAY);
         this.setEditable(editable);  
         this.setEnabled(editable);
         //this.getCaret().setVisible(editable);
         this.setCaretPosition(0);
         if (editable) this.requestFocusInWindow();         
      }
    
    /**
     *  Returns the undo manager for this editing area
     *  @return the undo manager
     */
       public UndoManager getUndoManager() {
         return undoManager;
      }
    
     /**
      * Undo previous edit
    */
       public void undo() {
       // “unredoing” is mode used by DocumentHandler’s insertUpdate() and removeUpdate()
       // to pleasingly mark the text and location of the undo.
         unredoing = true; 
         try { 
            this.undoManager.undo();
         } 
             catch (CannotUndoException ex) {
               System.out.println(“Unable to undo: ” + ex);
               ex.printStackTrace();
            } 
         unredoing = false;
         this.setCaretVisible(true);
      }
    
    /**
     * Redo previous edit
     */
       public void redo() {
       // “unredoing” is mode used by DocumentHandler’s insertUpdate() and removeUpdate()
       // to pleasingly mark the text and location of the redo.
         unredoing = true;
         try {
            this.undoManager.redo();
         } 
             catch (CannotRedoException ex) {
               System.out.println(“Unable to redo: ” + ex);
               ex.printStackTrace();
            }
         unredoing = false;
         this.setCaretVisible(true);
      }
    
    
   //////////////////////////////////////////////////////////////////////////
   //  Methods to support Find/Replace feature
   //
   // Basis for this Find/Replace solution is:
   // http://java.ittoolbox.com/groups/technical-functional/java-l/search-and-replace-using-jtextpane-630964
   // as written by Chris Dickenson in 2005
   //
   
   
    /** Finds next occurrence of text in a forward search of a string. Search begins 
     * at the current cursor location, and wraps around when the end of the string
     * is reached.
     * @param find the text to locate in the string 
     * @param caseSensitive true if search is to be case-sensitive, false otherwise
     * @return TEXT_FOUND or TEXT_NOT_FOUND, depending on the result.
     */
       public int doFindText(String find, boolean caseSensitive) {
         int findPosn = sourceCode.getCaretPosition();
         int nextPosn = 0;
         nextPosn = nextIndex( sourceCode.getText(), find, findPosn, caseSensitive );
         if ( nextPosn >= 0 ) {
            sourceCode.requestFocus(); // guarantees visibility of the blue highlight 
            sourceCode.setSelectionStart( nextPosn ); // position cursor at word start
            sourceCode.setSelectionEnd( nextPosn + find.length() );
            // Need to repeat start due to quirk in JEditTextArea implementation of setSelectionStart.
            sourceCode.setSelectionStart( nextPosn );
            return TEXT_FOUND;
         } 
         else {
            return TEXT_NOT_FOUND;
         }
      }
     
   /** Returns next posn of word in text – forward search.  If end of string is
    *  reached during the search, will wrap around to the beginning one time.
   * @return next indexed position of found text or -1 if not found
   * @param input the string to search
   * @param find the string to find
   * @param start the character position to start the search
   * @param caseSensitive true for case sensitive. false to ignore case
   */
       public int nextIndex(String input, String find, int start, boolean caseSensitive ) {
         int textPosn = -1;
         if ( input != null && find != null && start < input.length() ) {             if ( caseSensitive ) { // indexOf() returns -1 if not found                textPosn = input.indexOf( find, start );                // If not found from non-starting cursor position, wrap around                if (start > 0 && textPosn < 0) {                   textPosn = input.indexOf( find );                }             }              else {                String lowerCaseText = input.toLowerCase();                textPosn = lowerCaseText.indexOf( find.toLowerCase(), start );                 // If not found from non-starting cursor position, wrap around                if (start > 0 && textPosn < 0) {                   textPosn = lowerCaseText.indexOf( find.toLowerCase() );                }             }          }          return textPosn;       }            /** Finds and replaces next occurrence of text in a string in a forward search.    * If cursor is initially at end    *  of matching selection, will immediately replace then find and select the    *  next occurrence if any.  Otherwise it performs a find operation.  The replace    *  can be undone with one undo operation.    *    * @param find the text to locate in the string    * @param replace the text to replace the find text with - if the find text exists    * @param caseSensitive true for case sensitive. false to ignore case    * @return Returns TEXT_FOUND if not initially at end of selected match and matching    * occurrence is found.  Returns TEXT_NOT_FOUND if the text is not matched.    * Returns TEXT_REPLACED_NOT_FOUND_NEXT if replacement is successful but there are     * no additional matches.  Returns TEXT_REPLACED_FOUND_NEXT if reaplacement is    * successful and there is at least one additional match.    */        public int doReplace(String find, String replace, boolean caseSensitive) {          int nextPosn = 0;          int posn;          // Will perform a "find" and return, unless positioned at the end of         // a selected "find" result.            if (find==null || !find.equals(sourceCode.getSelectedText()) ||              sourceCode.getSelectionEnd()!=sourceCode.getCaretPosition()) {             return doFindText(find, caseSensitive);          }         // We are positioned at end of selected "find".  Rreplace and find next.          nextPosn = sourceCode.getSelectionStart();          sourceCode.grabFocus();          sourceCode.setSelectionStart( nextPosn ); // posn cursor at word start          sourceCode.setSelectionEnd( nextPosn + find.length() ); //select found text         // Need to repeat start due to quirk in JEditTextArea implementation of setSelectionStart.          sourceCode.setSelectionStart( nextPosn );          isCompoundEdit = true;          compoundEdit = new CompoundEdit();          sourceCode.replaceSelection(replace);          compoundEdit.end();          undoManager.addEdit( compoundEdit );          editPane.updateUndoState();          editPane.updateRedoState();          isCompoundEdit = false;          sourceCode.setCaretPosition(nextPosn + replace.length());          if (doFindText(find, caseSensitive) == TEXT_NOT_FOUND) {             return TEXT_REPLACED_NOT_FOUND_NEXT;          }           else {                          return TEXT_REPLACED_FOUND_NEXT;          }       }           /** Finds and replaces ALL occurrences of text in a string in a forward search.
   *  All replacements are bundled into one CompoundEdit, so one Undo operation will 
   *  undo all of them.
   * @param find the text to locate in the string
   * @param replace the text to replace the find text with – if the find text exists 
   * @param caseSensitive true for case sensitive. false to ignore case
   * @return the number of occurrences that were matched and replaced.
   */
       public int doReplaceAll(String find, String replace, boolean caseSensitive) {
         int nextPosn = 0;
         int findPosn = 0; // *** begin at start of text
         int replaceCount = 0;
         compoundEdit = null; // new one will be created upon first replacement
         isCompoundEdit = true; // undo manager’s action listener needs this
         while (nextPosn >= 0) {
            nextPosn = nextIndex( sourceCode.getText(), find, findPosn, caseSensitive );
            if ( nextPosn >= 0 ) {
               // nextIndex() will wrap around, which causes infinite loop if
                // find string is a substring of replacement string.  This 
                // statement will prevent that.
               if (nextPosn < findPosn) {                    break;                }                sourceCode.grabFocus();                sourceCode.setSelectionStart( nextPosn ); // posn cursor at word start                sourceCode.setSelectionEnd( nextPosn + find.length() ); //select found text                // Need to repeat start due to quirk in JEditTextArea implementation of setSelectionStart.                sourceCode.setSelectionStart( nextPosn );                if (compoundEdit == null) {                   compoundEdit = new CompoundEdit();                }                sourceCode.replaceSelection(replace);                findPosn = nextPosn + replace.length(); // set for next search                replaceCount++;             }          }          isCompoundEdit = false;          // Will be true if any replacements were performed          if (compoundEdit != null) {             compoundEdit.end();             undoManager.addEdit( compoundEdit );             editPane.updateUndoState();             editPane.updateRedoState();          }          return replaceCount;       }    //     /////////////////////////////  End Find/Replace methods //////////////////////////                  //      //////////////////////////////////////////////////////////////////                     } InputHandler$Wrapper package mars.venus.editors.jeditsyntax; public abstract interface InputHandler$Wrapper { } mars/venus/editors/jeditsyntax/tokenmarker/TokenMarker.java mars/venus/editors/jeditsyntax/tokenmarker/TokenMarker.java /*  * TokenMarker.java - Generic token marker  * Copyright (C) 1998, 1999 Slava Pestov  *  * You may use and modify this package for any purpose. Redistribution is  * permitted, in both source and binary form, provided that this notice  * remains intact in all source distributions of this package.  */    package mars.venus.editors.jeditsyntax.tokenmarker;    import javax.swing.text.Segment;    import java.util.*; /**  * A token marker that splits lines of text into tokens. Each token carries  * a length field and an indentification tag that can be mapped to a color  * for painting that token.

 *
 * For performance reasons, the linked list of tokens is reused after each
 * line is tokenized. Therefore, the return value of markTokens
 * should only be used for immediate painting. Notably, it cannot be
 * cached.
 *
 * @author Slava Pestov
 * @version $Id: TokenMarker.java,v 1.32 1999/12/13 03:40:30 sp Exp $
 *
 * @see org.syntax.jedit.Token
 */
    public abstract class TokenMarker {
   /**
    * A wrapper for the lower-level markTokensImpl method
    * that is called to split a line up into tokens.
    * @param line The line
    * @param lineIndex The line number
    */
       public Token markTokens(Segment line, int lineIndex) {
         if(lineIndex >= length) {
            throw new IllegalArgumentException(“Tokenizing invalid line: ”
               + lineIndex);
         }
      
         lastToken = null;
      
         LineInfo info = lineInfo[lineIndex];
         LineInfo prev;
         if(lineIndex == 0)
            prev = null;
         else
            prev = lineInfo[lineIndex – 1];
      
         byte oldToken = info.token;
         byte token = markTokensImpl(prev == null ?
            Token.NULL : prev.token,line,lineIndex);
      
         info.token = token;
      
      /*
       * This is a foul hack. It stops nextLineRequested from being cleared if
       * the same line is marked twice.
       * 
       * Why is this necessary? It’s all JEditTextArea’s fault. When something
       * is inserted into the text, firing a document event, the
       * insertUpdate() method shifts the caret (if necessary) by the amount
       * inserted.
       * 
       * All caret movement is handled by the select() method, which
       * eventually pipes the new position to scrollTo() and calls repaint().
       * 
       * Note that at this point in time, the new line hasn’t yet been
       * painted; the caret is moved first.
       * 
       * scrollTo() calls offsetToX(), which tokenizes the line unless it is
       * being called on the last line painted (in which case it uses the text
       * area’s painter cached token list). What scrollTo() does next is
       * irrelevant.
       * 
       * After scrollTo() has done it’s job, repaint() is called, and
       * eventually we end up in paintLine(), whose job is to paint the
       * changed line. It, too, calls markTokens().
       * 
       * The problem was that if the line started a multiline token, the first
       * markTokens() (done in offsetToX()) would set nextLineRequested
       * (because the line end token had changed) but the second would clear
       * it (because the line was the same that time) and therefore
       * paintLine() would never know that it needed to repaint subsequent
       * lines.
       * 
       * This bug took me ages to track down, that’s why I wrote all the
       * relevant info down so that others wouldn’t duplicate it.
       */
         if(!(lastLine == lineIndex && nextLineRequested))
            nextLineRequested = (oldToken != token);
      
         lastLine = lineIndex;
      
         addToken(0,Token.END);
      
         return firstToken;
      }
   
   /**
    * An abstract method that splits a line up into tokens. It
    * should parse the line, and call addToken() to
    * add syntax tokens to the token list. Then, it should return
    * the initial token type for the next line.

    *
    * For example if the current line contains the start of a 
    * multiline comment that doesn’t end on that line, this method
    * should return the comment token type so that it continues on
    * the next line.
    *
    * @param token The initial token type for this line
    * @param line The line to be tokenized
    * @param lineIndex The index of the line in the document, starting at 0
    * @return The initial token type for the next line
    */
       protected abstract byte markTokensImpl(byte token, Segment line,
       int lineIndex);
   
   /**
    * Returns if the token marker supports tokens that span multiple
    * lines. If this is true, the object using this token marker is
    * required to pass all lines in the document to the
    * markTokens() method (in turn).

    *
    * The default implementation returns true; it should be overridden
    * to return false on simpler token markers for increased speed.
    */
       public boolean supportsMultilineTokens() {
         return true;
      }
   
   /**
    * Informs the token marker that lines have been inserted into
    * the document. This inserts a gap in the lineInfo
    * array.
    * @param index The first line number
    * @param lines The number of lines 
    */
       public void insertLines(int index, int lines) {
         if(lines <= 0)             return;          length += lines;          ensureCapacity(length);          int len = index + lines;          System.arraycopy(lineInfo,index,lineInfo,len, lineInfo.length - len);                 for(int i = index + lines - 1; i >= index; i–){
            lineInfo[i] = new LineInfo();
         }
      }
   
   /**
    * Informs the token marker that line have been deleted from
    * the document. This removes the lines in question from the
    * lineInfo array.
    * @param index The first line number
    * @param lines The number of lines
    */
       public void deleteLines(int index, int lines) {
         if (lines <= 0)             return;          int len = index + lines;          length -= lines;          System.arraycopy(lineInfo,len,lineInfo,             index,lineInfo.length - len);       }        /**     * Returns the number of lines in this token marker.     */        public int getLineCount() {          return length;       }        /**     * Returns true if the next line should be repainted. This     * will return true after a line has been tokenized that starts     * a multiline token that continues onto the next line.     */        public boolean isNextLineRequested() {          return nextLineRequested;       }        /**     *  Construct and return any appropriate help information for     *  the given token.  This default definition returns null;     *  override it in language-specific subclasses.     *  @param token the pertinent Token object     *  @param tokenText the source String that matched to the token     *  @return ArrayList containing PopupHelpItem objects, one per match.       */        public ArrayList getTokenExactMatchHelp(Token token, String tokenText) {          return null;       }        /**     *  Construct and return any appropriate help information for     *  the given token or "token prefix".  Will match instruction prefixes, e.g. "s" matches "sw".     *  This default definition returns null;     *  override it in language-specific subclasses.     *  @param line String containing current line     *  @param tokenList first Token on the current line     *  @param token the pertinent Token object     *  @param tokenText the source String that matched to the token     *  @return ArrayList containing PopupHelpItem objects, one per match.       */              public ArrayList getTokenPrefixMatchHelp(String line, Token tokenList, Token tokenAtOffset, String tokenText) {          return null;       }        // protected members        /**     * The first token in the list. This should be used as the return     * value from markTokens().
    */
      protected Token firstToken;
   
   /**
    * The last token in the list. New tokens are added here.
    * This should be set to null before a new line is to be tokenized.
    */
      protected Token lastToken;
   
   /**
    * An array for storing information about lines. It is enlarged and
    * shrunk automatically by the insertLines() and
    * deleteLines() methods.
    */
      protected LineInfo[] lineInfo;
   
   /**
    * The number of lines in the model being tokenized. This can be
    * less than the length of the lineInfo array.
    */
      protected int length;
   
   /**
    * The last tokenized line.
    */
      protected int lastLine;
   
   /**
    * True if the next line should be painted.
    */
      protected boolean nextLineRequested;
   
   /**
    * Creates a new TokenMarker. This DOES NOT create
    * a lineInfo array; an initial call to insertLines()
    * does that.
    */
       protected TokenMarker() {
         lastLine = -1;
      }
   
   /**
    * Ensures that the lineInfo array can contain the
    * specified index. This enlarges it if necessary. No action is
    * taken if the array is large enough already.

    *
    * It should be unnecessary to call this under normal
    * circumstances; insertLine() should take care of
    * enlarging the line info array automatically.
    *
    * @param index The array index
    */
       protected void ensureCapacity(int index) {
         if(lineInfo == null)
            lineInfo = new LineInfo[index + 1];
         else if(lineInfo.length <= index) {             LineInfo[] lineInfoN = new LineInfo[(index + 1) * 2];             System.arraycopy(lineInfo,0,lineInfoN,0,                 lineInfo.length);             lineInfo = lineInfoN;          }       }        /**     * Adds a token to the token list.     * @param length The length of the token     * @param id The id of the token     */        protected void addToken(int length, byte id) {          if(id >= Token.INTERNAL_FIRST && id <= Token.INTERNAL_LAST)             throw new InternalError("Invalid id: " + id);                 if(length == 0 && id != Token.END)             return;                 if(firstToken == null) {             firstToken = new Token(length,id);             lastToken = firstToken;          }          else if(lastToken == null) {             lastToken = firstToken;             firstToken.length = length;             firstToken.id = id;          }          else if(lastToken.next == null) {             lastToken.next = new Token(length,id);             lastToken = lastToken.next;          }          else {             lastToken = lastToken.next;             lastToken.length = length;             lastToken.id = id;          }       }        /**     * Inner class for storing information about tokenized lines.     */        public class LineInfo {       /**        * Creates a new LineInfo object with token = Token.NULL        * and obj = null.        */           public LineInfo() {          }              /**        * Creates a new LineInfo object with the specified        * parameters.        */           public LineInfo(byte token, Object obj) {             this.token = token;             this.obj = obj;          }              /**        * The id of the last token of the line.        */          public byte token;              /**        * This is for use by the token marker implementations        * themselves. It can be used to store anything that        * is an object and that needs to exist on a per-line        * basis.        */          public Object obj;       }    } mars/venus/editors/jeditsyntax/tokenmarker/MIPSTokenMarker.java mars/venus/editors/jeditsyntax/tokenmarker/MIPSTokenMarker.java/*  * MIPSTokenMarker.java - MIPS Assembly token marker  * Copyright (C) 1998, 1999 Slava Pestov, 2010 Pete Sanderson  *  * You may use and modify this package for any purpose. Redistribution is  * permitted, in both source and binary form, provided that this notice  * remains intact in all source distributions of this package.  */    package mars.venus.editors.jeditsyntax.tokenmarker;    import mars.venus.editors.jeditsyntax.*;    import mars.mips.instructions.*;    import mars.assembler.*;    import javax.swing.text.Segment;    import java.util.*; /**  * MIPS token marker.  *  * @author Pete Sanderson (2010) and Slava Pestov (1999)  */     public class MIPSTokenMarker extends TokenMarker    {        public MIPSTokenMarker()       {          this(getKeywords());       }            public MIPSTokenMarker(KeywordMap keywords)       {          this.keywords = keywords;       }            public static String[] getMIPSTokenLabels()        {          if (tokenLabels == null)           {             tokenLabels = new String[Token.ID_COUNT];             tokenLabels[Token.COMMENT1] = "Comment";             tokenLabels[Token.LITERAL1] = "String literal";             tokenLabels[Token.LITERAL2] = "Character literal";             tokenLabels[Token.LABEL]    = "Label";             tokenLabels[Token.KEYWORD1] = "MIPS instruction";             tokenLabels[Token.KEYWORD2] = "Assembler directive";             tokenLabels[Token.KEYWORD3] = "Register";             tokenLabels[Token.INVALID]  = "In-progress, invalid";             tokenLabels[Token.MACRO_ARG]= "Macro parameter";            }          return tokenLabels;       }            public static String[] getMIPSTokenExamples()        {          if (tokenExamples == null)           {             tokenExamples = new String[Token.ID_COUNT];             tokenExamples[Token.COMMENT1] = "# Load";             tokenExamples[Token.LITERAL1] = "\"First\"";             tokenExamples[Token.LITERAL2] = "'\\n'";             tokenExamples[Token.LABEL]    = "main:";             tokenExamples[Token.KEYWORD1] = "lui";             tokenExamples[Token.KEYWORD2] = ".text";             tokenExamples[Token.KEYWORD3] = "$zero";             tokenExamples[Token.INVALID]  = "\"Regi";             tokenExamples[Token.MACRO_ARG]= "%arg";          }          return tokenExamples;       }                      public byte markTokensImpl(byte token, Segment line, int lineIndex)       {          char[] array = line.array;          int offset = line.offset;          lastOffset = offset;          lastKeyword = offset;          int length = line.count + offset;          boolean backslash = false;              loop:               for(int i = offset; i < length; i++)          {             int i1 = (i+1);                       char c = array[i];             if(c == '\\')             {                backslash = !backslash;                continue;             }                       switch(token)             {                case Token.NULL:                   switch(c)                   {                      case '"':                         doKeyword(line,i,c);                         if(backslash)                            backslash = false;                         else                         {                            addToken(i - lastOffset,token);                            token = Token.LITERAL1;                            lastOffset = lastKeyword = i;                         }                         break;                      case '\'':                         doKeyword(line,i,c);                         if(backslash)                            backslash = false;                         else                         {                            addToken(i - lastOffset,token);                            token = Token.LITERAL2;                            lastOffset = lastKeyword = i;                         }                         break;                      case ':':                       /*  Original code for ':' case, replaced 3 Aug 2010. Details below.                         if(lastKeyword == offset)                         { // Commenting out this IF statement permits recognition of keywords                           // used as labels when terminated with ":".  The most common example                           // is "b:" (where b is mnemonic for branch instruction). DPS 6-July-2010.                           //                           // if(doKeyword(line,i,c))                            //   break;                            backslash = false;                            addToken(i1 - lastOffset,Token.LABEL);                            lastOffset = lastKeyword = i1;                         }                         else if(doKeyword(line,i,c))                            break;                         break;                      */                        // Replacement code 3 Aug 2010.  Will recognize label definitions when:                        // (1) label is same as instruction name, (2) label begins after column 1,                        // (3) there are spaces between label name and colon, (4) label is valid                        // MIPS identifier (otherwise would catch, say, 0 (zero) in .word 0:10)                         backslash = false;                         //String lab = new String(array, lastOffset, i1-lastOffset-1).trim();                         boolean validIdentifier = false;                         try {                            validIdentifier = mars.assembler.TokenTypes.isValidIdentifier(new String(array, lastOffset, i1-lastOffset-1).trim());                         }                             catch (StringIndexOutOfBoundsException e) {                               validIdentifier = false;                            }                         if (validIdentifier) {                            addToken(i1 - lastOffset,Token.LABEL);                            lastOffset = lastKeyword = i1;                         }                         break;                      case '#':                         backslash = false;                         doKeyword(line,i,c);                         if(length - i >= 1)
                        {
                           addToken(i – lastOffset,token);
                           addToken(length – i,Token.COMMENT1);
                           lastOffset = lastKeyword = length;
                           break loop;
                        }
                        break;
                     default:
                        backslash = false;
                                // . and $ added 4/6/10 DPS; % added 12/12 M.Sekhavat
                        if(!Character.isLetterOrDigit(c)
                        && c != ‘_’ && c != ‘.’ && c != ‘$’ && c!=’%’) 
                           doKeyword(line,i,c);
                        break;
                  }
                  break;
               case Token.LITERAL1:
                  if(backslash)
                     backslash = false;
                  else if(c == ‘”‘)
                  {
                     addToken(i1 – lastOffset,token);
                     token = Token.NULL;
                     lastOffset = lastKeyword = i1;
                  }
                  break;
               case Token.LITERAL2:
                  if(backslash)
                     backslash = false;
                  else if(c == ‘\”)
                  {
                     addToken(i1 – lastOffset,Token.LITERAL1);
                     token = Token.NULL;
                     lastOffset = lastKeyword = i1;
                  }
                  break;
               default:
                  throw new InternalError(“Invalid state: ”
                     + token);
            }
         }
      
         if(token == Token.NULL)
            doKeyword(line,length,’\0’);
      
         switch(token)
         {
            case Token.LITERAL1:
            case Token.LITERAL2:
               addToken(length – lastOffset,Token.INVALID);
               token = Token.NULL;
               break;
            case Token.KEYWORD2:
               addToken(length – lastOffset,token);
               if(!backslash)
                  token = Token.NULL;
            default:
               addToken(length – lastOffset,token);
               break;
         }
      
         return token;
      }
   
   
   /**
    *  Construct and return any appropriate help information for
    *  the given token.  
    *  @param token the pertinent Token object
    *  @param tokenText the source String that matched to the token
    *  @return ArrayList of PopupHelpItem objects, one per match.  
    */
       public ArrayList getTokenExactMatchHelp(Token token, String tokenText) 
      {  
         ArrayList matches = null;
         if (token != null && token.id == Token.KEYWORD1) {
            ArrayList instrMatches =  mars.Globals.instructionSet.matchOperator(tokenText);
            if (instrMatches.size() > 0) {
               int realMatches = 0;
               matches = new ArrayList();
               for (int i=0; i 0) {
               if (trimmedTokenText.charAt(0)==’.’) {
                  return getTextFromDirectiveMatch(trimmedTokenText, false);
               } 
               else
                  if (trimmedTokenText.length() >= mars.Globals.getSettings().getEditorPopupPrefixLength()) { 
                     return getTextFromInstructionMatch(trimmedTokenText, false);
                  }
            }
         }
         // should never get here…
         return null;        
      }
    
   
      ///////////////////////////////////////////////////////////////////////////
      // Return ArrayList of PopupHelpItem for match of directives.  If second argument
    // true, will do exact match.  If false, will do prefix match.  Returns null
    // if no matches.
       private ArrayList getTextFromDirectiveMatch(String tokenText, boolean exact) {
         ArrayList matches = null;
         ArrayList directiveMatches = null;
         if (exact) {
            Object dir = Directives.matchDirective(tokenText);
            if (dir != null) {
               directiveMatches = new ArrayList();
               directiveMatches.add(dir);
            }
         } 
         else {
            directiveMatches =  Directives.prefixMatchDirectives(tokenText);
         }
         if (directiveMatches != null) {
            matches = new ArrayList();
            for (int i=0; iSyntaxDocument.getColors()
 * to get a color value, a length value which is the length of the
 * token in the text, and a pointer to the next token in the list.
 *
 * @author Slava Pestov
 * @version $Id: Token.java,v 1.12 1999/12/13 03:40:30 sp Exp $
 */

public class Token
{
 // NOTE from DPS 13-May-2010.
 // Please do not modify any of these constants!  It’s not fatal or 
 // anything, but will cause funny results in the MARS Settings 
 // mechanism (at least temporarily until changed).  The
 // associated values here are appended into the key names for
 // persistent storage (e.g. registry) of syntax style information
 // for the various tokens.
 
    /**
     * Normal text token id. This should be used to mark
     * normal text.
     */
    public static final byte NULL = 0;

    /**
     * Comment 1 token id. This can be used to mark a comment.
     */
    public static final byte COMMENT1 = 1;

    /**
     * Comment 2 token id. This can be used to mark a comment.
     */
    public static final byte COMMENT2 = 2;

    
    /**
     * Literal 1 token id. This can be used to mark a string
     * literal (eg, C mode uses this to mark “…” literals)
     */
    public static final byte LITERAL1 = 3;

    /**
     * Literal 2 token id. This can be used to mark an object
     * literal (eg, Java mode uses this to mark true, false, etc)
     */
    public static final byte LITERAL2 = 4;

    /**
     * Label token id. This can be used to mark labels
     * (eg, C mode uses this to mark …: sequences)
     */
    public static final byte LABEL = 5;

    /**
     * Keyword 1 token id. This can be used to mark a
     * keyword. This should be used for general language
     * constructs.
     */
    public static final byte KEYWORD1 = 6;

    /**
     * Keyword 2 token id. This can be used to mark a
     * keyword. This should be used for preprocessor
     * commands, or variables.
     */
    public static final byte KEYWORD2 = 7;

    /**
     * Keyword 3 token id. This can be used to mark a
     * keyword. This should be used for data types.
     */
    public static final byte KEYWORD3 = 8;

    /**
     * Operator token id. This can be used to mark an
     * operator. (eg, SQL mode marks +, -, etc with this
     * token type)
     */
    public static final byte OPERATOR = 9;

    /**
     * Invalid token id. This can be used to mark invalid
     * or incomplete tokens, so the user can easily spot
     * syntax errors.
     */
    public static final byte INVALID = 10;

   /**
     * Macro parameter token.  Added for MARS 4.3.
     */
    public static final byte MACRO_ARG = 11;
    
    /**
     * The total number of defined token ids.
     */
    public static final byte ID_COUNT = 12;

    /**
     * The first id that can be used for internal state
     * in a token marker.
     */
    public static final byte INTERNAL_FIRST = 100;

    /**
     * The last id that can be used for internal state
     * in a token marker.
     */
    public static final byte INTERNAL_LAST = 126;

    /**
     * The token type, that along with a length of 0
     * marks the end of the token list.
     */
    public static final byte END = 127;

    /**
     * The length of this token.
     */
    public int length;

    /**
     * The id of this token.
     */
    public byte id;

    /**
     * The next token in the linked list.
     */
    public Token next;

    /**
     * Creates a new token.
     * @param length The length of the token
     * @param id The id of the token
     */
    public Token(int length, byte id)
    {
        this.length = length;
        this.id = id;
    }

    /**
     * Returns a string representation of this token.
     */
    public String toString()
    {
        return “[id=” + id + “,length=” + length + “]”;
    }
}

TokenMarker$LineInfo

package mars.venus.editors.jeditsyntax.tokenmarker;
public synchronized class TokenMarker$LineInfo {
public byte token;
public Object obj;
public void TokenMarker$LineInfo(TokenMarker);
public void TokenMarker$LineInfo(TokenMarker, byte, Object);
}

InputHandler$prev_line

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$prev_line implements java.awt.event.ActionListener {
private boolean select;
public void InputHandler$prev_line(boolean);
public void actionPerformed(java.awt.event.ActionEvent);
}

SyntaxStyle

package mars.venus.editors.jeditsyntax;
public synchronized class SyntaxStyle {
private java.awt.Color color;
private boolean italic;
private boolean bold;
private java.awt.Font lastFont;
private java.awt.Font lastStyledFont;
private java.awt.FontMetrics fontMetrics;
public void SyntaxStyle(java.awt.Color, boolean, boolean);
public java.awt.Color getColor();
public String getColorAsHexString();
public boolean isPlain();
public boolean isItalic();
public boolean isBold();
public java.awt.Font getStyledFont(java.awt.Font);
public java.awt.FontMetrics getFontMetrics(java.awt.Font);
public void setGraphicsFlags(java.awt.Graphics, java.awt.Font);
public String toString();
}

InputHandler$overwrite

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$overwrite implements java.awt.event.ActionListener {
public void InputHandler$overwrite();
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$select_all

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$select_all implements java.awt.event.ActionListener {
public void InputHandler$select_all();
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/editors/jeditsyntax/InputHandler.java
mars/venus/editors/jeditsyntax/InputHandler.java/*
 * InputHandler.java – Manages key bindings and executes actions
 * Copyright (C) 1999 Slava Pestov
 *
 * You may use and modify this package for any purpose. Redistribution is
 * permitted, in both source and binary form, provided that this notice
 * remains intact in all source distributions of this package.
 */

   package mars.venus.editors.jeditsyntax;

   import javax.swing.text.*;
   import javax.swing.JPopupMenu;
   import java.awt.event.*;
   import java.awt.Component;
   import java.util.*;

/**
 * An input handler converts the user’s key strokes into concrete actions.
 * It also takes care of macro recording and action repetition.

 *
 * This class provides all the necessary support code for an input
 * handler, but doesn’t actually do any key binding logic. It is up
 * to the implementations of this class to do so.
 * 
 * @author Slava Pestov
 * @version $Id: InputHandler.java,v 1.14 1999/12/13 03:40:30 sp Exp $
 * @see org.syntax.jedit.DefaultInputHandler
 * 
 * 08/12/2002   Clipboard actions   (Oliver Henning)
 */
    public abstract class InputHandler extends KeyAdapter
   {
   /**
    * If this client property is set to Boolean.TRUE on the text area,
    * the home/end keys will support ‘smart’ BRIEF-like behaviour
    * (one press = start/end of line, two presses = start/end of
    * viewscreen, three presses = start/end of document). By default,
    * this property is not set.
    */
      public static final String SMART_HOME_END_PROPERTY = “InputHandler.homeEnd”;
   
      public static final ActionListener BACKSPACE = new backspace();
      public static final ActionListener BACKSPACE_WORD = new backspace_word();
      public static final ActionListener DELETE = new delete();
      public static final ActionListener DELETE_WORD = new delete_word();
      public static final ActionListener END = new end(false);
      public static final ActionListener DOCUMENT_END = new document_end(false);
      public static final ActionListener SELECT_ALL = new select_all();
      public static final ActionListener SELECT_END = new end(true);
      public static final ActionListener SELECT_DOC_END = new document_end(true);
      public static final ActionListener INSERT_BREAK = new insert_break();
      public static final ActionListener INSERT_TAB = new insert_tab();
      public static final ActionListener HOME = new home(false);
      public static final ActionListener DOCUMENT_HOME = new document_home(false);
      public static final ActionListener SELECT_HOME = new home(true);
      public static final ActionListener SELECT_DOC_HOME = new document_home(true);
      public static final ActionListener NEXT_CHAR = new next_char(false);
      public static final ActionListener NEXT_LINE = new next_line(false);
      public static final ActionListener NEXT_PAGE = new next_page(false);
      public static final ActionListener NEXT_WORD = new next_word(false);
      public static final ActionListener SELECT_NEXT_CHAR = new next_char(true);
      public static final ActionListener SELECT_NEXT_LINE = new next_line(true);
      public static final ActionListener SELECT_NEXT_PAGE = new next_page(true);
      public static final ActionListener SELECT_NEXT_WORD = new next_word(true);
      public static final ActionListener OVERWRITE = new overwrite();
      public static final ActionListener PREV_CHAR = new prev_char(false);
      public static final ActionListener PREV_LINE = new prev_line(false);
      public static final ActionListener PREV_PAGE = new prev_page(false);
      public static final ActionListener PREV_WORD = new prev_word(false);
      public static final ActionListener SELECT_PREV_CHAR = new prev_char(true);
      public static final ActionListener SELECT_PREV_LINE = new prev_line(true);
      public static final ActionListener SELECT_PREV_PAGE = new prev_page(true);
      public static final ActionListener SELECT_PREV_WORD = new prev_word(true);
      public static final ActionListener REPEAT = new repeat();
      public static final ActionListener TOGGLE_RECT = new toggle_rect();
   // Clipboard
      public static final ActionListener CLIP_COPY = new clip_copy();
      public static final ActionListener CLIP_PASTE = new clip_paste();
      public static final ActionListener CLIP_CUT = new clip_cut();
   
   // Default action
      public static final ActionListener INSERT_CHAR = new insert_char();
   
      private static Hashtable actions;
   
      static
      {
         actions = new Hashtable();
         actions.put(“backspace”,BACKSPACE);
         actions.put(“backspace-word”,BACKSPACE_WORD);
         actions.put(“delete”,DELETE);
         actions.put(“delete-word”,DELETE_WORD);
         actions.put(“end”,END);
         actions.put(“select-all”,SELECT_ALL);
         actions.put(“select-end”,SELECT_END);
         actions.put(“document-end”,DOCUMENT_END);
         actions.put(“select-doc-end”,SELECT_DOC_END);
         actions.put(“insert-break”,INSERT_BREAK);
         actions.put(“insert-tab”,INSERT_TAB);
         actions.put(“home”,HOME);
         actions.put(“select-home”,SELECT_HOME);
         actions.put(“document-home”,DOCUMENT_HOME);
         actions.put(“select-doc-home”,SELECT_DOC_HOME);
         actions.put(“next-char”,NEXT_CHAR);
         actions.put(“next-line”,NEXT_LINE);
         actions.put(“next-page”,NEXT_PAGE);
         actions.put(“next-word”,NEXT_WORD);
         actions.put(“select-next-char”,SELECT_NEXT_CHAR);
         actions.put(“select-next-line”,SELECT_NEXT_LINE);
         actions.put(“select-next-page”,SELECT_NEXT_PAGE);
         actions.put(“select-next-word”,SELECT_NEXT_WORD);
         actions.put(“overwrite”,OVERWRITE);
         actions.put(“prev-char”,PREV_CHAR);
         actions.put(“prev-line”,PREV_LINE);
         actions.put(“prev-page”,PREV_PAGE);
         actions.put(“prev-word”,PREV_WORD);
         actions.put(“select-prev-char”,SELECT_PREV_CHAR);
         actions.put(“select-prev-line”,SELECT_PREV_LINE);
         actions.put(“select-prev-page”,SELECT_PREV_PAGE);
         actions.put(“select-prev-word”,SELECT_PREV_WORD);
         actions.put(“repeat”,REPEAT);
         actions.put(“toggle-rect”,TOGGLE_RECT);
         actions.put(“insert-char”,INSERT_CHAR);
         actions.put(“clipboard-copy”,CLIP_COPY);
         actions.put(“clipboard-paste”,CLIP_PASTE);
         actions.put(“clipboard-cut”,CLIP_CUT);
      }
   
   /**
    * Returns a named text area action.
    * @param name The action name
    */
       public static ActionListener getAction(String name)
      {
         return (ActionListener)actions.get(name);
      }
   
   /**
    * Returns the name of the specified text area action.
    * @param listener The action
    */
       public static String getActionName(ActionListener listener)
      {
         Enumeration enumeration = getActions();
         while(enumeration.hasMoreElements())
         {
            String name = (String)enumeration.nextElement();
            ActionListener _listener = getAction(name);
            if(_listener == listener)
               return name;
         }
         return null;
      }
   
   /**
    * Returns an enumeration of all available actions.
    */
       public static Enumeration getActions()
      {
         return actions.keys();
      }
   
   /**
    * Adds the default key bindings to this input handler.
    * This should not be called in the constructor of this
    * input handler, because applications might load the
    * key bindings from a file, etc.
    */
       public abstract void addDefaultKeyBindings();
   
   /**
    * Adds a key binding to this input handler.
    * @param keyBinding The key binding (the format of this is
    * input-handler specific)
    * @param action The action
    */
       public abstract void addKeyBinding(String keyBinding, ActionListener action);
   
   /**
    * Removes a key binding from this input handler.
    * @param keyBinding The key binding
    */
       public abstract void removeKeyBinding(String keyBinding);
   
   /**
    * Removes all key bindings from this input handler.
    */
       public abstract void removeAllKeyBindings();
   
   /**
    * Grabs the next key typed event and invokes the specified
    * action with the key as a the action command.
    * @param action The action
    */
       public void grabNextKeyStroke(ActionListener listener)
      {
         grabAction = listener;
      }
   
   /**
    * Returns if repeating is enabled. When repeating is enabled,
    * actions will be executed multiple times. This is usually
    * invoked with a special key stroke in the input handler.
    */
       public boolean isRepeatEnabled()
      {
         return repeat;
      }
   
   /**
    * Enables repeating. When repeating is enabled, actions will be
    * executed multiple times. Once repeating is enabled, the input
    * handler should read a number from the keyboard.
    */
       public void setRepeatEnabled(boolean repeat)
      {
         this.repeat = repeat;
      }
   
   /**
    * Returns the number of times the next action will be repeated.
    */
       public int getRepeatCount()
      {
         return (repeat ? Math.max(1,repeatCount) : 1);
      }
   
   /**
    * Sets the number of times the next action will be repeated.
    * @param repeatCount The repeat count
    */
       public void setRepeatCount(int repeatCount)
      {
         this.repeatCount = repeatCount;
      }
   
   /**
    * Returns the macro recorder. If this is non-null, all executed
    * actions should be forwarded to the recorder.
    */
       public InputHandler.MacroRecorder getMacroRecorder()
      {
         return recorder;
      }
   
   /**
    * Sets the macro recorder. If this is non-null, all executed
    * actions should be forwarded to the recorder.
    * @param recorder The macro recorder
    */
       public void setMacroRecorder(InputHandler.MacroRecorder recorder)
      {
         this.recorder = recorder;
      }
   
   /**
    * Returns a copy of this input handler that shares the same
    * key bindings. Setting key bindings in the copy will also
    * set them in the original.
    */
       public abstract InputHandler copy();
   
   /**
    * Executes the specified action, repeating and recording it as
    * necessary.
    * @param listener The action listener
    * @param source The event source
    * @param actionCommand The action command
    */
       public void executeAction(ActionListener listener, Object source,
       String actionCommand)
      {
      // create event
         ActionEvent evt = new ActionEvent(source,
            ActionEvent.ACTION_PERFORMED,
            actionCommand);
      
      // don’t do anything if the action is a wrapper
      // (like EditAction.Wrapper)
         if(listener instanceof Wrapper)
         {
            listener.actionPerformed(evt);
            return;
         }
      
      // remember old values, in case action changes them
         boolean _repeat = repeat;
         int _repeatCount = getRepeatCount();
      
      // execute the action
         if(listener instanceof InputHandler.NonRepeatable)
         {
            listener.actionPerformed(evt);
         }
         else
         {
            for(int i = 0; i < Math.max(1,repeatCount); i++)                listener.actionPerformed(evt);          }              // do recording. Notice that we do no recording whatsoever       // for actions that grab keys          if(grabAction == null)          {             if(recorder != null)             {                if(!(listener instanceof InputHandler.NonRecordable))                {                   if(_repeatCount != 1)                      recorder.actionPerformed(REPEAT,String.valueOf(_repeatCount));                                   recorder.actionPerformed(listener,actionCommand);                }             }                    // If repeat was true originally, clear it          // Otherwise it might have been set by the action, etc             if(_repeat)             {                repeat = false;                repeatCount = 0;             }          }       }        /**     * Returns the text area that fired the specified event.     * @param evt The event     */        public static JEditTextArea getTextArea(EventObject evt)       {          if(evt != null)          {             Object o = evt.getSource();             if(o instanceof Component)             {             // find the parent text area                Component c = (Component)o;                for(;;)                {                   if(c instanceof JEditTextArea)                      return (JEditTextArea)c;                   else if(c == null)                      break;                   if(c instanceof JPopupMenu)                      c = ((JPopupMenu)c)                         .getInvoker();                   else                      c = c.getParent();                }             }          }              // this shouldn't happen          System.err.println("BUG: getTextArea() returning null");          System.err.println("Report this to Slava Pestov < >“);
         return null;
      }
   
   
   // protected members
   
   /**
    * If a key is being grabbed, this method should be called with
    * the appropriate key event. It executes the grab action with
    * the typed character as the parameter.
    */
       protected void handleGrabAction(KeyEvent evt)
      {
      // Clear it *before* it is executed so that executeAction()
      // resets the repeat count
         ActionListener _grabAction = grabAction;
         grabAction = null;
         executeAction(_grabAction,evt.getSource(),
            String.valueOf(evt.getKeyChar()));
      }
   
   // protected members
      protected ActionListener grabAction;
      protected boolean repeat;
      protected int repeatCount;
      protected InputHandler.MacroRecorder recorder;
   
   /**
    * If an action implements this interface, it should not be repeated.
    * Instead, it will handle the repetition itself.
    */
       public interface NonRepeatable {}
   
   /**
    * If an action implements this interface, it should not be recorded
    * by the macro recorder. Instead, it will do its own recording.
    */
       public interface NonRecordable {}
   
   /**
    * For use by EditAction.Wrapper only.
    * @since jEdit 2.2final
    */
       public interface Wrapper {}
   
   /**
    * Macro recorder.
    */
       public interface MacroRecorder
      {
          void actionPerformed(ActionListener listener,
          String actionCommand);
      }
   
       public static class backspace implements ActionListener
      {
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
         
            if(!textArea.isEditable())
            {
               textArea.getToolkit().beep();
               return;
            }
         
            if(textArea.getSelectionStart()
            != textArea.getSelectionEnd())
            {
               textArea.setSelectedText(“”);
            }
            else
            {
               int caret = textArea.getCaretPosition();
               if(caret == 0)
               {
                  textArea.getToolkit().beep();
                  return;
               }
               try
               {
                  textArea.getDocument().remove(caret – 1,1);
               }
                   catch(BadLocationException bl)
                  {
                     bl.printStackTrace();
                  }
            }
         }
      }
   
       public static class backspace_word implements ActionListener
      {
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            int start = textArea.getSelectionStart();
            if(start != textArea.getSelectionEnd())
            {
               textArea.setSelectedText(“”);
            }
         
            int line = textArea.getCaretLine();
            int lineStart = textArea.getLineStartOffset(line);
            int caret = start – lineStart;
         
            String lineText = textArea.getLineText(textArea
               .getCaretLine());
         
            if(caret == 0)
            {
               if(lineStart == 0)
               {
                  textArea.getToolkit().beep();
                  return;
               }
               caret–;
            }
            else
            {
               String noWordSep = (String)textArea.getDocument().getProperty(“noWordSep”);
               caret = TextUtilities.findWordStart(lineText,caret,noWordSep);
            }
         
            try
            {
               textArea.getDocument().remove(
                  caret + lineStart,
                  start – (caret + lineStart));
            }
                catch(BadLocationException bl)
               {
                  bl.printStackTrace();
               }
         }
      }
   
       public static class delete implements ActionListener
      {
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
         
            if(!textArea.isEditable())
            {
               textArea.getToolkit().beep();
               return;
            }
         
            if(textArea.getSelectionStart()
            != textArea.getSelectionEnd())
            {
               textArea.setSelectedText(“”);
            }
            else
            {
               int caret = textArea.getCaretPosition();
               if(caret == textArea.getDocumentLength())
               {
                  textArea.getToolkit().beep();
                  return;
               }
               try
               {
                  textArea.getDocument().remove(caret,1);
               }
                   catch(BadLocationException bl)
                  {
                     bl.printStackTrace();
                  }
            }
         }
      }
   
       public static class delete_word implements ActionListener
      {
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            int start = textArea.getSelectionStart();
            if(start != textArea.getSelectionEnd())
            {
               textArea.setSelectedText(“”);
            }
         
            int line = textArea.getCaretLine();
            int lineStart = textArea.getLineStartOffset(line);
            int caret = start – lineStart;
         
            String lineText = textArea.getLineText(textArea
               .getCaretLine());
         
            if(caret == lineText.length())
            {
               if(lineStart + caret == textArea.getDocumentLength())
               {
                  textArea.getToolkit().beep();
                  return;
               }
               caret++;
            }
            else
            {
               String noWordSep = (String)textArea.getDocument().getProperty(“noWordSep”);
               caret = TextUtilities.findWordEnd(lineText,caret,noWordSep);
            }
         
            try
            {
               textArea.getDocument().remove(start,
                  (caret + lineStart) – start);
            }
                catch(BadLocationException bl)
               {
                  bl.printStackTrace();
               }
         }
      }
   
       public static class end implements ActionListener
      {
         private boolean select;
      
          public end(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
         
            int caret = textArea.getCaretPosition();
         
            int lastOfLine = textArea.getLineEndOffset(
               textArea.getCaretLine()) – 1;
            int lastVisibleLine = textArea.getFirstLine()
               + textArea.getVisibleLines();
            if(lastVisibleLine >= textArea.getLineCount())
            {
               lastVisibleLine = Math.min(textArea.getLineCount() – 1,
                  lastVisibleLine);
            }
            else
               lastVisibleLine -= (textArea.getElectricScroll() + 1);
         
            int lastVisible = textArea.getLineEndOffset(lastVisibleLine) – 1;
            int lastDocument = textArea.getDocumentLength();
         
            if(caret == lastDocument)
            {
               textArea.getToolkit().beep();
               return;
            }
            else if(!Boolean.TRUE.equals(textArea.getClientProperty(
            SMART_HOME_END_PROPERTY)))
               caret = lastOfLine;
            else if(caret == lastVisible)
               caret = lastDocument;
            else if(caret == lastOfLine)
               caret = lastVisible;
            else
               caret = lastOfLine;
         
            if(select)
               textArea.select(textArea.getMarkPosition(),caret);
            else
               textArea.setCaretPosition(caret);
         }
      }
   
       public static class select_all implements ActionListener {
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            textArea.selectAll();
         }
      }
   
       public static class document_end implements ActionListener
      {
         private boolean select;
      
          public document_end(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            if(select)
               textArea.select(textArea.getMarkPosition(),
                  textArea.getDocumentLength());
            else
               textArea.setCaretPosition(textArea
                  .getDocumentLength());
         }
      }
   
       public static class home implements ActionListener
      {
         private boolean select;
      
          public home(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
         
            int caret = textArea.getCaretPosition();
         
            int firstLine = textArea.getFirstLine();
         
            int firstOfLine = textArea.getLineStartOffset(
               textArea.getCaretLine());
            int firstVisibleLine = (firstLine == 0 ? 0 :
               firstLine + textArea.getElectricScroll());
            int firstVisible = textArea.getLineStartOffset(
               firstVisibleLine);
         
            if(caret == 0)
            {
               textArea.getToolkit().beep();
               return;
            }
            else if(!Boolean.TRUE.equals(textArea.getClientProperty(
            SMART_HOME_END_PROPERTY)))
               caret = firstOfLine;
            else if(caret == firstVisible)
               caret = 0;
            else if(caret == firstOfLine)
               caret = firstVisible;
            else
               caret = firstOfLine;
         
            if(select)
               textArea.select(textArea.getMarkPosition(),caret);
            else
               textArea.setCaretPosition(caret);
         }
      }
   
       public static class document_home implements ActionListener
      {
         private boolean select;
      
          public document_home(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            if(select)
               textArea.select(textArea.getMarkPosition(),0);
            else
               textArea.setCaretPosition(0);
         }
      }
   
       public static class insert_break implements ActionListener
      {
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
         
            if(!textArea.isEditable())
            {
               textArea.getToolkit().beep();
               return;
            }
            // AutoIndent feature added DPS 31-Dec-2010
            textArea.setSelectedText(“\n”+textArea.getAutoIndent());
         }
      }
   
       public static class insert_tab implements ActionListener
      {
          public void actionPerformed(ActionEvent evt)
         { 
            JEditTextArea textArea = getTextArea(evt);
         
            if(!textArea.isEditable())
            {
               textArea.getToolkit().beep();
               return;
            }
         
            textArea.overwriteSetSelectedText(“\t”);
         }
      }
   
       public static class next_char implements ActionListener
      {
         private boolean select;
      
          public next_char(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            int caret = textArea.getCaretPosition();
            if(caret == textArea.getDocumentLength())
            {
               textArea.getToolkit().beep();
               return;
            }
         
            if(select)
               textArea.select(textArea.getMarkPosition(),
                  caret + 1);
            else
               textArea.setCaretPosition(caret + 1);
         }
      }
   
       public static class next_line implements ActionListener
      {
         private boolean select;
      
          public next_line(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            int caret = textArea.getCaretPosition();
            int line = textArea.getCaretLine();
         
            if(line == textArea.getLineCount() – 1)
            {
               textArea.getToolkit().beep();
               return;
            }
         
            int magic = textArea.getMagicCaretPosition();
            if(magic == -1)
            {
               magic = textArea.offsetToX(line,
                  caret – textArea.getLineStartOffset(line));
            }
         
            caret = textArea.getLineStartOffset(line + 1)
               + textArea.xToOffset(line + 1,magic);
            if(select)
               textArea.select(textArea.getMarkPosition(),caret);
            else
               textArea.setCaretPosition(caret);
            textArea.setMagicCaretPosition(magic);
         }
      }
   
       public static class next_page implements ActionListener
      {
         private boolean select;
      
          public next_page(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            int lineCount = textArea.getLineCount();
            int firstLine = textArea.getFirstLine();
            int visibleLines = textArea.getVisibleLines();
            int line = textArea.getCaretLine();
         
            firstLine += visibleLines;
         
            if(firstLine + visibleLines >= lineCount – 1)
               firstLine = lineCount – visibleLines;
         
            textArea.setFirstLine(firstLine);
         
            int caret = textArea.getLineStartOffset(
               Math.min(textArea.getLineCount() – 1,
               line + visibleLines));
            if(select)
               textArea.select(textArea.getMarkPosition(),caret);
            else
               textArea.setCaretPosition(caret);
         }
      }
   
       public static class next_word implements ActionListener
      {
         private boolean select;
      
          public next_word(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            int caret = textArea.getCaretPosition();
            int line = textArea.getCaretLine();
            int lineStart = textArea.getLineStartOffset(line);
            caret -= lineStart;
         
            String lineText = textArea.getLineText(textArea
               .getCaretLine());
         
            if(caret == lineText.length())
            {
               if(lineStart + caret == textArea.getDocumentLength())
               {
                  textArea.getToolkit().beep();
                  return;
               }
               caret++;
            }
            else
            {
               String noWordSep = (String)textArea.getDocument().getProperty(“noWordSep”);
               caret = TextUtilities.findWordEnd(lineText,caret,noWordSep);
            }
         
            if(select)
               textArea.select(textArea.getMarkPosition(),
                  lineStart + caret);
            else
               textArea.setCaretPosition(lineStart + caret);
         }
      }
   
       public static class overwrite implements ActionListener
      {
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            textArea.setOverwriteEnabled(
               !textArea.isOverwriteEnabled());
         }
      }
   
       public static class prev_char implements ActionListener
      {
         private boolean select;
      
          public prev_char(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            int caret = textArea.getCaretPosition();
            if(caret == 0)
            {
               textArea.getToolkit().beep();
               return;
            }
         
            if(select)
               textArea.select(textArea.getMarkPosition(),
                  caret – 1);
            else
               textArea.setCaretPosition(caret – 1);
         }
      }
   
       public static class prev_line implements ActionListener
      {
         private boolean select;
      
          public prev_line(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            int caret = textArea.getCaretPosition();
            int line = textArea.getCaretLine();
         
            if(line == 0)
            {
               textArea.getToolkit().beep();
               return;
            }
         
            int magic = textArea.getMagicCaretPosition();
            if(magic == -1)
            {
               magic = textArea.offsetToX(line,
                  caret – textArea.getLineStartOffset(line));
            }
         
            caret = textArea.getLineStartOffset(line – 1)
               + textArea.xToOffset(line – 1,magic);
            if(select)
               textArea.select(textArea.getMarkPosition(),caret);
            else
               textArea.setCaretPosition(caret);
            textArea.setMagicCaretPosition(magic);
         }
      }
   
       public static class prev_page implements ActionListener
      {
         private boolean select;
      
          public prev_page(boolean select)
         {
            this.select = select;
         }
      
          public void actionPerformed(ActionEvent evt)
         {
            JEditTextArea textArea = getTextArea(evt);
            int firstLine = textArea.getFirstLine();
            int visibleLines = textArea.getVisibleLines();
            int line = textArea.getCaretLine();
         
            if(firstLine < visibleLines)                firstLine = visibleLines;                       textArea.setFirstLine(firstLine - visibleLines);                       int caret = textArea.getLineStartOffset(                Math.max(0,line - visibleLines));             if(select)                textArea.select(textArea.getMarkPosition(),caret);             else                textArea.setCaretPosition(caret);          }       }            public static class prev_word implements ActionListener       {          private boolean select;                  public prev_word(boolean select)          {             this.select = select;          }                  public void actionPerformed(ActionEvent evt)          {             JEditTextArea textArea = getTextArea(evt);             int caret = textArea.getCaretPosition();             int line = textArea.getCaretLine();             int lineStart = textArea.getLineStartOffset(line);             caret -= lineStart;                       String lineText = textArea.getLineText(textArea                .getCaretLine());                       if(caret == 0)             {                if(lineStart == 0)                {                   textArea.getToolkit().beep();                   return;                }                caret--;             }             else             {                String noWordSep = (String)textArea.getDocument().getProperty("noWordSep");                caret = TextUtilities.findWordStart(lineText,caret,noWordSep);             }                       if(select)                textArea.select(textArea.getMarkPosition(),                   lineStart + caret);             else                textArea.setCaretPosition(lineStart + caret);          }       }            public static class repeat implements ActionListener,        InputHandler.NonRecordable       {           public void actionPerformed(ActionEvent evt)          {             JEditTextArea textArea = getTextArea(evt);             textArea.getInputHandler().setRepeatEnabled(true);             String actionCommand = evt.getActionCommand();             if(actionCommand != null)             {                textArea.getInputHandler().setRepeatCount(                   Integer.parseInt(actionCommand));             }          }       }            public static class toggle_rect implements ActionListener       {           public void actionPerformed(ActionEvent evt)          {             JEditTextArea textArea = getTextArea(evt);             textArea.setSelectionRectangular(                !textArea.isSelectionRectangular());          }       }            public static class insert_char implements ActionListener,        InputHandler.NonRepeatable       {           public void actionPerformed(ActionEvent evt)          {              JEditTextArea textArea = getTextArea(evt);             String str = evt.getActionCommand();             int repeatCount = textArea.getInputHandler().getRepeatCount();                       if(textArea.isEditable())             {                StringBuffer buf = new StringBuffer();                for(int i = 0; i < repeatCount; i++)                   buf.append(str);                textArea.overwriteSetSelectedText(buf.toString());             }             else             {                textArea.getToolkit().beep();             }          }       }            public static class clip_copy implements ActionListener {           public void actionPerformed(ActionEvent evt)          {             JEditTextArea textArea = getTextArea(evt);             textArea.copy();          }       }            public static class clip_paste implements ActionListener {           public void actionPerformed(ActionEvent evt)          {             JEditTextArea textArea = getTextArea(evt);             textArea.paste();          }       }            public static class clip_cut implements ActionListener {           public void actionPerformed(ActionEvent evt)          {             JEditTextArea textArea = getTextArea(evt);             textArea.cut();          }       }    } mars/venus/editors/jeditsyntax/TextAreaDefaults.java mars/venus/editors/jeditsyntax/TextAreaDefaults.java/*  * TextAreaDefaults.java - Encapsulates default values for various settings  * Copyright (C) 1999 Slava Pestov  *  * You may use and modify this package for any purpose. Redistribution is  * permitted, in both source and binary form, provided that this notice  * remains intact in all source distributions of this package.  */    package mars.venus.editors.jeditsyntax;    import mars.Settings;    import javax.swing.JPopupMenu;    import java.awt.Color; /**  * Encapsulates default settings for a text area. This can be passed  * to the constructor once the necessary fields have been filled out.  * The advantage of doing this over calling lots of set() methods after  * creating the text area is that this method is faster.  */     public class TextAreaDefaults    {       private static TextAreaDefaults DEFAULTS;           public InputHandler inputHandler;       public SyntaxDocument document;       public boolean editable;           public boolean caretVisible;       public boolean caretBlinks;       public boolean blockCaret;       public int caretBlinkRate;       public int electricScroll;       public int tabSize;           public int cols;       public int rows;       public SyntaxStyle[] styles;       public Color caretColor;       public Color selectionColor;       public Color lineHighlightColor;       public boolean lineHighlight;       public Color bracketHighlightColor;       public boolean bracketHighlight;       public Color eolMarkerColor;       public boolean eolMarkers;       public boolean paintInvalid;           public JPopupMenu popup;        /**     * Returns a new TextAreaDefaults object with the default values filled     * in.     */        public static TextAreaDefaults getDefaults()       {          DEFAULTS = new TextAreaDefaults();                 DEFAULTS.inputHandler = new DefaultInputHandler();          DEFAULTS.inputHandler.addDefaultKeyBindings();          DEFAULTS.editable = true;                 DEFAULTS.blockCaret = false;          DEFAULTS.caretVisible = true;          DEFAULTS.caretBlinks = (mars.Globals.getSettings().getCaretBlinkRate() != 0);          DEFAULTS.caretBlinkRate = mars.Globals.getSettings().getCaretBlinkRate();          DEFAULTS.tabSize = mars.Globals.getSettings().getEditorTabSize();          DEFAULTS.electricScroll = 0;// was 3.  Will begin scrolling when cursor is this many lines from the edge.                 DEFAULTS.cols = 80;          DEFAULTS.rows = 25;          DEFAULTS.styles = SyntaxUtilities.getCurrentSyntaxStyles(); // was getDefaultSyntaxStyles()          DEFAULTS.caretColor = Color.black; // Color.red;          DEFAULTS.selectionColor = new Color(0xccccff);          DEFAULTS.lineHighlightColor = new Color(0xeeeeee);//0xe0e0e0);          DEFAULTS.lineHighlight = mars.Globals.getSettings().getBooleanSetting(Settings.EDITOR_CURRENT_LINE_HIGHLIGHTING);          DEFAULTS.bracketHighlightColor = Color.black;          DEFAULTS.bracketHighlight = false; // assembly language doesn't need this.          DEFAULTS.eolMarkerColor = new Color(0x009999);          DEFAULTS.eolMarkers = false; // true;          DEFAULTS.paintInvalid = false; //true;          DEFAULTS.document = new SyntaxDocument();          return DEFAULTS;       }    } JEditTextArea$2 package mars.venus.editors.jeditsyntax; synchronized class JEditTextArea$2 implements Runnable { void JEditTextArea$2(JEditTextArea, javax.swing.MenuElement[]); public void run(); } InputHandler$document_end package mars.venus.editors.jeditsyntax; public synchronized class InputHandler$document_end implements java.awt.event.ActionListener { private boolean select; public void InputHandler$document_end(boolean); public void actionPerformed(java.awt.event.ActionEvent); } TextAreaDefaults package mars.venus.editors.jeditsyntax; public synchronized class TextAreaDefaults { private static TextAreaDefaults DEFAULTS; public InputHandler inputHandler; public SyntaxDocument document; public boolean editable; public boolean caretVisible; public boolean caretBlinks; public boolean blockCaret; public int caretBlinkRate; public int electricScroll; public int tabSize; public int cols; public int rows; public SyntaxStyle[] styles; public java.awt.Color caretColor; public java.awt.Color selectionColor; public java.awt.Color lineHighlightColor; public boolean lineHighlight; public java.awt.Color bracketHighlightColor; public boolean bracketHighlight; public java.awt.Color eolMarkerColor; public boolean eolMarkers; public boolean paintInvalid; public javax.swing.JPopupMenu popup; public void TextAreaDefaults(); public static TextAreaDefaults getDefaults(); } JEditTextArea$PopupHelpActionListener package mars.venus.editors.jeditsyntax; synchronized class JEditTextArea$PopupHelpActionListener implements java.awt.event.ActionListener { private String tokenText; private String text; public void JEditTextArea$PopupHelpActionListener(JEditTextArea, String, String); public void actionPerformed(java.awt.event.ActionEvent); } mars/venus/editors/jeditsyntax/SyntaxStyle.java mars/venus/editors/jeditsyntax/SyntaxStyle.java/*  * SyntaxStyle.java - A simple text style class  * Copyright (C) 1999 Slava Pestov  *  * You may use and modify this package for any purpose. Redistribution is  * permitted, in both source and binary form, provided that this notice  * remains intact in all source distributions of this package.  */    package mars.venus.editors.jeditsyntax;    import java.awt.*;    import java.util.StringTokenizer; /**  * A simple text style class. It can specify the color, italic flag,  * and bold flag of a run of text.  * @author Slava Pestov  * @version $Id: SyntaxStyle.java,v 1.6 1999/12/13 03:40:30 sp Exp $  */     public class SyntaxStyle    {    /**     * Creates a new SyntaxStyle.     * @param color The text color     * @param italic True if the text should be italics     * @param bold True if the text should be bold     */        public SyntaxStyle(Color color, boolean italic, boolean bold)       {          this.color = color;          this.italic = italic;          this.bold = bold;       }        /**     * Returns the color specified in this style.     */        public Color getColor()       {          return color;       }         /**     * Returns the color coded as Stringified 32-bit hex with     * Red in bits 16-23, Green in bits 8-15, Blue in bits 0-7     * e.g. "0x00FF3366" where Red is FF, Green is 33, Blue is 66.     * This is used by Settings initialization to avoid direct      * use of Color class.  Long story. DPS 13-May-2010     * @return String containing hex-coded color value.     */             public String getColorAsHexString()        {          return mars.util.Binary.intToHexString( color.getRed()<<16 | color.getGreen()<<8 | color.getBlue() );       }        /**     * Returns true if no font styles are enabled.     */        public boolean isPlain()       {          return !(bold || italic);       }        /**     * Returns true if italics is enabled for this style.     */        public boolean isItalic()       {          return italic;       }        /**     * Returns true if boldface is enabled for this style.     */        public boolean isBold()       {          return bold;       }        /**     * Returns the specified font, but with the style's bold and     * italic flags applied.     */        public Font getStyledFont(Font font)       {          if(font == null)             throw new NullPointerException("font param must not"                + " be null");          if(font.equals(lastFont))             return lastStyledFont;          lastFont = font;          lastStyledFont = new Font(font.getFamily(),             (bold ? Font.BOLD : 0)             | (italic ? Font.ITALIC : 0),             font.getSize());          return lastStyledFont;       }        /**     * Returns the font metrics for the styled font.     */        public FontMetrics getFontMetrics(Font font)       {          if(font == null)             throw new NullPointerException("font param must not"                + " be null");          if(font.equals(lastFont) && fontMetrics != null)             return fontMetrics;          lastFont = font;          lastStyledFont = new Font(font.getFamily(),             (bold ? Font.BOLD : 0)             | (italic ? Font.ITALIC : 0),             font.getSize());          fontMetrics = Toolkit.getDefaultToolkit().getFontMetrics(              lastStyledFont);          return fontMetrics;       }            /**     * Sets the foreground color and font of the specified graphics     * context to that specified in this style.     * @param gfx The graphics context     * @param font The font to add the styles to     */        public void setGraphicsFlags(Graphics gfx, Font font)       {          Font _font = getStyledFont(font);          gfx.setFont(_font);          gfx.setColor(color);       }        /**     * Returns a string representation of this object.     */        public String toString()       {          return getClass().getName() + "[color=" + color +             (italic ? ",italic" : "") +             (bold ? ",bold" : "") + "]";       }        // private members       private Color color;       private boolean italic;       private boolean bold;       private Font lastFont;       private Font lastStyledFont;       private FontMetrics fontMetrics;    } TextAreaPainter package mars.venus.editors.jeditsyntax; public synchronized class TextAreaPainter extends javax.swing.JComponent implements javax.swing.text.TabExpander { int currentLineIndex; tokenmarker.Token currentLineTokens; javax.swing.text.Segment currentLine; protected JEditTextArea textArea; protected SyntaxStyle[] styles; protected java.awt.Color caretColor; protected java.awt.Color selectionColor; protected java.awt.Color lineHighlightColor; protected java.awt.Color bracketHighlightColor; protected java.awt.Color eolMarkerColor; protected boolean blockCaret; protected boolean lineHighlight; protected boolean bracketHighlight; protected boolean paintInvalid; protected boolean eolMarkers; protected int cols; protected int rows; protected int tabSize; protected int tabSizeChars; protected java.awt.FontMetrics fm; protected TextAreaPainter$Highlight highlights; public void TextAreaPainter(JEditTextArea, TextAreaDefaults); public final boolean isManagingFocus(); public int getTabSize(); public void setTabSize(int); public final SyntaxStyle[] getStyles(); public final void setStyles(SyntaxStyle[]); public final java.awt.Color getCaretColor(); public final void setCaretColor(java.awt.Color); public final java.awt.Color getSelectionColor(); public final void setSelectionColor(java.awt.Color); public final java.awt.Color getLineHighlightColor(); public final void setLineHighlightColor(java.awt.Color); public final boolean isLineHighlightEnabled(); public final void setLineHighlightEnabled(boolean); public final java.awt.Color getBracketHighlightColor(); public final void setBracketHighlightColor(java.awt.Color); public final boolean isBracketHighlightEnabled(); public final void setBracketHighlightEnabled(boolean); public final boolean isBlockCaretEnabled(); public final void setBlockCaretEnabled(boolean); public final java.awt.Color getEOLMarkerColor(); public final void setEOLMarkerColor(java.awt.Color); public final boolean getEOLMarkersPainted(); public final void setEOLMarkersPainted(boolean); public boolean getInvalidLinesPainted(); public void setInvalidLinesPainted(boolean); public void addCustomHighlight(TextAreaPainter$Highlight); public String getToolTipText(java.awt.event.MouseEvent); public java.awt.FontMetrics getFontMetrics(); public void setFont(java.awt.Font); public void paint(java.awt.Graphics); public final void invalidateLine(int); public final void invalidateLineRange(int, int); public final void invalidateSelectedLines(); public float nextTabStop(float, int); public java.awt.Dimension getPreferredSize(); public java.awt.Dimension getMinimumSize(); protected void paintLine(java.awt.Graphics, tokenmarker.TokenMarker, int, int); protected void paintPlainLine(java.awt.Graphics, int, java.awt.Font, java.awt.Color, int, int); protected void paintSyntaxLine(java.awt.Graphics, tokenmarker.TokenMarker, int, java.awt.Font, java.awt.Color, int, int); protected void paintHighlight(java.awt.Graphics, int, int); protected void paintLineHighlight(java.awt.Graphics, int, int); protected void paintBracketHighlight(java.awt.Graphics, int, int); protected void paintCaret(java.awt.Graphics, int, int); } InputHandler$next_word package mars.venus.editors.jeditsyntax; public synchronized class InputHandler$next_word implements java.awt.event.ActionListener { private boolean select; public void InputHandler$next_word(boolean); public void actionPerformed(java.awt.event.ActionEvent); } JEditBasedTextArea$1 package mars.venus.editors.jeditsyntax; synchronized class JEditBasedTextArea$1 implements javax.swing.event.UndoableEditListener { void JEditBasedTextArea$1(JEditBasedTextArea); public void undoableEditHappened(javax.swing.event.UndoableEditEvent); } JEditBasedTextArea package mars.venus.editors.jeditsyntax; public synchronized class JEditBasedTextArea extends JEditTextArea implements mars.venus.editors.MARSTextEditingArea, javax.swing.event.CaretListener { private mars.venus.EditPane editPane; private javax.swing.undo.UndoManager undoManager; private javax.swing.event.UndoableEditListener undoableEditListener; private boolean isCompoundEdit; private javax.swing.undo.CompoundEdit compoundEdit; private JEditBasedTextArea sourceCode; public void JEditBasedTextArea(mars.venus.EditPane, javax.swing.JComponent); public void setFont(java.awt.Font); public java.awt.Font getFont(); public void setLineHighlightEnabled(boolean); public void setCaretBlinkRate(int); public void setTabSize(int); public void updateSyntaxStyles(); public java.awt.Component getOuterComponent(); public void discardAllUndoableEdits(); public void caretUpdate(javax.swing.event.CaretEvent); public void replaceSelection(String); public void setSelectionVisible(boolean); public void setSourceCode(String, boolean); public javax.swing.undo.UndoManager getUndoManager(); public void undo(); public void redo(); public int doFindText(String, boolean); public int nextIndex(String, String, int, boolean); public int doReplace(String, String, boolean); public int doReplaceAll(String, String, boolean); } JEditTextArea$MouseHandler package mars.venus.editors.jeditsyntax; synchronized class JEditTextArea$MouseHandler extends java.awt.event.MouseAdapter { void JEditTextArea$MouseHandler(JEditTextArea); public void mousePressed(java.awt.event.MouseEvent); private void doSingleClick(java.awt.event.MouseEvent, int, int, int); private void doDoubleClick(java.awt.event.MouseEvent, int, int, int) throws javax.swing.text.BadLocationException; private void doTripleClick(java.awt.event.MouseEvent, int, int, int); } InputHandler$next_page package mars.venus.editors.jeditsyntax; public synchronized class InputHandler$next_page implements java.awt.event.ActionListener { private boolean select; public void InputHandler$next_page(boolean); public void actionPerformed(java.awt.event.ActionEvent); } JEditTextArea$CaretBlinker package mars.venus.editors.jeditsyntax; synchronized class JEditTextArea$CaretBlinker implements java.awt.event.ActionListener { void JEditTextArea$CaretBlinker(); public void actionPerformed(java.awt.event.ActionEvent); } JEditTextArea$ComponentHandler package mars.venus.editors.jeditsyntax; synchronized class JEditTextArea$ComponentHandler extends java.awt.event.ComponentAdapter { void JEditTextArea$ComponentHandler(JEditTextArea); public void componentResized(java.awt.event.ComponentEvent); } JEditTextArea$MutableCaretEvent package mars.venus.editors.jeditsyntax; synchronized class JEditTextArea$MutableCaretEvent extends javax.swing.event.CaretEvent { void JEditTextArea$MutableCaretEvent(JEditTextArea); public int getDot(); public int getMark(); } InputHandler$document_home package mars.venus.editors.jeditsyntax; public synchronized class InputHandler$document_home implements java.awt.event.ActionListener { private boolean select; public void InputHandler$document_home(boolean); public void actionPerformed(java.awt.event.ActionEvent); } mars/venus/editors/jeditsyntax/TextUtilities.java mars/venus/editors/jeditsyntax/TextUtilities.java/*  * TextUtilities.java - Utility functions used by the text area classes  * Copyright (C) 1999 Slava Pestov  *  * You may use and modify this package for any purpose. Redistribution is  * permitted, in both source and binary form, provided that this notice  * remains intact in all source distributions of this package.  */ package mars.venus.editors.jeditsyntax; import javax.swing.text.*; /**  * Class with several utility functions used by the text area component.  * @author Slava Pestov  * @version $Id: TextUtilities.java,v 1.4 1999/12/13 03:40:30 sp Exp $  */ public class TextUtilities {     /**      * Returns the offset of the bracket matching the one at the      * specified offset of the document, or -1 if the bracket is      * unmatched (or if the character is not a bracket).      * @param doc The document      * @param offset The offset      * @exception BadLocationException If an out-of-bounds access      * was attempted on the document text      */     public static int findMatchingBracket(Document doc, int offset)         throws BadLocationException     {         if(doc.getLength() == 0)             return -1;         char c = doc.getText(offset,1).charAt(0);         char cprime; // c` - corresponding character         boolean direction; // true = back, false = forward         switch(c)         {         case '(': cprime = ')'; direction = false; break;         case ')': cprime = '('; direction = true; break;         case '[': cprime = ']'; direction = false; break;         case ']': cprime = '['; direction = true; break;         case '{': cprime = '}'; direction = false; break;         case '}': cprime = '{'; direction = true; break;         default: return -1;         }         int count;         // How to merge these two cases is left as an exercise         // for the reader.         // Go back or forward         if(direction)         {             // Count is 1 initially because we have already             // `found' one closing bracket             count = 1;             // Get text[0,offset-1];             String text = doc.getText(0,offset);             // Scan backwards             for(int i = offset - 1; i >= 0; i–)
            {
                // If text[i] == c, we have found another
                // closing bracket, therefore we will need
                // two opening brackets to complete the
                // match.
                char x = text.charAt(i);
                if(x == c)
                    count++;

                // If text[i] == cprime, we have found a
                // opening bracket, so we return i if
                // –count == 0
                else if(x == cprime)
                {
                    if(–count == 0)
                        return i;
                }
            }
        }
        else
        {
            // Count is 1 initially because we have already
            // `found’ one opening bracket
            count = 1;

            // So we don’t have to + 1 in every loop
            offset++;

            // Number of characters to check
            int len = doc.getLength() – offset;

            // Get text[offset+1,len];
            String text = doc.getText(offset,len);

            // Scan forwards
            for(int i = 0; i < len; i++)             {                 // If text[i] == c, we have found another                 // opening bracket, therefore we will need                 // two closing brackets to complete the                 // match.                 char x = text.charAt(i);                 if(x == c)                     count++;                 // If text[i] == cprime, we have found an                 // closing bracket, so we return i if                 // --count == 0                 else if(x == cprime)                 {                     if(--count == 0)                         return i + offset;                 }             }         }         // Nothing found         return -1;     }     /**      * Locates the start of the word at the specified position.      * @param line The text      * @param pos The position      */     public static int findWordStart(String line, int pos, String noWordSep)     {         char ch = line.charAt(pos - 1);         if(noWordSep == null)             noWordSep = "";         boolean selectNoLetter = (!Character.isLetterOrDigit(ch)             && noWordSep.indexOf(ch) == -1);         int wordStart = 0;         for(int i = pos - 1; i >= 0; i–)
        {
            ch = line.charAt(i);
            if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) &&
                noWordSep.indexOf(ch) == -1))
            {
                wordStart = i + 1;
                break;
            }
        }

        return wordStart;
    }

    /**
     * Locates the end of the word at the specified position.
     * @param line The text
     * @param pos The position
     */
    public static int findWordEnd(String line, int pos, String noWordSep)
    {
        char ch = line.charAt(pos);

        if(noWordSep == null)
            noWordSep = “”;
        boolean selectNoLetter = (!Character.isLetterOrDigit(ch)
            && noWordSep.indexOf(ch) == -1);

        int wordEnd = line.length();
        for(int i = pos; i < line.length(); i++)         {             ch = line.charAt(i);             if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) &&                 noWordSep.indexOf(ch) == -1))             {                 wordEnd = i;                 break;             }         }         return wordEnd;     } } mars/venus/editors/jeditsyntax/SyntaxUtilities.java mars/venus/editors/jeditsyntax/SyntaxUtilities.java/*  * SyntaxUtilities.java - Utility functions used by syntax colorizing  * Copyright (C) 1999 Slava Pestov  *  * You may use and modify this package for any purpose. Redistribution is  * permitted, in both source and binary form, provided that this notice  * remains intact in all source distributions of this package.  */    package mars.venus.editors.jeditsyntax;    import mars.venus.editors.jeditsyntax.tokenmarker.*;    import mars.Globals;    import javax.swing.text.*;    import javax.swing.*;    import java.awt.*;    import java.awt.event.*; /**  * Class with several utility functions used by jEdit's syntax colorizing  * subsystem.  *  * @author Slava Pestov  * @version $Id: SyntaxUtilities.java,v 1.9 1999/12/13 03:40:30 sp Exp $  */     public class SyntaxUtilities    {    /**     * Checks if a subregion of a Segment is equal to a
    * string.
    * @param ignoreCase True if case should be ignored, false otherwise
    * @param text The segment
    * @param offset The offset into the segment
    * @param match The string to match
    */
       public static boolean regionMatches(boolean ignoreCase, Segment text,
                    int offset, String match)
      {
         int length = offset + match.length();
         char[] textArray = text.array;
         if(length > text.offset + text.count)
            return false;
         for(int i = offset, j = 0; i < length; i++, j++)          {             char c1 = textArray[i];             char c2 = match.charAt(j);             if(ignoreCase)             {                c1 = Character.toUpperCase(c1);                c2 = Character.toUpperCase(c2);             }             if(c1 != c2)                return false;          }          return true;       }        /**     * Checks if a subregion of a Segment is equal to a
    * character array.
    * @param ignoreCase True if case should be ignored, false otherwise
    * @param text The segment
    * @param offset The offset into the segment
    * @param match The character array to match
    */
       public static boolean regionMatches(boolean ignoreCase, Segment text,
                    int offset, char[] match)
      {
         int length = offset + match.length;
         char[] textArray = text.array;
         if(length > text.offset + text.count)
            return false;
         for(int i = offset, j = 0; i < length; i++, j++)          {             char c1 = textArray[i];             char c2 = match[j];             if(ignoreCase)             {                c1 = Character.toUpperCase(c1);                c2 = Character.toUpperCase(c2);             }             if(c1 != c2)                return false;          }          return true;       }        /**     * Returns the default style table. This can be passed to the     * setStyles() method of SyntaxDocument
    * to use the default syntax styles.
    */
       public static SyntaxStyle[] getDefaultSyntaxStyles()
      {
         SyntaxStyle[] styles = new SyntaxStyle[Token.ID_COUNT];
      
      // SyntaxStyle constructor params: color, italic?, bold?
      // All need to be assigned even if not used by language (no gaps in array)
         styles[Token.NULL]     = new SyntaxStyle(Color.black,false,false);
         styles[Token.COMMENT1] = new SyntaxStyle(new Color(0x00CC33),true,false);//(Color.black,true,false);
         styles[Token.COMMENT2] = new SyntaxStyle(new Color(0x990033),true,false);
         styles[Token.KEYWORD1] = new SyntaxStyle(Color.blue,false,false);//(Color.black,false,true);
         styles[Token.KEYWORD2] = new SyntaxStyle(Color.magenta,false,false);
         styles[Token.KEYWORD3] = new SyntaxStyle(Color.red,false,false);//(new Color(0x009600),false,false);
         styles[Token.LITERAL1] = new SyntaxStyle(new Color(0x00CC33),false,false);//(new Color(0x650099),false,false);
         styles[Token.LITERAL2] = new SyntaxStyle(new Color(0x00CC33),false,false);//(new Color(0x650099),false,true);
         styles[Token.LABEL]    = new SyntaxStyle(Color.black,true,false);//(new Color(0x990033),false,true);
         styles[Token.OPERATOR] = new SyntaxStyle(Color.black,false,true);
         styles[Token.INVALID]  = new SyntaxStyle(Color.red,false,false);
         styles[Token.MACRO_ARG]= new SyntaxStyle(new Color(150, 150,0), false, false);      
         return styles;
      }
   
   /**
    * Returns the CURRENT style table. This can be passed to the
    * setStyles() method of SyntaxDocument
    * to use the current syntax styles.  If changes have been made
    * via MARS Settings menu, the current settings will not be the 
    * same as the default settings.
    */
       public static SyntaxStyle[] getCurrentSyntaxStyles()
      {
         SyntaxStyle[] styles = new SyntaxStyle[Token.ID_COUNT];
      
         styles[Token.NULL]     = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.NULL);
         styles[Token.COMMENT1] = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.COMMENT1);
         styles[Token.COMMENT2] = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.COMMENT2);
         styles[Token.KEYWORD1] = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.KEYWORD1);
         styles[Token.KEYWORD2] = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.KEYWORD2);
         styles[Token.KEYWORD3] = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.KEYWORD3);
         styles[Token.LITERAL1] = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.LITERAL1);
         styles[Token.LITERAL2] = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.LITERAL2);
         styles[Token.LABEL]    = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.LABEL);
         styles[Token.OPERATOR] = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.OPERATOR);
         styles[Token.INVALID]  = Globals.getSettings().getEditorSyntaxStyleByPosition(Token.INVALID);
         styles[Token.MACRO_ARG]= Globals.getSettings().getEditorSyntaxStyleByPosition(Token.MACRO_ARG);      
         return styles;
      }
   
   /**
    * Paints the specified line onto the graphics context. Note that this
    * method munges the offset and count values of the segment.
    * @param line The line segment
    * @param tokens The token list for the line
    * @param styles The syntax style list
    * @param expander The tab expander used to determine tab stops. May
    * be null
    * @param gfx The graphics context
    * @param x The x co-ordinate
    * @param y The y co-ordinate
    * @return The x co-ordinate, plus the width of the painted string
    */ public static boolean popupShowing = false;
      public static Popup popup;
       public static int paintSyntaxLine(Segment line, Token tokens,
       SyntaxStyle[] styles, TabExpander expander, Graphics gfx,
       int x, int y)
      {
         Font defaultFont = gfx.getFont();
         Color defaultColor = gfx.getColor();
      
         int offset = 0;
         for(;;)
         {
            byte id = tokens.id;
            if(id == Token.END)
               break;
         
            int length = tokens.length;
            if(id == Token.NULL)
            {
               if(!defaultColor.equals(gfx.getColor()))
                  gfx.setColor(defaultColor);
               if(!defaultFont.equals(gfx.getFont()))
                  gfx.setFont(defaultFont);
            }
            else
               styles[id].setGraphicsFlags(gfx,defaultFont);
            line.count = length; 
         
            if (id == Token.KEYWORD1){ 
               //System.out.println(“Instruction: “+line);
               if (!popupShowing) {// System.out.println(“creating popup”);
//                   JComponent paintArea = (JComponent) expander;
//                   JToolTip tip = paintArea.createToolTip();
//                   tip.setTipText(“Instruction: “+line);
//                   Point screenLocation = paintArea.getLocationOnScreen();
//                   PopupFactory popupFactory = PopupFactory.getSharedInstance();
//                   popup = popupFactory.getPopup(paintArea, tip, screenLocation.x + x, screenLocation.y + y); 
//                   popupShowing = true;
//                   popup.show();
//                   int delay = 200; //milliseconds 
//                   ActionListener taskPerformer = 
//                       new ActionListener() { 
//                          public void actionPerformed(ActionEvent evt) { 
//                            //popupShowing = false;
//                            if (popup!= null) {
//                               popup.hide();
//                            }
//                         } 
//                      }; 
//                   Timer popupTimer = new Timer(delay, taskPerformer);
//                   popupTimer.setRepeats(false);
//                   popupTimer.start();
               
               }    
            
              // ToolTipManager.sharedInstance().mouseMoved(
            //     new MouseEvent((Component)expander, MouseEvent.MOUSE_MOVED, new java.util.Date().getTime(), 0, x, y, 0, false));
              //    new InstructionMouseEvent((Component)expander, x, y, line));
            }
                    
            x = Utilities.drawTabbedText(line,x,y,gfx,expander,0);
            line.offset += length;
            offset += length;
         
            tokens = tokens.next;
         }
      
         return x;
      }
   
   // private members
       private SyntaxUtilities() {}
   }
    
    class InstructionMouseEvent extends MouseEvent {
      private Segment line;
       public InstructionMouseEvent(Component component, int x, int y, Segment line) {
         super(component, MouseEvent.MOUSE_MOVED, new java.util.Date().getTime(), 0, x, y, 0, false);
         System.out.println(“Create InstructionMouseEvent “+x+” “+y+” “+line);
         this.line = line;
      }
       public Segment getLine() {
         return this.line;
      }
   }

JEditTextArea$CaretUndo

package mars.venus.editors.jeditsyntax;
synchronized class JEditTextArea$CaretUndo extends javax.swing.undo.AbstractUndoableEdit {
private int start;
private int end;
void JEditTextArea$CaretUndo(JEditTextArea, int, int);
public boolean isSignificant();
public String getPresentationName();
public void undo() throws javax.swing.undo.CannotUndoException;
public void redo() throws javax.swing.undo.CannotRedoException;
public boolean addEdit(javax.swing.undo.UndoableEdit);
}

JEditTextArea$1

package mars.venus.editors.jeditsyntax;
synchronized class JEditTextArea$1 implements java.awt.KeyEventDispatcher {
void JEditTextArea$1(JEditTextArea);
public boolean dispatchKeyEvent(java.awt.event.KeyEvent);
}

TextAreaPainter$Highlight

package mars.venus.editors.jeditsyntax;
public abstract interface TextAreaPainter$Highlight {
public abstract void init(JEditTextArea, TextAreaPainter$Highlight);
public abstract void paintHighlight(java.awt.Graphics, int, int);
public abstract String getToolTipText(java.awt.event.MouseEvent);
}

InputHandler$prev_char

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$prev_char implements java.awt.event.ActionListener {
private boolean select;
public void InputHandler$prev_char(boolean);
public void actionPerformed(java.awt.event.ActionEvent);
}

JEditTextArea$AdjustHandler$1

package mars.venus.editors.jeditsyntax;
synchronized class JEditTextArea$AdjustHandler$1 implements Runnable {
void JEditTextArea$AdjustHandler$1(JEditTextArea$AdjustHandler, java.awt.event.AdjustmentEvent);
public void run();
}

TextUtilities

package mars.venus.editors.jeditsyntax;
public synchronized class TextUtilities {
public void TextUtilities();
public static int findMatchingBracket(javax.swing.text.Document, int) throws javax.swing.text.BadLocationException;
public static int findWordStart(String, int, String);
public static int findWordEnd(String, int, String);
}

InputHandler$clip_paste

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$clip_paste implements java.awt.event.ActionListener {
public void InputHandler$clip_paste();
public void actionPerformed(java.awt.event.ActionEvent);
}

DefaultInputHandler

package mars.venus.editors.jeditsyntax;
public synchronized class DefaultInputHandler extends InputHandler {
private java.util.Hashtable bindings;
private java.util.Hashtable currentBindings;
public void DefaultInputHandler();
public void addDefaultKeyBindings();
public void addKeyBinding(String, java.awt.event.ActionListener);
public void removeKeyBinding(String);
public void removeAllKeyBindings();
public InputHandler copy();
public void keyPressed(java.awt.event.KeyEvent);
public void keyTyped(java.awt.event.KeyEvent);
public static javax.swing.KeyStroke parseKeyStroke(String);
private void DefaultInputHandler(DefaultInputHandler);
}

JEditTextArea$DragHandler

package mars.venus.editors.jeditsyntax;
synchronized class JEditTextArea$DragHandler implements java.awt.event.MouseMotionListener {
void JEditTextArea$DragHandler(JEditTextArea);
public void mouseDragged(java.awt.event.MouseEvent);
public void mouseMoved(java.awt.event.MouseEvent);
}

InputHandler$NonRecordable

package mars.venus.editors.jeditsyntax;
public abstract interface InputHandler$NonRecordable {
}

InputHandler$next_line

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$next_line implements java.awt.event.ActionListener {
private boolean select;
public void InputHandler$next_line(boolean);
public void actionPerformed(java.awt.event.ActionEvent);
}

InputHandler$toggle_rect

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$toggle_rect implements java.awt.event.ActionListener {
public void InputHandler$toggle_rect();
public void actionPerformed(java.awt.event.ActionEvent);
}

JEditTextArea$MouseWheelHandler

package mars.venus.editors.jeditsyntax;
synchronized class JEditTextArea$MouseWheelHandler implements java.awt.event.MouseWheelListener {
void JEditTextArea$MouseWheelHandler(JEditTextArea);
public void mouseWheelMoved(java.awt.event.MouseWheelEvent);
}

InstructionMouseEvent

package mars.venus.editors.jeditsyntax;
synchronized class InstructionMouseEvent extends java.awt.event.MouseEvent {
private javax.swing.text.Segment line;
public void InstructionMouseEvent(java.awt.Component, int, int, javax.swing.text.Segment);
public javax.swing.text.Segment getLine();
}

JEditTextArea$DocumentHandler

package mars.venus.editors.jeditsyntax;
synchronized class JEditTextArea$DocumentHandler implements javax.swing.event.DocumentListener {
void JEditTextArea$DocumentHandler(JEditTextArea);
public void insertUpdate(javax.swing.event.DocumentEvent);
public void removeUpdate(javax.swing.event.DocumentEvent);
public void changedUpdate(javax.swing.event.DocumentEvent);
}

InputHandler$delete

package mars.venus.editors.jeditsyntax;
public synchronized class InputHandler$delete implements java.awt.event.ActionListener {
public void InputHandler$delete();
public void actionPerformed(java.awt.event.ActionEvent);
}

GenericTextArea$1

package mars.venus.editors.generic;
synchronized class GenericTextArea$1 implements javax.swing.event.ChangeListener {
void GenericTextArea$1(GenericTextArea);
public void stateChanged(javax.swing.event.ChangeEvent);
}

GenericTextArea

package mars.venus.editors.generic;
public synchronized class GenericTextArea extends javax.swing.JTextArea implements mars.venus.editors.MARSTextEditingArea {
private mars.venus.EditPane editPane;
private javax.swing.undo.UndoManager undoManager;
private javax.swing.event.UndoableEditListener undoableEditListener;
private javax.swing.JTextArea sourceCode;
private javax.swing.JScrollPane editAreaScrollPane;
private boolean isCompoundEdit;
private javax.swing.undo.CompoundEdit compoundEdit;
public void GenericTextArea(mars.venus.EditPane, javax.swing.JComponent);
public void setLineHighlightEnabled(boolean);
public void updateSyntaxStyles();
public void setCaretBlinkRate(int);
public java.awt.Component getOuterComponent();
public void setSourceCode(String, boolean);
public void discardAllUndoableEdits();
public void setText(String);
public void setCaretVisible(boolean);
public void setSelectionVisible(boolean);
public javax.swing.undo.UndoManager getUndoManager();
public void undo();
public void redo();
public int doFindText(String, boolean);
public int nextIndex(String, String, int, boolean);
public int doReplace(String, String, boolean);
public int doReplaceAll(String, String, boolean);
}

GenericTextArea$2

package mars.venus.editors.generic;
synchronized class GenericTextArea$2 implements javax.swing.event.UndoableEditListener {
void GenericTextArea$2(GenericTextArea);
public void undoableEditHappened(javax.swing.event.UndoableEditEvent);
}

mars/venus/editors/generic/GenericTextArea.java
mars/venus/editors/generic/GenericTextArea.java   package mars.venus.editors.generic;

   import mars.Globals;
   import mars.venus.EditPane;
   import mars.venus.editors.MARSTextEditingArea;
   import java.awt.*;
   import javax.swing.*;
   import javax.swing.event.*;
   import javax.swing.undo.*;
   import java.util.*;

/*
Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

    public class GenericTextArea extends JTextArea implements MARSTextEditingArea {
    
   
      private EditPane editPane;
      private UndoManager undoManager;
      private UndoableEditListener undoableEditListener;
      private JTextArea sourceCode;
      private JScrollPane editAreaScrollPane;
   
      private boolean isCompoundEdit = false;
      private CompoundEdit compoundEdit;
     
       public GenericTextArea(EditPane editPain, JComponent lineNumbers) {
         this.editPane = editPain;
         this.sourceCode = this;
         this.setFont(Globals.getSettings().getEditorFont());
         this.setTabSize(Globals.getSettings().getEditorTabSize());
         this.setMargin(new Insets(0,3,3,3));
         this.setCaretBlinkRate(Globals.getSettings().getCaretBlinkRate());
      
         JPanel source = new JPanel(new BorderLayout());
         source.add(lineNumbers, BorderLayout.WEST);
         source.add(this, BorderLayout.CENTER);
         editAreaScrollPane = new JScrollPane(source, 
                       ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, 
                       ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
         editAreaScrollPane.getVerticalScrollBar().setUnitIncrement(
                       sourceCode.getFontMetrics(this.sourceCode.getFont()).getHeight());
      
         this.undoManager = new UndoManager();
      
         this.getCaret().addChangeListener(
                new ChangeListener() {
                   public void stateChanged(ChangeEvent e) {
                     editPane.displayCaretPosition(getCaretPosition());
                  }
               });
               
         // Needed to support unlimited undo/redo capability
         undoableEditListener = 
             new UndoableEditListener() {
                public void undoableEditHappened(UndoableEditEvent e) {
                  //Remember the edit and update the menus.
                  if (isCompoundEdit) {
                     compoundEdit.addEdit(e.getEdit());
                  } 
                  else {
                     undoManager.addEdit(e.getEdit());
                     editPane.updateUndoState();
                     editPane.updateRedoState();
                  }
               }
            };
         this.getDocument().addUndoableEditListener(undoableEditListener);      
      }
    
     /**
      *  Does nothing, but required by the interface.  This editor does not support
    *   highlighting of the line currently being edited.
    */
       public void setLineHighlightEnabled(boolean highlight) {
      }
    
     /**
      *  Does nothing, but required by the interface.  This editor does not support
    *   syntax styling (colors, bold/italic).
    */
       public void updateSyntaxStyles() {
      }
   
     /**
      *  Set the caret blinking rate in milliseconds.  If rate is 0
    *  it will not blink.  If negative, do nothing.
    *  @param rate blinking rate in milliseconds
    */
       public void setCaretBlinkRate(int rate) {
         if (rate >= 0) {
            getCaret().setBlinkRate(rate);
         }
      }
   
    
       public Component getOuterComponent() {
         return editAreaScrollPane;
      }
      
    /**
      *  For initalizing the source code when opening an ASM file
      *   @param s String containing text
      *   @param editable set true if code is editable else false
      **/   
   
       public void setSourceCode(String s, boolean editable){
         this.setText(s);
         this.setBackground( (editable)? Color.WHITE : Color.GRAY);
         this.setEditable(editable);  
         this.setEnabled(editable);
         this.getCaret().setVisible(editable);
         this.setCaretPosition(0);
         if (editable) this.requestFocusInWindow();
      }
   
      /**
     *  Tell UndoManager to discard all its collected undoable edits.
     */
       public void discardAllUndoableEdits() {
         undoManager.discardAllEdits();
      }
      
    /**
     * Override inherited setText to temporarily remove UndoableEditListener because this
     * operation is not undoable.
     *
     * @param s String with new contents for the editing area. Replaces current content.
     */
       public void setText(String s) {
         this.getDocument().removeUndoableEditListener(undoableEditListener);
         super.setText(s);
         this.getDocument().addUndoableEditListener(undoableEditListener);      
      }
   
     /**
      * Control caret visibility
      *
      * @param vis true to display caret, false to hide it
      */
       public void setCaretVisible(boolean vis) {
         this.getCaret().setVisible(vis);
      }
      
     /**
      * Control selection visibility
      *
      * @param vis true to display selection, false to hide it
      */      
       public void setSelectionVisible(boolean vis) {
         this.getCaret().setSelectionVisible(vis);
      }
   
   
    /**
     *  Returns the undo manager for this editing area
     *  @return the undo manager
     */
       public UndoManager getUndoManager() {
         return undoManager;
      }
   
     /**
      * Undo previous edit
    */
       public void undo() {
         try {
            this.undoManager.undo();
         } 
             catch (CannotUndoException ex) {
               System.out.println(“Unable to undo: ” + ex);
               ex.printStackTrace();
            }
         this.setCaretVisible(true);
      }
    
    /**
     * Redo previous edit
     */
       public void redo() {
         try {
            this.undoManager.redo();
         } 
             catch (CannotRedoException ex) {
               System.out.println(“Unable to redo: ” + ex);
               ex.printStackTrace();
            }
         this.setCaretVisible(true);
      }
   
   
    
    
    
   //////////////////////////////////////////////////////////////////////////
   //  Methods to support Find/Replace feature
   //
   // Basis for this Find/Replace solution is:
   // http://java.ittoolbox.com/groups/technical-functional/java-l/search-and-replace-using-jtextpane-630964
   // as written by Chris Dickenson in 2005
   //
   // sourceCode is implemented as JTextArea rather than JTextPane but the necessary methods are inherited
   // by both from JTextComponent.
   
    /** Finds next occurrence of text in a forward search of a string. Search begins 
     * at the current cursor location, and wraps around when the end of the string
     * is reached.
     * @param find the text to locate in the string 
     * @param caseSensitive true if search is to be case-sensitive, false otherwise
     * @return TEXT_FOUND or TEXT_NOT_FOUND, depending on the result.
     */
       public int doFindText(String find, boolean caseSensitive) {
         int findPosn = sourceCode.getCaretPosition();
         int nextPosn = 0;
         nextPosn = nextIndex( sourceCode.getText(), find, findPosn, caseSensitive );
         if ( nextPosn >= 0 ) {
            sourceCode.requestFocus(); // guarantees visibility of the blue highlight 
            sourceCode.setSelectionStart( nextPosn ); // position cursor at word start
            sourceCode.setSelectionEnd( nextPosn + find.length() );
            sourceCode.setSelectionStart( nextPosn ); // position cursor at word start
            return TEXT_FOUND;
         } 
         else {
            return TEXT_NOT_FOUND;
         }
      }
     
   /** Returns next posn of word in text – forward search.  If end of string is
    *  reached during the search, will wrap around to the beginning one time.
   * @return next indexed position of found text or -1 if not found
   * @param input the string to search
   * @param find the string to find
   * @param start the character position to start the search
   * @param caseSensitive true for case sensitive. false to ignore case
   */
       public int nextIndex(String input, String find, int start, boolean caseSensitive ) {
         int textPosn = -1;
         if ( input != null && find != null && start < input.length() ) {             if ( caseSensitive ) { // indexOf() returns -1 if not found                textPosn = input.indexOf( find, start );                // If not found from non-starting cursor position, wrap around                if (start > 0 && textPosn < 0) {                   textPosn = input.indexOf( find );                }             }              else {                String lowerCaseText = input.toLowerCase();                textPosn = lowerCaseText.indexOf( find.toLowerCase(), start );                 // If not found from non-starting cursor position, wrap around                if (start > 0 && textPosn < 0) {                   textPosn = lowerCaseText.indexOf( find.toLowerCase() );                }             }          }          return textPosn;       }            /** Finds and replaces next occurrence of text in a string in a forward search.    * If cursor is initially at end    *  of matching selection, will immediately replace then find and select the    *  next occurrence if any.  Otherwise it performs a find operation.  The replace    *  can be undone with one undo operation.    *    * @param find the text to locate in the string    * @param replace the text to replace the find text with - if the find text exists    * @param caseSensitive true for case sensitive. false to ignore case    * @return Returns TEXT_FOUND if not initially at end of selected match and matching    * occurrence is found.  Returns TEXT_NOT_FOUND if the text is not matched.    * Returns TEXT_REPLACED_NOT_FOUND_NEXT if replacement is successful but there are     * no additional matches.  Returns TEXT_REPLACED_FOUND_NEXT if reaplacement is    * successful and there is at least one additional match.    */        public int doReplace(String find, String replace, boolean caseSensitive) {          int nextPosn = 0;          int posn;          // Will perform a "find" and return, unless positioned at the end of         // a selected "find" result.            if (find==null || !find.equals(sourceCode.getSelectedText()) ||              sourceCode.getSelectionEnd()!=sourceCode.getCaretPosition()) {             return doFindText(find, caseSensitive);          }         // We are positioned at end of selected "find".  Rreplace and find next.          nextPosn = sourceCode.getSelectionStart();          sourceCode.grabFocus();          sourceCode.setSelectionStart( nextPosn ); // posn cursor at word start          sourceCode.setSelectionEnd( nextPosn + find.length() ); //select found text          isCompoundEdit = true;          compoundEdit = new CompoundEdit();          sourceCode.replaceSelection(replace);          compoundEdit.end();          undoManager.addEdit( compoundEdit );          editPane.updateUndoState();          editPane.updateRedoState();          isCompoundEdit = false;          sourceCode.setCaretPosition(nextPosn + replace.length());          if (doFindText(find, caseSensitive) == TEXT_NOT_FOUND) {             return TEXT_REPLACED_NOT_FOUND_NEXT;          }           else {                          return TEXT_REPLACED_FOUND_NEXT;          }       }           /** Finds and replaces ALL occurrences of text in a string in a forward search.
   *  All replacements are bundled into one CompoundEdit, so one Undo operation will 
   *  undo all of them.
   * @param find the text to locate in the string
   * @param replace the text to replace the find text with – if the find text exists 
   * @param caseSensitive true for case sensitive. false to ignore case
   * @return the number of occurrences that were matched and replaced.
   */
       public int doReplaceAll(String find, String replace, boolean caseSensitive) {
         int nextPosn = 0;
         int findPosn = 0; // *** begin at start of text
         int replaceCount = 0;
         compoundEdit = null; // new one will be created upon first replacement
         isCompoundEdit = true; // undo manager’s action listener needs this
         while (nextPosn >= 0) {
            nextPosn = nextIndex( sourceCode.getText(), find, findPosn, caseSensitive );
            if ( nextPosn >= 0 ) {
               // nextIndex() will wrap around, which causes infinite loop if
                // find string is a substring of replacement string.  This 
                // statement will prevent that.
               if (nextPosn < findPosn) {                    break;                }                sourceCode.grabFocus();                sourceCode.setSelectionStart( nextPosn ); // posn cursor at word start                sourceCode.setSelectionEnd( nextPosn + find.length() ); //select found text                if (compoundEdit == null) {                   compoundEdit = new CompoundEdit();                }                sourceCode.replaceSelection(replace);                findPosn = nextPosn + replace.length(); // set for next search                replaceCount++;             }          }          isCompoundEdit = false;          // Will be true if any replacements were performed          if (compoundEdit != null) {             compoundEdit.end();             undoManager.addEdit( compoundEdit );             editPane.updateUndoState();             editPane.updateRedoState();          }          return replaceCount;       }    //     /////////////////////////////  End Find/Replace methods //////////////////////////                      } mars/venus/editors/MARSTextEditingArea.java mars/venus/editors/MARSTextEditingArea.java   package mars.venus.editors;    import javax.swing.text.*;    import javax.swing.undo.*;    import javax.swing.*;    import java.awt.*; /* Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  *  Specifies capabilities that any test editor used in MARS must have.  *  */       public interface MARSTextEditingArea {            // Used by Find/Replace        public static final int TEXT_NOT_FOUND = 0;       public static final int TEXT_FOUND = 1;       public static final int TEXT_REPLACED_FOUND_NEXT = 2;       public static final int TEXT_REPLACED_NOT_FOUND_NEXT = 3;                public void copy();        public void cut();        public int doFindText(String find, boolean caseSensitive);        public int doReplace(String find, String replace, boolean caseSensitive);         public int doReplaceAll(String find, String replace, boolean caseSensitive);              public int getCaretPosition();        public Document getDocument();        public String getSelectedText();        public int getSelectionEnd();        public int getSelectionStart();          public void select(int selectionStart, int selectionEnd);          public void selectAll();        public String getText();        public UndoManager getUndoManager();        public void paste();        public void replaceSelection(String str);        public void setCaretPosition(int position);        public void setEditable(boolean editable);        public void setSelectionEnd(int pos);        public void setSelectionStart(int pos);        public void setText(String text);        public void setFont(Font f);        public Font getFont();        public boolean requestFocusInWindow();        public FontMetrics getFontMetrics(Font f);        public void setBackground(Color c);        public void setEnabled(boolean enabled);        public void grabFocus();        public void redo();        public void revalidate();        public void setSourceCode(String code, boolean editable);        public void setCaretVisible(boolean vis);        public void setSelectionVisible(boolean vis);        public void undo();        public void discardAllUndoableEdits();          public void setLineHighlightEnabled(boolean highlight);          public void setCaretBlinkRate(int rate);          public void setTabSize(int chars);          public void updateSyntaxStyles();        public Component getOuterComponent();    } MARSTextEditingArea package mars.venus.editors; public abstract interface MARSTextEditingArea { public static final int TEXT_NOT_FOUND = 0; public static final int TEXT_FOUND = 1; public static final int TEXT_REPLACED_FOUND_NEXT = 2; public static final int TEXT_REPLACED_NOT_FOUND_NEXT = 3; public abstract void copy(); public abstract void cut(); public abstract int doFindText(String, boolean); public abstract int doReplace(String, String, boolean); public abstract int doReplaceAll(String, String, boolean); public abstract int getCaretPosition(); public abstract javax.swing.text.Document getDocument(); public abstract String getSelectedText(); public abstract int getSelectionEnd(); public abstract int getSelectionStart(); public abstract void select(int, int); public abstract void selectAll(); public abstract String getText(); public abstract javax.swing.undo.UndoManager getUndoManager(); public abstract void paste(); public abstract void replaceSelection(String); public abstract void setCaretPosition(int); public abstract void setEditable(boolean); public abstract void setSelectionEnd(int); public abstract void setSelectionStart(int); public abstract void setText(String); public abstract void setFont(java.awt.Font); public abstract java.awt.Font getFont(); public abstract boolean requestFocusInWindow(); public abstract java.awt.FontMetrics getFontMetrics(java.awt.Font); public abstract void setBackground(java.awt.Color); public abstract void setEnabled(boolean); public abstract void grabFocus(); public abstract void redo(); public abstract void revalidate(); public abstract void setSourceCode(String, boolean); public abstract void setCaretVisible(boolean); public abstract void setSelectionVisible(boolean); public abstract void undo(); public abstract void discardAllUndoableEdits(); public abstract void setLineHighlightEnabled(boolean); public abstract void setCaretBlinkRate(int); public abstract void setTabSize(int); public abstract void updateSyntaxStyles(); public abstract java.awt.Component getOuterComponent(); } EditPane$1 package mars.venus; synchronized class EditPane$1 implements javax.swing.event.DocumentListener { void EditPane$1(EditPane); public void insertUpdate(javax.swing.event.DocumentEvent); public void removeUpdate(javax.swing.event.DocumentEvent); public void changedUpdate(javax.swing.event.DocumentEvent); } SettingsHighlightingAction$1 package mars.venus; synchronized class SettingsHighlightingAction$1 extends java.awt.event.WindowAdapter { void SettingsHighlightingAction$1(SettingsHighlightingAction); public void windowClosing(java.awt.event.WindowEvent); } SettingsValueDisplayBaseAction package mars.venus; public synchronized class SettingsValueDisplayBaseAction extends GuiAction { public void SettingsValueDisplayBaseAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI); public void actionPerformed(java.awt.event.ActionEvent); } MessagesPane$Asker$1$2 package mars.venus; synchronized class MessagesPane$Asker$1$2 implements Runnable { void MessagesPane$Asker$1$2(MessagesPane$Asker$1, javax.swing.event.DocumentEvent); public void run(); } LabelsWindow$MyTippedJTable package mars.venus; synchronized class LabelsWindow$MyTippedJTable extends javax.swing.JTable { void LabelsWindow$MyTippedJTable(LabelsWindow, LabelsWindow$LabelTableModel); protected javax.swing.table.JTableHeader createDefaultTableHeader(); public java.awt.Component prepareRenderer(javax.swing.table.TableCellRenderer, int, int); } SettingsPopupInputAction package mars.venus; public synchronized class SettingsPopupInputAction extends GuiAction { public void SettingsPopupInputAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI); public void actionPerformed(java.awt.event.ActionEvent); } mars/venus/FileSaveAction.java mars/venus/FileSaveAction.java   package mars.venus;    import mars.*;    import java.awt.*;    import java.awt.event.*;    import javax.swing.*;    import java.io.*;    /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */       /**     * Action  for the File -> Save menu item
    */              
    public class FileSaveAction extends GuiAction {
     
       public FileSaveAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
   
        /** 
            * saves the file, if not alredy saved it will do a saveAs
            */
   
       public void actionPerformed(ActionEvent e){
         mainUI.editor.save();
      }
                  
   }

EditSelectAllAction

package mars.venus;
public synchronized class EditSelectAllAction extends GuiAction {
public void EditSelectAllAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/PopupListener.java
mars/venus/PopupListener.java   package mars.venus;
   import java.awt.event.*;
   import javax.swing.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

// Experimental version 3 August 2006 Pete Sanderson
// This will display the Settings popup menu upon right-click.
// Menu selections themselves are handled separately.
// Code below is adapted from Java Tutorial on working with menus.

    public class PopupListener extends MouseAdapter { 
       private JPopupMenu popup;
     
     public PopupListener(JPopupMenu p) {
        popup = p;
        }
        
       public void mousePressed(MouseEvent e) { 
         maybeShowPopup(e); 
      } 
      
       public void mouseReleased(MouseEvent e) { 
         maybeShowPopup(e); 
      } 
      
       private void maybeShowPopup(MouseEvent e) {
         if (e.isPopupTrigger()) {
            popup.show(e.getComponent(), e.getX(), e.getY()); 
         }
      }
   }

mars/venus/EditUndoAction.java
mars/venus/EditUndoAction.java   package mars.venus;
   import mars.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.undo.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the Edit -> Undo menu item
    */              
    public class EditUndoAction extends GuiAction {
     
       public EditUndoAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
         setEnabled(false);
      }
      /**
       * Adapted from TextComponentDemo.java in the
       * Java Tutorial “Text Component Features”
        */
       public void actionPerformed(ActionEvent e) {
         EditPane editPane = mainUI.getMainPane().getEditPane();
         if (editPane != null) {
            editPane.undo();
            updateUndoState();
            mainUI.editRedoAction.updateRedoState();
         }
      }
   
       void updateUndoState() { 
         EditPane editPane = mainUI.getMainPane().getEditPane();
         setEnabled(editPane != null && editPane.getUndoManager().canUndo());
            //new Throwable(“update undo state: “+(editPane != null && editPane.getUndoManager().canUndo())).printStackTrace();
      }
   }

EditFindReplaceAction$FindReplaceDialog$3

package mars.venus;
synchronized class EditFindReplaceAction$FindReplaceDialog$3 implements java.awt.event.ActionListener {
void EditFindReplaceAction$FindReplaceDialog$3(EditFindReplaceAction$FindReplaceDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

DataSegmentWindow$PrevButton

package mars.venus;
synchronized class DataSegmentWindow$PrevButton extends RepeatButton {
public void DataSegmentWindow$PrevButton(DataSegmentWindow, javax.swing.Icon);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/RegistersWindow.java
mars/venus/RegistersWindow.java   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.*;

/*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

  /**
    *  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];                   }                };          }       }        } VenusUI package mars.venus; public synchronized class VenusUI extends javax.swing.JFrame { VenusUI mainUI; public javax.swing.JMenuBar menu; javax.swing.JToolBar toolbar; MainPane mainPane; RegistersPane registersPane; RegistersWindow registersTab; Coprocessor1Window coprocessor1Tab; Coprocessor0Window coprocessor0Tab; MessagesPane messagesPane; javax.swing.JSplitPane splitter; javax.swing.JSplitPane horizonSplitter; javax.swing.JPanel north; private int frameState; private static int menuState; private static boolean reset; private static boolean started; Editor editor; private javax.swing.JMenu file; private javax.swing.JMenu run; private javax.swing.JMenu window; private javax.swing.JMenu help; private javax.swing.JMenu edit; private javax.swing.JMenu settings; private javax.swing.JMenuItem fileNew; private javax.swing.JMenuItem fileOpen; private javax.swing.JMenuItem fileClose; private javax.swing.JMenuItem fileCloseAll; private javax.swing.JMenuItem fileSave; private javax.swing.JMenuItem fileSaveAs; private javax.swing.JMenuItem fileSaveAll; private javax.swing.JMenuItem fileDumpMemory; private javax.swing.JMenuItem filePrint; private javax.swing.JMenuItem fileExit; private javax.swing.JMenuItem editUndo; private javax.swing.JMenuItem editRedo; private javax.swing.JMenuItem editCut; private javax.swing.JMenuItem editCopy; private javax.swing.JMenuItem editPaste; private javax.swing.JMenuItem editFindReplace; private javax.swing.JMenuItem editSelectAll; private javax.swing.JMenuItem runGo; private javax.swing.JMenuItem runStep; private javax.swing.JMenuItem runBackstep; private javax.swing.JMenuItem runReset; private javax.swing.JMenuItem runAssemble; private javax.swing.JMenuItem runStop; private javax.swing.JMenuItem runPause; private javax.swing.JMenuItem runClearBreakpoints; private javax.swing.JMenuItem runToggleBreakpoints; private javax.swing.JCheckBoxMenuItem settingsLabel; private javax.swing.JCheckBoxMenuItem settingsPopupInput; private javax.swing.JCheckBoxMenuItem settingsValueDisplayBase; private javax.swing.JCheckBoxMenuItem settingsAddressDisplayBase; private javax.swing.JCheckBoxMenuItem settingsExtended; private javax.swing.JCheckBoxMenuItem settingsAssembleOnOpen; private javax.swing.JCheckBoxMenuItem settingsAssembleAll; private javax.swing.JCheckBoxMenuItem settingsWarningsAreErrors; private javax.swing.JCheckBoxMenuItem settingsStartAtMain; private javax.swing.JCheckBoxMenuItem settingsDelayedBranching; private javax.swing.JCheckBoxMenuItem settingsProgramArguments; private javax.swing.JMenuItem settingsExceptionHandler; private javax.swing.JMenuItem settingsEditor; private javax.swing.JMenuItem settingsHighlighting; private javax.swing.JMenuItem settingsMemoryConfiguration; private javax.swing.JMenuItem helpHelp; private javax.swing.JMenuItem helpAbout; private javax.swing.JButton Undo; private javax.swing.JButton Redo; private javax.swing.JButton Cut; private javax.swing.JButton Copy; private javax.swing.JButton Paste; private javax.swing.JButton FindReplace; private javax.swing.JButton SelectAll; private javax.swing.JButton New; private javax.swing.JButton Open; private javax.swing.JButton Save; private javax.swing.JButton SaveAs; private javax.swing.JButton SaveAll; private javax.swing.JButton DumpMemory; private javax.swing.JButton Print; private javax.swing.JButton Run; private javax.swing.JButton Assemble; private javax.swing.JButton Reset; private javax.swing.JButton Step; private javax.swing.JButton Backstep; private javax.swing.JButton Stop; private javax.swing.JButton Pause; private javax.swing.JButton Help; private javax.swing.Action fileNewAction; private javax.swing.Action fileOpenAction; private javax.swing.Action fileCloseAction; private javax.swing.Action fileCloseAllAction; private javax.swing.Action fileSaveAction; private javax.swing.Action fileSaveAsAction; private javax.swing.Action fileSaveAllAction; private javax.swing.Action fileDumpMemoryAction; private javax.swing.Action filePrintAction; private javax.swing.Action fileExitAction; EditUndoAction editUndoAction; EditRedoAction editRedoAction; private javax.swing.Action editCutAction; private javax.swing.Action editCopyAction; private javax.swing.Action editPasteAction; private javax.swing.Action editFindReplaceAction; private javax.swing.Action editSelectAllAction; private javax.swing.Action runAssembleAction; private javax.swing.Action runGoAction; private javax.swing.Action runStepAction; private javax.swing.Action runBackstepAction; private javax.swing.Action runResetAction; private javax.swing.Action runStopAction; private javax.swing.Action runPauseAction; private javax.swing.Action runClearBreakpointsAction; private javax.swing.Action runToggleBreakpointsAction; private javax.swing.Action settingsLabelAction; private javax.swing.Action settingsPopupInputAction; private javax.swing.Action settingsValueDisplayBaseAction; private javax.swing.Action settingsAddressDisplayBaseAction; private javax.swing.Action settingsExtendedAction; private javax.swing.Action settingsAssembleOnOpenAction; private javax.swing.Action settingsAssembleAllAction; private javax.swing.Action settingsWarningsAreErrorsAction; private javax.swing.Action settingsStartAtMainAction; private javax.swing.Action settingsProgramArgumentsAction; private javax.swing.Action settingsDelayedBranchingAction; private javax.swing.Action settingsExceptionHandlerAction; private javax.swing.Action settingsEditorAction; private javax.swing.Action settingsHighlightingAction; private javax.swing.Action settingsMemoryConfigurationAction; private javax.swing.Action helpHelpAction; private javax.swing.Action helpAboutAction; static void ();
public void VenusUI(String);
private void createActionObjects();
private javax.swing.JMenuBar setUpMenuBar();
javax.swing.JToolBar setUpToolBar();
void setMenuState(int);
void setMenuStateInitial();
void setMenuStateNotEdited();
void setMenuStateEditing();
void setMenuStateEditingNew();
void setMenuStateRunnable();
void setMenuStateRunning();
void setMenuStateTerminated();
public static int getMenuState();
public static void setReset(boolean);
public static void setStarted(boolean);
public static boolean getReset();
public static boolean getStarted();
public Editor getEditor();
public MainPane getMainPane();
public MessagesPane getMessagesPane();
public RegistersPane getRegistersPane();
public javax.swing.JCheckBoxMenuItem getValueDisplayBaseMenuItem();
public javax.swing.JCheckBoxMenuItem getAddressDisplayBaseMenuItem();
public javax.swing.Action getRunAssembleAction();
public void haveMenuRequestFocus();
public void dispatchEventToMenu(java.awt.event.KeyEvent);
private void setupPopupMenu();
}

Coprocessor1Window$RegTableModel

package mars.venus;
synchronized class Coprocessor1Window$RegTableModel extends javax.swing.table.AbstractTableModel {
final String[] columnNames;
Object[][] data;
public void Coprocessor1Window$RegTableModel(Coprocessor1Window, Object[][]);
public int getColumnCount();
public int getRowCount();
public String getColumnName(int);
public Object getValueAt(int, int);
public Class getColumnClass(int);
public boolean isCellEditable(int, int);
public void setValueAt(Object, int, int);
private void setDisplayAndModelValueAt(Object, int, int);
private void printDebugData();
}

DataSegmentWindow$9

package mars.venus;
synchronized class DataSegmentWindow$9 implements java.awt.event.ActionListener {
void DataSegmentWindow$9(DataSegmentWindow);
public void actionPerformed(java.awt.event.ActionEvent);
}

SettingsStartAtMainAction

package mars.venus;
public synchronized class SettingsStartAtMainAction extends GuiAction {
public void SettingsStartAtMainAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

FileDumpMemoryAction

package mars.venus;
public synchronized class FileDumpMemoryAction extends GuiAction {
private javax.swing.JDialog dumpDialog;
private static final String title = Dump Memory To File;
private String[] segmentArray;
private int[] baseAddressArray;
private int[] limitAddressArray;
private int[] highAddressArray;
private String[] segmentListArray;
private int[] segmentListBaseArray;
private int[] segmentListHighArray;
private javax.swing.JComboBox segmentListSelector;
private javax.swing.JComboBox formatListSelector;
public void FileDumpMemoryAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
private boolean dumpMemory();
private javax.swing.JDialog createDumpDialog();
private javax.swing.JPanel buildDialogPanel();
private boolean performDump(int, int, mars.mips.dump.DumpFormat);
private void closeDialog();
}

mars/venus/EditFindReplaceAction.java
mars/venus/EditFindReplaceAction.java   package mars.venus;
   import mars.*;
    import mars.venus.editors.MARSTextEditingArea;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the Edit -> Find/Replace menu item
    */              
    public class EditFindReplaceAction extends GuiAction {
      private static String searchString = “”;
        private static boolean caseSensitivity = true;
        private static final String DIALOG_TITLE = “Find and Replace”;
      JDialog findReplaceDialog;
       public EditFindReplaceAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
          
       public void actionPerformed(ActionEvent e){
         findReplaceDialog = new FindReplaceDialog(Globals.getGui(), DIALOG_TITLE, false );
         findReplaceDialog.setVisible(true);
      }
    
     //////////////////////////////////////////////////////////////////////////////
     //
     //   Private class to do all the work!
     //
       private class FindReplaceDialog extends JDialog {
         JButton findButton, replaceButton, replaceAllButton, closeButton;
         JTextField findInputField, replaceInputField;
         JCheckBox caseSensitiveCheckBox;
         JRadioButton linearFromStart, circularFromCursor;
         private JLabel resultsLabel;
      
         public static final String FIND_TOOL_TIP_TEXT = “Find next occurrence of given text; wraps around at end”;
         public static final String REPLACE_TOOL_TIP_TEXT = “Replace current occurrence of text then find next”;
         public static final String REPLACE_ALL_TOOL_TIP_TEXT = “Replace all occurrences of text”;
         public static final String CLOSE_TOOL_TIP_TEXT = “Close the dialog”;
         public static final String RESULTS_TOOL_TIP_TEXT = “Outcome of latest operation (button click)”;
        
         public static final String RESULTS_TEXT_FOUND = “Text found”;
         public static final String RESULTS_TEXT_NOT_FOUND = “Text not found”;
         public static final String RESULTS_TEXT_REPLACED = “Text replaced and found next”;
         public static final String RESULTS_TEXT_REPLACED_LAST = “Text replaced; last occurrence”;
         public static final String RESULTS_TEXT_REPLACED_ALL = “Replaced”;
         public static final String RESULTS_NO_TEXT_TO_FIND = “No text to find”;
         
          public FindReplaceDialog(Frame owner, String title, boolean modality) {
            super(owner, title, modality);
            this.setContentPane(buildDialogPanel());
            this.setDefaultCloseOperation(
                        JDialog.DO_NOTHING_ON_CLOSE);
            this.addWindowListener(
                   new WindowAdapter() {
                      public void windowClosing(WindowEvent we) {
                        performClose();
                     }
                  });
            this.pack();
            this.setLocationRelativeTo(owner);
         }
          
             // Constructs the dialog’s main panel.
          private JPanel buildDialogPanel() {
            JPanel dialogPanel = new JPanel(new BorderLayout());
            dialogPanel.setBorder(new javax.swing.border.EmptyBorder(10,10,10,10));
            dialogPanel.add(buildInputPanel(), BorderLayout.NORTH);
            dialogPanel.add(buildOptionsPanel());
            dialogPanel.add(buildControlPanel(),BorderLayout.SOUTH);                
            return dialogPanel;
         }
        
             // Top part of the dialog, to contain the two input text fields.
          private Component buildInputPanel() {
            findInputField = new JTextField(30);
            if (searchString.length() > 0) {
               findInputField.setText(searchString);
               findInputField.selectAll();
            }
            replaceInputField = new JTextField(30);
            JPanel inputPanel = new JPanel();
            JPanel labelsPanel = new JPanel(new GridLayout(2,1,5,5));
            JPanel fieldsPanel = new JPanel(new GridLayout(2,1,5,5));
            labelsPanel.add(new JLabel(“Find what:”));
            labelsPanel.add(new JLabel(“Replace with:”));
            fieldsPanel.add(findInputField);
            fieldsPanel.add(replaceInputField);
            
            Box columns = Box.createHorizontalBox();
            columns.add(labelsPanel);
            columns.add(Box.createHorizontalStrut(6));
            columns.add(fieldsPanel);
            inputPanel.add(columns);
            return inputPanel;  
         }
        
            // Center part of the dialog, which contains the check box
            // for case sensitivity along with a label to display the
            // outcome of each operation.
          private Component buildOptionsPanel() {
            Box optionsPanel = Box.createHorizontalBox();
            caseSensitiveCheckBox = new JCheckBox(“Case Sensitive”,caseSensitivity);
            JPanel casePanel = new JPanel(new GridLayout(2,1));
            casePanel.add(caseSensitiveCheckBox);
            casePanel.setMaximumSize(casePanel.getPreferredSize());
            optionsPanel.add(casePanel);
            optionsPanel.add(Box.createHorizontalStrut(5));
            JPanel resultsPanel = new JPanel(new GridLayout(1,1));
            resultsPanel.setBorder(BorderFactory.createTitledBorder(“Outcome”));
            resultsLabel = new JLabel(“”);
            resultsLabel.setForeground(Color.RED);
            resultsLabel.setToolTipText(RESULTS_TOOL_TIP_TEXT);
            resultsPanel.add(resultsLabel);         
            optionsPanel.add(resultsPanel);
            return optionsPanel;
         }
         
        
       // Row of control buttons to be placed along the button of the dialog
          private Component buildControlPanel() {
            Box controlPanel = Box.createHorizontalBox();
            controlPanel.setBorder(BorderFactory.createEmptyBorder(6,0,0,0));
            findButton = new JButton(“Find”);
            findButton.setToolTipText(FIND_TOOL_TIP_TEXT);
            findButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        performFind();
                     }
                  });
            replaceButton = new JButton(“Replace then Find”);
            replaceButton.setToolTipText(REPLACE_TOOL_TIP_TEXT);
            replaceButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        performReplace();
                     }
                  });
            replaceAllButton = new JButton(“Replace all”);
            replaceAllButton.setToolTipText(REPLACE_ALL_TOOL_TIP_TEXT);
            replaceAllButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        performReplaceAll();
                     }
                  });
            closeButton = new JButton(“Close”);
            closeButton.setToolTipText(CLOSE_TOOL_TIP_TEXT);
            closeButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) { 
                        performClose();
                     }
                  });   
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(findButton);
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(replaceButton);
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(replaceAllButton);
            controlPanel.add(Box.createHorizontalGlue());
            controlPanel.add(closeButton);
            controlPanel.add(Box.createHorizontalGlue());        
            return controlPanel;
         }
      
            ////////////////////////////////////////////////////////////////////////
             //
             //  Private methods to carry out the button actions
             
             //  Performs a find.  The operation starts at the current cursor position
             //  which is not known to this object but is maintained by the EditPane
             //  object.  The operation will wrap around when it reaches the end of the 
             //  document.  If found, the matching text is selected.
          private void performFind() {
            resultsLabel.setText(“”);
            if (findInputField.getText().length() > 0) {
               EditPane editPane =  mainUI.getMainPane().getEditPane();
            // Being cautious. Should not be null because find/replace tool button disabled if no file open
               if (editPane != null) {
                  searchString = findInputField.getText();
                  int posn = editPane.doFindText(searchString, caseSensitiveCheckBox.isSelected());
                  if (posn == MARSTextEditingArea.TEXT_NOT_FOUND) {
                     resultsLabel.setText(findButton.getText()+”: “+RESULTS_TEXT_NOT_FOUND);
                  } 
                  else {
                     resultsLabel.setText(findButton.getText()+”: “+RESULTS_TEXT_FOUND);
                  }              
               }
            }  
            else {
               resultsLabel.setText(findButton.getText()+”: “+RESULTS_NO_TEXT_TO_FIND);
            }
         }
      
            // Performs a replace-and-find.  If the matched text is current selected with cursor at
             // its end, the replace happens immediately followed by a find for the next occurrence.
             // Otherwise, it performs a find.  This will select the matching text so the next press
             // of Replace will do the replace.  This is apparently common behavior for replace
             // buttons of different apps I’ve checked.
          private void performReplace() {
            resultsLabel.setText(“”);
            if (findInputField.getText().length() > 0) {
               EditPane editPane =  mainUI.getMainPane().getEditPane();
            // Being cautious. Should not be null b/c find/replace tool button disabled if no file open
               if (editPane != null) {
                  searchString = findInputField.getText();
                  int posn = editPane.doReplace(searchString, replaceInputField.getText(), caseSensitiveCheckBox.isSelected());
                  String result = replaceButton.getText()+”: “;
                  switch (posn) {
                  
                     case MARSTextEditingArea.TEXT_NOT_FOUND :
                        result += RESULTS_TEXT_NOT_FOUND;
                        break;
                     case MARSTextEditingArea.TEXT_FOUND : 
                        result += RESULTS_TEXT_FOUND;
                        break;
                     case MARSTextEditingArea.TEXT_REPLACED_NOT_FOUND_NEXT :
                        result += RESULTS_TEXT_REPLACED_LAST;
                        break;
                     case MARSTextEditingArea.TEXT_REPLACED_FOUND_NEXT :
                        result += RESULTS_TEXT_REPLACED;
                        break;
                  } 
                  resultsLabel.setText(result);
               }
            }  
            else {
               resultsLabel.setText(replaceButton.getText()+”: “+RESULTS_NO_TEXT_TO_FIND);
            }
         
         }
        
             // Performs a replace-all.  Makes one pass through the document starting at
             // position 0.
          private void performReplaceAll() {
            resultsLabel.setText(“”);
            if (findInputField.getText().length() > 0) {
               EditPane editPane =  mainUI.getMainPane().getEditPane();
            // Being cautious. Should not be null b/c find/replace tool button disabled if no file open
               if (editPane != null) {
                  searchString = findInputField.getText();
                  int replaceCount = editPane.doReplaceAll(searchString, replaceInputField.getText(), caseSensitiveCheckBox.isSelected());
                  if (replaceCount == 0) {
                     resultsLabel.setText(replaceAllButton.getText()+”: “+RESULTS_TEXT_NOT_FOUND);
                  } 
                  else {
                     resultsLabel.setText(replaceAllButton.getText()+”: “+RESULTS_TEXT_REPLACED_ALL + ” “+replaceCount+” occurrence”+(replaceCount==1 ? “” : “s”));
                  }
               }
            }  
            else {
               resultsLabel.setText(replaceAllButton.getText()+”: “+RESULTS_NO_TEXT_TO_FIND);
            }       
         }
              
             // Performs the close operation.  Records the current state of the case-sensitivity
             // checkbox into a static variable so it will be remembered across invocations within
             // the session.  This also happens with the contents of the “find” text field.
          private void performClose() {
               caseSensitivity = caseSensitiveCheckBox.isSelected();
            this.setVisible(false);
            this.dispose();
         }
            //
         ////////////////////////////////////////////////////////////////////////////////
      }
   
   }

SettingsHighlightingAction$5

package mars.venus;
synchronized class SettingsHighlightingAction$5 implements java.awt.event.ActionListener {
void SettingsHighlightingAction$5(SettingsHighlightingAction);
public void actionPerformed(java.awt.event.ActionEvent);
}

Coprocessor0Window

package mars.venus;
public synchronized class Coprocessor0Window extends javax.swing.JPanel implements java.util.Observer {
private static javax.swing.JTable table;
private static mars.mips.hardware.Register[] registers;
private Object[][] tableData;
private boolean highlighting;
private int highlightRow;
private ExecutePane executePane;
private int[] rowGivenRegNumber;
private static final int NAME_COLUMN = 0;
private static final int NUMBER_COLUMN = 1;
private static final int VALUE_COLUMN = 2;
private static mars.Settings settings;
public void Coprocessor0Window();
public Object[][] setupWindow();
public void clearWindow();
public void clearHighlighting();
public void refresh();
public void updateRegisters();
public void updateRegisters(int);
public void updateRegisterValue(int, int, int);
public void update(java.util.Observable, Object);
void highlightCellForRegister(mars.mips.hardware.Register);
}

RepeatButton

package mars.venus;
public synchronized class RepeatButton extends javax.swing.JButton implements java.awt.event.ActionListener, java.awt.event.MouseListener {
private boolean pressed;
private boolean repeatEnabled;
private javax.swing.Timer timer;
private int initialDelay;
private int delay;
private int modifiers;
private static boolean testing;
static void ();
public void RepeatButton();
public void RepeatButton(javax.swing.Action);
public void RepeatButton(javax.swing.Icon);
public void RepeatButton(String);
public void RepeatButton(String, javax.swing.Icon);
private void init();
public int getDelay();
public void setDelay(int);
public int getInitialDelay();
public void setInitialDelay(int);
public boolean isRepeatEnabled();
public void setRepeatEnabled(boolean);
public void setEnabled(boolean);
public void actionPerformed(java.awt.event.ActionEvent);
public void mouseClicked(java.awt.event.MouseEvent);
public void mousePressed(java.awt.event.MouseEvent);
public void mouseReleased(java.awt.event.MouseEvent);
public void mouseEntered(java.awt.event.MouseEvent);
public void mouseExited(java.awt.event.MouseEvent);
public static void main(String[]);
}

mars/venus/SettingsExtendedAction.java
mars/venus/SettingsExtendedAction.java   package mars.venus;
   import mars.simulator.*;
    import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item to control use of extended (pseudo) instructions or formats.
    */
    public class SettingsExtendedAction extends GuiAction  {
    
   
       public SettingsExtendedAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
           Globals.getSettings().setExtendedAssemblerEnabled(((JCheckBoxMenuItem)e.getSource()).isSelected());
      }
        
   }

SettingsLabelAction

package mars.venus;
public synchronized class SettingsLabelAction extends GuiAction {
public void SettingsLabelAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/SettingsLabelAction.java
mars/venus/SettingsLabelAction.java   package mars.venus;
   import mars.simulator.*;
    import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item to control display of Labels window (symbol table).
    */
    public class SettingsLabelAction extends GuiAction  {
    
   
       public SettingsLabelAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
           boolean visibility = ((JCheckBoxMenuItem) e.getSource()).isSelected();
           Globals.getGui().getMainPane().getExecutePane().setLabelWindowVisibility(visibility);
         Globals.getSettings().setLabelWindowVisibility(visibility);
      }
        
   }

LabelsWindow$MyTippedJTable$SymbolTableHeader$SymbolTableHeaderMouseListener

package mars.venus;
synchronized class LabelsWindow$MyTippedJTable$SymbolTableHeader$SymbolTableHeaderMouseListener implements java.awt.event.MouseListener {
private void LabelsWindow$MyTippedJTable$SymbolTableHeader$SymbolTableHeaderMouseListener(LabelsWindow$MyTippedJTable$SymbolTableHeader);
public void mouseClicked(java.awt.event.MouseEvent);
public void mouseEntered(java.awt.event.MouseEvent);
public void mouseExited(java.awt.event.MouseEvent);
public void mousePressed(java.awt.event.MouseEvent);
public void mouseReleased(java.awt.event.MouseEvent);
}

mars/venus/SettingsDelayedBranchingAction.java
mars/venus/SettingsDelayedBranchingAction.java   package mars.venus;
   import mars.simulator.*;
   import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2007,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item to control delayed branching.
     * Note: Changing this setting while the current program is runnable
     * (assembled, or stepped execution) or terminated triggers a re-assembly.  
     * This is necessary to maintain consistency because the machine
     * code assembled for branch instructions differs depending on
     * this setting — would branch to incorrect address if setting 
     * were changed between assembly and execution.  
     * Note: This action is disabled while the MIPS program is running.
     * The user need only pause or stop execution to re-enable it.
    */
    public class SettingsDelayedBranchingAction extends GuiAction  {
    
   
       public SettingsDelayedBranchingAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
         Globals.getSettings().setDelayedBranchingEnabled(
               ((JCheckBoxMenuItem) e.getSource()).isSelected());
            // 25 June 2007 Re-assemble if the situation demands it to maintain consistency.
         if (Globals.getGui() != null  && 
              (FileStatus.get() == FileStatus.RUNNABLE ||
               FileStatus.get() == FileStatus.RUNNING ||
                FileStatus.get() == FileStatus.TERMINATED)
            ) {
                // Stop execution if executing — should NEVER happen because this 
                // Action’s widget is disabled during MIPS execution.
            if (FileStatus.get() == FileStatus.RUNNING) {
               Simulator.getInstance().stopExecution(this);
            }
            Globals.getGui().getRunAssembleAction().actionPerformed(null);
         } 
      }
        
   }

mars/venus/Editor.java
mars/venus/Editor.java   package mars.venus;
   import mars.*;
   import javax.swing.*;
   import java.io.*;
 
 /*
Copyright (c) 2003-2007,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
 
 /**
  * Manage the file being edited.
  * Currently only manages one file at a time, but can be expanded. 
  */
 
    public class Editor {
   
      public static final int MIN_TAB_SIZE = 1;
      public static final int MAX_TAB_SIZE = 32;
      public static final int MIN_BLINK_RATE = 0;     // no flashing
      public static final int MAX_BLINK_RATE = 1000;  // once per second
   
      private VenusUI mainUI;
      private EditTabbedPane editTabbedPane;
      private String mainUIbaseTitle;
    /* number of times File->New has been selected.  Used to generate
     * default filename until first Save or Save As.
     */
      private int newUsageCount; 
    // Current Directory for Open operation, same for Save operation
    // Values will mainly be set by the EditTabbedPane as Open/Save operations occur.
      private String defaultOpenDirectory, currentOpenDirectory;
      private String defaultSaveDirectory, currentSaveDirectory;
    
    /**
     * Create editor.
     *
     * @param ui the GUI that owns this editor
     */
       public Editor(VenusUI ui) {
         mainUI = ui;
         FileStatus.reset(); 
         mainUIbaseTitle = mainUI.getTitle();
         newUsageCount = 0;
        // Directory from which MARS was launched. Guaranteed to have a value.
         defaultOpenDirectory = System.getProperty(“user.dir”);
         defaultSaveDirectory = System.getProperty(“user.dir”);
         currentOpenDirectory = defaultOpenDirectory;
         currentSaveDirectory = defaultSaveDirectory;
      }
    
    /**
     *  Set associated EditTabbedPane.  This is container for any/all open files.
     *
     * @param editTabbedPane an existing editTabbedPane object
     */     
       public void setEditTabbedPane(EditTabbedPane editTabbedPane) {
         this.editTabbedPane = editTabbedPane;
      }
   
     /**
      *  Get name of current directory for Open operation.
    *
    *  @return String containing directory pathname.  Returns null if there is
    *   no EditTabbedPane.  Returns default, directory MARS is launched from, if
    *   no Opens have been performed.
    */
    
       public String getCurrentOpenDirectory() {
         return currentOpenDirectory;
      }
   
     /**
      *  Set name of current directory for Open operation.  The contents of this directory will
    *  be displayed when Open dialog is launched.
    *
    *  @param currentOpenDirectory String containing pathname for current Open directory. If
    *  it does not exist or is not a directory, the default (MARS launch directory) will be used.
    */
    
       void setCurrentOpenDirectory(String currentOpenDirectory) {
         File file = new File(currentOpenDirectory);
         if ( !file.exists() || !file.isDirectory() ) {
            this.currentOpenDirectory = defaultOpenDirectory;
         } 
         else {
            this.currentOpenDirectory = currentOpenDirectory;
         }
      }
         
         
      
     /**
      *  Get name of current directory for Save or Save As operation.
    *
    *  @return String containing directory pathname.  Returns null if there is
    *   no EditTabbedPane.  Returns default, directory MARS is launched from, if
    *   no Save or Save As operations have been performed.
    */
    
       public String getCurrentSaveDirectory() {
         return currentSaveDirectory;
      }
   
     /**
      *  Set name of current directory for Save operation.  The contents of this directory will
    *  be displayed when Save dialog is launched.  
    *
    *  @param currentSaveDirectory String containing pathname for current Save directory. If
    *  it does not exist or is not a directory, the default (MARS launch directory) will be used.
    */
    
       void setCurrentSaveDirectory(String currentSaveDirectory) {
         File file = new File(currentSaveDirectory);
         if ( !file.exists() || !file.isDirectory() ) {
            this.currentSaveDirectory = defaultSaveDirectory;
         } 
         else {
            this.currentSaveDirectory = currentSaveDirectory;
         }
      }   
    
    
      /**
     * Generates a default file name
     *
     * @return returns string mipsN.asm, where N is 1,2,3,…
     */
       public String getNextDefaultFilename() {
         newUsageCount++;
         return “mips”+newUsageCount+”.asm”;
      }
    
   
      /** Places name of file currently being edited into its edit tab and
     *  the application’s title bar.  The edit tab will contain only
     *  the filename, the title bar will contain full pathname.
     *  If file has been modified since created, opened or saved, as
     *  indicated by value of the status parameter, the name and path
     *  will be followed with an ‘*’.  If newly-created file has not
     *  yet been saved, the title bar will show (temporary) file name
     *  but not path.
     *
     *  @param path Full pathname for file
     *  @param name Name of file (last component of path)
     *  @param status Edit status of file.  See FileStatus static constants.
     */
       public void setTitle(String path, String name, int status) {
         if (status == FileStatus.NO_FILE || name==null || name.length()==0) {
            mainUI.setTitle(mainUIbaseTitle);
         } 
         else {
            String edited = (status==FileStatus.NEW_EDITED || status==FileStatus.EDITED) ? “*” : ” “;
            String titleName = (status==FileStatus.NEW_EDITED || status==FileStatus.NEW_NOT_EDITED) ? name : path;
            mainUI.setTitle(titleName + edited + ” – ” + mainUIbaseTitle);
            editTabbedPane.setTitleAt(editTabbedPane.getSelectedIndex(), name + edited);
         }
      }
    
    
        
        /**
         *  Perform “new” operation to create an empty tab.
         */     
       public void newFile() {
         editTabbedPane.newFile();
      }
        
        /**
         *  Perform “close” operation on current tab’s file.
         *  @return true if succeeded, else false.
         */ 
       public boolean close() {
         return editTabbedPane.closeCurrentFile();
      }
    
        /**
         *  Close all currently open files.
         *  @return true if succeeded, else false.
         */     
       public boolean closeAll() {
         return editTabbedPane.closeAllFiles();
      }
        
        /**
         *  Perform “save” operation on current tab’s file.
         *  @return true if succeeded, else false.
         */    
       public boolean save() {
         return editTabbedPane.saveCurrentFile();
      }
    
        /**
         *  Perform “save as” operation on current tab’s file.
         *  @return true if succeeded, else false.
         */     
       public boolean saveAs() {
         return editTabbedPane.saveAsCurrentFile();
      }
        
        /**
         *  Perform save operation on all open files (tabs).
         *  @return true if succeeded, else false.
         */     
       public boolean saveAll() {
         return editTabbedPane.saveAllFiles();
      }
    
        /**
         *  Open file in a new tab.
         *  @return true if succeeded, else false.
         */
       public boolean open() {
         return editTabbedPane.openFile();
      }
   
   
   
   /**
    * Called by several of the Action objects when there is potential
    * loss of editing changes.  Specifically: if there is a current
    * file open for editing and its modify flag is true, then give user
    * a dialog box with choice to save, discard edits, or cancel and
    * carry out the decision.  This applies to File->New, File->Open,
    * File->Close, and File->Exit.
    *
    * @return false means user selected Cancel so caller should do that.
    * Return of true means caller can proceed (edits were saved or discarded).
    */
       public boolean editsSavedOrAbandoned() {
         return editTabbedPane.editsSavedOrAbandoned();
      }
   
   }

mars/venus/FileCloseAllAction.java
mars/venus/FileCloseAllAction.java   package mars.venus;
   import mars.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
 
 /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
 
    /**
    * Action  for the File -> Close All menu item
    */              
    public class FileCloseAllAction extends GuiAction {
     
       public FileCloseAllAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
    
       public void actionPerformed(ActionEvent e){
              mainUI.editor.closeAll();
      }
   }

RegistersPane

package mars.venus;
public synchronized class RegistersPane extends javax.swing.JTabbedPane {
RegistersWindow regsTab;
Coprocessor1Window cop1Tab;
Coprocessor0Window cop0Tab;
private VenusUI mainUI;
public void RegistersPane(VenusUI, RegistersWindow, Coprocessor1Window, Coprocessor0Window);
public RegistersWindow getRegistersWindow();
public Coprocessor1Window getCoprocessor1Window();
public Coprocessor0Window getCoprocessor0Window();
}

SettingsHighlightingAction

package mars.venus;
public synchronized class SettingsHighlightingAction extends GuiAction {
javax.swing.JDialog highlightDialog;
private static final int[] backgroundSettingPositions;
private static final int[] foregroundSettingPositions;
private static final int[] fontSettingPositions;
javax.swing.JButton[] backgroundButtons;
javax.swing.JButton[] foregroundButtons;
javax.swing.JButton[] fontButtons;
javax.swing.JCheckBox[] defaultCheckBoxes;
javax.swing.JLabel[] samples;
java.awt.Color[] currentNondefaultBackground;
java.awt.Color[] currentNondefaultForeground;
java.awt.Color[] initialSettingsBackground;
java.awt.Color[] initialSettingsForeground;
java.awt.Font[] initialFont;
java.awt.Font[] currentFont;
java.awt.Font[] currentNondefaultFont;
javax.swing.JButton dataHighlightButton;
javax.swing.JButton registerHighlightButton;
boolean currentDataHighlightSetting;
boolean initialDataHighlightSetting;
boolean currentRegisterHighlightSetting;
boolean initialRegisterHighlightSetting;
private static final int gridVGap = 2;
private static final int gridHGap = 2;
private static final String SAMPLE_TOOL_TIP_TEXT = Preview based on background and text color settings;
private static final String BACKGROUND_TOOL_TIP_TEXT = Click, to select background color;
private static final String FOREGROUND_TOOL_TIP_TEXT = Click, to select text color;
private static final String FONT_TOOL_TIP_TEXT = Click, to select text font;
private static final String DEFAULT_TOOL_TIP_TEXT = Check, to select default color (disables color select buttons);
public static final String CLOSE_TOOL_TIP_TEXT = Apply current settings and close dialog;
public static final String APPLY_TOOL_TIP_TEXT = Apply current settings now and leave dialog open;
public static final String RESET_TOOL_TIP_TEXT = Reset to initial settings without applying;
public static final String CANCEL_TOOL_TIP_TEXT = Close dialog without applying current settings;
private static final String DATA_HIGHLIGHT_ENABLE_TOOL_TIP_TEXT = Click, to enable or disable highlighting in Data Segment window;
private static final String REGISTER_HIGHLIGHT_ENABLE_TOOL_TIP_TEXT = Click, to enable or disable highlighting in Register windows;
private static final String fontButtonText = font;
static void ();
public void SettingsHighlightingAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
private javax.swing.JPanel buildDialogPanel();
private String getHighlightControlText(boolean);
private void initializeButtonColors();
private void setHighlightingSettings();
private void resetButtonColors();
private void closeDialog();
}

TextSegmentWindow$CheckBoxTableCellRenderer

package mars.venus;
synchronized class TextSegmentWindow$CheckBoxTableCellRenderer extends javax.swing.JCheckBox implements javax.swing.table.TableCellRenderer {
javax.swing.border.Border noFocusBorder;
javax.swing.border.Border focusBorder;
public void TextSegmentWindow$CheckBoxTableCellRenderer(TextSegmentWindow);
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable, Object, boolean, boolean, int, int);
}

EditTabbedPane

package mars.venus;
public synchronized class EditTabbedPane extends javax.swing.JTabbedPane {
EditPane editTab;
MainPane mainPane;
private VenusUI mainUI;
private Editor editor;
private EditTabbedPane$FileOpener fileOpener;
public void EditTabbedPane(VenusUI, Editor, MainPane);
public EditPane getCurrentEditTab();
public void setCurrentEditTab(EditPane);
public EditPane getCurrentEditTabForFile(java.io.File);
public void newFile();
public boolean openFile();
public boolean openFile(java.io.File);
public boolean closeCurrentFile();
public boolean closeAllFiles();
public boolean saveCurrentFile();
private boolean saveFile(EditPane);
public boolean saveAsCurrentFile();
private java.io.File saveAsFile(EditPane);
public boolean saveAllFiles();
public void remove(EditPane);
private void updateTitlesAndMenuState(EditPane);
private void updateTitles(EditPane);
public EditPane getEditPaneForFile(String);
public boolean editsSavedOrAbandoned();
private int confirm(String);
}

HelpHelpAction$MyCellRenderer

package mars.venus;
synchronized class HelpHelpAction$MyCellRenderer extends javax.swing.JLabel implements javax.swing.ListCellRenderer {
private void HelpHelpAction$MyCellRenderer(HelpHelpAction);
public java.awt.Component getListCellRendererComponent(javax.swing.JList, Object, int, boolean, boolean);
}

EditFindReplaceAction$FindReplaceDialog$5

package mars.venus;
synchronized class EditFindReplaceAction$FindReplaceDialog$5 implements java.awt.event.ActionListener {
void EditFindReplaceAction$FindReplaceDialog$5(EditFindReplaceAction$FindReplaceDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

HelpHelpAction

package mars.venus;
public synchronized class HelpHelpAction extends GuiAction {
static java.awt.Color altBackgroundColor;
public static final String descriptionDetailSeparator = :;
static void ();
public void HelpHelpAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
private java.awt.Dimension getSize();
public void actionPerformed(java.awt.event.ActionEvent);
private javax.swing.JPanel createHTMLHelpPanel(String);
private javax.swing.JPanel createCopyrightInfoPanel();
private javax.swing.JPanel createMarsHelpInfoPanel();
private javax.swing.JPanel createMipsHelpInfoPanel();
private javax.swing.JScrollPane createMipsDirectivesHelpPane();
private javax.swing.JScrollPane createMipsInstructionHelpPane(String);
}

EditUndoAction

package mars.venus;
public synchronized class EditUndoAction extends GuiAction {
public void EditUndoAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
void updateUndoState();
}

mars/venus/ExecutePane.java
mars/venus/ExecutePane.java   package mars.venus;
   import mars.*;
   import javax.swing.*;
   import java.awt.*;
   import java.util.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

 /**
   * Container for the execution-related windows.  Currently displayed as a tabbed pane.
    *   @author Sanderson and Team JSpim
    **/

    public class ExecutePane extends JDesktopPane {
      private RegistersWindow registerValues;
      private Coprocessor1Window coprocessor1Values;
      private Coprocessor0Window coprocessor0Values;
      private DataSegmentWindow dataSegment;
      private TextSegmentWindow  textSegment;
      private LabelsWindow labelValues;
      private VenusUI mainUI;   
      private NumberDisplayBaseChooser valueDisplayBase;
      private NumberDisplayBaseChooser addressDisplayBase;
      private boolean labelWindowVisible;
   
   /**
   * initialize the Execute pane with major components
   *
   * @param mainUI the parent GUI
   * @param regs window containing integer register set
   * @param cop1Regs window containing Coprocessor 1 register set
   * @param cop0Regs window containing Coprocessor 0 register set
   */
   
       public ExecutePane(VenusUI mainUI, RegistersWindow regs, Coprocessor1Window cop1Regs, Coprocessor0Window cop0Regs) {
         this.mainUI = mainUI;
        // Although these are displayed in Data Segment, they apply to all three internal
        // windows within the Execute pane.  So they will be housed here.
         addressDisplayBase = new NumberDisplayBaseChooser(“Hexadecimal Addresses”,
                                    Globals.getSettings().getDisplayAddressesInHex());
         valueDisplayBase = new NumberDisplayBaseChooser(“Hexadecimal Values”,
                                    Globals.getSettings().getDisplayValuesInHex());//VenusUI.DEFAULT_NUMBER_BASE);
         addressDisplayBase.setToolTipText(“If checked, displays all memory addresses in hexadecimal.  Otherwise, decimal.”);
         valueDisplayBase.setToolTipText(“If checked, displays all memory and register contents in hexadecimal.  Otherwise, decimal.”);
         NumberDisplayBaseChooser[] choosers = { addressDisplayBase, valueDisplayBase };
         registerValues = regs; 
         coprocessor1Values = cop1Regs;
         coprocessor0Values = cop0Regs;                                                                 
         textSegment = new TextSegmentWindow();
         dataSegment = new DataSegmentWindow(choosers);
         labelValues = new LabelsWindow();
         labelWindowVisible = Globals.getSettings().getLabelWindowVisibility();
         textSegment.setVisible(true);
         dataSegment.setVisible(true);
         labelValues.setVisible(labelWindowVisible);
         this.add(textSegment);
         this.add(dataSegment);
         this.add(labelValues);
      }
    
    /**
     * This method will set the bounds of this JDesktopPane’s internal windows 
     * relative to the current size of this JDesktopPane.  Such an operation
     * cannot be adequately done at constructor time because the actual
     * size of the desktop pane window is not yet established.  Layout manager
     * is not a good option here because JDesktopPane does not work well with
     * them (the whole idea of using JDesktopPane with internal frames is to 
     * have mini-frames that you can resize, move around, minimize, etc).  This  
     * method should be invoked only once: the first time the Execute tab is 
     * selected (a change listener invokes it).  We do not want it invoked
     * on subsequent tab selections; otherwise, user manipulations of the
     * internal frames would be lost the next time execute tab is selected. 
     */
       public void setWindowBounds() {
      
         int fullWidth = this.getSize().width – this.getInsets().left – this.getInsets().right;
         int fullHeight = this.getSize().height – this.getInsets().top – this.getInsets().bottom;
         int halfHeight = fullHeight/2;
         Dimension textDim = new Dimension((int)(fullWidth*.75),halfHeight);
         Dimension dataDim = new Dimension((int)(fullWidth),halfHeight);
         Dimension lablDim = new Dimension((int)(fullWidth*.25), halfHeight);
         Dimension textFullDim = new Dimension((int)(fullWidth), halfHeight);
         dataSegment.setBounds(0,textDim.height+1, dataDim.width, dataDim.height);
         if (labelWindowVisible) {
            textSegment.setBounds(0, 0, textDim.width, textDim.height);
            labelValues.setBounds(textDim.width+1, 0, lablDim.width, lablDim.height);
         } 
         else {
            textSegment.setBounds(0, 0, textFullDim.width, textFullDim.height);
            labelValues.setBounds(0, 0, 0, 0);          
         }
      }
    
    /**
     * Show or hide the label window (symbol table).  If visible, it is displayed
     * to the right of the text segment and the latter is shrunk accordingly.
     * @param visibility set to true or false
     */
     
       public void setLabelWindowVisibility(boolean visibility) {
         if (!visibility && labelWindowVisible) {
            labelWindowVisible = false;
            textSegment.setVisible(false);
            labelValues.setVisible(false);
            setWindowBounds();
            textSegment.setVisible(true);
         } 
         else 
            if (visibility && !labelWindowVisible) {
               labelWindowVisible = true;
               textSegment.setVisible(false);
               setWindowBounds();
               textSegment.setVisible(true);    
               labelValues.setVisible(true);        
            }
      }
     
      /** Clears out all components of the Execute tab: text segment
     * display, data segment display, label display and register display.
     * This will typically be done upon File->Close, Open, New.
     */
    
       public void clearPane() {
         this.getTextSegmentWindow().clearWindow();
         this.getDataSegmentWindow().clearWindow();
         this.getRegistersWindow().clearWindow();
         this.getCoprocessor1Window().clearWindow();
         this.getCoprocessor0Window().clearWindow();
         this.getLabelsWindow().clearWindow();
            // seems to be required, to display cleared Execute tab contents…
         if (mainUI.getMainPane().getSelectedComponent()== this) {
            mainUI.getMainPane().setSelectedComponent(mainUI.getMainPane().getEditTabbedPane());
            mainUI.getMainPane().setSelectedComponent(this);
         }
      }
    
    /**
     * Access the text segment window.
     */
       public TextSegmentWindow getTextSegmentWindow() {
         return textSegment;
      }
    
    /**
     * Access the data segment window.
     */     
       public DataSegmentWindow getDataSegmentWindow() {
         return dataSegment;
      }
    
        /**
     * Access the register values window.
     */     
       public RegistersWindow getRegistersWindow() {
         return registerValues;
      }
   
        /**
     * Access the coprocessor1 values window.
     */     
       public Coprocessor1Window getCoprocessor1Window() {
         return coprocessor1Values;
      }
   
        /**
     * Access the coprocessor0 values window.
     */     
       public Coprocessor0Window getCoprocessor0Window() {
         return coprocessor0Values;
      }
    
        /**
     * Access the label values window.
     */     
       public LabelsWindow getLabelsWindow() {
         return labelValues;
      }
        /**
     * Retrieve the number system base for displaying values (mem/register contents)
     */     
       public int getValueDisplayBase() {
         return valueDisplayBase.getBase();
      }
   
        /**
     * Retrieve the number system base for displaying memory addresses
     */     
       public int getAddressDisplayBase() {
         return addressDisplayBase.getBase();
      }
    
    /**
     * Retrieve component used to set numerical base (10 or 16) of data value display.
     * @return the chooser
     */
       public NumberDisplayBaseChooser getValueDisplayBaseChooser() {
         return valueDisplayBase;
      }
   
    /**
     * Retrieve component used to set numerical base (10 or 16) of address display.
     * @return the chooser
     */
       public NumberDisplayBaseChooser getAddressDisplayBaseChooser() {
         return addressDisplayBase;
      }
        
    /**
     * Update display of columns based on state of given chooser.  Normally
     * called only by the chooser’s ItemListener.
     * @param chooser the GUI object manipulated by the user to change number base
     */
       public void numberDisplayBaseChanged(NumberDisplayBaseChooser chooser) {
         if (chooser == valueDisplayBase) {
           // Have all internal windows update their value columns
            registerValues.updateRegisters();
            coprocessor1Values.updateRegisters();
            coprocessor0Values.updateRegisters();
            dataSegment.updateValues();
            textSegment.updateBasicStatements();
         } 
         else { // addressDisplayBase
           // Have all internal windows update their address columns
            dataSegment.updateDataAddresses();
            labelValues.updateLabelAddresses();
            textSegment.updateCodeAddresses();
            textSegment.updateBasicStatements();
         }
      }
    
   }

SettingsExceptionHandlerAction$ExceptionHandlerSettingAction

package mars.venus;
synchronized class SettingsExceptionHandlerAction$ExceptionHandlerSettingAction implements java.awt.event.ActionListener {
private void SettingsExceptionHandlerAction$ExceptionHandlerSettingAction(SettingsExceptionHandlerAction);
public void actionPerformed(java.awt.event.ActionEvent);
}

FileSaveAllAction

package mars.venus;
public synchronized class FileSaveAllAction extends GuiAction {
public void FileSaveAllAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

SettingsHighlightingAction$7

package mars.venus;
synchronized class SettingsHighlightingAction$7 implements java.awt.event.ActionListener {
void SettingsHighlightingAction$7(SettingsHighlightingAction);
public void actionPerformed(java.awt.event.ActionEvent);
}

ExecutePane

package mars.venus;
public synchronized class ExecutePane extends javax.swing.JDesktopPane {
private RegistersWindow registerValues;
private Coprocessor1Window coprocessor1Values;
private Coprocessor0Window coprocessor0Values;
private DataSegmentWindow dataSegment;
private TextSegmentWindow textSegment;
private LabelsWindow labelValues;
private VenusUI mainUI;
private NumberDisplayBaseChooser valueDisplayBase;
private NumberDisplayBaseChooser addressDisplayBase;
private boolean labelWindowVisible;
public void ExecutePane(VenusUI, RegistersWindow, Coprocessor1Window, Coprocessor0Window);
public void setWindowBounds();
public void setLabelWindowVisibility(boolean);
public void clearPane();
public TextSegmentWindow getTextSegmentWindow();
public DataSegmentWindow getDataSegmentWindow();
public RegistersWindow getRegistersWindow();
public Coprocessor1Window getCoprocessor1Window();
public Coprocessor0Window getCoprocessor0Window();
public LabelsWindow getLabelsWindow();
public int getValueDisplayBase();
public int getAddressDisplayBase();
public NumberDisplayBaseChooser getValueDisplayBaseChooser();
public NumberDisplayBaseChooser getAddressDisplayBaseChooser();
public void numberDisplayBaseChanged(NumberDisplayBaseChooser);
}

VenusUI$1

package mars.venus;
synchronized class VenusUI$1 extends java.awt.event.WindowAdapter {
void VenusUI$1(VenusUI);
public void windowOpened(java.awt.event.WindowEvent);
}

DataSegmentWindow$7

package mars.venus;
synchronized class DataSegmentWindow$7 implements java.awt.event.ActionListener {
void DataSegmentWindow$7(DataSegmentWindow);
public void actionPerformed(java.awt.event.ActionEvent);
}

TextSegmentWindow$MachineCodeCellRenderer

package mars.venus;
synchronized class TextSegmentWindow$MachineCodeCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
void TextSegmentWindow$MachineCodeCellRenderer(TextSegmentWindow);
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable, Object, boolean, boolean, int, int);
}

mars/venus/RunClearBreakpointsAction.java
mars/venus/RunClearBreakpointsAction.java   package mars.venus;
   import mars.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.event.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Run menu item to clear execution breakpoints that have been set.
     * It is a listener and is notified whenever a breakpoint is added or removed, thus will
     * set its enabled status true or false depending on whether breakpoints remain after that action. 
    */
    public class RunClearBreakpointsAction extends GuiAction implements TableModelListener  {
    
       /**
          * Create the object and register with text segment window as a listener on its table model.
          * The table model has not been created yet, so text segment window will hang onto this
          * registration info and transfer it to the table model upon creation (which happens with
          * each successful assembly).
          */
       public RunClearBreakpointsAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
         Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().registerTableModelListener(this);
      }
     /**
          *  When this option is selected, tell text segment window to clear breakpoints in its table model.
          */
       public void actionPerformed(ActionEvent e) {
         Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().clearAllBreakpoints();
        }
    
         /**
          *  Required TableModelListener method.  This is response upon editing of text segment table
          *  model.  The only editable column is breakpoints so this method is called only when user
          *  adds or removes a breakpoint.  Gets new breakpoint count and sets enabled status 
          *  accordingly.
          */
       public void tableChanged(TableModelEvent e) {
         setEnabled(
            Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().getBreakpointCount()>0);
      }
        
   }

AbstractFontSettingDialog

package mars.venus;
public abstract synchronized class AbstractFontSettingDialog extends javax.swing.JDialog {
javax.swing.JDialog editorDialog;
javax.swing.JComboBox fontFamilySelector;
javax.swing.JComboBox fontStyleSelector;
javax.swing.JSlider fontSizeSelector;
javax.swing.JSpinner fontSizeSpinSelector;
javax.swing.JLabel fontSample;
protected java.awt.Font currentFont;
String initialFontFamily;
String initialFontStyle;
String initialFontSize;
private static String SEPARATOR;
static void ();
public void AbstractFontSettingDialog(java.awt.Frame, String, boolean, java.awt.Font);
protected javax.swing.JPanel buildDialogPanel();
protected abstract java.awt.Component buildControlPanel();
public java.awt.Font getFont();
protected void performApply();
protected void closeDialog();
protected void reset();
protected abstract void apply(java.awt.Font);
private java.util.Vector makeVectorData(String[][]);
}

SettingsEditorAction$EditorFontDialog$1

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog$1 implements java.awt.event.ActionListener {
void SettingsEditorAction$EditorFontDialog$1(SettingsEditorAction$EditorFontDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

RegistersWindow$RegTableModel

package mars.venus;
synchronized class RegistersWindow$RegTableModel extends javax.swing.table.AbstractTableModel {
final String[] columnNames;
Object[][] data;
public void RegistersWindow$RegTableModel(RegistersWindow, Object[][]);
public int getColumnCount();
public int getRowCount();
public String getColumnName(int);
public Object getValueAt(int, int);
public Class getColumnClass(int);
public boolean isCellEditable(int, int);
public void setValueAt(Object, int, int);
private void setDisplayAndModelValueAt(Object, int, int);
private void printDebugData();
}

MessagesPane$Asker$3

package mars.venus;
synchronized class MessagesPane$Asker$3 implements mars.simulator.Simulator$StopListener {
void MessagesPane$Asker$3(MessagesPane$Asker);
public void stopped(mars.simulator.Simulator);
}

DataSegmentWindow$DataTableModel

package mars.venus;
synchronized class DataSegmentWindow$DataTableModel extends javax.swing.table.AbstractTableModel {
String[] columnNames;
Object[][] data;
public void DataSegmentWindow$DataTableModel(DataSegmentWindow, Object[][], String[]);
public int getColumnCount();
public int getRowCount();
public String getColumnName(int);
public Object getValueAt(int, int);
public boolean isCellEditable(int, int);
public Class getColumnClass(int);
public void setValueAt(Object, int, int);
private void setDisplayAndModelValueAt(Object, int, int);
private void printDebugData();
}

mars/venus/Coprocessor0Window.java
mars/venus/Coprocessor0Window.java   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.*;

/*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

  /**
    *  Sets up a window to display registers in the UI.
     *   @author Sanderson, Bumgarner
     **/
    
    public class Coprocessor0Window 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 int[] rowGivenRegNumber; // translate register number to table row.
      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 Coprocessor0Window() {
         Simulator.getInstance().addObserver(this);
            settings = Globals.getSettings();
         this.highlighting = false;
         table = new MyTippedJTable(new RegTableModel(setupWindow()));
         table.getColumnModel().getColumn(NAME_COLUMN).setPreferredWidth(50);
         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_AS_NEEDED));
      }
    
    /**
      *  Sets up the data for the window.
    *   @return The array object with the data for the window.
    **/  
    
       public Object[][] setupWindow(){
         registers = Coprocessor0.getRegisters();
         tableData = new Object[registers.length][3];
         rowGivenRegNumber = new int[32]; // maximum number of registers
         for(int i=0; i< registers.length; i++){             rowGivenRegNumber[registers[i].getNumber()] = i;             tableData[i][0]= registers[i].getName();             tableData[i][1]= new Integer(registers[i].getNumber());             tableData[i][2]= NumberDisplayBaseChooser.formatNumber(registers[i].getValue(), NumberDisplayBaseChooser.getBase(settings.getDisplayValuesInHex()));          }          return tableData;       }            /**      * Reset and redisplay registers      */        public void clearWindow() {          this.clearHighlighting();          Coprocessor0.resetRegisters();          this.updateRegisters(Globals.getGui().getMainPane().getExecutePane().getValueDisplayBase());       }          /**      * Clear highlight background color from any row 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 display base (10 or 16)      */        public void updateRegisters() {          this.updateRegisters(Globals.getGui().getMainPane().getExecutePane().getValueDisplayBase());       }          /**      * Update register display using specified display base      *      * @param base  number base for display (10 or 16)      */        public void updateRegisters(int base) {          registers = Coprocessor0.getRegisters();          for(int i=0; i< registers.length; i++){             this.updateRegisterValue(registers[i].getNumber(), registers[i].getValue(), 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), rowGivenRegNumber[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) {                   Coprocessor0.addRegistersObserver(this);                   this.highlighting = true;                }             }              else {                // Simulated MIPS execution stops.  Stop responding.                Coprocessor0.deleteRegistersObserver(this);             }          }           else if (obj instanceof RegisterAccessNotice) {              // NOTE: each register is a separate Observable             RegisterAccessNotice access = (RegisterAccessNotice) obj;             if (access.getAccessType()==AccessNotice.WRITE) {                 // For now, use highlighting technique used by Label Window feature to highlight                 // memory cell corresponding to a selected label.  The highlighting is not                 // as visually distinct as changing the background color, but will do for now.                 // Ideally, use 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) {          int registerRow    = Coprocessor0.getRegisterPosition(register);          if (registerRow < 0)              return; // not valid coprocessor0 register          this.highlightRow = registerRow;          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.             if (col == VALUE_COLUMN) {                 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) {                Coprocessor0.updateRegister(registers[row].getNumber(), 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 = {             /* $8  */  "Memory address at which address exception occurred",               /* $12 */  "Interrupt mask and enable bits",             /* $13 */  "Exception type and pending interrupt bits",             /* $14 */  "Address of instruction that caused exception"             };                    //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 */ "Register number.  In your program, precede it with $",             /* 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];                   }                };          }       }        } mars/venus/RegistersPane.java mars/venus/RegistersPane.java   package mars.venus;    import mars.*;    import javax.swing.*;    import javax.swing.event.*;    import java.awt.*;    import java.awt.event.*;    import javax.swing.undo.*;    import java.text.*;    import java.util.*;    import java.io.*; /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */     /**       *  Contains tabbed areas in the UI to display register contents       *   @author Sanderson        *   @version August 2005       **/     public class RegistersPane extends JTabbedPane{       RegistersWindow regsTab;         Coprocessor1Window cop1Tab;         Coprocessor0Window cop0Tab;            private VenusUI mainUI;         /**       *  Constructor for the RegistersPane class.      **/             public RegistersPane(VenusUI appFrame, RegistersWindow regs, Coprocessor1Window cop1,                               Coprocessor0Window cop0){          super();          this.mainUI = appFrame;             regsTab = regs;             cop1Tab = cop1;             cop0Tab = cop0;             regsTab.setVisible(true);             cop1Tab.setVisible(true);             cop0Tab.setVisible(true);          this.addTab("Registers", regsTab);             this.addTab("Coproc 1", cop1Tab);             this.addTab("Coproc 0", cop0Tab);          this.setToolTipTextAt(0,"CPU registers");             this.setToolTipTextAt(1,"Coprocessor 1 (floating point unit) registers");             this.setToolTipTextAt(2,"selected Coprocessor 0 (exceptions and interrupts) registers");       }              /**          * Return component containing integer register set.          *          * @return integer register window          */        public RegistersWindow getRegistersWindow() {          return regsTab;       }         /**          * Return component containing coprocessor 1 (floating point) register set.          *          * @return floating point register window          */        public Coprocessor1Window getCoprocessor1Window() {          return cop1Tab;       }              /**          * Return component containing coprocessor 0 (exceptions) register set.          *          * @return exceptions register window          */           public Coprocessor0Window getCoprocessor0Window() {          return cop0Tab;       }         } LabelsWindow package mars.venus; public synchronized class LabelsWindow extends javax.swing.JInternalFrame { private java.awt.Container contentPane; private javax.swing.JPanel labelPanel; private javax.swing.JCheckBox dataLabels; private javax.swing.JCheckBox textLabels; private java.util.ArrayList listOfLabelsForSymbolTable; private LabelsWindow labelsWindow; private static final int MAX_DISPLAYED_CHARS = 24; private static final int PREFERRED_NAME_COLUMN_WIDTH = 60; private static final int PREFERRED_ADDRESS_COLUMN_WIDTH = 60; private static final int LABEL_COLUMN = 0; private static final int ADDRESS_COLUMN = 1; private static final String[] columnToolTips; private static String[] columnNames; private java.util.Comparator tableSortComparator; private final java.util.Comparator[] tableSortingComparators; private static final int[][] sortStateTransitions; private static final char ASCENDING_SYMBOL = 9650; private static final char DESCENDING_SYMBOL = 9660; private static final String[][] sortColumnHeadings; private int sortState; static void ();
public void LabelsWindow();
public void setupTable();
public void clearWindow();
private javax.swing.JScrollPane generateLabelScrollPane();
public void updateLabelAddresses();
}

LabelsWindow$MyTippedJTable$SymbolTableHeader

package mars.venus;
synchronized class LabelsWindow$MyTippedJTable$SymbolTableHeader extends javax.swing.table.JTableHeader {
public void LabelsWindow$MyTippedJTable$SymbolTableHeader(LabelsWindow$MyTippedJTable, javax.swing.table.TableColumnModel);
public String getToolTipText(java.awt.event.MouseEvent);
}

TextSegmentWindow$CodeCellRenderer

package mars.venus;
synchronized class TextSegmentWindow$CodeCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
void TextSegmentWindow$CodeCellRenderer(TextSegmentWindow);
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable, Object, boolean, boolean, int, int);
}

MainPane$1

package mars.venus;
synchronized class MainPane$1 implements javax.swing.event.ChangeListener {
void MainPane$1(MainPane);
public void stateChanged(javax.swing.event.ChangeEvent);
}

SettingsHighlightingAction$FontSettingDialog$2

package mars.venus;
synchronized class SettingsHighlightingAction$FontSettingDialog$2 implements java.awt.event.ActionListener {
void SettingsHighlightingAction$FontSettingDialog$2(SettingsHighlightingAction$FontSettingDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

TextSegmentWindow$MyTippedJTable

package mars.venus;
synchronized class TextSegmentWindow$MyTippedJTable extends javax.swing.JTable {
private javax.swing.table.JTableHeader tableHeader;
private String[] columnToolTips;
void TextSegmentWindow$MyTippedJTable(TextSegmentWindow, TextSegmentWindow$TextTableModel);
protected javax.swing.table.JTableHeader createDefaultTableHeader();
public java.awt.Rectangle getRectForColumnIndex(int);
}

EditFindReplaceAction$FindReplaceDialog

package mars.venus;
synchronized class EditFindReplaceAction$FindReplaceDialog extends javax.swing.JDialog {
javax.swing.JButton findButton;
javax.swing.JButton replaceButton;
javax.swing.JButton replaceAllButton;
javax.swing.JButton closeButton;
javax.swing.JTextField findInputField;
javax.swing.JTextField replaceInputField;
javax.swing.JCheckBox caseSensitiveCheckBox;
javax.swing.JRadioButton linearFromStart;
javax.swing.JRadioButton circularFromCursor;
private javax.swing.JLabel resultsLabel;
public static final String FIND_TOOL_TIP_TEXT = Find next occurrence of given text; wraps around at end;
public static final String REPLACE_TOOL_TIP_TEXT = Replace current occurrence of text then find next;
public static final String REPLACE_ALL_TOOL_TIP_TEXT = Replace all occurrences of text;
public static final String CLOSE_TOOL_TIP_TEXT = Close the dialog;
public static final String RESULTS_TOOL_TIP_TEXT = Outcome of latest operation (button click);
public static final String RESULTS_TEXT_FOUND = Text found;
public static final String RESULTS_TEXT_NOT_FOUND = Text not found;
public static final String RESULTS_TEXT_REPLACED = Text replaced and found next;
public static final String RESULTS_TEXT_REPLACED_LAST = Text replaced; last occurrence;
public static final String RESULTS_TEXT_REPLACED_ALL = Replaced;
public static final String RESULTS_NO_TEXT_TO_FIND = No text to find;
public void EditFindReplaceAction$FindReplaceDialog(EditFindReplaceAction, java.awt.Frame, String, boolean);
private javax.swing.JPanel buildDialogPanel();
private java.awt.Component buildInputPanel();
private java.awt.Component buildOptionsPanel();
private java.awt.Component buildControlPanel();
private void performFind();
private void performReplace();
private void performReplaceAll();
private void performClose();
}

HardcopyWriter

package mars.venus;
public synchronized class HardcopyWriter extends java.io.Writer {
protected java.awt.PrintJob job;
protected java.awt.Graphics page;
protected String jobname;
protected int fontsize;
protected String time;
protected java.awt.Dimension pagesize;
protected int pagedpi;
protected java.awt.Font font;
protected java.awt.Font headerfont;
protected java.awt.FontMetrics metrics;
protected java.awt.FontMetrics headermetrics;
protected int x0;
protected int y0;
protected int width;
protected int height;
protected int headery;
protected int charwidth;
protected int lineheight;
protected int lineascent;
protected int chars_per_line;
protected int lines_per_page;
protected int chars_per_tab;
protected int charnum;
protected int linenum;
protected int pagenum;
private boolean last_char_was_return;
protected static java.util.Properties printprops;
static void ();
public void HardcopyWriter(java.awt.Frame, String, int, double, double, double, double) throws HardcopyWriter$PrintCanceledException;
public void write(char[], int, int);
public void flush();
public void close();
public void setFontStyle(int);
public void pageBreak();
public int getCharactersPerLine();
public int getLinesPerPage();
protected void newline();
protected void newpage();
public static void main(String[]);
}

NumberDisplayBaseChooser$1

package mars.venus;
synchronized class NumberDisplayBaseChooser$1 implements java.awt.event.ItemListener {
void NumberDisplayBaseChooser$1(NumberDisplayBaseChooser);
public void itemStateChanged(java.awt.event.ItemEvent);
}

MessagesPane$4

package mars.venus;
synchronized class MessagesPane$4 implements Runnable {
void MessagesPane$4(MessagesPane, String);
public void run();
}

SettingsExceptionHandlerAction

package mars.venus;
public synchronized class SettingsExceptionHandlerAction extends GuiAction {
javax.swing.JDialog exceptionHandlerDialog;
javax.swing.JCheckBox exceptionHandlerSetting;
javax.swing.JButton exceptionHandlerSelectionButton;
javax.swing.JTextField exceptionHandlerDisplay;
boolean initialSelected;
String initialPathname;
public void SettingsExceptionHandlerAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
private javax.swing.JPanel buildDialogPanel();
private void performOK();
private void closeDialog();
}

SettingsAddressDisplayBaseAction

package mars.venus;
public synchronized class SettingsAddressDisplayBaseAction extends GuiAction {
public void SettingsAddressDisplayBaseAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

DataSegmentWindow$AddressCellRenderer

package mars.venus;
synchronized class DataSegmentWindow$AddressCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
void DataSegmentWindow$AddressCellRenderer(DataSegmentWindow);
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable, Object, boolean, boolean, int, int);
}

mars/venus/HelpHelpAction.java
mars/venus/HelpHelpAction.java   package mars.venus;
   import mars.*;
   import mars.assembler.*;
   import mars.mips.instructions.*;
   import java.util.*;
   import java.io.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.event.*;
   import javax.swing.text.html.*;
    
    /*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the Help -> Help menu item
    */              
    public class HelpHelpAction extends GuiAction {
       public  HelpHelpAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
    
    // ideally read or computed from config file…
       private Dimension getSize() {
         return new Dimension(800,600);
      }

      // Light gray background color for alternating lines of the instruction lists
      static Color altBackgroundColor = new Color(0xEE,0xEE,0xEE);  
        
        /**
         *  Separates Instruction name descriptor from detailed (operation) description 
         *  in help string.
         */
        public static final String descriptionDetailSeparator = “:”;
            
    /**
     * Displays tabs with categories of information
     */   
       public void actionPerformed(ActionEvent e) {
         JTabbedPane tabbedPane = new JTabbedPane();
         tabbedPane.addTab(“MIPS”, createMipsHelpInfoPanel());
         tabbedPane.addTab(“MARS”, createMarsHelpInfoPanel());
         tabbedPane.addTab(“License”, createCopyrightInfoPanel());
         tabbedPane.addTab(“Bugs/Comments”, createHTMLHelpPanel(“BugReportingHelp.html”));   
         tabbedPane.addTab(“Acknowledgements”, createHTMLHelpPanel(“Acknowledgements.html”));
         tabbedPane.addTab(“Instruction Set Song”, createHTMLHelpPanel(“MIPSInstructionSetSong.html”));
         // Create non-modal dialog. Based on java.sun.com “How to Make Dialogs”, DialogDemo.java       
         final JDialog dialog = new JDialog(mainUI, “MARS “+Globals.version+” Help”);
        // assure the dialog goes away if user clicks the X
         dialog.addWindowListener(
                new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                     dialog.setVisible(false);
                     dialog.dispose();
                  }
               });
         //Add a “close” button to the non-modal help dialog.
         JButton closeButton = new JButton(“Close”);
         closeButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     dialog.setVisible(false);
                     dialog.dispose();
                  }
               });
         JPanel closePanel = new JPanel();
         closePanel.setLayout(new BoxLayout(closePanel,BoxLayout.LINE_AXIS));
         closePanel.add(Box.createHorizontalGlue());
         closePanel.add(closeButton);
         closePanel.add(Box.createHorizontalGlue());
         closePanel.setBorder(BorderFactory.createEmptyBorder(0,0,5,5));
         JPanel contentPane = new JPanel();
         contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.PAGE_AXIS));
         contentPane.add(tabbedPane);
         contentPane.add(Box.createRigidArea(new Dimension(0,5)));
         contentPane.add(closePanel);
         contentPane.setOpaque(true);
         dialog.setContentPane(contentPane);      
         //Show it.
         dialog.setSize(this.getSize());
         dialog.setLocationRelativeTo(mainUI);
         dialog.setVisible(true);
      
      //////////////////////////////////////////////////////////////////
      }
    
    
    // Create panel containing Help Info read from html document.
       private JPanel createHTMLHelpPanel(String filename) {
         JPanel helpPanel = new JPanel(new BorderLayout());
         JScrollPane helpScrollPane;
         JEditorPane helpDisplay;  
         try {
            InputStream is = this.getClass().getResourceAsStream(Globals.helpPath+filename);
            BufferedReader in = new BufferedReader(new InputStreamReader(is));        
            String line;
            StringBuffer text = new StringBuffer();
            while ( (line=in.readLine()) != null ) {
               text.append(line+”\n”);
            }
            in.close();
            helpDisplay = new JEditorPane(“text/html”,text.toString());
            helpDisplay.setEditable(false);
            helpDisplay.setCaretPosition(0); // assure top of document displayed
            helpScrollPane = new JScrollPane(helpDisplay, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            helpDisplay.addHyperlinkListener(new HelpHyperlinkListener());
         } 
             catch (Exception ie) {
               helpScrollPane = new JScrollPane(
                       new JLabel(“Error (“+ie+”): “+filename+” contents could not be loaded.”));
            }
         helpPanel.add(helpScrollPane);
         return helpPanel;
      }     
   
        
    // Set up the copyright notice for display.
       private JPanel createCopyrightInfoPanel() {
         JPanel marsCopyrightInfo = new JPanel(new BorderLayout());
         JScrollPane marsCopyrightScrollPane;
         JEditorPane marsCopyrightDisplay;  
         try {
            InputStream is = this.getClass().getResourceAsStream(“/MARSlicense.txt”);
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer text = new StringBuffer(“

");
            while ( (line=in.readLine()) != null ) {
               text.append(line+"\n");
            }
            in.close();
            text.append("

“);        
            marsCopyrightDisplay = new JEditorPane(“text/html”,text.toString());
            marsCopyrightDisplay.setEditable(false);
            marsCopyrightDisplay.setCaretPosition(0); // assure top of document displayed
            marsCopyrightScrollPane = new JScrollPane(marsCopyrightDisplay, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         }
             catch (Exception ioe) {
               marsCopyrightScrollPane = new JScrollPane(
                       new JLabel(“Error: license contents could not be loaded.”));
            }
         marsCopyrightInfo.add(marsCopyrightScrollPane);
         return marsCopyrightInfo;
      }
    
    // Set up MARS help tab.  Subtabs get their contents from HTML files.
       private JPanel createMarsHelpInfoPanel() {
         JPanel marsHelpInfo = new JPanel(new BorderLayout());
         JTabbedPane tabbedPane = new JTabbedPane();
         tabbedPane.addTab(“Intro”, createHTMLHelpPanel(“MarsHelpIntro.html”));
         tabbedPane.addTab(“IDE”, createHTMLHelpPanel(“MarsHelpIDE.html”));
         tabbedPane.addTab(“Debugging”, createHTMLHelpPanel(“MarsHelpDebugging.html”));
         tabbedPane.addTab(“Settings”, createHTMLHelpPanel(“MarsHelpSettings.html”));
         tabbedPane.addTab(“Tools”, createHTMLHelpPanel(“MarsHelpTools.html”));
         tabbedPane.addTab(“Command”, createHTMLHelpPanel(“MarsHelpCommand.html”));
         tabbedPane.addTab(“Limits”, createHTMLHelpPanel(“MarsHelpLimits.html”));
         tabbedPane.addTab(“History”, createHTMLHelpPanel(“MarsHelpHistory.html”));
         marsHelpInfo.add(tabbedPane);
         return marsHelpInfo;
      }
    
        
    // Set up MIPS help tab.  Most contents are generated from instruction set info.
       private JPanel createMipsHelpInfoPanel() {
         JPanel mipsHelpInfo = new JPanel(new BorderLayout());
         String helpRemarksColor = “CCFF99”;
       // Introductory remarks go at the top as a label
         String helpRemarks = 
            “

“+// width=”+this.getSize().getWidth()+”>”+
            “

“+
              “  Operand Key for Example Instructions  

“+
            “

“+
            “

“+
               “

label, target any textual label

“+
            “ “+
               “

$t1, $t2, $t3 any integer register

” +
            “ “+
               “

$f2, $f4, $f6 even-numbered floating point register

“+
            “ “+
               “

$f0, $f1, $f3 any floating point register

“+
            “ “+
               “

$8 any Coprocessor 0 register

“+
            “ “+
               “

1 condition flag (0 to 7)

” +
            “ “+
               “

10 unsigned 5-bit integer (0 to 31)

“+
            “ ” +
               “

-100 signed 16-bit integer (-32768 to 32767)

” + 
            “ ” +
               “

100 unsigned 16-bit integer (0 to 65535)

” + 
            “ ” +
               “

100000 signed 32-bit integer (-2147483648 to 2147483647)

” +
            “ ” +
            “ ” +
               “Load & Store addressing mode, basic instructions

” +
            “ ” +
               “

-100($t2) sign-extended 16-bit integer added to contents of $t2

” + 
            “ ” +
            “ ” +
               “Load & Store addressing modes, pseudo instructions

” + 
            “ ” +
               “

($t2) contents of $t2

” + 
            “ ” +
               “

-100 signed 16-bit integer

” + 
            “ ” +
               “

100 unsigned 16-bit integer

” + 
            “ ” +
               “

100000 signed 32-bit integer

” +
            “ ” +
               “

100($t2) zero-extended unsigned 16-bit integer added to contents of $t2

” + 
            “ ” +
               “

100000($t2) signed 32-bit integer added to contents of $t2

” + 
            “ ” +
               “

label 32-bit address of label

” + 
            “ ” +
               “

label($t2) 32-bit address of label added to contents of $t2

” + 
            “ ” +
               “

label+100000 32-bit integer added to label’s address

” + 
            “ ” +
               “

label+100000($t2)    sum of 32-bit integer, label’s address, and contents of $t2

“+
            “

” +
            “

“;
        // Original code:         mipsHelpInfo.add(new JLabel(helpRemarks, JLabel.CENTER), BorderLayout.NORTH);
         JLabel helpRemarksLabel = new JLabel(helpRemarks, JLabel.CENTER);
         helpRemarksLabel.setOpaque(true);
         helpRemarksLabel.setBackground(Color.decode(“0x”+helpRemarksColor));
         JScrollPane operandsScrollPane = new JScrollPane(helpRemarksLabel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
         mipsHelpInfo.add(operandsScrollPane, BorderLayout.NORTH);
         // Below the label is a tabbed pane with categories of MIPS help
         JTabbedPane tabbedPane = new JTabbedPane();
         tabbedPane.addTab(“Basic Instructions”, createMipsInstructionHelpPane(“mars.mips.instructions.BasicInstruction”));
         tabbedPane.addTab(“Extended (pseudo) Instructions”, createMipsInstructionHelpPane(“mars.mips.instructions.ExtendedInstruction”));
         tabbedPane.addTab(“Directives”, createMipsDirectivesHelpPane());
         tabbedPane.addTab(“Syscalls”, createHTMLHelpPanel(“SyscallHelp.html”));
         tabbedPane.addTab(“Exceptions”, createHTMLHelpPanel(“ExceptionsHelp.html”));
         tabbedPane.addTab(“Macros”, createHTMLHelpPanel(“MacrosHelp.html”));
         operandsScrollPane.setPreferredSize(new Dimension((int)this.getSize().getWidth(), (int) (this.getSize().getHeight()*.2)));
         operandsScrollPane.getVerticalScrollBar().setUnitIncrement(10);
         tabbedPane.setPreferredSize(new Dimension((int)this.getSize().getWidth(), (int) (this.getSize().getHeight()*.6)));
         JSplitPane splitsville = new JSplitPane(JSplitPane.VERTICAL_SPLIT, operandsScrollPane, tabbedPane);
         splitsville.setOneTouchExpandable(true);
         splitsville.resetToPreferredSizes();
         mipsHelpInfo.add(splitsville);
         //mipsHelpInfo.add(tabbedPane);
         return mipsHelpInfo;
      }
    
    ///////////////  Methods to construct MIPS help tabs from internal MARS objects  //////////////
                 
       /////////////////////////////////////////////////////////////////////////////
       private JScrollPane createMipsDirectivesHelpPane() {
         Vector exampleList = new Vector();
         String blanks = ”            “;  // 12 blanks
         Directives direct;
         Iterator it = Directives.getDirectiveList().iterator();
         while (it.hasNext()) {
            direct = (Directives)it.next();
            exampleList.add(direct.toString()
                            + blanks.substring(0,Math.max(0,blanks.length()-direct.toString().length()))
                                  + direct.getDescription());
         }
         Collections.sort(exampleList);
         JList examples = new JList(exampleList);
         JScrollPane mipsScrollPane = new JScrollPane(examples,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
         examples.setFont(new Font(“Monospaced”,Font.PLAIN,12));
         return mipsScrollPane;
      }
    
     ////////////////////////////////////////////////////////////////////////////
       private JScrollPane createMipsInstructionHelpPane(String instructionClassName) {
         ArrayList instructionList = Globals.instructionSet.getInstructionList();
         Vector exampleList = new Vector(instructionList.size());
         Iterator it = instructionList.iterator();
         Instruction instr;
         String blanks = ”                        “;  // 24 blanks
         Class instructionClass;
         while (it.hasNext()) {
            instr = (Instruction) it.next();
            try {
               if (Class.forName(instructionClassName).isInstance(instr)) {
                  exampleList.add(instr.getExampleFormat() 
                                + blanks.substring(0,Math.max(0,blanks.length()-instr.getExampleFormat().length()))
                                  + instr.getDescription());
               }
            }
                catch (ClassNotFoundException cnfe) {
                  System.out.println(cnfe+” “+instructionClassName);
               }
         }
         Collections.sort(exampleList);
         JList examples = new JList(exampleList);
         JScrollPane mipsScrollPane = new JScrollPane(examples,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
         examples.setFont(new Font(“Monospaced”,Font.PLAIN,12));
         examples.setCellRenderer(new MyCellRenderer());
         return mipsScrollPane;
      }
 

       private class MyCellRenderer extends JLabel implements ListCellRenderer {    
      // This is the only method defined by ListCellRenderer. 
      // We just reconfigure the JLabel each time we’re called. 
          public Component getListCellRendererComponent( 
             JList list, // the list 
          Object value, // value to display 
          int index, // cell index 
          boolean isSelected, // is the cell selected 
          boolean cellHasFocus) // does the cell have focus 
         { 
            String s = value.toString(); 
                setText(s); 
            if (isSelected) { 
               setBackground(list.getSelectionBackground()); 
               setForeground(list.getSelectionForeground()); 
            } 
            else {
               setBackground((index % 2 == 0) ? altBackgroundColor : list.getBackground()); 
               setForeground(list.getForeground());
            } 
            setEnabled(list.isEnabled()); 
            setFont(list.getFont()); 
            setOpaque(true); 
            return this; 
         } 
      }             
   
    /*
     *  Determines MARS response when user click on hyperlink in displayed help page.
     *  The response will be to pop up a simple dialog with the page contents.  It
     *  will not display URL, no navigation, nothing.  Just display the page and 
     *  provide a Close button.
     */
       private class HelpHyperlinkListener implements HyperlinkListener {
         JDialog webpageDisplay;
         JTextField webpageURL;
         private static final String cannotDisplayMessage =
            “Unable to display requested document.“;
          public void hyperlinkUpdate(HyperlinkEvent e) { 
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { 
               JEditorPane pane = (JEditorPane) e.getSource();
               if (e instanceof HTMLFrameHyperlinkEvent) { 
                  HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e; 
                  HTMLDocument doc = (HTMLDocument)pane.getDocument(); 
                  doc.processHTMLFrameHyperlinkEvent(evt); 
               } 
               else {
                  webpageDisplay = new JDialog(mainUI, “Primitive HTML Viewer”);
                  webpageDisplay.setLayout(new BorderLayout());
                  webpageDisplay.setLocation(mainUI.getSize().width/6, mainUI.getSize().height/6);
                  JEditorPane webpagePane;
                  try { 
                     webpagePane = new JEditorPane(e.getURL());
                  } 
                      catch (Throwable t) {
                        webpagePane = new JEditorPane(“text/html”,cannotDisplayMessage);
                     }
                  webpagePane.addHyperlinkListener(
                         new HyperlinkListener() {
                            public void hyperlinkUpdate(HyperlinkEvent e) {
                              if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                 JEditorPane pane = (JEditorPane) e.getSource();
                                 if (e instanceof HTMLFrameHyperlinkEvent) { 
                                    HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e; 
                                    HTMLDocument doc = (HTMLDocument)pane.getDocument(); 
                                    doc.processHTMLFrameHyperlinkEvent(evt); 
                                 } 
                                 else { 
                                    try { 
                                       pane.setPage(e.getURL()); 
                                    } 
                                        catch (Throwable t) {
                                          pane.setText(cannotDisplayMessage);
                                       }
                                    webpageURL.setText(e.getURL().toString());
                                 }
                              }
                           }        
                        });
                  webpagePane.setPreferredSize(new Dimension(mainUI.getSize().width*2/3, mainUI.getSize().height*2/3));
                  webpagePane.setEditable(false);
                  webpagePane.setCaretPosition(0);
                  JScrollPane webpageScrollPane = new JScrollPane(webpagePane, 
                                      JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                      JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                  webpageURL = new JTextField(e.getURL().toString(), 50);
                  webpageURL.setEditable(false);
                  webpageURL.setBackground(Color.WHITE);
                  JPanel URLPanel= new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 4));
                  URLPanel.add(new JLabel(“URL: “));
                  URLPanel.add(webpageURL);
                  webpageDisplay.add(URLPanel, BorderLayout.NORTH);
                  webpageDisplay.add(webpageScrollPane);
                  JButton closeButton = new JButton(“Close”);
                  closeButton.addActionListener(
                         new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                              webpageDisplay.setVisible(false);
                              webpageDisplay.dispose();
                           }
                        });
                  JPanel closePanel = new JPanel();
                  closePanel.setLayout(new BoxLayout(closePanel,BoxLayout.LINE_AXIS));
                  closePanel.setBorder(BorderFactory.createEmptyBorder(0,0,5,5));
                  closePanel.add(Box.createHorizontalGlue());
                  closePanel.add(closeButton);
                  closePanel.add(Box.createHorizontalGlue());
                  webpageDisplay.add(closePanel,BorderLayout.SOUTH);
                  webpageDisplay.pack();
                  webpageDisplay.setVisible(true);
               }
            } 
         }
      }
   }

DataSegmentWindow$MyTippedJTable

package mars.venus;
synchronized class DataSegmentWindow$MyTippedJTable extends javax.swing.JTable {
private String[] columnToolTips;
void DataSegmentWindow$MyTippedJTable(DataSegmentWindow, DataSegmentWindow$DataTableModel);
protected javax.swing.table.JTableHeader createDefaultTableHeader();
}

SettingsMemoryConfigurationAction$MemoryConfigurationDialog$4

package mars.venus;
synchronized class SettingsMemoryConfigurationAction$MemoryConfigurationDialog$4 implements java.awt.event.ActionListener {
void SettingsMemoryConfigurationAction$MemoryConfigurationDialog$4(SettingsMemoryConfigurationAction$MemoryConfigurationDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

AbstractFontSettingDialog$2

package mars.venus;
synchronized class AbstractFontSettingDialog$2 implements javax.swing.event.ChangeListener {
void AbstractFontSettingDialog$2(AbstractFontSettingDialog);
public void stateChanged(javax.swing.event.ChangeEvent);
}

SettingsExceptionHandlerAction$2

package mars.venus;
synchronized class SettingsExceptionHandlerAction$2 implements java.awt.event.ActionListener {
void SettingsExceptionHandlerAction$2(SettingsExceptionHandlerAction);
public void actionPerformed(java.awt.event.ActionEvent);
}

SettingsEditorAction$EditorFontDialog$3

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog$3 implements java.awt.event.ActionListener {
void SettingsEditorAction$EditorFontDialog$3(SettingsEditorAction$EditorFontDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

Coprocessor0Window$RegTableModel

package mars.venus;
synchronized class Coprocessor0Window$RegTableModel extends javax.swing.table.AbstractTableModel {
final String[] columnNames;
Object[][] data;
public void Coprocessor0Window$RegTableModel(Coprocessor0Window, Object[][]);
public int getColumnCount();
public int getRowCount();
public String getColumnName(int);
public Object getValueAt(int, int);
public Class getColumnClass(int);
public boolean isCellEditable(int, int);
public void setValueAt(Object, int, int);
private void setDisplayAndModelValueAt(Object, int, int);
private void printDebugData();
}

mars/venus/EditCutAction.java
mars/venus/EditCutAction.java   package mars.venus;
   import mars.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the Edit -> Cut menu item
    */              
    public class EditCutAction extends GuiAction {
     
       public EditCutAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
          
       public void actionPerformed(ActionEvent e){
            mainUI.getMainPane().getEditPane().cutText();
      }
   }

MessagesPane$Asker$1

package mars.venus;
synchronized class MessagesPane$Asker$1 implements javax.swing.event.DocumentListener {
void MessagesPane$Asker$1(MessagesPane$Asker);
public void insertUpdate(javax.swing.event.DocumentEvent);
public void removeUpdate(javax.swing.event.DocumentEvent);
public void changedUpdate(javax.swing.event.DocumentEvent);
}

RunClearBreakpointsAction

package mars.venus;
public synchronized class RunClearBreakpointsAction extends GuiAction implements javax.swing.event.TableModelListener {
public void RunClearBreakpointsAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
public void tableChanged(javax.swing.event.TableModelEvent);
}

DataSegmentWindow$5

package mars.venus;
synchronized class DataSegmentWindow$5 implements java.awt.event.ActionListener {
void DataSegmentWindow$5(DataSegmentWindow);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/RepeatButton.java
mars/venus/RepeatButton.javapackage mars.venus;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;
 
/////////////////////////////  CREDIT  /////////////////////////////////////
// http://forums.sun.com/thread.jspa?threadID=499183&messageID=2505646
// bsampieri, 4 March 2004
// Java Developer Forum, Useful Code of the Day: Button Fires Events While Held
// Adopted/adapted by DPS 20 July 2008
//
// This is NOT one of the MARS buttons!  It is a subclass of JButton that can
// be used to create buttons that fire events after being held down for a 
// specified period of time and at a specified rate. 
 
/**
 * RepeatButton is a JButton which contains a timer 
 * for firing events while the button is held down.  There is a default 
 * initial delay of 300ms before the first event is fired and a 60ms delay 
 * between subsequent events.  When the user holds the button down and moves 
 * the mouse out from over the button, the timer stops, but if the user moves 
 * the mouse back over the button without having released the mouse button, 
 * the timer starts up again at the same delay rate.  If the enabled state is 
 * changed while the timer is active, it will be stopped. 
 * 
 * NOTE:  The normal button behavior is that the action event is fired after 
 * the button is released.  It may be important to konw then that this is 
 * still the case.  So in effect, listeners will get 1 more event then what 
 * the internal timer fires.  It’s not a “bug”, per se, just something to be 
 * aware of.  There seems to be no way to suppress the final event from 
 * firing anyway, except to process all ActionListeners internally.  But 
 * realistically, it probably doesn’t matter.  
 */
public class RepeatButton extends JButton 
        implements ActionListener, MouseListener {
    /**
     * The pressed state for this button.
     */
    private boolean pressed = false;
 
    /**
     * Flag to indicate that the button should fire events when held.  
     * If false, the button is effectively a plain old JButton, but 
     * there may be times when this feature might wish to be disabled.  
     */
    private boolean repeatEnabled = true;
 
    /**
     * The hold-down timer for this button.
     */
    private Timer timer = null;
 

    /**
     * The initial delay for this button.  Hold-down time before first
     * timer firing.  In milliseconds.
     */
    private int initialDelay = 300;
    
    /**
     * The delay between timer firings for this button once the delay
     * period is past. In milliseconds.
     */
    private int delay = 60;
 

 
    /**
     * Holder of the modifiers used when the mouse pressed the button.  
     * This is used for subsequently fired action events.  This may change 
     * after mouse pressed if the user moves the mouse out, releases a key 
     * and then moves the mouse back in.  
     */
    private int modifiers = 0;
 
    /**
     * Creates a button with no set text or icon.
     */
    public RepeatButton() {
        super();
        init();
    }
 
    /**
     * Creates a button where properties are taken from the Action supplied.
     * 
     * @param  a  the button action
     */
    public RepeatButton(Action a) {
        super(a);
        init();
    }
 
    /**
     * Creates a button with an icon.
     * 
     * @param  icon  the button icon
     */
    public RepeatButton(Icon icon) {
        super(icon);
        init();
    }
 
    /**
     * Creates a button with text.
     * 
     * @param  text  the button text
     */
    public RepeatButton(String text) {
        super(text);
        init();
    }
 
    /**
     * Creates a button with initial text and an icon.
     * 
     * @param  text  the button text
     * @param  icon  the button icon
     */
    public RepeatButton(String text, Icon icon) {
        super(text, icon);
        init();
    }
 
    /**
     * Initializes the button.
     */
    private void init() {
        this.addMouseListener(this);
        // initialize timers for button holding…
        this.timer = new Timer(this.delay, this);
        this.timer.setRepeats(true);
    }
 
    /**
     * Gets the delay for the timer of this button.  
     * 
     * @return  the delay
     */
    public int getDelay() {
        return this.delay;
    }
 
    /**
     * Set the delay for the timer of this button.  
     * 
     * @param  d  the delay
     */
    public void setDelay(int d) {
        this.delay = d;
    }
 
    /**
     * Gets the initial delay for the timer of this button.  
     * 
     * @return  the initial delay
     */
    public int getInitialDelay() {
        return this.initialDelay;
    }
 
    /**
     * Sets the initial delay for the timer of this button.  
     * 
     * @param  d  the initial delay
     */
    public void setInitialDelay(int d) {
        this.initialDelay = d;
    }
 
    /**
     * Checks if the button should fire events when held.  If false, the 
     * button is effectively a plain old JButton, but there may be times 
     * when this feature might wish to be disabled.  
     * 
     * @return  if true, the button should fire events when held
     */
    public boolean isRepeatEnabled() {
        return this.repeatEnabled;
    }
 
    /**
     * Sets if the button should fire events when held.  If false, the 
     * button is effectively a plain old JButton, but there may be times 
     * when this feature might wish to be disabled.  If false, it will 
     * also stop the timer if it’s running.
     * 
     * @param  en  if true, the button should fire events when held
     */
    public void setRepeatEnabled(boolean en) {
        if(!en) {
            this.pressed = false;
            if(timer.isRunning()) {
                timer.stop();
            }
        }
        this.repeatEnabled = en;
    }
 
    /**
     * Sets the enabled state of this button.  Overridden to stop the timer 
     * if it’s running.
     * 
     * @param  en  if true, enables the button
     */
    public void setEnabled(boolean en) {
        if(en != super.isEnabled()) {
            this.pressed = false;
            if(timer.isRunning()) {
                timer.stop();
            }
        }
        super.setEnabled(en);
    }
 
    /**
     * Handle action events. OVERRIDE THIS IN SUBCLASS!
     *
     * @param  ae  the action event
     */
    public void actionPerformed(ActionEvent ae) {
        // process events only from this components
        if(ae.getSource() == this.timer) {
            ActionEvent event = new ActionEvent(
                this, ActionEvent.ACTION_PERFORMED, 
                super.getActionCommand(), this.modifiers);
            super.fireActionPerformed(event); 
        }
        // testing code…
        else if(testing && ae.getSource() == this) {
            System.out.println(ae.getActionCommand());
        }
    }
 
    /**
     * Handle mouse clicked events.
     *
     * @param  me  the mouse event
     */
    public void mouseClicked(MouseEvent me) {
        // process events only from this components
        if(me.getSource() == this) {
            this.pressed = false;
            if(this.timer.isRunning()) {
                this.timer.stop();
            }
        }
    }
 
    /**
     * Handle mouse pressed events.
     *
     * @param  me  the mouse event
     */
    public void mousePressed(MouseEvent me) {
        // process events only from this components
        if(me.getSource() == this && this.isEnabled() && this.isRepeatEnabled()) {
            this.pressed = true;
            if(!this.timer.isRunning()) {
                this.modifiers = me.getModifiers();
                this.timer.setInitialDelay(this.initialDelay);
                this.timer.start();
            }
        }
    }
 
    /**
     * Handle mouse released events.
     *
     * @param  me  the mouse event
     */
    public void mouseReleased(MouseEvent me) {
        // process events only from this components
        if(me.getSource() == this) {
            this.pressed = false;
            if(this.timer.isRunning()) {
                this.timer.stop();
            }
        }
    }
 
    /**
     * Handle mouse entered events.
     *
     * @param  me  the mouse event
     */
    public void mouseEntered(MouseEvent me) {
        // process events only from this components
        if(me.getSource() == this && this.isEnabled() && this.isRepeatEnabled()) {
            if(this.pressed && !this.timer.isRunning()) {
                this.modifiers = me.getModifiers();
                this.timer.setInitialDelay(this.delay);
                this.timer.start();
            }
        }
    }
 
    /**
     * Handle mouse exited events.
     *
     * @param  me  the mouse event
     */
    public void mouseExited(MouseEvent me) {
        // process events only from this components
        if(me.getSource() == this) {
            if(this.timer.isRunning()) {
                this.timer.stop();
            }
        }
    }
 
    /**
     * Testing flag.  Set in main method.
     */
    private static boolean testing = false;
 
    /**
     * Main method, for testing.  Creates a frame with both styles of menu.
     *
     * @param  args  the command-line arguments
     */
    public static void main(String[] args) {
        testing = true;
        JFrame f = new JFrame(“RepeatButton Test”);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        JPanel p = new JPanel();
        RepeatButton b = new RepeatButton(“hold me”);
        b.setActionCommand(“test”);
        b.addActionListener(b);
        p.add(b);
        f.getContentPane().add(p);
        f.pack();
        f.setVisible(true);
    }
}

HelpHelpAction$HelpHyperlinkListener$2

package mars.venus;
synchronized class HelpHelpAction$HelpHyperlinkListener$2 implements java.awt.event.ActionListener {
void HelpHelpAction$HelpHyperlinkListener$2(HelpHelpAction$HelpHyperlinkListener);
public void actionPerformed(java.awt.event.ActionEvent);
}

SettingsEditorAction$EditorFontDialog$7

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog$7 implements javax.swing.event.ChangeListener {
void SettingsEditorAction$EditorFontDialog$7(SettingsEditorAction$EditorFontDialog);
public void stateChanged(javax.swing.event.ChangeEvent);
}

FileOpenAction

package mars.venus;
public synchronized class FileOpenAction extends GuiAction {
private java.io.File mostRecentlyOpenedFile;
private javax.swing.JFileChooser fileChooser;
private int fileFilterCount;
private java.util.ArrayList fileFilterList;
private java.beans.PropertyChangeListener listenForUserAddedFileFilter;
public void FileOpenAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/FileDumpMemoryAction.java
mars/venus/FileDumpMemoryAction.java   package mars.venus;
   import mars.*;
   import mars.util.*;
   import mars.mips.dump.*;
   import mars.mips.hardware.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.border.*;
   import java.io.*;
   import java.util.*;
   import javax.swing.plaf.basic.*;
    
    /*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the File -> Save For Dump Memory menu item
    */              
    public class FileDumpMemoryAction extends GuiAction {
    
      private JDialog dumpDialog;
      private static final String title = “Dump Memory To File”;
   
      // A series of parallel arrays representing the memory segments that can be dumped.
      private String[] segmentArray;         
      private int[] baseAddressArray;      
      private int[] limitAddressArray;
      private int[] highAddressArray;
    // These three are allocated and filled by buildDialogPanel() and used by action listeners.
      private String[] segmentListArray;  
      private int[] segmentListBaseArray; 
      private int[] segmentListHighArray;
     
      private JComboBox segmentListSelector;
      private JComboBox formatListSelector;
       public FileDumpMemoryAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      
      }
   
   
       public void actionPerformed(ActionEvent e){
         dumpMemory();        
      }
    
        /* Save the memory segment in a supported format.
     */
       private boolean dumpMemory() {
         dumpDialog = createDumpDialog();
         dumpDialog.pack();
         dumpDialog.setLocationRelativeTo(Globals.getGui());
         dumpDialog.setVisible(true);   
         return true;
        /////////////////////////////////////////////////////////////////////
      }
    
    
     // The dump dialog that appears when menu item is selected.
       private JDialog createDumpDialog() {
         JDialog dumpDialog = new JDialog(Globals.getGui(), title, true);
         dumpDialog.setContentPane(buildDialogPanel());
         dumpDialog.setDefaultCloseOperation(
                        JDialog.DO_NOTHING_ON_CLOSE);
         dumpDialog.addWindowListener(
                new WindowAdapter() {
                   public void windowClosing(WindowEvent we) {
                     closeDialog();
                  }
               });
         return dumpDialog;
      }
    
     // Set contents of dump dialog.
       private JPanel buildDialogPanel() {
         JPanel contents = new JPanel(new BorderLayout(20,20));
         contents.setBorder(new EmptyBorder(10,10,10,10));
      
         segmentArray = MemoryDump.getSegmentNames();
         baseAddressArray = MemoryDump.getBaseAddresses(segmentArray);
         limitAddressArray = MemoryDump.getLimitAddresses(segmentArray);
         highAddressArray = new int[segmentArray.length];
      
      
      
         segmentListArray = new String[segmentArray.length];
         segmentListBaseArray = new int[segmentArray.length];
         segmentListHighArray = new int[segmentArray.length];
        
         // Calculate the actual highest address to be dumped.  For text segment, this depends on the
        // program length (number of machine code instructions).  For data segment, this depends on
        // how many MARS 4K word blocks have been referenced during assembly and/or execution.
        // Then generate label from concatentation of segmentArray[i], baseAddressArray[i]
        // and highAddressArray[i].  This lets user know exactly what range will be dumped.  Initially not
        // editable but maybe add this later.
        // If there is nothing to dump (e.g. address of first null == base address), then
        // the segment will not be listed.
         int segmentCount = 0;
        
         for (int i=0; i= baseAddressArray[i]) {
               segmentListBaseArray[segmentCount] = baseAddressArray[i];
               segmentListHighArray[segmentCount] = highAddressArray[i];
               segmentListArray[segmentCount] = 
                       segmentArray[i] + ” (” + Binary.intToHexString(baseAddressArray[i]) + 
                       ” – ” + Binary.intToHexString(highAddressArray[i]) + “)”;
               segmentCount++;
            }
         }
        
        // It is highly unlikely that no segments remain after the null check, since 
        // there will always be at least one instruction (.text segment has one non-null).
        // But just in case…
         if (segmentCount == 0) {
            contents.add(new Label(“There is nothing to dump!”), BorderLayout.NORTH);
            JButton OKButton = new JButton(“OK”);
            OKButton.addActionListener(
                   new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        closeDialog();
                     }
                  });
            contents.add(OKButton, BorderLayout.SOUTH);
            return contents;
         }
          
        // This is needed to assure no null array elements in ComboBox list.
         if (segmentCount < segmentListArray.length) {             String[] tempArray = new String[segmentCount];             System.arraycopy(segmentListArray, 0, tempArray, 0, segmentCount);             segmentListArray = tempArray;          }                  // Create segment selector.  First element selected by default.          segmentListSelector = new JComboBox(segmentListArray);          segmentListSelector.setSelectedIndex(0);            JPanel segmentPanel = new JPanel(new BorderLayout());          segmentPanel.add(new Label("Memory Segment"), BorderLayout.NORTH);          segmentPanel.add(segmentListSelector);          contents.add(segmentPanel, BorderLayout.WEST);                   // Next, create list of all available dump formats.          ArrayList dumpFormats = (new DumpFormatLoader()).loadDumpFormats();          formatListSelector = new JComboBox(dumpFormats.toArray());          formatListSelector.setRenderer(new DumpFormatComboBoxRenderer(formatListSelector));          formatListSelector.setSelectedIndex(0);            JPanel formatPanel = new JPanel(new BorderLayout());          formatPanel.add(new Label("Dump Format"), BorderLayout.NORTH);          formatPanel.add(formatListSelector);          contents.add(formatPanel, BorderLayout.EAST);                // Bottom row - the control buttons for Dump and Cancel          Box controlPanel = Box.createHorizontalBox();          JButton dumpButton = new JButton("Dump To File...");          dumpButton.addActionListener(                 new ActionListener() {                    public void actionPerformed(ActionEvent e) {                      if (performDump(segmentListBaseArray[segmentListSelector.getSelectedIndex()],                                   segmentListHighArray[segmentListSelector.getSelectedIndex()],                                      (DumpFormat)formatListSelector.getSelectedItem())) {                         closeDialog();                      }                   }                });          JButton cancelButton = new JButton("Cancel");          cancelButton.addActionListener(                 new ActionListener() {                    public void actionPerformed(ActionEvent e) {                      closeDialog();                   }                });            controlPanel.add(Box.createHorizontalGlue());          controlPanel.add(dumpButton);          controlPanel.add(Box.createHorizontalGlue());          controlPanel.add(cancelButton);          controlPanel.add(Box.createHorizontalGlue());          contents.add(controlPanel,BorderLayout.SOUTH);          return contents;       }            // User has clicked "Dump" button, so launch a file chooser then get     // segment (memory range) and format selections and save to the file.        private boolean performDump(int firstAddress, int lastAddress, DumpFormat format) {            File theFile = null;          JFileChooser saveDialog = null;          boolean operationOK = false;                 saveDialog = new JFileChooser(mainUI.getEditor().getCurrentSaveDirectory());          saveDialog.setDialogTitle(title);          while (!operationOK) {             int decision = saveDialog.showSaveDialog(mainUI);             if (decision != JFileChooser.APPROVE_OPTION) {                return false;             }             theFile = saveDialog.getSelectedFile();             operationOK = true;             if (theFile.exists()) {                int overwrite = JOptionPane.showConfirmDialog(mainUI,                      "File "+theFile.getName()+" already exists.  Do you wish to overwrite it?",                      "Overwrite existing file?",                      JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);                switch (overwrite) {                   case JOptionPane.YES_OPTION :                      operationOK = true;                      break;                   case JOptionPane.NO_OPTION :                      operationOK = false;                      break;                   case JOptionPane.CANCEL_OPTION :                      return false;                   default : // should never occur                      return false;                }             }             if (operationOK) {                try {                   format.dumpMemoryRange(theFile, firstAddress, lastAddress);                }                     catch (AddressErrorException aee) {                                      }                     catch (IOException ioe) {                   }             }          }          return true;       }          // We're finished with this modal dialog.        private void closeDialog() {          dumpDialog.setVisible(false);          dumpDialog.dispose();       }               // Display tool tip for dump format list items.  Got the technique from     // http://forum.java.sun.com/thread.jspa?threadID=488762&messageID=2292482             private class DumpFormatComboBoxRenderer extends BasicComboBoxRenderer {          private JComboBox myMaster;                     public DumpFormatComboBoxRenderer(JComboBox myMaster) {             super();             this.myMaster = myMaster;          }                     public Component getListCellRendererComponent( JList list, Object value, int index,                                                        boolean isSelected, boolean cellHasFocus) {              super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);              setToolTipText(value.toString());             if (index >=0 && ((DumpFormat)(myMaster.getItemAt(index))).getDescription() != null) {
               setToolTipText(((DumpFormat)(myMaster.getItemAt(index))).getDescription());
            }
            return this;
         } 
      }
   
   
   }

RegistersWindow$RegisterCellRenderer

package mars.venus;
synchronized class RegistersWindow$RegisterCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
private java.awt.Font font;
private int alignment;
public void RegistersWindow$RegisterCellRenderer(RegistersWindow, java.awt.Font, int);
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable, Object, boolean, boolean, int, int);
}

SettingsHighlightingAction$FontSettingDialog

package mars.venus;
synchronized class SettingsHighlightingAction$FontSettingDialog extends AbstractFontSettingDialog {
private boolean resultOK;
public void SettingsHighlightingAction$FontSettingDialog(SettingsHighlightingAction, java.awt.Frame, String, java.awt.Font);
private java.awt.Font showDialog();
protected void closeDialog();
private void performOK();
private void performCancel();
protected java.awt.Component buildControlPanel();
protected void apply(java.awt.Font);
}

DataSegmentWindow$1

package mars.venus;
synchronized class DataSegmentWindow$1 implements java.awt.event.ActionListener {
void DataSegmentWindow$1(DataSegmentWindow);
public void actionPerformed(java.awt.event.ActionEvent);
}

FileDumpMemoryAction$1

package mars.venus;
synchronized class FileDumpMemoryAction$1 extends java.awt.event.WindowAdapter {
void FileDumpMemoryAction$1(FileDumpMemoryAction);
public void windowClosing(java.awt.event.WindowEvent);
}

SettingsMemoryConfigurationAction

package mars.venus;
public synchronized class SettingsMemoryConfigurationAction extends GuiAction {
javax.swing.JDialog configDialog;
javax.swing.JComboBox fontFamilySelector;
javax.swing.JComboBox fontStyleSelector;
javax.swing.JSlider fontSizeSelector;
javax.swing.JTextField fontSizeDisplay;
SettingsMemoryConfigurationAction thisAction;
String initialFontFamily;
String initialFontStyle;
String initialFontSize;
public void SettingsMemoryConfigurationAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

SettingsDelayedBranchingAction

package mars.venus;
public synchronized class SettingsDelayedBranchingAction extends GuiAction {
public void SettingsDelayedBranchingAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

MessagesPane

package mars.venus;
public synchronized class MessagesPane extends javax.swing.JTabbedPane {
javax.swing.JTextArea assemble;
javax.swing.JTextArea run;
javax.swing.JPanel assembleTab;
javax.swing.JPanel runTab;
public static final int MAXIMUM_SCROLLED_CHARACTERS;
public static final int NUMBER_OF_CHARACTERS_TO_CUT;
static void ();
public void MessagesPane();
private javax.swing.Box createBoxForButton(javax.swing.JButton);
public void selectErrorMessage(String, int, int);
public void selectEditorTextLine(String, int, int);
public javax.swing.JTextArea getAssembleTextArea();
public javax.swing.JTextArea getRunTextArea();
public void postMarsMessage(String);
public void postRunMessage(String);
public void selectMarsMessageTab();
public void selectRunMessageTab();
public String getInputString(String);
public String getInputString(int);
}

SettingsEditorAction$EditorFontDialog$DefaultChanger

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog$DefaultChanger implements java.awt.event.ItemListener {
private int row;
public void SettingsEditorAction$EditorFontDialog$DefaultChanger(SettingsEditorAction$EditorFontDialog, int);
public void itemStateChanged(java.awt.event.ItemEvent);
}

mars/venus/FileSaveAllAction.java
mars/venus/FileSaveAllAction.java   package mars.venus;
   import mars.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
 
 /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
 
    /**
    * Action  for the File -> Close All menu item
    */              
    public class FileSaveAllAction extends GuiAction {
     
       public FileSaveAllAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
    
       public void actionPerformed(ActionEvent e){
              mainUI.editor.saveAll();
      }
   }

RunBackstepAction

package mars.venus;
public synchronized class RunBackstepAction extends GuiAction {
String name;
ExecutePane executePane;
public void RunBackstepAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

EditTabbedPane$FileOpener

package mars.venus;
synchronized class EditTabbedPane$FileOpener {
private java.io.File mostRecentlyOpenedFile;
private javax.swing.JFileChooser fileChooser;
private int fileFilterCount;
private java.util.ArrayList fileFilterList;
private java.beans.PropertyChangeListener listenForUserAddedFileFilter;
private Editor theEditor;
public void EditTabbedPane$FileOpener(EditTabbedPane, Editor);
private boolean openFile();
private boolean openFile(java.io.File);
private void setChoosableFileFilters();
}

RunSpeedPanel$RunSpeedListener

package mars.venus;
synchronized class RunSpeedPanel$RunSpeedListener implements javax.swing.event.ChangeListener {
private void RunSpeedPanel$RunSpeedListener(RunSpeedPanel);
public void stateChanged(javax.swing.event.ChangeEvent);
}

mars/venus/EditCopyAction.java
mars/venus/EditCopyAction.java   package mars.venus;
   import mars.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the Edit -> Copy menu item
    */              
    public class EditCopyAction extends GuiAction {
     
       public EditCopyAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
          
       public void actionPerformed(ActionEvent e){
            mainUI.getMainPane().getEditPane().copyText();
      }
   }

TextSegmentWindow

package mars.venus;
public synchronized class TextSegmentWindow extends javax.swing.JInternalFrame {
private javax.swing.JPanel programArgumentsPanel;
private javax.swing.JTextField programArgumentsTextField;
private static final int PROGRAM_ARGUMENT_TEXTFIELD_COLUMNS = 40;
private javax.swing.JTable table;
private javax.swing.JScrollPane tableScroller;
private Object[][] data;
private int[] intAddresses;
private java.util.Hashtable addressRows;
private java.awt.Container contentPane;
private TextSegmentWindow$TextTableModel tableModel;
private java.awt.Font tableCellFont;
private boolean codeHighlighting;
private boolean breakpointsEnabled;
private int highlightAddress;
private javax.swing.event.TableModelListener tableModelListener;
private boolean inDelaySlot;
private static String[] columnNames;
private static final int BREAK_COLUMN = 0;
private static final int ADDRESS_COLUMN = 1;
private static final int CODE_COLUMN = 2;
private static final int BASIC_COLUMN = 3;
private static final int SOURCE_COLUMN = 4;
private static final java.awt.Font monospacedPlain12Point;
static void ();
public void TextSegmentWindow();
public void setupTable();
public String getProgramArguments();
public void addProgramArgumentsPanel();
public void removeProgramArgumentsPanel();
public void clearWindow();
public void registerTableModelListener(javax.swing.event.TableModelListener);
public void updateCodeAddresses();
public void updateBasicStatements();
int getIntCodeAddressAtRow(int);
public int getBreakpointCount();
public int[] getSortedBreakPointsArray();
public void clearAllBreakpoints();
public void highlightStepAtPC();
public void highlightStepAtPC(boolean);
public void highlightStepAtAddress(int);
public void highlightStepAtAddress(int, boolean);
public void setCodeHighlighting(boolean);
public boolean getCodeHighlighting();
public void unhighlightAllSteps();
void selectStepAtAddress(int);
public void toggleBreakpoints();
private void reorderColumns();
private int findRowForAddress(int);
}

mars/venus/NumberDisplayBaseChooser.java
mars/venus/NumberDisplayBaseChooser.java   package mars.venus;
   import mars.*;
   import mars.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
/**
 * Use to select base for displaying numbers.  Initially the
 * choices are only 10 (decimal) and 16 (hex), so I’m using
 * a check box where checked means hex.  If base 8 (octal) 
 * is added later, the Component will need to change.
 */
 
    public class NumberDisplayBaseChooser extends JCheckBox {
      public static final int DECIMAL = 10;
      public static final int HEXADECIMAL = 16;
      public static final int ASCII = 0;
      private int base;
      private JCheckBoxMenuItem settingMenuItem;
   
   /**
    * constructor. It assumes the text will be worded
    * so that a checked box means hexadecimal!
    * @param text Text to accompany the check box.
    * @param defaultBase Currently either DECIMAL or HEXADECIMAL
    */
       public NumberDisplayBaseChooser(String text, boolean displayInHex) {
         super(text, displayInHex);
         base = getBase(displayInHex);
         addItemListener(
                new  ItemListener() {
                   public void itemStateChanged(ItemEvent ie) {
                     NumberDisplayBaseChooser choose = (NumberDisplayBaseChooser)ie.getItem();
                     if (ie.getStateChange() == ItemEvent.SELECTED) {
                        choose.setBase(NumberDisplayBaseChooser.HEXADECIMAL);
                     } 
                     else {
                        choose.setBase(NumberDisplayBaseChooser.DECIMAL);
                     }
                    // Better to use notify, but I am tired…
                     if (settingMenuItem!=null) {
                        settingMenuItem.setSelected(choose.isSelected());
                        ActionListener[] listeners = settingMenuItem.getActionListeners();
                        ActionEvent event = new ActionEvent(settingMenuItem, 0, “chooser”);
                        for (int i=0; i 0) {
            executePane.getDataSegmentWindow().updateValues();
            executePane.getTextSegmentWindow().highlightStepAtPC();
         }
      }
                    
     // Called when Reset selected.  
       private void resetButtonColors() {
         Settings settings = Globals.getSettings();
         dataHighlightButton.setText(getHighlightControlText(initialDataHighlightSetting));
         registerHighlightButton.setText(getHighlightControlText(initialRegisterHighlightSetting));
         Color backgroundSetting, foregroundSetting;
         Font fontSetting;
         for (int i=0; i Step menu item
    */              
    public class RunStepAction extends GuiAction {
     
      String name;
      ExecutePane executePane;
       public RunStepAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
        /**
             * perform next simulated instruction step.
             */  
       public void actionPerformed(ActionEvent e){
         name = this.getValue(Action.NAME).toString();
         executePane = mainUI.getMainPane().getExecutePane();
         boolean done = false;
         if(FileStatus.isAssembled()){
               if (!mainUI.getStarted()) {  // DPS 17-July-2008
                   processProgramArgumentsIfAny();
                }
            mainUI.setStarted(true);
            mainUI.messagesPane.setSelectedComponent(mainUI.messagesPane.runTab);
            executePane.getTextSegmentWindow().setCodeHighlighting(true);
            try {
               done = Globals.program.simulateStepAtPC(this);
            } 
                catch (ProcessingException ev) {}
         }
         else{
            // note: this should never occur since “Step” is only enabled after successful assembly.
            JOptionPane.showMessageDialog(mainUI,”The program must be assembled before it can be run.”);
         }
      }
      
    // When step is completed, control returns here (from execution thread, indirectly) 
    // to update the GUI.
       public void stepped(boolean done, int reason, ProcessingException pe) {
         executePane.getRegistersWindow().updateRegisters();
         executePane.getCoprocessor1Window().updateRegisters();
         executePane.getCoprocessor0Window().updateRegisters();
         executePane.getDataSegmentWindow().updateValues();
         if (!done) {
            executePane.getTextSegmentWindow().highlightStepAtPC();
            FileStatus.set(FileStatus.RUNNABLE);
         } 
         if (done) {
            RunGoAction.resetMaxSteps();
            executePane.getTextSegmentWindow().unhighlightAllSteps();
            FileStatus.set(FileStatus.TERMINATED);
         }
         if (done && pe == null) {
            mainUI.getMessagesPane().postMarsMessage(
                             “\n”+name+”: execution “+
                                      ((reason==Simulator.CLIFF_TERMINATION) ? “terminated due to null instruction.”
                                                                             : “completed successfully.”)+”\n\n”);
            mainUI.getMessagesPane().postRunMessage(
                             “\n– program is finished running “+
                                      ((reason==Simulator.CLIFF_TERMINATION)? “(dropped off bottom)” : “”) +” –\n\n”);
            mainUI.getMessagesPane().selectRunMessageTab();
         }
         if (pe !=null) {
            RunGoAction.resetMaxSteps();
            mainUI.getMessagesPane().postMarsMessage(
                                pe.errors().generateErrorReport());
            mainUI.getMessagesPane().postMarsMessage(
                                “\n”+name+”: execution terminated with errors.\n\n”);
            mainUI.getRegistersPane().setSelectedComponent(executePane.getCoprocessor0Window());
            FileStatus.set(FileStatus.TERMINATED); // should be redundant.
                                executePane.getTextSegmentWindow().setCodeHighlighting(true);
                executePane.getTextSegmentWindow().unhighlightAllSteps();
            executePane.getTextSegmentWindow().highlightStepAtAddress(RegisterFile.getProgramCounter()-4);
         }
         mainUI.setReset(false);   
      }
        
        ////////////////////////////////////////////////////////////////////////////////////
        // Method to store any program arguments into MIPS memory and registers before
        // execution begins. Arguments go into the gap between $sp and kernel memory.  
        // Argument pointers and count go into runtime stack and $sp is adjusted accordingly.
        // $a0 gets argument count (argc), $a1 gets stack address of first arg pointer (argv).
       private void processProgramArgumentsIfAny() {
         String programArguments = executePane.getTextSegmentWindow().getProgramArguments();
         if (programArguments == null || programArguments.length() == 0 ||
               !Globals.getSettings().getProgramArguments()) {
            return;
         }
            new ProgramArgumentList(programArguments).storeProgramArguments();
      }
   }

AbstractFontSettingDialog$4

package mars.venus;
synchronized class AbstractFontSettingDialog$4 implements java.awt.event.ActionListener {
void AbstractFontSettingDialog$4(AbstractFontSettingDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/MessagesPane.java
mars/venus/MessagesPane.java   package mars.venus;
   import mars.*;
   import javax.swing.*;
   import javax.swing.text.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.util.concurrent.ArrayBlockingQueue;
   import javax.swing.event.DocumentListener;
   import javax.swing.undo.UndoableEdit;
   import mars.simulator.Simulator;
   import javax.swing.event.DocumentEvent;
   import javax.swing.text.Position.Bias;

/*
Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
  *  Creates the message window at the bottom of the UI.
  *   @author Team JSpim
  **/

    public class MessagesPane extends JTabbedPane{
      JTextArea assemble, run;
      JPanel assembleTab, runTab;
    // These constants are designed to keep scrolled contents of the 
    // two message areas from becoming overwhelmingly large (which
    // seems to slow things down as new text is appended).  Once it
    // reaches MAXIMUM_SCROLLED_CHARACTERS in length then cut off 
    // the first NUMBER_OF_CHARACTERS_TO_CUT characters.  The latter
    // must obviously be smaller than the former.
      public static final int MAXIMUM_SCROLLED_CHARACTERS = Globals.maximumMessageCharacters;
      public static final int NUMBER_OF_CHARACTERS_TO_CUT = Globals.maximumMessageCharacters/10 ; // 10%
   
   /**
     *  Constructor for the class, sets up two fresh tabbed text areas for program feedback.
     **/
   
       public MessagesPane() {
         super();
         this.setMinimumSize(new Dimension(0,0));
         assemble= new JTextArea();
         run= new JTextArea();
         assemble.setEditable(false); 
         run.setEditable(false);
        // Set both text areas to mono font.  For assemble
        // pane, will make messages more readable.  For run
        // pane, will allow properly aligned “text graphics”
        // DPS 15 Dec 2008
         Font monoFont = new Font(Font.MONOSPACED, Font.PLAIN, 12);
         assemble.setFont(monoFont);
         run.setFont(monoFont);         
        
         JButton assembleTabClearButton = new JButton(“Clear”);
         assembleTabClearButton.setToolTipText(“Clear the Mars Messages area”);
         assembleTabClearButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e){ 
                     assemble.setText(“”);
                  }
               });
         assembleTab = new JPanel(new BorderLayout());
         assembleTab.add(createBoxForButton(assembleTabClearButton),BorderLayout.WEST);
         assembleTab.add(new JScrollPane(assemble, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, 
                       ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
         assemble.addMouseListener(
                new MouseAdapter() {
                   public void mouseClicked(MouseEvent e) {
                     String text;
                     int lineStart = 0;
                     int lineEnd = 0;
                     try {
                        int line = assemble.getLineOfOffset(assemble.viewToModel(e.getPoint()));
                        lineStart = assemble.getLineStartOffset(line);
                        lineEnd = assemble.getLineEndOffset(line);
                        text = assemble.getText(lineStart, lineEnd-lineStart);
                     } 
                         catch (BadLocationException ble) {
                           text = “”;
                        }
                     if (text.length() > 0) {
                     // If error or warning, parse out the line and column number.
                        if (text.startsWith(ErrorList.ERROR_MESSAGE_PREFIX) || text.startsWith(ErrorList.WARNING_MESSAGE_PREFIX)) {
                           assemble.select(lineStart,lineEnd); 
                           assemble.setSelectionColor(Color.YELLOW);
                           assemble.repaint();
                           int separatorPosition = text.indexOf(ErrorList.MESSAGE_SEPARATOR);
                           if (separatorPosition >= 0) {
                              text = text.substring(0,separatorPosition);
                           }
                           String[] stringTokens = text.split(“\\s”); // tokenize with whitespace delimiter
                           String lineToken = ErrorList.LINE_PREFIX.trim();
                           String columnToken = ErrorList.POSITION_PREFIX.trim();
                           String lineString = “”;
                           String columnString = “”;
                           for (int i=0; i= ErrorList.FILENAME_PREFIX.length()) {
                              fileName = text.substring(fileNameStart, fileNameEnd).trim();
                           }
                           selectEditorTextLine(fileName, line, column);
                           selectErrorMessage(fileName, line, column);                        
                        }
                     }
                  }
               });  
                                              
         JButton runTabClearButton = new JButton(“Clear”);
         runTabClearButton.setToolTipText(“Clear the Run I/O area”);
         runTabClearButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e){ 
                     run.setText(“”);
                  }
               });
         runTab = new JPanel(new BorderLayout());
         runTab.add(createBoxForButton(runTabClearButton),BorderLayout.WEST);
         runTab.add(new JScrollPane(run, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, 
                       ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);               
         this.addTab(“Mars Messages”, assembleTab);
         this.addTab(“Run I/O”, runTab);
         this.setToolTipTextAt(0,”Messages produced by Run menu. Click on assemble error message to select erroneous line”);
         this.setToolTipTextAt(1,”Simulated MIPS console input and output”);
      }
    
      // Center given button in a box, centered vertically and 6 pixels on left and right
       private Box createBoxForButton(JButton button) {
         Box buttonRow = Box.createHorizontalBox();
         buttonRow.add(Box.createHorizontalStrut(6));
         buttonRow.add(button);
         buttonRow.add(Box.createHorizontalStrut(6));
         Box buttonBox = Box.createVerticalBox();
         buttonBox.add(Box.createVerticalGlue());
         buttonBox.add(buttonRow);
         buttonBox.add(Box.createVerticalGlue());
         return buttonBox;
      }
    
    /**
     *  Will select the Mars Messages tab error message that matches the given 
     *  specifications, if it is found. Matching is done by constructing
     *  a string using the parameter values and searching the text area for the last 
     *  occurrance of that string.
     *  @param fileName  A String containing the file path name.
     *  @param line  Line number for error message
     *  @param column Column number for error message
     */
       public void selectErrorMessage(String fileName, int line, int column) {
         String errorReportSubstring = new java.io.File(fileName).getName() + ErrorList.LINE_PREFIX + line + ErrorList.POSITION_PREFIX + column;
         int textPosition = assemble.getText().lastIndexOf(errorReportSubstring);
         if (textPosition >= 0) {
            int textLine = 0;
            int lineStart = 0;
            int lineEnd = 0;
            try {
               textLine = assemble.getLineOfOffset(textPosition);
               lineStart = assemble.getLineStartOffset(textLine);
               lineEnd = assemble.getLineEndOffset(textLine);
               assemble.setSelectionColor(Color.YELLOW);
               assemble.select(lineStart,lineEnd);
               assemble.getCaret().setSelectionVisible(true);
               assemble.repaint();               
            } 
                catch (BadLocationException ble) {
               // If there is a problem, simply skip the selection
               }
         }  
      }
   
    
    /**
     *  Will select the specified line in an editor tab.  If the file is open
     *  but not current, its tab will be made current.  If the file is not open,
     *  it will be opened in a new tab and made current, however the line will
     *  not be selected (apparent apparent problem with JEditTextArea). 
     *  @param fileName  A String containing the file path name.
     *  @param line  Line number for error message
     *  @param column Column number for error message
     */   
       public void selectEditorTextLine(String fileName, int line, int column) {
         EditTabbedPane editTabbedPane = (EditTabbedPane) Globals.getGui().getMainPane().getEditTabbedPane();      
         EditPane editPane, currentPane = null;
         editPane = editTabbedPane.getEditPaneForFile(new java.io.File(fileName).getPath());
         if (editPane != null) {
            if (editPane != editTabbedPane.getCurrentEditTab()) {
               editTabbedPane.setCurrentEditTab(editPane);
            }
            currentPane = editPane;     
         } 
         else { // file is not open.  Try to open it.
            if (editTabbedPane.openFile(new java.io.File(fileName))) {
               currentPane = editTabbedPane.getCurrentEditTab();
            }
         }
        // If editPane == null, it means the desired file was not open.  Line selection
        // does not properly with the JEditTextArea editor in this situation (it works
        // fine for the original generic editor).  So we just won’t do it. DPS 9-Aug-2010
         if (editPane != null && currentPane != null) {
            currentPane.selectLine(line, column); 
         }
      }
    
    /**
     * Returns component used to display assembler messages
     *
     * @return assembler message text component
     */
       public JTextArea getAssembleTextArea() {
         return assemble;
      }
    /**
     * Returns component used to display runtime messages
     *
     * @return runtime message text component
     */     
       public JTextArea getRunTextArea() {
         return run;
      }
    
    /**
     *  Post a message to the assembler display
     *
     *  @param message String to append to assembler display text
     */
       public void postMarsMessage(String message) {
         assemble.append(message);
        // can do some crude cutting here.  If the document gets “very large”, 
        // let’s cut off the oldest text. This will limit scrolling but the limit 
        // can be set reasonably high.
         if (assemble.getDocument().getLength() > MAXIMUM_SCROLLED_CHARACTERS) {
            try {
               assemble.getDocument().remove(0, NUMBER_OF_CHARACTERS_TO_CUT);
            } 
                catch (BadLocationException ble) { 
                       // only if NUMBER_OF_CHARACTERS_TO_CUT > MAXIMUM_SCROLLED_CHARACTERS
               }
         }
            assemble.setCaretPosition(assemble.getDocument().getLength());
         setSelectedComponent(assembleTab);
      }
    
      /**
     *  Post a message to the runtime display
     *
     *  @param message String to append to runtime display text
     */
    // The work of this method is done by “invokeLater” because
    // its JTextArea is maintained by the main event thread
    // but also used, via this method, by the execution thread for 
    // “print” syscalls. “invokeLater” schedules the code to be
    // run under the event-processing thread no matter what.
    // DPS, 23 Aug 2005.
       public void postRunMessage(String message) {
         final String mess = message;
         SwingUtilities.invokeLater(
                new Runnable() { 
                   public void run() { 
                     setSelectedComponent(runTab);
                     run.append(mess);
                  // can do some crude cutting here.  If the document gets “very large”, 
                  // let’s cut off the oldest text. This will limit scrolling but the limit 
                  // can be set reasonably high.
                     if (run.getDocument().getLength() > MAXIMUM_SCROLLED_CHARACTERS) {
                        try {
                           run.getDocument().remove(0, NUMBER_OF_CHARACTERS_TO_CUT);
                        } 
                            catch (BadLocationException ble) { 
                           // only if NUMBER_OF_CHARACTERS_TO_CUT > MAXIMUM_SCROLLED_CHARACTERS
                           }
                     }
                  } 
               });
      }
    
    /**
     * Make the assembler message tab current (up front)
     */
       public void selectMarsMessageTab() {
         setSelectedComponent(assembleTab);
      }
    /**
     * Make the runtime message tab current (up front)
     */     
       public void selectRunMessageTab() {
         setSelectedComponent(runTab);
      }
   
        /**
     *  Method used by the SystemIO class to get interactive user input
     *  requested by a running MIPS program (e.g. syscall #5 to read an
     *  integer).  SystemIO knows whether simulator is being run at 
     *  command line by the user, or by the GUI. If run at command line, 
     *  it gets input from System.in rather than here.
     *
     *  This is an overloaded method.  This version, with the String parameter,
     *  is used to get input from a popup dialog.
     *
     *  @param prompt Prompt to display to the user.
     *  @return User input.
     */
       public String getInputString(String prompt) {
         String input;
         JOptionPane pane = new JOptionPane(prompt,JOptionPane.QUESTION_MESSAGE,JOptionPane.DEFAULT_OPTION); 
         pane.setWantsInput(true);
         JDialog dialog = pane.createDialog(Globals.getGui(), “MIPS Keyboard Input”); 
         dialog.setVisible(true); 
         input = (String) pane.getInputValue();
         this.postRunMessage(Globals.userInputAlert+input+”\n”);
         return input;
      }
   
    /**
     *  Method used by the SystemIO class to get interactive user input
     *  requested by a running MIPS program (e.g. syscall #5 to read an
     *  integer).  SystemIO knows whether simulator is being run at 
     *  command line by the user, or by the GUI. If run at command line, 
     *  it gets input from System.in rather than here.
     *
     *  This is an overloaded method.  This version, with the int parameter,
     *  is used to get input from the MARS Run I/O window.
     *
     *  @param maxLen: maximum length of input. This method returns when maxLen characters have been read. Use -1 for no length restrictions.
     *  @return User input.
     */
       public String getInputString(int maxLen) {
         Asker asker = new Asker(maxLen); // Asker defined immediately below.
         return asker.response();
      }
      
      ////////////////////////////////////////////////////////////////////////////
      // Thread class for obtaining user input in the Run I/O window (MessagesPane)
      // Written by Ricardo Fernández Pascual [ .es] December 2009.
       class Asker implements Runnable {
         ArrayBlockingQueue resultQueue = new ArrayBlockingQueue(1);
         int initialPos;
         int maxLen;
          Asker(int maxLen) {
            this.maxLen = maxLen;
                // initialPos will be set in run()
         }
         final DocumentListener listener = 
             new DocumentListener() {
                public void insertUpdate(final DocumentEvent e) {
                  EventQueue.invokeLater(
                         new Runnable() {
                            public void run() {
                              try {
                                 String inserted = e.getDocument().getText(e.getOffset(), e.getLength());
                                 int i = inserted.indexOf(‘\n’);
                                 if (i >= 0) {
                                    int offset = e.getOffset() + i;
                                    if (offset + 1 == e.getDocument().getLength()) {
                                       returnResponse();
                                    } 
                                    else {
                                        // remove the ‘\n’ and put it at the end
                                       e.getDocument().remove(offset, 1);
                                       e.getDocument().insertString(e.getDocument().getLength(), “\n”, null);
                                        // insertUpdate will be called again, since we have inserted the ‘\n’ at the end
                                    }
                                 } 
                                 else if (maxLen >= 0 && e.getDocument().getLength() – initialPos >= maxLen) {
                                    returnResponse();
                                 }
                              } 
                                  catch (BadLocationException ex) {
                                    returnResponse();
                                 }
                           }
                        });
               }
                public void removeUpdate(final DocumentEvent e) {
                  EventQueue.invokeLater(
                         new Runnable() {
                            public void run() {
                              if ((e.getDocument().getLength() < initialPos || e.getOffset() < initialPos) && e instanceof UndoableEdit) {                                  ((UndoableEdit) e).undo();                                  run.setCaretPosition(e.getOffset() + e.getLength());                               }                            }                         });                }                 public void changedUpdate(DocumentEvent e) { }             };          final NavigationFilter navigationFilter =               new NavigationFilter() {                 public void moveDot(FilterBypass fb, int dot, Bias bias) {                   if (dot < initialPos) {                      dot = Math.min(initialPos, run.getDocument().getLength());                   }                   fb.moveDot(dot, bias);                }                 public void setDot(FilterBypass fb, int dot, Bias bias) {                   if (dot < initialPos) {                      dot = Math.min(initialPos, run.getDocument().getLength());                   }                   fb.setDot(dot, bias);                }             };          final Simulator.StopListener stopListener =               new Simulator.StopListener() {                 public void stopped(Simulator s) {                   returnResponse();                }             };           public void run() { // must be invoked from the GUI thread             setSelectedComponent(runTab);             run.setEditable(true);             run.requestFocusInWindow();             run.setCaretPosition(run.getDocument().getLength());             initialPos = run.getCaretPosition();             run.setNavigationFilter(navigationFilter);             run.getDocument().addDocumentListener(listener);             Simulator.getInstance().addStopListener(stopListener);          }           void cleanup() { // not required to be called from the GUI thread             EventQueue.invokeLater(                    new Runnable() {                       public void run() {                         run.getDocument().removeDocumentListener(listener);                         run.setEditable(false);                         run.setNavigationFilter(null);                         run.setCaretPosition(run.getDocument().getLength());                         Simulator.getInstance().removeStopListener(stopListener);                      }                   });          }           void returnResponse() {             try {                int p = Math.min(initialPos, run.getDocument().getLength());                int l = Math.min(run.getDocument().getLength() - p, maxLen >= 0 ? maxLen : Integer.MAX_VALUE);
               resultQueue.offer(run.getText(p, l));
            } 
                catch (BadLocationException ex) {
                    // this cannot happen
                  resultQueue.offer(“”);
               }
         }
          String response() {
            EventQueue.invokeLater(this);
            try {
               return resultQueue.take();
            } 
                catch (InterruptedException ex) {
                  return null;
               } 
            finally {
               cleanup();
            }
         }
      }  // Asker class
      ////////////////////////////////////////////////////////////////////////////
   }

LabelsWindow$LabelAddressAscendingComparator

package mars.venus;
synchronized class LabelsWindow$LabelAddressAscendingComparator implements java.util.Comparator {
private void LabelsWindow$LabelAddressAscendingComparator(LabelsWindow);
public int compare(Object, Object);
}

FileDumpMemoryAction$3

package mars.venus;
synchronized class FileDumpMemoryAction$3 implements java.awt.event.ActionListener {
void FileDumpMemoryAction$3(FileDumpMemoryAction);
public void actionPerformed(java.awt.event.ActionEvent);
}

MessagesPane$2

package mars.venus;
synchronized class MessagesPane$2 extends java.awt.event.MouseAdapter {
void MessagesPane$2(MessagesPane);
public void mouseClicked(java.awt.event.MouseEvent);
}

RegistersWindow$MyTippedJTable

package mars.venus;
synchronized class RegistersWindow$MyTippedJTable extends javax.swing.JTable {
private String[] regToolTips;
private String[] columnToolTips;
void RegistersWindow$MyTippedJTable(RegistersWindow, RegistersWindow$RegTableModel);
public String getToolTipText(java.awt.event.MouseEvent);
protected javax.swing.table.JTableHeader createDefaultTableHeader();
}

mars/venus/SettingsWarningsAreErrorsAction.java
mars/venus/SettingsWarningsAreErrorsAction.java   package mars.venus;
   import mars.simulator.*;
    import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item to control whether or not
     * assembler warnings are considered errors.  If so, a program generating
     * warnings but not errors will not assemble.
    */
    public class SettingsWarningsAreErrorsAction extends GuiAction  {
    
   
       public SettingsWarningsAreErrorsAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
           Globals.getSettings().setWarningsAreErrors(((JCheckBoxMenuItem)e.getSource()).isSelected());
      }
        
   }

SettingsEditorAction$EditorFontDialog

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog extends AbstractFontSettingDialog {
private javax.swing.JButton[] foregroundButtons;
private javax.swing.JLabel[] samples;
private javax.swing.JToggleButton[] bold;
private javax.swing.JToggleButton[] italic;
private javax.swing.JCheckBox[] useDefault;
private int[] syntaxStyleIndex;
private editors.jeditsyntax.SyntaxStyle[] defaultStyles;
private editors.jeditsyntax.SyntaxStyle[] initialStyles;
private editors.jeditsyntax.SyntaxStyle[] currentStyles;
private java.awt.Font previewFont;
private javax.swing.JPanel dialogPanel;
private javax.swing.JPanel syntaxStylePanel;
private javax.swing.JPanel otherSettingsPanel;
private javax.swing.JSlider tabSizeSelector;
private javax.swing.JSpinner tabSizeSpinSelector;
private javax.swing.JSpinner blinkRateSpinSelector;
private javax.swing.JSpinner popupPrefixLengthSpinSelector;
private javax.swing.JCheckBox lineHighlightCheck;
private javax.swing.JCheckBox genericEditorCheck;
private javax.swing.JCheckBox autoIndentCheck;
private javax.swing.text.Caret blinkCaret;
private javax.swing.JTextField blinkSample;
private javax.swing.ButtonGroup popupGuidanceButtons;
private javax.swing.JRadioButton[] popupGuidanceOptions;
private boolean syntaxStylesAction;
private int initialEditorTabSize;
private int initialCaretBlinkRate;
private int initialPopupGuidance;
private boolean initialLineHighlighting;
private boolean initialGenericTextEditor;
private boolean initialAutoIndent;
public void SettingsEditorAction$EditorFontDialog(SettingsEditorAction, java.awt.Frame, String, boolean, java.awt.Font);
protected javax.swing.JPanel buildDialogPanel();
protected java.awt.Component buildControlPanel();
protected void apply(java.awt.Font);
protected void reset();
private void resetOtherSettings();
private javax.swing.JPanel buildOtherSettingsPanel();
private javax.swing.JPanel buildSyntaxStylePanel();
private void initializeSyntaxStyleChangeables();
private void setSampleStyles(javax.swing.JLabel, editors.jeditsyntax.SyntaxStyle);
}

LabelsWindow$LabelNameAscendingComparator

package mars.venus;
synchronized class LabelsWindow$LabelNameAscendingComparator implements java.util.Comparator {
private void LabelsWindow$LabelNameAscendingComparator(LabelsWindow);
public int compare(Object, Object);
}

RunSpeedPanel

package mars.venus;
public synchronized class RunSpeedPanel extends javax.swing.JPanel {
public static final double UNLIMITED_SPEED = 40.0;
private static final int SPEED_INDEX_MIN = 0;
private static final int SPEED_INDEX_MAX = 40;
private static final int SPEED_INDEX_INIT = 40;
private static final int SPEED_INDEX_INTERACTION_LIMIT = 35;
private double[] speedTable;
private javax.swing.JLabel sliderLabel;
private javax.swing.JSlider runSpeedSlider;
private static RunSpeedPanel runSpeedPanel;
private volatile int runSpeedIndex;
static void ();
public static RunSpeedPanel getInstance();
private void RunSpeedPanel();
public double getRunSpeed();
private String setLabel(int);
}

DataSegmentWindow$3

package mars.venus;
synchronized class DataSegmentWindow$3 implements java.awt.event.ActionListener {
void DataSegmentWindow$3(DataSegmentWindow);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/EditPane.java
mars/venus/EditPane.java   package mars.venus;
   import mars.*;
   import mars.venus.editors.MARSTextEditingArea;
   import mars.venus.editors.generic.GenericTextArea;
   import mars.venus.editors.jeditsyntax.JEditBasedTextArea;
   import javax.swing.*;
   import javax.swing.event.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.undo.*;
   import java.text.*;
   import java.util.*;
   import java.io.*;

/*
Copyright (c) 2003-2011,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

     /**
      *  Represents one file opened for editing.  Maintains required internal structures. 
      *  Before Mars 4.0, there was only one editor pane, a tab, and only one file could
      *  be open at a time.  With 4.0 came the multifile (pane, tab) editor, and existing 
      *  duties were split between EditPane and the new EditTabbedPane class.
      *   @author Sanderson and Bumgarner
      */

   public class EditPane extends JPanel implements Observer {
   
      private MARSTextEditingArea sourceCode;
      private VenusUI mainUI;
      private String currentDirectoryPath;
      private JLabel caretPositionLabel;
      private JCheckBox showLineNumbers;
      private JLabel lineNumbers;
      private static int count = 0;
      private boolean isCompoundEdit = false;
      private CompoundEdit compoundEdit;
      private FileStatus fileStatus;
   
     /**
      *  Constructor for the EditPane class. 
    */
    
      public EditPane(VenusUI appFrame){
         super(new BorderLayout());
         this.mainUI = appFrame;
        // user.dir, user’s current working directory, is guaranteed to have a value
         currentDirectoryPath = System.getProperty(“user.dir”);
         // mainUI.editor = new Editor(mainUI);
        // We want to be notified of editor font changes! See update() below.
         Globals.getSettings().addObserver(this);
         this.fileStatus = new FileStatus();      
         lineNumbers = new JLabel();
      
         if (Globals.getSettings().getBooleanSetting(Settings.GENERIC_TEXT_EDITOR)) {
            this.sourceCode = new GenericTextArea(this, lineNumbers);
         } 
         else {
            this.sourceCode = new JEditBasedTextArea(this, lineNumbers);
         }
        // sourceCode is responsible for its own scrolling
         this.add(this.sourceCode.getOuterComponent(), BorderLayout.CENTER);        
        
        // If source code is modified, will set flag to trigger/request file save.
         sourceCode.getDocument().addDocumentListener(
               new DocumentListener() {
                  public void insertUpdate(DocumentEvent evt) {
                     // IF statement added DPS 9-Aug-2011
                    // This method is triggered when file contents added to document
                    // upon opening, even though not edited by user.  The IF
                    // statement will sense this situation and immediately return.
                     if (FileStatus.get() == FileStatus.OPENING) { 
                        setFileStatus(FileStatus.NOT_EDITED); 
                        FileStatus.set(FileStatus.NOT_EDITED);
                        if (showingLineNumbers()) {
                           lineNumbers.setText(getLineNumbersList(sourceCode.getDocument()));
                        }
                        return;
                     } 
                    // End of 9-Aug-2011 modification.                    
                     if (getFileStatus() == FileStatus.NEW_NOT_EDITED) {
                        setFileStatus(FileStatus.NEW_EDITED);
                     }
                     if (getFileStatus() == FileStatus.NOT_EDITED) {
                        setFileStatus(FileStatus.EDITED);
                     }
                     if (getFileStatus() == FileStatus.NEW_EDITED) {
                        mainUI.editor.setTitle( “”, getFilename(), getFileStatus());
                     } 
                     else {
                        mainUI.editor.setTitle(getPathname(), getFilename(), getFileStatus());
                     }
                                
                     FileStatus.setEdited(true);
                     switch (FileStatus.get()) {
                        case FileStatus.NEW_NOT_EDITED:
                           FileStatus.set(FileStatus.NEW_EDITED);
                           break;
                        case FileStatus.NEW_EDITED:
                           break;
                        default:
                           FileStatus.set(FileStatus.EDITED);
                     }
                    
                     Globals.getGui().getMainPane().getExecutePane().clearPane(); // DPS 9-Aug-2011
                    
                     if (showingLineNumbers()) {
                        lineNumbers.setText(getLineNumbersList(sourceCode.getDocument()));
                     }
                  }
                  public void removeUpdate(DocumentEvent evt) {
                     this.insertUpdate(evt);
                  }
                  public void changedUpdate(DocumentEvent evt) {
                     this.insertUpdate(evt);
                  }
               });
         
         showLineNumbers = new JCheckBox(“Show Line Numbers”);
         showLineNumbers.setToolTipText(“If checked, will display line number for each line of text.”);
         showLineNumbers.setEnabled(false);
        // Show line numbers by default.
         showLineNumbers.setSelected(Globals.getSettings().getEditorLineNumbersDisplayed());     
                
         this.setSourceCode(“”,false);
           
         lineNumbers.setFont(getLineNumberFont(sourceCode.getFont()));
         lineNumbers.setVerticalAlignment(JLabel.TOP);
         lineNumbers.setText(“”);
         lineNumbers.setVisible(true);
        
        // Listener fires when “Show Line Numbers” check box is clicked.
         showLineNumbers.addItemListener(
               new ItemListener() {
                  public void itemStateChanged(ItemEvent e) {
                     if (showLineNumbers.isSelected()) {
                        lineNumbers.setText(getLineNumbersList(sourceCode.getDocument()));
                        lineNumbers.setVisible(true);
                     } 
                     else {
                        lineNumbers.setText(“”);
                        lineNumbers.setVisible(false);
                     }
                     sourceCode.revalidate(); // added 16 Jan 2012 to assure label redrawn.
                     Globals.getSettings().setEditorLineNumbersDisplayed(showLineNumbers.isSelected());
                    // needed because caret disappears when checkbox clicked
                     sourceCode.setCaretVisible(true); 
                     sourceCode.requestFocusInWindow();
                  }
               });
      
         JPanel editInfo = new JPanel(new BorderLayout());
         caretPositionLabel = new JLabel();
         caretPositionLabel.setToolTipText(“Tracks the current position of the text editing cursor.”);
         displayCaretPosition(new Point());
         editInfo.add(caretPositionLabel,BorderLayout.WEST);
         editInfo.add(showLineNumbers,BorderLayout.CENTER);
         this.add(editInfo,BorderLayout.SOUTH);
      }
    
      
         /**
      *  For initalizing the source code when opening an ASM file
      *   @param s String containing text
      *   @param editable set true if code is editable else false
      */
    
      public void setSourceCode(String s, boolean editable){
         sourceCode.setSourceCode(s, editable);
      }
      
    /**
     *  Get rid of any accumulated undoable edits.  It is useful to call
     *  this method after opening a file into the text area.  The 
     *  act of setting its text content upon reading the file will generate 
     *  an undoable edit.  Normally you don’t want a freshly-opened file
     *  to appear with its Undo action enabled.  But it will unless you
     *  call this after setting the text.
     */ 
      public void discardAllUndoableEdits() {
         sourceCode.discardAllUndoableEdits();
      }
   
    /** Form string with source code line numbers.
     * Resulting string is HTML, for which JLabel will happily honor 
 to do
     * multiline label (it ignores ‘\n’).  The line number list is a JLabel with
     * one line number per line.
     */
      private static final String spaces = ”         “;
      public String getLineNumbersList(javax.swing.text.Document doc) {
         StringBuffer lineNumberList = new StringBuffer(““);
         int lineCount = doc.getDefaultRootElement().getElementCount(); //this.getSourceLineCount();
         int digits = Integer.toString(lineCount).length();
         for (int i=1; i<=lineCount;i++) {             String lineStr = Integer.toString(i);             int leadingSpaces = digits-lineStr.length();             if (leadingSpaces == 0) {                lineNumberList.append(lineStr+" 
“);
            } 
            else {
               lineNumberList.append(spaces.substring(0,leadingSpaces*6)+lineStr+” 
“);
            }
         }
         lineNumberList.append(“
“);
         return lineNumberList.toString();
      }
   
   
      /** Calculate and return number of lines in source code text.
     * Do this by counting newline characters then adding one if last line does
     * not end with newline character.
     */
     
    /*  IMPLEMENTATION NOTE:
     * Tried repeatedly to use StringTokenizer to count lines but got bad results 
     * on empty lines (consecutive delimiters) even when returning delimiter as token.
     * BufferedReader on StringReader seems to work better.
     */
      public int getSourceLineCount() {
         BufferedReader bufStringReader = new BufferedReader(new StringReader(sourceCode.getText()));
         int lineNums = 0;
         try {
            while (bufStringReader.readLine() != null) {
               lineNums++;
            }
         }
            catch (IOException e) {
            }
         return lineNums;
      }
   
      /**
     * Get source code text
     *
     * @return Sting containing source code
     */
      public String getSource(){
         return sourceCode.getText();
      }
    
   
    /**
     *  Set the editing status for this EditPane’s associated document.
     *  For the argument, use one of the constants from class FileStatus.
     *  
     * @param FileStatus the status constant from class FileStatus
     */   
      public void setFileStatus(int fileStatus) {
         this.fileStatus.setFileStatus(fileStatus);
      }
   
   
    /**
     *  Get the editing status for this EditPane’s associated document.
     *  This will be one of the constants from class FileStatus.
     */    
   
      public int getFileStatus() {
         return this.fileStatus.getFileStatus();
      }
      
    /**
     * Delegates to corresponding FileStatus method
     */   
      public String getFilename() {
         return this.fileStatus.getFilename();
      }
    
      
    /**
     * Delegates to corresponding FileStatus method
     */   
      public String getPathname() {
         return this.fileStatus.getPathname();
      }
    
      
    /**
     * Delegates to corresponding FileStatus method
     */   
      public void setPathname(String pathname) {
         this.fileStatus.setPathname(pathname);
      }
      
    /**
     * Delegates to corresponding FileStatus method
     */
      public boolean hasUnsavedEdits() {
         return this.fileStatus.hasUnsavedEdits();
      }
   
      
    /**
     * Delegates to corresponding FileStatus method
     */     
      public boolean isNew() {
         return this.fileStatus.isNew();
      }
   
      
    /**
     * Delegates to text area’s requestFocusInWindow method.
     */
            
      public void tellEditingComponentToRequestFocusInWindow() {
         this.sourceCode.requestFocusInWindow();
      }
        
      
    /**
     * Delegates to corresponding FileStatus method
     */         
      public void updateStaticFileStatus() {
         fileStatus.updateStaticFileStatus();
      }
    
    
      /**
     *  get the manager in charge of Undo and Redo operations
     *  @return the UnDo manager
     */
      public UndoManager getUndoManager() {
         return sourceCode.getUndoManager();
      }
    
      /*       Note: these are invoked only when copy/cut/paste are used from the
                   toolbar or menu or the defined menu Alt codes.  When
                        Ctrl-C, Ctrl-X or Ctrl-V are used, this code is NOT invoked
                        but the operation works correctly!
                The “set visible” operations are used because clicking on the toolbar
                icon causes both the selection highlighting AND the blinking cursor
                to disappear!  This does not happen when using menu selection or 
                Ctrl-C/X/V
    */
    /**
     * copy currently-selected text into clipboard
     */
      public void copyText() {
         sourceCode.copy();
         sourceCode.setCaretVisible(true);
         sourceCode.setSelectionVisible(true);
      }
     
    /**
     * cut currently-selected text into clipboard
     */
      public void cutText() {
         sourceCode.cut();       
         sourceCode.setCaretVisible(true);
      }
    /**
     * paste clipboard contents at cursor position
     */  
      public void pasteText() {
         sourceCode.paste();         
         sourceCode.setCaretVisible(true);
      }      
    /**
     * select all text
     */
      public void selectAllText() {
         sourceCode.selectAll();
         sourceCode.setCaretVisible(true);
         sourceCode.setSelectionVisible(true);
      }
        
     /**
      * Undo previous edit
    */
      public void undo() {
         sourceCode.undo();
      }
      
    /**
     * Redo previous edit
     */
      public void redo() {
         sourceCode.redo();
      }
    
    /**
     *  Update state of Edit menu’s Undo menu item.
     */ 
      public void updateUndoState() {
         mainUI.editUndoAction.updateUndoState();
      }
    
    /**
     *  Update state of Edit menu’s Redo menu item.
     */ 
      public void updateRedoState() {
         mainUI.editRedoAction.updateRedoState();
      } 
     
    /**
     *  get editor’s line number display status 
     *
     *  @return true if editor is current displaying line numbers, false otherwise.
     */
      public boolean showingLineNumbers() {
         return showLineNumbers.isSelected();
      }
   
    /**
     *  enable or disable checkbox that controls display of line numbers 
     *
     *  @param enable True to enable box, false to disable.
     */      
      public void setShowLineNumbersEnabled(boolean enabled) {
         showLineNumbers.setEnabled(enabled);
         //showLineNumbers.setSelected(false); // set off, whether closing or opening
      }
   
      /**
     *  Update the caret position label on the editor’s border to
     *  display the current line and column.  The position is given
     *  as text stream offset and will be converted into line and column.
     *  @param pos Offset into the text stream of caret.  
     */ 
      public void displayCaretPosition(int pos) {
         displayCaretPosition(convertStreamPositionToLineColumn(pos));
      }
     /**
      *  Display cursor coordinates
      *
      *  @param p  Point object with x-y (column, line number) coordinates of cursor
      */
      public void displayCaretPosition(Point p) {
         caretPositionLabel.setText(“Line: “+ p.y + ” Column: “+ p.x);
      }
   
         /**
      * Given byte stream position in text being edited, calculate its column and line
      * number coordinates.
      *
      * @param stream position of character
      * @return position Its column and line number coordinate as a Point. 
      */
      private static final char newline = ‘\n’;
      public Point convertStreamPositionToLineColumn(int position) {
         String textStream = sourceCode.getText();
         int line = 1;
         int column = 1;
         for (int i=0; i 0) { 
            int lineStartPosition = convertLineColumnToStreamPosition(line,1);
            int lineEndPosition = convertLineColumnToStreamPosition(line+1,1)-1;
            if (lineEndPosition < 0) { // DPS 19 Sept 2012.  Happens if "line" is last line of file.                                 lineEndPosition = sourceCode.getText().length()-1;             }             if (lineStartPosition >= 0) {
               sourceCode.select(lineStartPosition, lineEndPosition);
               sourceCode.setSelectionVisible(true);        
            }           
         }
      }
   
   
   /**
    * Select the specified editor text line.  Lines are numbered starting with 1, consistent
    * with line numbers displayed by the editor.
    * @param line The desired line number of this TextPane’s text.  Numbering starts at 1, and
    * nothing will happen if the parameter value is less than 1
    * @param column Desired column at which to place the cursor.
    */
      public void selectLine(int line, int column) {
         selectLine(line);
        // Made one attempt at setting cursor; didn’t work but here’s the attempt
        // (imagine using it in the one-parameter overloaded method above)
        //sourceCode.setCaretPosition(lineStartPosition+column-1);        
      } 
      
    /** Finds next occurrence of text in a forward search of a string. Search begins 
     * at the current cursor location, and wraps around when the end of the string
     * is reached.
     * @param find the text to locate in the string 
     * @param caseSensitive true if search is to be case-sensitive, false otherwise
     * @return TEXT_FOUND or TEXT_NOT_FOUND, depending on the result.
     */
      public int doFindText(String find, boolean caseSensitive) {
         return sourceCode.doFindText(find, caseSensitive);
      }
   
    /** Finds and replaces next occurrence of text in a string in a forward search.
     *  If cursor is initially at end
     *  of matching selection, will immediately replace then find and select the
     *  next occurrence if any.  Otherwise it performs a find operation.  The replace
     *  can be undone with one undo operation.
     *
     * @param find the text to locate in the string
     * @param replace the text to replace the find text with – if the find text exists
     * @param caseSensitive true for case sensitive. false to ignore case
     * @return Returns TEXT_FOUND if not initially at end of selected match and matching
     * occurrence is found.  Returns TEXT_NOT_FOUND if the text is not matched.
     * Returns TEXT_REPLACED_NOT_FOUND_NEXT if replacement is successful but there are 
     * no additional matches.  Returns TEXT_REPLACED_FOUND_NEXT if reaplacement is
     * successful and there is at least one additional match.
     */   
      public int doReplace(String find, String replace, boolean caseSensitive) {
         return sourceCode.doReplace(find, replace, caseSensitive);
      }
   
   
      
   /** Finds and replaces ALL occurrences of text in a string in a forward search.
    *  All replacements are bundled into one CompoundEdit, so one Undo operation will 
    *  undo all of them.
    * @param find the text to locate in the string
    * @param replace the text to replace the find text with – if the find text exists 
    * @param caseSensitive true for case sensitive. false to ignore case
    * @return the number of occurrences that were matched and replaced.
    */   
      public int doReplaceAll(String find, String replace, boolean caseSensitive) {
         return sourceCode.doReplaceAll(find, replace, caseSensitive);
      }
   
     
    
    /**
     *  Update, if source code is visible, when Font setting changes.
     *  This method is specified by the Observer interface.
     */
      public void update(Observable fontChanger, Object arg) {
         sourceCode.setFont(Globals.getSettings().getEditorFont());
         sourceCode.setLineHighlightEnabled(Globals.getSettings().getBooleanSetting(Settings.EDITOR_CURRENT_LINE_HIGHLIGHTING));
         sourceCode.setCaretBlinkRate(Globals.getSettings().getCaretBlinkRate());
         sourceCode.setTabSize(Globals.getSettings().getEditorTabSize());
         sourceCode.updateSyntaxStyles();
         sourceCode.revalidate();
        // We want line numbers to be displayed same size but always PLAIN style.
        // Easiest way to get same pixel height as source code is to set to same
        // font family as the source code! It can get a bit complicated otherwise
        // because different fonts will render the same font size in different
        // pixel heights.  This is a factor because the line numbers as displayed
        // in the editor form a separate column from the source code and if the
        // pixel height is not the same then the numbers will not line up with
        // the source lines.
         lineNumbers.setFont(getLineNumberFont(sourceCode.getFont()));
         lineNumbers.revalidate();
      }
    
    
    /* Private helper method.
     * Determine font to use for editor line number display, given current
     * font for source code.
     */
      private Font getLineNumberFont(Font sourceFont) {
         return  (sourceCode.getFont().getStyle() == Font.PLAIN) 
                 ? sourceFont
                  : new Font(sourceFont.getFamily(), Font.PLAIN, sourceFont.getSize());
      }
      
    
   }

RunGoAction

package mars.venus;
public synchronized class RunGoAction extends GuiAction {
public static int defaultMaxSteps;
public static int maxSteps;
private String name;
private ExecutePane executePane;
static void ();
public void RunGoAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
public void paused(boolean, int, mars.ProcessingException);
public void stopped(mars.ProcessingException, int);
public static void resetMaxSteps();
private void processProgramArgumentsIfAny();
}

EditTabbedPane$1

package mars.venus;
synchronized class EditTabbedPane$1 implements javax.swing.event.ChangeListener {
void EditTabbedPane$1(EditTabbedPane);
public void stateChanged(javax.swing.event.ChangeEvent);
}

mars/venus/SettingsProgramArgumentsAction.java
mars/venus/SettingsProgramArgumentsAction.java   package mars.venus;
   import mars.simulator.*;
    import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item to control whether or not
     * program arguments can be entered and used.  If so, a text field
     * will be displayed where they can be interactively entered.
    */
    public class SettingsProgramArgumentsAction extends GuiAction  {
    
   
       public SettingsProgramArgumentsAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
           boolean selected = ((JCheckBoxMenuItem)e.getSource()).isSelected();
           Globals.getSettings().setProgramArguments(selected);
            if (selected) {
               Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().addProgramArgumentsPanel();
            } else {
               Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().removeProgramArgumentsPanel();            
            }
      }
        
   }

SettingsEditorAction$EditorFontDialog$5

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog$5 implements java.awt.event.ItemListener {
void SettingsEditorAction$EditorFontDialog$5(SettingsEditorAction$EditorFontDialog);
public void itemStateChanged(java.awt.event.ItemEvent);
}

TextSegmentWindow$MyTippedJTable$TextTableHeader

package mars.venus;
synchronized class TextSegmentWindow$MyTippedJTable$TextTableHeader extends javax.swing.table.JTableHeader {
public void TextSegmentWindow$MyTippedJTable$TextTableHeader(TextSegmentWindow$MyTippedJTable, javax.swing.table.TableColumnModel);
public String getToolTipText(java.awt.event.MouseEvent);
}

SettingsExtendedAction

package mars.venus;
public synchronized class SettingsExtendedAction extends GuiAction {
public void SettingsExtendedAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/ToolLoader.java
mars/venus/ToolLoader.java   package mars.venus;
   import mars.tools.*;
   import mars.util.*;
   import javax.swing.*;
   import java.awt.event.*;
   import java.io.*;
   import java.util.*;
   import java.util.zip.*;
   import java.lang.reflect.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

   /**
     * This class provides functionality to bring external Mars tools into the Mars
     * system by adding them to its Tools menu.  This permits anyone with knowledge
     * of the Mars public interfaces, in particular of the Memory and Register 
     * classes, to write applications which can interact with a MIPS program 
     * executing under Mars.  The execution is of course simulated.  The
     * private method for loading tool classes is adapted from Bret Barker’s
     * GameServer class from the book “Developing Games In Java”.
     *
     *  @author Pete Sanderson with help from Bret Barker
     *  @version August 2005
     */
     
    public class ToolLoader {
   
      private static final String CLASS_PREFIX = “mars.tools.”;
      private static final String TOOLS_DIRECTORY_PATH = “mars/tools”;
      private static final String TOOLS_MENU_NAME = “Tools”;
      private static final String MARSTOOL_INTERFACE = “MarsTool.class”;
      private static final String CLASS_EXTENSION = “class”;
    
    /**
     *  Called in VenusUI to build its Tools menu.  If there are no qualifying tools
     *  or any problems accessing those tools, it returns null.  A qualifying tool
     *  must be a class in the Tools package that implements MarsTool, must be compiled 
     *  into a .class file, and its .class file must be in the same Tools folder as 
     *  MarsTool.class.
     *
     *  @return a Tools JMenu if qualifying tool classes are found, otherwise null
     */
       public JMenu buildToolsMenu() {
         JMenu menu = null;
         ArrayList marsToolList = loadMarsTools();
         if (!marsToolList.isEmpty()) {
            menu = new JMenu(TOOLS_MENU_NAME);
            menu.setMnemonic(KeyEvent.VK_T);
         // traverse array list and build menu
            MarsToolClassAndInstance listItem;
            for (int i=0; i Save As menu item
    */              
    public class FileSaveAsAction extends GuiAction {
     
       public FileSaveAsAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
   
   
       public void actionPerformed(ActionEvent e){
            mainUI.editor.saveAs();        
      }
   }

SettingsHighlightingAction$8

package mars.venus;
synchronized class SettingsHighlightingAction$8 implements java.awt.event.ActionListener {
void SettingsHighlightingAction$8(SettingsHighlightingAction);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/RunBackstepAction.java
mars/venus/RunBackstepAction.java   package mars.venus;
   import mars.*;
   import mars.mips.hardware.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
    * Action  for the Run -> Backstep menu item
    */              
    public class RunBackstepAction extends GuiAction {
     
      String name;
      ExecutePane executePane;
       public RunBackstepAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
        /**
         * perform next simulated instruction step.
         */  
       public void actionPerformed(ActionEvent e){
         name = this.getValue(Action.NAME).toString();
         executePane = mainUI.getMainPane().getExecutePane();
         boolean done = false;
         if(!FileStatus.isAssembled()){
                     // note: this should never occur since backstepping is only enabled after successful assembly.
            JOptionPane.showMessageDialog(mainUI,”The program must be assembled before it can be run.”);
            return;
         }
         mainUI.setStarted(true);
         mainUI.messagesPane.setSelectedComponent(mainUI.messagesPane.runTab);
         executePane.getTextSegmentWindow().setCodeHighlighting(true);
            
         if (Globals.getSettings().getBackSteppingEnabled()) {
            boolean inDelaySlot = Globals.program.getBackStepper().inDelaySlot(); // Added 25 June 2007
                Memory.getInstance().addObserver(executePane.getDataSegmentWindow());
                RegisterFile.addRegistersObserver(executePane.getRegistersWindow());
                Coprocessor0.addRegistersObserver(executePane.getCoprocessor0Window());
                Coprocessor1.addRegistersObserver(executePane.getCoprocessor1Window());
            Globals.program.getBackStepper().backStep();
                Memory.getInstance().deleteObserver(executePane.getDataSegmentWindow());
                RegisterFile.deleteRegistersObserver(executePane.getRegistersWindow());
            executePane.getRegistersWindow().updateRegisters();
            executePane.getCoprocessor1Window().updateRegisters();
            executePane.getCoprocessor0Window().updateRegisters();
            executePane.getDataSegmentWindow().updateValues();
            executePane.getTextSegmentWindow().highlightStepAtPC(inDelaySlot); // Argument aded 25 June 2007
            FileStatus.set(FileStatus.RUNNABLE);
         // if we’ve backed all the way, disable the button
         //    if (Globals.program.getBackStepper().empty()) {
         //     ((AbstractAction)((AbstractButton)e.getSource()).getAction()).setEnabled(false);
         //}
         /*
         if (pe !=null) {
            RunGoAction.resetMaxSteps();
            mainUI.getMessagesPane().postMarsMessage(
                                pe.errors().generateErrorReport());
            mainUI.getMessagesPane().postMarsMessage(
                                “\n”+name+”: execution terminated with errors.\n\n”);
            mainUI.getRegistersPane().setSelectedComponent(executePane.getCoprocessor0Window());
            FileStatus.set(FileStatus.TERMINATED); // should be redundant.
                            executePane.getTextSegmentWindow().setCodeHighlighting(true);
            executePane.getTextSegmentWindow().unhighlightAllSteps();
            executePane.getTextSegmentWindow().highlightStepAtAddress(RegisterFile.getProgramCounter()-4);
         }
         */
            mainUI.setReset(false);   
         }
      }
   }

mars/venus/VenusUI.java
mars/venus/VenusUI.java   package mars.venus;
   import mars.*;
   import mars.mips.dump.*;
   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.event.*;
   import java.io.*;
   import java.net.*;

/*
Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

    /**
      *  Top level container for Venus GUI.
      *   @author Sanderson and Team JSpim
      **/
      
      /* Heavily modified by Pete Sanderson, July 2004, to incorporate JSPIMMenu and JSPIMToolbar
       * not as subclasses of JMenuBar and JToolBar, but as instances of them.  They are both
        * here primarily so both can share the Action objects.
        */
    
    public class VenusUI extends JFrame{
      VenusUI mainUI;
      public JMenuBar menu;
      JToolBar toolbar;
      MainPane mainPane; 
      RegistersPane registersPane; 
      RegistersWindow registersTab;
      Coprocessor1Window coprocessor1Tab;
      Coprocessor0Window coprocessor0Tab;
      MessagesPane messagesPane;
      JSplitPane splitter, horizonSplitter;
      JPanel north;
   
      private int frameState; // see windowActivated() and windowDeactivated()
      private static int menuState = FileStatus.NO_FILE;
        
    // PLEASE PUT THESE TWO (& THEIR METHODS) SOMEWHERE THEY BELONG, NOT HERE
      private static boolean reset= true; // registers/memory reset for execution
      private static boolean started = false;  // started execution
      Editor editor;
    
    // components of the menubar
      private JMenu file, run, window, help, edit, settings;
      private JMenuItem fileNew, fileOpen, fileClose, fileCloseAll, fileSave, fileSaveAs, fileSaveAll, fileDumpMemory, filePrint, fileExit;
      private JMenuItem editUndo, editRedo, editCut, editCopy, editPaste, editFindReplace, editSelectAll;
      private JMenuItem runGo, runStep, runBackstep, runReset, runAssemble, runStop, runPause, runClearBreakpoints, runToggleBreakpoints;
      private JCheckBoxMenuItem settingsLabel, settingsPopupInput, settingsValueDisplayBase, settingsAddressDisplayBase,
              settingsExtended, settingsAssembleOnOpen, settingsAssembleAll, settingsWarningsAreErrors, settingsStartAtMain,
              settingsDelayedBranching, settingsProgramArguments;
      private JMenuItem settingsExceptionHandler, settingsEditor, settingsHighlighting, settingsMemoryConfiguration;
      private JMenuItem helpHelp, helpAbout;
         
      // components of the toolbar
      private JButton Undo, Redo, Cut, Copy, Paste, FindReplace, SelectAll;
      private JButton New, Open, Save, SaveAs, SaveAll, DumpMemory, Print;
      private JButton Run, Assemble, Reset, Step, Backstep, Stop, Pause;
      private JButton Help;
   
      // The “action” objects, which include action listeners.  One of each will be created then
    // shared between a menu item and its corresponding toolbar button.  This is a very cool
    // technique because it relates the button and menu item so closely
    
      private Action fileNewAction, fileOpenAction, fileCloseAction, fileCloseAllAction, fileSaveAction;
      private Action fileSaveAsAction, fileSaveAllAction, fileDumpMemoryAction, filePrintAction, fileExitAction;
      EditUndoAction editUndoAction;
      EditRedoAction editRedoAction;
      private Action editCutAction, editCopyAction, editPasteAction, editFindReplaceAction, editSelectAllAction;
      private Action runAssembleAction, runGoAction, runStepAction, runBackstepAction, runResetAction, 
                     runStopAction, runPauseAction, runClearBreakpointsAction, runToggleBreakpointsAction;
      private Action settingsLabelAction, settingsPopupInputAction, settingsValueDisplayBaseAction, settingsAddressDisplayBaseAction,
                     settingsExtendedAction, settingsAssembleOnOpenAction, settingsAssembleAllAction,
                        settingsWarningsAreErrorsAction, settingsStartAtMainAction, settingsProgramArgumentsAction,
                        settingsDelayedBranchingAction, settingsExceptionHandlerAction, settingsEditorAction,
                        settingsHighlightingAction, settingsMemoryConfigurationAction;    
      private Action helpHelpAction, helpAboutAction;
   
   
    /**
      *  Constructor for the Class. Sets up a window object for the UI
    *   @param s Name of the window to be created.
    **/     
   
       public VenusUI(String s) {
         super(s);
         mainUI = this;
         Globals.setGui(this);
         this.editor = new Editor(this);
             
         double screenWidth  = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
         double screenHeight = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
         // basically give up some screen space if running at 800 x 600
         double messageWidthPct = (screenWidth<1000.0)? 0.67 : 0.73;          double messageHeightPct = (screenWidth<1000.0)? 0.12 : 0.15;          double mainWidthPct = (screenWidth<1000.0)? 0.67 : 0.73;          double mainHeightPct = (screenWidth<1000.0)? 0.60 : 0.65;          double registersWidthPct = (screenWidth<1000.0)? 0.18 : 0.22;          double registersHeightPct = (screenWidth<1000.0)? 0.72 : 0.80;                               Dimension messagesPanePreferredSize = new Dimension((int)(screenWidth*messageWidthPct),(int)(screenHeight*messageHeightPct));           Dimension mainPanePreferredSize = new Dimension((int)(screenWidth*mainWidthPct),(int)(screenHeight*mainHeightPct));          Dimension registersPanePreferredSize = new Dimension((int)(screenWidth*registersWidthPct),(int)(screenHeight*registersHeightPct));                   // the "restore" size (window control button that toggles with maximize)         // I want to keep it large, with enough room for user to get handles          //this.setSize((int)(screenWidth*.8),(int)(screenHeight*.8));                 Globals.initialize(true);                          //  image courtesy of NASA/JPL.            URL im = this.getClass().getResource(Globals.imagesPath+"RedMars16.gif");          if (im == null) {             System.out.println("Internal Error: images folder or file not found");             System.exit(0);          }                        Image mars = Toolkit.getDefaultToolkit().getImage(im);          this.setIconImage(mars);         // Everything in frame will be arranged on JPanel "center", which is only frame component.         // "center" has BorderLayout and 2 major components:         //   -- panel (jp) on North with 2 components         //      1. toolbar         //      2. run speed slider.         //   -- split pane (horizonSplitter) in center with 2 components side-by-side         //      1. split pane (splitter) with 2 components stacked         //         a. main pane, with 2 tabs (edit, execute)         //         b. messages pane with 2 tabs (mars, run I/O)         //      2. registers pane with 3 tabs (register file, coproc 0, coproc 1)         // I should probably run this breakdown out to full detail.  The components are created         // roughly in bottom-up order; some are created in component constructors and thus are         // not visible here.                   registersTab = new RegistersWindow();          coprocessor1Tab = new Coprocessor1Window();          coprocessor0Tab = new Coprocessor0Window();          registersPane = new RegistersPane(mainUI, registersTab,coprocessor1Tab, coprocessor0Tab);          registersPane.setPreferredSize(registersPanePreferredSize);                  //Insets defaultTabInsets = (Insets)UIManager.get("TabbedPane.tabInsets");         //UIManager.put("TabbedPane.tabInsets", new Insets(1, 1, 1, 1));          mainPane = new MainPane(mainUI, editor, registersTab, coprocessor1Tab, coprocessor0Tab);         //UIManager.put("TabbedPane.tabInsets", defaultTabInsets);                    mainPane.setPreferredSize(mainPanePreferredSize);          messagesPane= new MessagesPane();          messagesPane.setPreferredSize(messagesPanePreferredSize);          splitter= new JSplitPane(JSplitPane.VERTICAL_SPLIT, mainPane, messagesPane);          splitter.setOneTouchExpandable(true);          splitter.resetToPreferredSizes();          horizonSplitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, splitter, registersPane);          horizonSplitter.setOneTouchExpandable(true);          horizonSplitter.resetToPreferredSizes();                    // due to dependencies, do not set up menu/toolbar until now.          this.createActionObjects();          menu= this.setUpMenuBar();          this.setJMenuBar(menu);                   toolbar= this.setUpToolBar();                 JPanel jp = new JPanel(new FlowLayout(FlowLayout.LEFT));          jp.add(toolbar);          jp.add(RunSpeedPanel.getInstance());          JPanel center= new JPanel(new BorderLayout());          center.add(jp, BorderLayout.NORTH);          center.add(horizonSplitter);                                               this.getContentPane().add(center);                 FileStatus.reset();         // The following has side effect of establishing menu state          FileStatus.set(FileStatus.NO_FILE);                                 // This is invoked when opening the app.  It will set the app to          // appear at full screen size.          this.addWindowListener(                 new WindowAdapter() {                    public void windowOpened(WindowEvent e) {                      mainUI.setExtendedState(JFrame.MAXIMIZED_BOTH);                    }                });                // This is invoked when exiting the app through the X icon.  It will in turn         // check for unsaved edits before exiting.          this.addWindowListener(                 new WindowAdapter() {                    public void windowClosing(WindowEvent e) {                      if (mainUI.editor.closeAll()) {                         System.exit(0);                      }                    }                });                          // The following will handle the windowClosing event properly in the          // situation where user Cancels out of "save edits?" dialog.  By default,         // the GUI frame will be hidden but I want it to do nothing.          this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);                 this.pack();          this.setVisible(true);       }               /*      * Action objects are used instead of action listeners because one can be easily shared between      * a menu item and a toolbar button.  Does nice things like disable both if the action is      * disabled, etc.      */        private void createActionObjects() {          Toolkit tk = Toolkit.getDefaultToolkit();          Class cs = this.getClass();           try {             fileNewAction = new FileNewAction("New",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"New22.png"))),                                             "Create a new file for editing", new Integer(KeyEvent.VK_N),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);                   fileOpenAction = new FileOpenAction("Open ...",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Open22.png"))),                                                   "Open a file for editing", new Integer(KeyEvent.VK_O),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);               fileCloseAction = new FileCloseAction("Close", null,                                             "Close the current file", new Integer(KeyEvent.VK_C),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);                                   fileCloseAllAction = new FileCloseAllAction("Close All", null,                                             "Close all open files", new Integer(KeyEvent.VK_L),                                                   null, mainUI);                 fileSaveAction = new FileSaveAction("Save",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Save22.png"))),                                                   "Save the current file", new Integer(KeyEvent.VK_S),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);               fileSaveAsAction = new FileSaveAsAction("Save as ...",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"SaveAs22.png"))),                                                   "Save current file with different name", new Integer(KeyEvent.VK_A),                                                   null, mainUI);                 fileSaveAllAction = new FileSaveAllAction("Save All", null,                                             "Save all open files", new Integer(KeyEvent.VK_V),                                                   null, mainUI);                 fileDumpMemoryAction = new FileDumpMemoryAction("Dump Memory ...",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Dump22.png"))),                                                   "Dump machine code or data in an available format", new Integer(KeyEvent.VK_D),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);               filePrintAction = new FilePrintAction("Print ...",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Print22.gif"))),                                                   "Print current file", new Integer(KeyEvent.VK_P),                                                   null, mainUI);                 fileExitAction = new FileExitAction("Exit", null,                                          "Exit Mars", new Integer(KeyEvent.VK_X),                                                   null, mainUI);                 editUndoAction = new EditUndoAction("Undo",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Undo22.png"))),                                                   "Undo last edit", new Integer(KeyEvent.VK_U),                                             KeyStroke.getKeyStroke( KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);               editRedoAction = new EditRedoAction("Redo",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Redo22.png"))),                                                   "Redo last edit", new Integer(KeyEvent.VK_R),                                             KeyStroke.getKeyStroke( KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);                       editCutAction = new EditCutAction("Cut",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Cut22.gif"))),                                                   "Cut", new Integer(KeyEvent.VK_C),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);               editCopyAction = new EditCopyAction("Copy",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Copy22.png"))),                                                   "Copy", new Integer(KeyEvent.VK_O),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);               editPasteAction = new EditPasteAction("Paste",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Paste22.png"))),                                                   "Paste", new Integer(KeyEvent.VK_P),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);               editFindReplaceAction = new EditFindReplaceAction("Find/Replace",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Find22.png"))),                                                   "Find/Replace", new Integer(KeyEvent.VK_F),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_F, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);             editSelectAllAction = new EditSelectAllAction("Select All",                                              null, //new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Find22.png"))),                                                   "Select All", new Integer(KeyEvent.VK_A),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);             runAssembleAction = new RunAssembleAction("Assemble",                                               new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Assemble22.png"))),                                                   "Assemble the current file and clear breakpoints", new Integer(KeyEvent.VK_A),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_F3, 0),                                                    mainUI);                       runGoAction = new RunGoAction("Go",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Play22.png"))),                                                   "Run the current program", new Integer(KeyEvent.VK_G),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_F5, 0),                                                   mainUI);               runStepAction = new RunStepAction("Step",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"StepForward22.png"))),                                                   "Run one step at a time", new Integer(KeyEvent.VK_T),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_F7, 0),                                                   mainUI);               runBackstepAction = new RunBackstepAction("Backstep",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"StepBack22.png"))),                                                   "Undo the last step", new Integer(KeyEvent.VK_B),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_F8, 0),                                                    mainUI);               runPauseAction = new RunPauseAction("Pause",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Pause22.png"))),                                                   "Pause the currently running program", new Integer(KeyEvent.VK_P),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_F9, 0),                                                    mainUI);               runStopAction = new RunStopAction("Stop",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Stop22.png"))),                                                   "Stop the currently running program", new Integer(KeyEvent.VK_S),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_F11, 0),                                                    mainUI);             runResetAction = new RunResetAction("Reset",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Reset22.png"))),                                                   "Reset MIPS memory and registers", new Integer(KeyEvent.VK_R),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_F12,0),                                                   mainUI);               runClearBreakpointsAction = new RunClearBreakpointsAction("Clear all breakpoints",                                             null,                                                   "Clears all execution breakpoints set since the last assemble.",                                                   new Integer(KeyEvent.VK_K),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_K, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);               runToggleBreakpointsAction = new RunToggleBreakpointsAction("Toggle all breakpoints",                                             null,                                                   "Disable/enable all breakpoints without clearing (can also click Bkpt column header)",                                                   new Integer(KeyEvent.VK_T),                                                   KeyStroke.getKeyStroke( KeyEvent.VK_T, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),                                                   mainUI);               settingsLabelAction = new SettingsLabelAction("Show Labels Window (symbol table)",                                             null,                                                   "Toggle visibility of Labels window (symbol table) in the Execute tab",                                                   null,null,                                                   mainUI);             settingsPopupInputAction = new SettingsPopupInputAction("Popup dialog for input syscalls (5,6,7,8,12)",                                             null,                                                   "If set, use popup dialog for input syscalls (5,6,7,8,12) instead of cursor in Run I/O window",                                                   null,null,                                                   mainUI);                       settingsValueDisplayBaseAction = new SettingsValueDisplayBaseAction("Values displayed in hexadecimal",                                             null,                                                   "Toggle between hexadecimal and decimal display of memory/register values",                                                   null,null,                                                   mainUI);             settingsAddressDisplayBaseAction = new SettingsAddressDisplayBaseAction("Addresses displayed in hexadecimal",                                             null,                                                   "Toggle between hexadecimal and decimal display of memory addresses",                                                   null,null,                                                   mainUI);             settingsExtendedAction          = new SettingsExtendedAction("Permit extended (pseudo) instructions and formats",                                             null,                                                   "If set, MIPS extended (pseudo) instructions are formats are permitted.",                                                   null,null,                                                   mainUI);                 settingsAssembleOnOpenAction    = new SettingsAssembleOnOpenAction("Assemble file upon opening",                                             null,                                                   "If set, a file will be automatically assembled as soon as it is opened.  File Open dialog will show most recently opened file.",                                                   null,null,                                                   mainUI);             settingsAssembleAllAction       = new SettingsAssembleAllAction("Assemble all files in directory",                                             null,                                                   "If set, all files in current directory will be assembled when Assemble operation is selected.",                                                   null,null,                                                   mainUI);             settingsWarningsAreErrorsAction = new SettingsWarningsAreErrorsAction("Assembler warnings are considered errors",                                             null,                                                   "If set, assembler warnings will be interpreted as errors and prevent successful assembly.",                                                   null,null,                                                   mainUI);             settingsStartAtMainAction       = new SettingsStartAtMainAction("Initialize Program Counter to global 'main' if defined",                                             null,                                                   "If set, assembler will initialize Program Counter to text address globally labeled 'main', if defined.",                                                   null,null,                                                   mainUI);             settingsProgramArgumentsAction = new SettingsProgramArgumentsAction("Program arguments provided to MIPS program",                                             null,                                                   "If set, program arguments for MIPS program can be entered in border of Text Segment window.",                                                   null,null,                                                   mainUI);             settingsDelayedBranchingAction  = new SettingsDelayedBranchingAction("Delayed branching",                                             null,                                                   "If set, delayed branching will occur during MIPS execution.",                                                   null,null,                                                   mainUI);             settingsEditorAction          = new SettingsEditorAction("Editor...",                                             null,                                                   "View and modify text editor settings.",                                                   null,null,                                                   mainUI);             settingsHighlightingAction          = new SettingsHighlightingAction("Highlighting...",                                             null,                                                   "View and modify Execute Tab highlighting colors",                                                   null,null,                                                   mainUI);             settingsExceptionHandlerAction  = new SettingsExceptionHandlerAction("Exception Handler...",                                             null,                                                   "If set, the specified exception handler file will be included in all Assemble operations.",                                                   null,null,                                                   mainUI);             settingsMemoryConfigurationAction  = new SettingsMemoryConfigurationAction("Memory Configuration...",                                             null,                                                   "View and modify memory segment base addresses for simulated MIPS.",                                                   null,null,                                                   mainUI);             helpHelpAction = new HelpHelpAction("Help",                                              new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Help22.png"))),                                                   "Help", new Integer(KeyEvent.VK_H),                                                   KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0),                                                   mainUI);               helpAboutAction = new HelpAboutAction("About ...",null,                                              "Information about Mars", null,null, mainUI);             }               catch (NullPointerException e) {                System.out.println("Internal Error: images folder not found, or other null pointer exception while creating Action objects");                e.printStackTrace();                System.exit(0);             }       }         /*      * build the menus and connect them to action objects (which serve as action listeners      * shared between menu item and corresponding toolbar icon).      */             private JMenuBar setUpMenuBar() {                 Toolkit tk = Toolkit.getDefaultToolkit();          Class cs = this.getClass();           JMenuBar menuBar = new JMenuBar();          file=new JMenu("File");          file.setMnemonic(KeyEvent.VK_F);          edit = new JMenu("Edit");          edit.setMnemonic(KeyEvent.VK_E);          run=new JMenu("Run");          run.setMnemonic(KeyEvent.VK_R);          //window = new JMenu("Window");          //window.setMnemonic(KeyEvent.VK_W);          settings = new JMenu("Settings");          settings.setMnemonic(KeyEvent.VK_S);          help = new JMenu("Help");          help.setMnemonic(KeyEvent.VK_H);          // slight bug: user typing alt-H activates help menu item directly, not help menu                 fileNew = new JMenuItem(fileNewAction);          fileNew.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"New16.png"))));          fileOpen = new JMenuItem(fileOpenAction);          fileOpen.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Open16.png"))));          fileClose = new JMenuItem(fileCloseAction);          fileClose.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"MyBlank16.gif"))));          fileCloseAll = new JMenuItem(fileCloseAllAction);          fileCloseAll.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"MyBlank16.gif"))));          fileSave = new JMenuItem(fileSaveAction);          fileSave.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Save16.png"))));          fileSaveAs = new JMenuItem(fileSaveAsAction);          fileSaveAs.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"SaveAs16.png"))));          fileSaveAll = new JMenuItem(fileSaveAllAction);          fileSaveAll.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"MyBlank16.gif"))));          fileDumpMemory = new JMenuItem(fileDumpMemoryAction);          fileDumpMemory.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Dump16.png"))));          filePrint = new JMenuItem(filePrintAction);          filePrint.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"Print16.gif"))));          fileExit = new JMenuItem(fileExitAction);          fileExit.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+"MyBlank16.gif"))));          file.add(fileNew);          file.add(fileOpen);          file.add(fileClose);          file.add(fileCloseAll);          file.addSeparator();          file.add(fileSave);          file.add(fileSaveAs);          file.add(fileSaveAll);          if (new mars.mips.dump.DumpFormatLoader().loadDumpFormats().size() > 0) {
            file.add(fileDumpMemory);
         }
         file.addSeparator();
         file.add(filePrint);
         file.addSeparator();
         file.add(fileExit);
        
         editUndo = new JMenuItem(editUndoAction);
         editUndo.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Undo16.png”))));//”Undo16.gif”))));
         editRedo = new JMenuItem(editRedoAction);
         editRedo.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Redo16.png”))));//”Redo16.gif”))));      
         editCut = new JMenuItem(editCutAction);
         editCut.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Cut16.gif”))));
         editCopy = new JMenuItem(editCopyAction);
         editCopy.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Copy16.png”))));//”Copy16.gif”))));
         editPaste = new JMenuItem(editPasteAction);
         editPaste.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Paste16.png”))));//”Paste16.gif”))));
         editFindReplace = new JMenuItem(editFindReplaceAction);
         editFindReplace.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Find16.png”))));//”Paste16.gif”))));
         editSelectAll = new JMenuItem(editSelectAllAction);
         editSelectAll.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”MyBlank16.gif”))));
         edit.add(editUndo);
         edit.add(editRedo);
         edit.addSeparator();
         edit.add(editCut);
         edit.add(editCopy);
         edit.add(editPaste);
         edit.addSeparator();
         edit.add(editFindReplace);
         edit.add(editSelectAll);
      
         runAssemble = new JMenuItem(runAssembleAction);
         runAssemble.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Assemble16.png”))));//”MyAssemble16.gif”))));
         runGo = new JMenuItem(runGoAction);
         runGo.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Play16.png”))));//”Play16.gif”))));
         runStep = new JMenuItem(runStepAction);
         runStep.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”StepForward16.png”))));//”MyStepForward16.gif”))));
         runBackstep = new JMenuItem(runBackstepAction);
         runBackstep.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”StepBack16.png”))));//”MyStepBack16.gif”))));
         runReset = new JMenuItem(runResetAction);
         runReset.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Reset16.png”))));//”MyReset16.gif”))));
         runStop = new JMenuItem(runStopAction);
         runStop.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Stop16.png”))));//”Stop16.gif”))));
         runPause = new JMenuItem(runPauseAction);
         runPause.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Pause16.png”))));//”Pause16.gif”))));
         runClearBreakpoints = new JMenuItem(runClearBreakpointsAction);
         runClearBreakpoints.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”MyBlank16.gif”))));
         runToggleBreakpoints = new JMenuItem(runToggleBreakpointsAction);
         runToggleBreakpoints.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”MyBlank16.gif”))));
      
         run.add(runAssemble);
         run.add(runGo);
         run.add(runStep);
         run.add(runBackstep);
         run.add(runPause);
         run.add(runStop);
         run.add(runReset);
         run.addSeparator();
         run.add(runClearBreakpoints);
         run.add(runToggleBreakpoints);
        
         settingsLabel = new JCheckBoxMenuItem(settingsLabelAction);
         settingsLabel.setSelected(Globals.getSettings().getLabelWindowVisibility());
         settingsPopupInput = new JCheckBoxMenuItem(settingsPopupInputAction);
         settingsPopupInput.setSelected(Globals.getSettings().getBooleanSetting(Settings.POPUP_SYSCALL_INPUT));
         settingsValueDisplayBase = new JCheckBoxMenuItem(settingsValueDisplayBaseAction);
         settingsValueDisplayBase.setSelected(Globals.getSettings().getDisplayValuesInHex());//mainPane.getExecutePane().getValueDisplayBaseChooser().isSelected());
         // Tell the corresponding JCheckBox in the Execute Pane about me — it has already been created.
         mainPane.getExecutePane().getValueDisplayBaseChooser().setSettingsMenuItem(settingsValueDisplayBase);
         settingsAddressDisplayBase = new JCheckBoxMenuItem(settingsAddressDisplayBaseAction);
         settingsAddressDisplayBase.setSelected(Globals.getSettings().getDisplayAddressesInHex());//mainPane.getExecutePane().getValueDisplayBaseChooser().isSelected());
         // Tell the corresponding JCheckBox in the Execute Pane about me — it has already been created.
         mainPane.getExecutePane().getAddressDisplayBaseChooser().setSettingsMenuItem(settingsAddressDisplayBase);
         settingsExtended = new JCheckBoxMenuItem(settingsExtendedAction);
         settingsExtended.setSelected(Globals.getSettings().getExtendedAssemblerEnabled());
         settingsDelayedBranching = new JCheckBoxMenuItem(settingsDelayedBranchingAction);
         settingsDelayedBranching.setSelected(Globals.getSettings().getDelayedBranchingEnabled());
         settingsAssembleOnOpen = new JCheckBoxMenuItem(settingsAssembleOnOpenAction);
         settingsAssembleOnOpen.setSelected(Globals.getSettings().getAssembleOnOpenEnabled());
         settingsAssembleAll = new JCheckBoxMenuItem(settingsAssembleAllAction);
         settingsAssembleAll.setSelected(Globals.getSettings().getAssembleAllEnabled());
         settingsWarningsAreErrors = new JCheckBoxMenuItem(settingsWarningsAreErrorsAction);
         settingsWarningsAreErrors.setSelected(Globals.getSettings().getWarningsAreErrors());
         settingsStartAtMain = new JCheckBoxMenuItem(settingsStartAtMainAction);
         settingsStartAtMain.setSelected(Globals.getSettings().getStartAtMain()); 
         settingsProgramArguments = new JCheckBoxMenuItem(settingsProgramArgumentsAction);
         settingsProgramArguments.setSelected(Globals.getSettings().getProgramArguments());
         settingsEditor = new JMenuItem(settingsEditorAction);
         settingsHighlighting = new JMenuItem(settingsHighlightingAction);
         settingsExceptionHandler = new JMenuItem(settingsExceptionHandlerAction);
         settingsMemoryConfiguration = new JMenuItem(settingsMemoryConfigurationAction);
        
         settings.add(settingsLabel);
         settings.add(settingsProgramArguments);
         settings.add(settingsPopupInput);
         settings.add(settingsAddressDisplayBase);
         settings.add(settingsValueDisplayBase);
         settings.addSeparator();
         settings.add(settingsAssembleOnOpen);
         settings.add(settingsAssembleAll);
         settings.add(settingsWarningsAreErrors);
         settings.add(settingsStartAtMain);
         settings.addSeparator();
         settings.add(settingsExtended);
         settings.add(settingsDelayedBranching);
         settings.addSeparator();
         settings.add(settingsEditor);
         settings.add(settingsHighlighting);
         settings.add(settingsExceptionHandler);
         settings.add(settingsMemoryConfiguration);
                
         helpHelp = new JMenuItem(helpHelpAction);
         helpHelp.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”Help16.png”))));//”Help16.gif”))));
         helpAbout = new JMenuItem(helpAboutAction);
         helpAbout.setIcon(new ImageIcon(tk.getImage(cs.getResource(Globals.imagesPath+”MyBlank16.gif”))));
         help.add(helpHelp);
         help.addSeparator();
         help.add(helpAbout);
      
         menuBar.add(file);
         menuBar.add(edit);
         menuBar.add(run);
         menuBar.add(settings);
         JMenu toolMenu = new ToolLoader().buildToolsMenu();
         if (toolMenu != null) menuBar.add(toolMenu);
         menuBar.add(help);
        
        // experiment with popup menu for settings. 3 Aug 2006 PS
         //setupPopupMenu();
        
         return menuBar;
      }
   
    /*
     * build the toolbar and connect items to action objects (which serve as action listeners
     * shared between toolbar icon and corresponding menu item).
     */
   
       JToolBar setUpToolBar() {
         JToolBar toolBar = new JToolBar();
        
         New = new JButton(fileNewAction);
         New.setText(“”);
         Open = new JButton(fileOpenAction);
         Open.setText(“”); 
         Save = new JButton(fileSaveAction);
         Save.setText(“”);
         SaveAs = new JButton(fileSaveAsAction);
         SaveAs.setText(“”);
         DumpMemory = new JButton(fileDumpMemoryAction);
         DumpMemory.setText(“”);
         Print= new JButton(filePrintAction);
         Print.setText(“”);
      
         Undo = new JButton(editUndoAction);
         Undo.setText(“”); 
         Redo = new JButton(editRedoAction);
         Redo.setText(“”);      
         Cut= new JButton(editCutAction);
         Cut.setText(“”);
         Copy= new JButton(editCopyAction);
         Copy.setText(“”);
         Paste= new JButton(editPasteAction);
         Paste.setText(“”);
         FindReplace = new JButton(editFindReplaceAction);
         FindReplace.setText(“”);
         SelectAll = new JButton(editSelectAllAction);
         SelectAll.setText(“”);
        
         Run = new JButton(runGoAction);
         Run.setText(“”);
         Assemble = new JButton(runAssembleAction);
         Assemble.setText(“”); 
         Step = new JButton(runStepAction);
         Step.setText(“”); 
         Backstep = new JButton(runBackstepAction);
         Backstep.setText(“”);
         Reset = new JButton(runResetAction);
         Reset.setText(“”); 
         Stop = new JButton(runStopAction);
         Stop.setText(“”);
         Pause = new JButton(runPauseAction);
         Pause.setText(“”);         
         Help= new JButton(helpHelpAction);
         Help.setText(“”);
         
         toolBar.add(New);
         toolBar.add(Open);
         toolBar.add(Save);
         toolBar.add(SaveAs);
         if (new mars.mips.dump.DumpFormatLoader().loadDumpFormats().size() > 0) {
            toolBar.add(DumpMemory);
         }
         toolBar.add(Print);
         toolBar.add(new JToolBar.Separator());
         toolBar.add(Undo);
         toolBar.add(Redo);
         toolBar.add(Cut);
         toolBar.add(Copy);
         toolBar.add(Paste);
         toolBar.add(FindReplace);
         toolBar.add(new JToolBar.Separator());
         toolBar.add(Assemble);
         toolBar.add(Run);   
         toolBar.add(Step);
         toolBar.add(Backstep);
         toolBar.add(Pause);
         toolBar.add(Stop);
         toolBar.add(Reset);
         toolBar.add(new JToolBar.Separator());
         toolBar.add(Help);
         toolBar.add(new JToolBar.Separator());
        
         return toolBar;
      }
      
    
    /* Determine from FileStatus what the menu state (enabled/disabled)should 
     * be then call the appropriate method to set it.  Current states are:
     *
     * setMenuStateInitial: set upon startup and after File->Close
     * setMenuStateEditingNew: set upon File->New
     * setMenuStateEditing: set upon File->Open or File->Save or erroneous Run->Assemble
     * setMenuStateRunnable: set upon successful Run->Assemble
     * setMenuStateRunning: set upon Run->Go
     * setMenuStateTerminated: set upon completion of simulated execution
     */
       void setMenuState(int status) {
         menuState = status; 
         switch (status) {
            case FileStatus.NO_FILE:
               setMenuStateInitial();
               break;
            case FileStatus.NEW_NOT_EDITED:
               setMenuStateEditingNew();
               break;
            case FileStatus.NEW_EDITED:
               setMenuStateEditingNew();
               break;
            case FileStatus.NOT_EDITED:
               setMenuStateNotEdited(); // was MenuStateEditing. DPS 9-Aug-2011
               break;
            case FileStatus.EDITED:
               setMenuStateEditing();
               break;
            case FileStatus.RUNNABLE:
               setMenuStateRunnable();
               break;
            case FileStatus.RUNNING:
               setMenuStateRunning();
               break;
            case FileStatus.TERMINATED:
               setMenuStateTerminated();
               break;
            case FileStatus.OPENING:// This is a temporary state. DPS 9-Aug-2011
               break;
            default:
               System.out.println(“Invalid File Status: “+status);
               break;
         }
      }
     
     
       void setMenuStateInitial() {
         fileNewAction.setEnabled(true);
         fileOpenAction.setEnabled(true);
         fileCloseAction.setEnabled(false);
         fileCloseAllAction.setEnabled(false);
         fileSaveAction.setEnabled(false);
         fileSaveAsAction.setEnabled(false);
         fileSaveAllAction.setEnabled(false);
         fileDumpMemoryAction.setEnabled(false);
         filePrintAction.setEnabled(false);
         fileExitAction.setEnabled(true);
         editUndoAction.setEnabled(false);
         editRedoAction.setEnabled(false);
         editCutAction.setEnabled(false);
         editCopyAction.setEnabled(false);
         editPasteAction.setEnabled(false);
         editFindReplaceAction.setEnabled(false);
         editSelectAllAction.setEnabled(false);
         settingsDelayedBranchingAction.setEnabled(true); // added 25 June 2007
         settingsMemoryConfigurationAction.setEnabled(true); // added 21 July 2009
         runAssembleAction.setEnabled(false);
         runGoAction.setEnabled(false);
         runStepAction.setEnabled(false);
         runBackstepAction.setEnabled(false);
         runResetAction.setEnabled(false);
         runStopAction.setEnabled(false);
         runPauseAction.setEnabled(false);
         runClearBreakpointsAction.setEnabled(false);
         runToggleBreakpointsAction.setEnabled(false);
         helpHelpAction.setEnabled(true);
         helpAboutAction.setEnabled(true);
         editUndoAction.updateUndoState();
         editRedoAction.updateRedoState();
      }
   
      /* Added DPS 9-Aug-2011, for newly-opened files.  Retain
       existing Run menu state (except Assemble, which is always true).
        Thus if there was a valid assembly it is retained. */
       void setMenuStateNotEdited() {
      /* Note: undo and redo are handled separately by the undo manager*/  
         fileNewAction.setEnabled(true);
         fileOpenAction.setEnabled(true);
         fileCloseAction.setEnabled(true);
         fileCloseAllAction.setEnabled(true);
         fileSaveAction.setEnabled(true);
         fileSaveAsAction.setEnabled(true);
         fileSaveAllAction.setEnabled(true);
         fileDumpMemoryAction.setEnabled(false);
         filePrintAction.setEnabled(true);
         fileExitAction.setEnabled(true);
         editCutAction.setEnabled(true);
         editCopyAction.setEnabled(true);
         editPasteAction.setEnabled(true);
         editFindReplaceAction.setEnabled(true);
         editSelectAllAction.setEnabled(true);
         settingsDelayedBranchingAction.setEnabled(true); 
         settingsMemoryConfigurationAction.setEnabled(true);
         runAssembleAction.setEnabled(true);
            // If assemble-all, allow previous Run menu settings to remain.
            // Otherwise, clear them out.  DPS 9-Aug-2011
         if (!Globals.getSettings().getBooleanSetting(mars.Settings.ASSEMBLE_ALL_ENABLED)) {
            runGoAction.setEnabled(false);
            runStepAction.setEnabled(false);
            runBackstepAction.setEnabled(false);
            runResetAction.setEnabled(false);
            runStopAction.setEnabled(false);
            runPauseAction.setEnabled(false);
            runClearBreakpointsAction.setEnabled(false);
            runToggleBreakpointsAction.setEnabled(false);
         } 
         helpHelpAction.setEnabled(true);
         helpAboutAction.setEnabled(true);
         editUndoAction.updateUndoState();
         editRedoAction.updateRedoState();
      }
   
   
   
   
       void setMenuStateEditing() {
      /* Note: undo and redo are handled separately by the undo manager*/  
         fileNewAction.setEnabled(true);
         fileOpenAction.setEnabled(true);
         fileCloseAction.setEnabled(true);
         fileCloseAllAction.setEnabled(true);
         fileSaveAction.setEnabled(true);
         fileSaveAsAction.setEnabled(true);
         fileSaveAllAction.setEnabled(true);
         fileDumpMemoryAction.setEnabled(false);
         filePrintAction.setEnabled(true);
         fileExitAction.setEnabled(true);
         editCutAction.setEnabled(true);
         editCopyAction.setEnabled(true);
         editPasteAction.setEnabled(true);
         editFindReplaceAction.setEnabled(true);
         editSelectAllAction.setEnabled(true);
         settingsDelayedBranchingAction.setEnabled(true); // added 25 June 2007
         settingsMemoryConfigurationAction.setEnabled(true); // added 21 July 2009
         runAssembleAction.setEnabled(true);
         runGoAction.setEnabled(false);
         runStepAction.setEnabled(false);
         runBackstepAction.setEnabled(false);
         runResetAction.setEnabled(false);
         runStopAction.setEnabled(false);
         runPauseAction.setEnabled(false);
         runClearBreakpointsAction.setEnabled(false);
         runToggleBreakpointsAction.setEnabled(false);
         helpHelpAction.setEnabled(true);
         helpAboutAction.setEnabled(true);
         editUndoAction.updateUndoState();
         editRedoAction.updateRedoState();
      }
   
     /* Use this when “File -> New” is used
      */
       void setMenuStateEditingNew() {
      /* Note: undo and redo are handled separately by the undo manager*/  
         fileNewAction.setEnabled(true);
         fileOpenAction.setEnabled(true);
         fileCloseAction.setEnabled(true);
         fileCloseAllAction.setEnabled(true);
         fileSaveAction.setEnabled(true);
         fileSaveAsAction.setEnabled(true);
         fileSaveAllAction.setEnabled(true);
         fileDumpMemoryAction.setEnabled(false);
         filePrintAction.setEnabled(true);
         fileExitAction.setEnabled(true);
         editCutAction.setEnabled(true);
         editCopyAction.setEnabled(true);
         editPasteAction.setEnabled(true);
         editFindReplaceAction.setEnabled(true);
         editSelectAllAction.setEnabled(true);
         settingsDelayedBranchingAction.setEnabled(true); // added 25 June 2007
         settingsMemoryConfigurationAction.setEnabled(true); // added 21 July 2009
         runAssembleAction.setEnabled(false);
         runGoAction.setEnabled(false);
         runStepAction.setEnabled(false);
         runBackstepAction.setEnabled(false);
         runResetAction.setEnabled(false);
         runStopAction.setEnabled(false);
         runPauseAction.setEnabled(false);
         runClearBreakpointsAction.setEnabled(false);
         runToggleBreakpointsAction.setEnabled(false);
         helpHelpAction.setEnabled(true);
         helpAboutAction.setEnabled(true);
         editUndoAction.updateUndoState();
         editRedoAction.updateRedoState();
      }
         
     /* Use this upon successful assemble or reset
      */
       void setMenuStateRunnable() {
      /* Note: undo and redo are handled separately by the undo manager */  
         fileNewAction.setEnabled(true);
         fileOpenAction.setEnabled(true);
         fileCloseAction.setEnabled(true);
         fileCloseAllAction.setEnabled(true);
         fileSaveAction.setEnabled(true);
         fileSaveAsAction.setEnabled(true);
         fileSaveAllAction.setEnabled(true);
         fileDumpMemoryAction.setEnabled(true);
         filePrintAction.setEnabled(true);
         fileExitAction.setEnabled(true);
         editCutAction.setEnabled(true);
         editCopyAction.setEnabled(true);
         editPasteAction.setEnabled(true);
         editFindReplaceAction.setEnabled(true);
         editSelectAllAction.setEnabled(true);
         settingsDelayedBranchingAction.setEnabled(true); // added 25 June 2007
         settingsMemoryConfigurationAction.setEnabled(true); // added 21 July 2009
         runAssembleAction.setEnabled(true);
         runGoAction.setEnabled(true);
         runStepAction.setEnabled(true);
         runBackstepAction.setEnabled(
            (Globals.getSettings().getBackSteppingEnabled()&& !Globals.program.getBackStepper().empty())
             ? true : false);
         runResetAction.setEnabled(true);
         runStopAction.setEnabled(false);
         runPauseAction.setEnabled(false);
         runToggleBreakpointsAction.setEnabled(true);
         helpHelpAction.setEnabled(true);
         helpAboutAction.setEnabled(true);
         editUndoAction.updateUndoState();
         editRedoAction.updateRedoState();
      }
   
     /* Use this while program is running
      */
       void setMenuStateRunning() {
      /* Note: undo and redo are handled separately by the undo manager */  
         fileNewAction.setEnabled(false);
         fileOpenAction.setEnabled(false);
         fileCloseAction.setEnabled(false);
         fileCloseAllAction.setEnabled(false);
         fileSaveAction.setEnabled(false);
         fileSaveAsAction.setEnabled(false);
         fileSaveAllAction.setEnabled(false);
         fileDumpMemoryAction.setEnabled(false);
         filePrintAction.setEnabled(false);
         fileExitAction.setEnabled(false);
         editCutAction.setEnabled(false);
         editCopyAction.setEnabled(false);
         editPasteAction.setEnabled(false);
         editFindReplaceAction.setEnabled(false);
         editSelectAllAction.setEnabled(false);
         settingsDelayedBranchingAction.setEnabled(false); // added 25 June 2007
         settingsMemoryConfigurationAction.setEnabled(false); // added 21 July 2009
         runAssembleAction.setEnabled(false);
         runGoAction.setEnabled(false);
         runStepAction.setEnabled(false);
         runBackstepAction.setEnabled(false);
         runResetAction.setEnabled(false);
         runStopAction.setEnabled(true);
         runPauseAction.setEnabled(true);
         runToggleBreakpointsAction.setEnabled(false);
         helpHelpAction.setEnabled(true);
         helpAboutAction.setEnabled(true);
         editUndoAction.setEnabled(false);//updateUndoState(); // DPS 10 Jan 2008
         editRedoAction.setEnabled(false);//updateRedoState(); // DPS 10 Jan 2008
      }   
     /* Use this upon completion of execution
      */
       void setMenuStateTerminated() {
      /* Note: undo and redo are handled separately by the undo manager */  
         fileNewAction.setEnabled(true);
         fileOpenAction.setEnabled(true);
         fileCloseAction.setEnabled(true);
         fileCloseAllAction.setEnabled(true);
         fileSaveAction.setEnabled(true);
         fileSaveAsAction.setEnabled(true);
         fileSaveAllAction.setEnabled(true);
         fileDumpMemoryAction.setEnabled(true);
         filePrintAction.setEnabled(true);
         fileExitAction.setEnabled(true);
         editCutAction.setEnabled(true);
         editCopyAction.setEnabled(true);
         editPasteAction.setEnabled(true);
         editFindReplaceAction.setEnabled(true);
         editSelectAllAction.setEnabled(true);
         settingsDelayedBranchingAction.setEnabled(true); // added 25 June 2007
         settingsMemoryConfigurationAction.setEnabled(true); // added 21 July 2009
         runAssembleAction.setEnabled(true);
         runGoAction.setEnabled(false);
         runStepAction.setEnabled(false);
         runBackstepAction.setEnabled(
            (Globals.getSettings().getBackSteppingEnabled()&& !Globals.program.getBackStepper().empty())
             ? true : false);
         runResetAction.setEnabled(true);
         runStopAction.setEnabled(false);
         runPauseAction.setEnabled(false);
         runToggleBreakpointsAction.setEnabled(true);
         helpHelpAction.setEnabled(true);
         helpAboutAction.setEnabled(true);
         editUndoAction.updateUndoState();
         editRedoAction.updateRedoState();
      }
   
    
    /**
     * Get current menu state.  State values are constants in FileStatus class.  DPS 23 July 2008
     * @return current menu state.
     **/
     
       public static int getMenuState() {
         return menuState;
      }
      
    /**
      *  To set whether the register values are reset.
      *   @param b Boolean true if the register values have been reset.
      **/
    
       public static void setReset(boolean b){
         reset=b;
      }
   
    /**
      *  To set whether MIPS program execution has started.
      *   @param b true if the MIPS program execution has started.
      **/
    
       public static void setStarted(boolean b){ 
         started=b;
      }
      /**
      *  To find out whether the register values are reset.
      *   @return Boolean true if the register values have been reset.
      **/
      
       public static boolean getReset(){
         return reset;
      }
    
      /**
      *  To find out whether MIPS program is currently executing.
      *   @return  true if MIPS program is currently executing.
      **/
       public static boolean getStarted(){
         return started;
      }
    
      /**
      *  Get reference to Editor object associated with this GUI.
      *   @return Editor for the GUI.
      **/
            
       public Editor getEditor() {
         return editor;
      }     
    
      /**
      *  Get reference to messages pane associated with this GUI.
      *   @return MessagesPane object associated with the GUI.
      **/
            
       public MainPane getMainPane() {
         return mainPane;
      }      /**
      *  Get reference to messages pane associated with this GUI.
      *   @return MessagesPane object associated with the GUI.
      **/
            
       public MessagesPane getMessagesPane() {
         return messagesPane;
      }
   
      /**
      *  Get reference to registers pane associated with this GUI.
      *   @return RegistersPane object associated with the GUI.
      **/
            
       public RegistersPane getRegistersPane() {
         return registersPane;
      }     
   
      /**
      *  Get reference to settings menu item for display base of memory/register values.
      *   @return the menu item
      **/
            
       public JCheckBoxMenuItem getValueDisplayBaseMenuItem() {
         return settingsValueDisplayBase;
      }          
   
      /**
      *  Get reference to settings menu item for display base of memory/register values.
      *   @return the menu item
      **/
            
       public JCheckBoxMenuItem getAddressDisplayBaseMenuItem() {
         return settingsAddressDisplayBase;
      }               
    
    /**
     * Return reference tothe Run->Assemble item’s action.  Needed by File->Open in case
     * assemble-upon-open flag is set.
     * @return the Action object for the Run->Assemble operation.
     */
       public Action getRunAssembleAction() {
         return runAssembleAction;
      }
    
    /**
     * Have the menu request keyboard focus.  DPS 5-4-10
     */
       public void haveMenuRequestFocus() {
         this.menu.requestFocus();
      }
    
    /**
     * Send keyboard event to menu for possible processing.  DPS 5-4-10
     * @param evt KeyEvent for menu component to consider for processing.
     */
       public void dispatchEventToMenu(KeyEvent evt) {
         this.menu.dispatchEvent(evt);
      }
     
     // pop up menu experiment 3 Aug 2006.  Keep for possible later revival.
       private void setupPopupMenu() {
         JPopupMenu popup; 
         popup = new JPopupMenu();
        // cannot put the same menu item object on two different menus.
        // If you want to duplicate functionality, need a different item.
        // Should be able to share listeners, but if both menu items are
        // JCheckBoxMenuItem, how to keep their checked status in synch?
        // If you popup this menu and check the box, the right action occurs
        // but its counterpart on the regular menu is not checked.
         popup.add(new JCheckBoxMenuItem(settingsLabelAction)); 
      //Add listener to components that can bring up popup menus. 
         MouseListener popupListener = new PopupListener(popup); 
         this.addMouseListener(popupListener); 
      }
     
   
   
   }

MainPane

package mars.venus;
public synchronized class MainPane extends javax.swing.JTabbedPane {
EditPane editTab;
ExecutePane executeTab;
EditTabbedPane editTabbedPane;
private VenusUI mainUI;
public void MainPane(VenusUI, Editor, RegistersWindow, Coprocessor1Window, Coprocessor0Window);
public EditPane getEditPane();
public javax.swing.JComponent getEditTabbedPane();
public ExecutePane getExecutePane();
public ExecutePane getExecuteTab();
}

package mars.venus;
import mars.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.undo.*;
import java.text.*;
import java.util.*;
import java.io.*;
import javax.swing.plaf.basic.BasicTabbedPaneUI;

/*
Copyright (c) 2003-2006, Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
“Software”), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject
to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
*/

/**
* Creates the tabbed areas in the UI and also created the internal windows that
* exist in them.
* @author Sanderson and Bumgarner
**/

public class MainPane extends JTabbedPane{
EditPane editTab;
ExecutePane executeTab;
EditTabbedPane editTabbedPane;

private VenusUI mainUI;

/**
* Constructor for the MainPane class.
**/

public MainPane(VenusUI appFrame, Editor editor, RegistersWindow regs,
Coprocessor1Window cop1Regs,Coprocessor0Window cop0Regs){
super();
this.mainUI = appFrame;
this.setTabPlacement(JTabbedPane.TOP); //LEFT);
if (this.getUI() instanceof BasicTabbedPaneUI) {
BasicTabbedPaneUI ui = (BasicTabbedPaneUI) this.getUI();
}
editTabbedPane = new EditTabbedPane(appFrame, editor, this);
executeTab = new ExecutePane(appFrame, regs, cop1Regs, cop0Regs);
String editTabTitle = “Edit”; //” 
E
d
i
t
 “;
String executeTabTitle = “Execute”; //” 
E
x
e
c
u
t
e
 “;
Icon editTabIcon = null;//new ImageIcon(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(Globals.imagesPath+”Edit_tab.jpg”)));
Icon executeTabIcon = null;//new ImageIcon(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(Globals.imagesPath+”Execute_tab.jpg”)));

this.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
this.addTab(editTabTitle, editTabIcon, editTabbedPane);

// this.addTab(” 
P
r
o
j
 
1″, null, new JTabbedPane());
// this.addTab(” 
P
r
o
j
 
2″, null, new JTabbedPane());
// this.addTab(” 
P
r
o
j
 
3″, null, new JTabbedPane());
// this.addTab(” 
P
r
o
j
 
4″, null, new JTabbedPane());

this.addTab(executeTabTitle, executeTabIcon, executeTab);

this.setToolTipTextAt(0,”Text editor for composing MIPS programs.”);
this.setToolTipTextAt(1,”View and control assembly language program execution. Enabled upon successful assemble.”);

/* Listener has one specific purpose: when Execute tab is selected for the
* first time, set the bounds of its internal frames by invoking the
* setWindowsBounds() method. Once this occurs, listener removes itself!
* We do NOT want to reset bounds each time Execute tab is selected.
* See ExecutePane.setWindowsBounds documentation for more details.
*/
this.addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
JTabbedPane tabbedPane = (JTabbedPane) ce.getSource();
int index = tabbedPane.getSelectedIndex();
Component c = tabbedPane.getComponentAt(index);
ExecutePane executePane = Globals.getGui().getMainPane().getExecutePane();
if (c == executePane) {
executePane.setWindowBounds();
Globals.getGui().getMainPane().removeChangeListener(this);
}
}
});
}

/**
* Returns current edit pane. Implementation changed for MARS 4.0 support
* for multiple panes, but specification is same.
*
* @return the editor pane
*/
public EditPane getEditPane() {
return editTabbedPane.getCurrentEditTab();
}

/**
* Returns component containing editor display
*
* @return the editor tabbed pane
*/
public JComponent getEditTabbedPane() {
return editTabbedPane;
}

/**
* returns component containing execution-time display
*
* @return the execute pane
*/
public ExecutePane getExecutePane() {
return executeTab;
}

/**
* returns component containing execution-time display.
* Same as getExecutePane().
*
* @return the execute pane
*/
public ExecutePane getExecuteTab() {
return executeTab;
}

}

DataSegmentWindow$4

package mars.venus;
synchronized class DataSegmentWindow$4 implements java.awt.event.ActionListener {
void DataSegmentWindow$4(DataSegmentWindow);
public void actionPerformed(java.awt.event.ActionEvent);
}

RegistersWindow

package mars.venus;
public synchronized class RegistersWindow extends javax.swing.JPanel implements java.util.Observer {
private static javax.swing.JTable table;
private static mars.mips.hardware.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 mars.Settings settings;
public void RegistersWindow();
public Object[][] setupWindow();
public void clearWindow();
public void clearHighlighting();
public void refresh();
public void updateRegisters();
public void updateRegisters(int);
public void updateRegisterValue(int, int, int);
private void updateRegisterUnsignedValue(int, int, int);
public void update(java.util.Observable, Object);
void highlightCellForRegister(mars.mips.hardware.Register);
}

mars/venus/GuiAction.java
mars/venus/GuiAction.java   package mars.venus;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
    /**
     * parent class for Action subclasses to be defined for every menu/toolbar
     * option.
     */
     
    public class GuiAction extends AbstractAction {
      protected VenusUI mainUI;
     
       protected GuiAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon);
         putValue(SHORT_DESCRIPTION, descrip);
         putValue(MNEMONIC_KEY, mnemonic);  
         putValue(ACCELERATOR_KEY, accel);
         mainUI = gui;
      }
        /** 
         * does nothing by default.  Should be over-ridden by subclass
         */
       public void actionPerformed(ActionEvent e) {
       
      }
   }

SettingsEditorAction$EditorFontDialog$2

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog$2 implements java.awt.event.ActionListener {
void SettingsEditorAction$EditorFontDialog$2(SettingsEditorAction$EditorFontDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

HelpHelpAction$HelpHyperlinkListener

package mars.venus;
synchronized class HelpHelpAction$HelpHyperlinkListener implements javax.swing.event.HyperlinkListener {
javax.swing.JDialog webpageDisplay;
javax.swing.JTextField webpageURL;
private static final String cannotDisplayMessage = Unable to display requested document.;
private void HelpHelpAction$HelpHyperlinkListener(HelpHelpAction);
public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent);
}

DataSegmentWindow

package mars.venus;
public synchronized class DataSegmentWindow extends javax.swing.JInternalFrame implements java.util.Observer {
private static final String[] dataSegmentNames;
private static Object[][] dataData;
private static javax.swing.JTable dataTable;
private javax.swing.JScrollPane dataTableScroller;
private java.awt.Container contentPane;
private javax.swing.JPanel tablePanel;
private javax.swing.JButton dataButton;
private javax.swing.JButton nextButton;
private javax.swing.JButton prevButton;
private javax.swing.JButton stakButton;
private javax.swing.JButton globButton;
private javax.swing.JButton heapButton;
private javax.swing.JButton kernButton;
private javax.swing.JButton extnButton;
private javax.swing.JButton mmioButton;
private javax.swing.JCheckBox asciiDisplayCheckBox;
static final int VALUES_PER_ROW = 8;
static final int NUMBER_OF_ROWS = 16;
static final int NUMBER_OF_COLUMNS = 9;
static final int BYTES_PER_VALUE = 4;
static final int BYTES_PER_ROW = 32;
static final int MEMORY_CHUNK_SIZE = 512;
static final int PREV_NEXT_CHUNK_SIZE = 256;
static final int ADDRESS_COLUMN = 0;
static final boolean USER_MODE = 0;
static final boolean KERNEL_MODE = 1;
private boolean addressHighlighting;
private boolean asciiDisplay;
private int addressRow;
private int addressColumn;
private int addressRowFirstAddress;
private mars.Settings settings;
int firstAddress;
int homeAddress;
boolean userOrKernelMode;
javax.swing.JComboBox baseAddressSelector;
private String[] displayBaseAddressChoices;
private int[] displayBaseAddresses;
private int defaultBaseAddressIndex;
javax.swing.JButton[] baseAddressButtons;
private static final int EXTERN_BASE_ADDRESS_INDEX = 0;
private static final int GLOBAL_POINTER_ADDRESS_INDEX = 1;
private static final int DATA_BASE_ADDRESS_INDEX = 2;
private static final int HEAP_BASE_ADDRESS_INDEX = 3;
private static final int STACK_POINTER_BASE_ADDRESS_INDEX = 4;
private static final int KERNEL_DATA_BASE_ADDRESS_INDEX = 5;
private static final int MMIO_BASE_ADDRESS_INDEX = 6;
private int[] displayBaseAddressArray;
String[] descriptions;
static void ();
public void DataSegmentWindow(NumberDisplayBaseChooser[]);
public void updateBaseAddressComboBox();
void selectCellForAddress(int);
void highlightCellForAddress(int);
private java.awt.Point displayCellForAddress(int);
private void initializeBaseAddressChoices();
private String[] createBaseAddressLabelsArray(int[], String[]);
private int getBaseAddressIndexForAddress(int);
private javax.swing.JScrollPane generateDataPanel();
private String getHeaderStringForColumn(int, int);
public void setupTable();
public void clearWindow();
public void clearHighlighting();
private int getValueDisplayFormat();
public void updateModelForMemoryRange(int);
public void updateCell(int, int);
public void updateDataAddresses();
public void updateValues();
public void resetMemoryRange();
public void resetValues();
private void disableAllButtons();
private void enableAllButtons();
private void addButtonActionListenersAndInitialize();
private int setFirstAddressAndPrevNextButtonEnableStatus(int);
public void update(java.util.Observable, Object);
}

MessagesPane$Asker$2

package mars.venus;
synchronized class MessagesPane$Asker$2 extends javax.swing.text.NavigationFilter {
void MessagesPane$Asker$2(MessagesPane$Asker);
public void moveDot(javax.swing.text.NavigationFilter$FilterBypass, int, javax.swing.text.Position$Bias);
public void setDot(javax.swing.text.NavigationFilter$FilterBypass, int, javax.swing.text.Position$Bias);
}

mars/venus/FileCloseAction.java
mars/venus/FileCloseAction.java   package mars.venus;
   import mars.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
 
 /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
 
    /**
    * Action  for the File -> Close menu item
    */              
    public class FileCloseAction extends GuiAction {
     
       public FileCloseAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
    
       public void actionPerformed(ActionEvent e){
              mainUI.editor.close();
      }
   }

mars/venus/SettingsPopupInputAction.java
mars/venus/SettingsPopupInputAction.java   package mars.venus;

    import mars.*;
   import java.awt.event.*;
   import javax.swing.*;
    
    /*
Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item to control use of popup dialog for input syscalls.
    */
    public class SettingsPopupInputAction extends GuiAction  {
    
   
       public SettingsPopupInputAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
           boolean usePopup = ((JCheckBoxMenuItem) e.getSource()).isSelected();
         Globals.getSettings().setBooleanSetting(Settings.POPUP_SYSCALL_INPUT, usePopup);
      }
        
   }

AbstractFontSettingDialog$BlockComboListener

package mars.venus;
synchronized class AbstractFontSettingDialog$BlockComboListener implements java.awt.event.ActionListener {
javax.swing.JComboBox combo;
Object currentItem;
void AbstractFontSettingDialog$BlockComboListener(AbstractFontSettingDialog, javax.swing.JComboBox);
public void actionPerformed(java.awt.event.ActionEvent);
}

Editor

package mars.venus;
public synchronized class Editor {
public static final int MIN_TAB_SIZE = 1;
public static final int MAX_TAB_SIZE = 32;
public static final int MIN_BLINK_RATE = 0;
public static final int MAX_BLINK_RATE = 1000;
private VenusUI mainUI;
private EditTabbedPane editTabbedPane;
private String mainUIbaseTitle;
private int newUsageCount;
private String defaultOpenDirectory;
private String currentOpenDirectory;
private String defaultSaveDirectory;
private String currentSaveDirectory;
public void Editor(VenusUI);
public void setEditTabbedPane(EditTabbedPane);
public String getCurrentOpenDirectory();
void setCurrentOpenDirectory(String);
public String getCurrentSaveDirectory();
void setCurrentSaveDirectory(String);
public String getNextDefaultFilename();
public void setTitle(String, String, int);
public void newFile();
public boolean close();
public boolean closeAll();
public boolean save();
public boolean saveAs();
public boolean saveAll();
public boolean open();
public boolean editsSavedOrAbandoned();
}

DataSegmentWindow$6

package mars.venus;
synchronized class DataSegmentWindow$6 implements java.awt.event.ActionListener {
void DataSegmentWindow$6(DataSegmentWindow);
public void actionPerformed(java.awt.event.ActionEvent);
}

LabelsWindow$DescendingComparator

package mars.venus;
synchronized class LabelsWindow$DescendingComparator implements java.util.Comparator {
private java.util.Comparator opposite;
private void LabelsWindow$DescendingComparator(LabelsWindow, java.util.Comparator);
public int compare(Object, Object);
}

FileSaveAction

package mars.venus;
public synchronized class FileSaveAction extends GuiAction {
public void FileSaveAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/SettingsAssembleOnOpenAction.java
mars/venus/SettingsAssembleOnOpenAction.java   package mars.venus;
   import mars.simulator.*;
    import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item to control automatic assemble of file upon opening.
    */
    public class SettingsAssembleOnOpenAction extends GuiAction  {
    
   
       public SettingsAssembleOnOpenAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
           Globals.getSettings().setAssembleOnOpenEnabled(
               ((JCheckBoxMenuItem) e.getSource()).isSelected());
      }
        
   }

SettingsHighlightingAction$FontSettingDialog$3

package mars.venus;
synchronized class SettingsHighlightingAction$FontSettingDialog$3 implements java.awt.event.ActionListener {
void SettingsHighlightingAction$FontSettingDialog$3(SettingsHighlightingAction$FontSettingDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/SettingsExceptionHandlerAction.java
mars/venus/SettingsExceptionHandlerAction.java   package mars.venus;
   import mars.simulator.*;
   import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.text.*;
   import javax.swing.border.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item for optionally loading a MIPS exception handler.
    */
    public class SettingsExceptionHandlerAction extends GuiAction  {
    
      JDialog exceptionHandlerDialog;
      JCheckBox exceptionHandlerSetting;
      JButton exceptionHandlerSelectionButton;
      JTextField exceptionHandlerDisplay;
    
      boolean initialSelected; // state of check box when dialog initiated.
      String initialPathname;  // selected exception handler when dialog initiated.
      
       public SettingsExceptionHandlerAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
     
     // launch dialog for setting and filename specification
       public void actionPerformed(ActionEvent e) {
         initialSelected = Globals.getSettings().getExceptionHandlerEnabled();
         initialPathname = Globals.getSettings().getExceptionHandler();
         exceptionHandlerDialog = new JDialog(Globals.getGui(), “Exception Handler”, true);
         exceptionHandlerDialog.setContentPane(buildDialogPanel());
         exceptionHandlerDialog.setDefaultCloseOperation(
                        JDialog.DO_NOTHING_ON_CLOSE);
         exceptionHandlerDialog.addWindowListener(
                new WindowAdapter() {
                   public void windowClosing(WindowEvent we) {
                     closeDialog();
                  }
               });
         exceptionHandlerDialog.pack();
         exceptionHandlerDialog.setLocationRelativeTo(Globals.getGui());
         exceptionHandlerDialog.setVisible(true);
      }
          
      // The dialog box that appears when menu item is selected.
       private JPanel buildDialogPanel() {
         JPanel contents = new JPanel(new BorderLayout(20,20));
         contents.setBorder(new EmptyBorder(10,10,10,10));
        // Top row – the check box for setting…
         exceptionHandlerSetting = new JCheckBox(“Include this exception handler file in all assemble operations”);
         exceptionHandlerSetting.setSelected(Globals.getSettings().getExceptionHandlerEnabled());
         exceptionHandlerSetting.addActionListener(new ExceptionHandlerSettingAction());
         contents.add(exceptionHandlerSetting,BorderLayout.NORTH);
        // Middle row – the button and text field for exception handler file selection
         JPanel specifyHandlerFile = new JPanel();
         exceptionHandlerSelectionButton = new JButton(“Browse”);
         exceptionHandlerSelectionButton.setEnabled(exceptionHandlerSetting.isSelected());
         exceptionHandlerSelectionButton.addActionListener(new ExceptionHandlerSelectionAction());
         exceptionHandlerDisplay = new JTextField(Globals.getSettings().getExceptionHandler(), 30);
         exceptionHandlerDisplay.setEditable(false);
         exceptionHandlerDisplay.setEnabled(exceptionHandlerSetting.isSelected());          
         specifyHandlerFile.add(exceptionHandlerSelectionButton);
         specifyHandlerFile.add(exceptionHandlerDisplay);
         contents.add(specifyHandlerFile, BorderLayout.CENTER);
        // Bottom row – the control buttons for OK and Cancel
         Box controlPanel = Box.createHorizontalBox();
         JButton okButton = new JButton(“OK”);
         okButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     performOK();
                     closeDialog();
                  }
               });
         JButton cancelButton = new JButton(“Cancel”);
         cancelButton.addActionListener(
                new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                     closeDialog();
                  }
               });  
         controlPanel.add(Box.createHorizontalGlue());
         controlPanel.add(okButton);
         controlPanel.add(Box.createHorizontalGlue());
         controlPanel.add(cancelButton);
         controlPanel.add(Box.createHorizontalGlue());
         contents.add(controlPanel,BorderLayout.SOUTH);
         return contents;
      }  
    
    // User has clicked “OK” button, so record status of the checkbox and text field.
       private void performOK() {
         boolean finalSelected = exceptionHandlerSetting.isSelected();
         String  finalPathname = exceptionHandlerDisplay.getText();
            // If nothing has changed then don’t modify setting variables or properties file.
         if (initialSelected != finalSelected
             || initialPathname==null && finalPathname!=null
             || initialPathname!=null && !initialPathname.equals(finalPathname)) 
         {
            Globals.getSettings().setExceptionHandlerEnabled(finalSelected);
            if (finalSelected) {
               Globals.getSettings().setExceptionHandler(finalPathname);
            }
         }
      }
    
    // We’re finished with this modal dialog.
       private void closeDialog() {
         exceptionHandlerDialog.setVisible(false);
         exceptionHandlerDialog.dispose();
      }
         
           
    /////////////////////////////////////////////////////////////////////////////////
    // Associated action class: exception handler setting.  Attached to check box.      
       private class ExceptionHandlerSettingAction implements ActionListener {
          public void actionPerformed(ActionEvent e) {
            boolean selected = ((JCheckBox) e.getSource()).isSelected();
            exceptionHandlerSelectionButton.setEnabled(selected);
            exceptionHandlerDisplay.setEnabled(selected);
         }
      }
                
                
    /////////////////////////////////////////////////////////////////////////////////
    // Associated action class: selecting exception handler file.  Attached to handler selector.
       private class ExceptionHandlerSelectionAction implements ActionListener {
          public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            String pathname = Globals.getSettings().getExceptionHandler();
            if (pathname != null) {
               File file = new File(pathname);
               if (file.exists()) chooser.setSelectedFile(file);
            }
            int result = chooser.showOpenDialog(Globals.getGui());
            if (result == JFileChooser.APPROVE_OPTION) {
               pathname = chooser.getSelectedFile().getPath();//.replaceAll(“\\\\”,”/”);
               exceptionHandlerDisplay.setText(pathname);
            }
         }
      }
        
   }

mars/venus/RunStopAction.java
mars/venus/RunStopAction.java   package mars.venus;
   import mars.simulator.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Run -> Stop menu item (and toolbar icon)
    */
    public class RunStopAction extends GuiAction  {
    
   
       public RunStopAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
         Simulator.getInstance().stopExecution(this);
            // RunGoAction’s “stopped” method will take care of the cleanup.
      }
        
   }

ToolAction

package mars.venus;
public synchronized class ToolAction extends javax.swing.AbstractAction {
private Class toolClass;
public void ToolAction(Class, String);
public void actionPerformed(java.awt.event.ActionEvent);
}

TextSegmentWindow$MyTippedJTable$TextTableHeader$TextTableHeaderMouseListener

package mars.venus;
synchronized class TextSegmentWindow$MyTippedJTable$TextTableHeader$TextTableHeaderMouseListener implements java.awt.event.MouseListener {
private void TextSegmentWindow$MyTippedJTable$TextTableHeader$TextTableHeaderMouseListener(TextSegmentWindow$MyTippedJTable$TextTableHeader);
public void mouseClicked(java.awt.event.MouseEvent);
public void mouseEntered(java.awt.event.MouseEvent);
public void mouseExited(java.awt.event.MouseEvent);
public void mousePressed(java.awt.event.MouseEvent);
public void mouseReleased(java.awt.event.MouseEvent);
}

AbstractFontSettingDialog$1

package mars.venus;
synchronized class AbstractFontSettingDialog$1 extends java.awt.event.WindowAdapter {
void AbstractFontSettingDialog$1(AbstractFontSettingDialog);
public void windowClosing(java.awt.event.WindowEvent);
}

SettingsExceptionHandlerAction$1

package mars.venus;
synchronized class SettingsExceptionHandlerAction$1 extends java.awt.event.WindowAdapter {
void SettingsExceptionHandlerAction$1(SettingsExceptionHandlerAction);
public void windowClosing(java.awt.event.WindowEvent);
}

Coprocessor1Window

package mars.venus;
public synchronized class Coprocessor1Window extends javax.swing.JPanel implements java.awt.event.ActionListener, java.util.Observer {
private static javax.swing.JTable table;
private static mars.mips.hardware.Register[] registers;
private Object[][] tableData;
private boolean highlighting;
private int highlightRow;
private ExecutePane executePane;
private javax.swing.JCheckBox[] conditionFlagCheckBox;
private static final int NAME_COLUMN = 0;
private static final int FLOAT_COLUMN = 1;
private static final int DOUBLE_COLUMN = 2;
private static mars.Settings settings;
public void Coprocessor1Window();
public void actionPerformed(java.awt.event.ActionEvent);
public Object[][] setupWindow();
public void clearWindow();
public void clearHighlighting();
public void refresh();
public void updateRegisters();
public void updateRegisters(int);
private void updateConditionFlagDisplay();
public void updateFloatRegisterValue(int, int, int);
public void updateDoubleRegisterValue(int, int);
public void update(java.util.Observable, Object);
void highlightCellForRegister(mars.mips.hardware.Register);
}

SettingsHighlightingAction$FontChanger

package mars.venus;
synchronized class SettingsHighlightingAction$FontChanger implements java.awt.event.ActionListener {
private int position;
public void SettingsHighlightingAction$FontChanger(SettingsHighlightingAction, int);
public void actionPerformed(java.awt.event.ActionEvent);
}

MessagesPane$3

package mars.venus;
synchronized class MessagesPane$3 implements java.awt.event.ActionListener {
void MessagesPane$3(MessagesPane);
public void actionPerformed(java.awt.event.ActionEvent);
}

SettingsExceptionHandlerAction$ExceptionHandlerSelectionAction

package mars.venus;
synchronized class SettingsExceptionHandlerAction$ExceptionHandlerSelectionAction implements java.awt.event.ActionListener {
private void SettingsExceptionHandlerAction$ExceptionHandlerSelectionAction(SettingsExceptionHandlerAction);
public void actionPerformed(java.awt.event.ActionEvent);
}

EditTabbedPane$FileOpener$ChoosableFileFilterChangeListener

package mars.venus;
synchronized class EditTabbedPane$FileOpener$ChoosableFileFilterChangeListener implements java.beans.PropertyChangeListener {
private void EditTabbedPane$FileOpener$ChoosableFileFilterChangeListener(EditTabbedPane$FileOpener);
public void propertyChange(java.beans.PropertyChangeEvent);
}

DataSegmentWindow$CustomComboBoxModel

package mars.venus;
synchronized class DataSegmentWindow$CustomComboBoxModel extends javax.swing.DefaultComboBoxModel {
public void DataSegmentWindow$CustomComboBoxModel(DataSegmentWindow, Object[]);
private void forceComboBoxUpdate(int);
}

FileDumpMemoryAction$2

package mars.venus;
synchronized class FileDumpMemoryAction$2 implements java.awt.event.ActionListener {
void FileDumpMemoryAction$2(FileDumpMemoryAction);
public void actionPerformed(java.awt.event.ActionEvent);
}

SettingsMemoryConfigurationAction$MemoryConfigurationDialog$3

package mars.venus;
synchronized class SettingsMemoryConfigurationAction$MemoryConfigurationDialog$3 implements java.awt.event.ActionListener {
void SettingsMemoryConfigurationAction$MemoryConfigurationDialog$3(SettingsMemoryConfigurationAction$MemoryConfigurationDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

FileSaveAsAction

package mars.venus;
public synchronized class FileSaveAsAction extends GuiAction {
public void FileSaveAsAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

FileCloseAllAction

package mars.venus;
public synchronized class FileCloseAllAction extends GuiAction {
public void FileCloseAllAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

mars/venus/SettingsValueDisplayBaseAction.java
mars/venus/SettingsValueDisplayBaseAction.java   package mars.venus;
   import mars.simulator.*;
    import mars.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Action class for the Settings menu item to control number base (10 or 16) of memory/register contents.
    */
    public class SettingsValueDisplayBaseAction extends GuiAction  {
    
   
       public SettingsValueDisplayBaseAction(String name, Icon icon, String descrip,
                             Integer mnemonic, KeyStroke accel, VenusUI gui) {
         super(name, icon, descrip, mnemonic, accel, gui);
      }
         
       public void actionPerformed(ActionEvent e) {
           boolean isHex = ((JCheckBoxMenuItem) e.getSource()).isSelected(); 
           Globals.getGui().getMainPane().getExecutePane().getValueDisplayBaseChooser().setSelected(isHex);
            Globals.getSettings().setDisplayValuesInHex(isHex);
      }
        
   }

SettingsEditorAction$EditorFontDialog$4

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog$4 implements java.awt.event.ActionListener {
void SettingsEditorAction$EditorFontDialog$4(SettingsEditorAction$EditorFontDialog);
public void actionPerformed(java.awt.event.ActionEvent);
}

HelpHelpAction$HelpHyperlinkListener$1

package mars.venus;
synchronized class HelpHelpAction$HelpHyperlinkListener$1 implements javax.swing.event.HyperlinkListener {
void HelpHelpAction$HelpHyperlinkListener$1(HelpHelpAction$HelpHyperlinkListener);
public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent);
}

SettingsMemoryConfigurationAction$ConfigurationButton

package mars.venus;
synchronized class SettingsMemoryConfigurationAction$ConfigurationButton extends javax.swing.JRadioButton {
private mars.mips.hardware.MemoryConfiguration configuration;
public void SettingsMemoryConfigurationAction$ConfigurationButton(SettingsMemoryConfigurationAction, mars.mips.hardware.MemoryConfiguration);
public mars.mips.hardware.MemoryConfiguration getConfiguration();
}

DataSegmentWindow$2

package mars.venus;
synchronized class DataSegmentWindow$2 implements java.awt.event.ItemListener {
void DataSegmentWindow$2(DataSegmentWindow);
public void itemStateChanged(java.awt.event.ItemEvent);
}

RunPauseAction

package mars.venus;
public synchronized class RunPauseAction extends GuiAction {
public void RunPauseAction(String, javax.swing.Icon, String, Integer, javax.swing.KeyStroke, VenusUI);
public void actionPerformed(java.awt.event.ActionEvent);
}

Coprocessor0Window$MyTippedJTable$1

package mars.venus;
synchronized class Coprocessor0Window$MyTippedJTable$1 extends javax.swing.table.JTableHeader {
void Coprocessor0Window$MyTippedJTable$1(Coprocessor0Window$MyTippedJTable, javax.swing.table.TableColumnModel);
public String getToolTipText(java.awt.event.MouseEvent);
}

EditPane

package mars.venus;
public synchronized class EditPane extends javax.swing.JPanel implements java.util.Observer {
private editors.MARSTextEditingArea sourceCode;
private VenusUI mainUI;
private String currentDirectoryPath;
private javax.swing.JLabel caretPositionLabel;
private javax.swing.JCheckBox showLineNumbers;
private javax.swing.JLabel lineNumbers;
private static int count;
private boolean isCompoundEdit;
private javax.swing.undo.CompoundEdit compoundEdit;
private FileStatus fileStatus;
private static final String spaces =          ;
private static final char newline = 10;
static void ();
public void EditPane(VenusUI);
public void setSourceCode(String, boolean);
public void discardAllUndoableEdits();
public String getLineNumbersList(javax.swing.text.Document);
public int getSourceLineCount();
public String getSource();
public void setFileStatus(int);
public int getFileStatus();
public String getFilename();
public String getPathname();
public void setPathname(String);
public boolean hasUnsavedEdits();
public boolean isNew();
public void tellEditingComponentToRequestFocusInWindow();
public void updateStaticFileStatus();
public javax.swing.undo.UndoManager getUndoManager();
public void copyText();
public void cutText();
public void pasteText();
public void selectAllText();
public void undo();
public void redo();
public void updateUndoState();
public void updateRedoState();
public boolean showingLineNumbers();
public void setShowLineNumbersEnabled(boolean);
public void displayCaretPosition(int);
public void displayCaretPosition(java.awt.Point);
public java.awt.Point convertStreamPositionToLineColumn(int);
public int convertLineColumnToStreamPosition(int, int);
public void selectLine(int);
public void selectLine(int, int);
public int doFindText(String, boolean);
public int doReplace(String, String, boolean);
public int doReplaceAll(String, String, boolean);
public void update(java.util.Observable, Object);
private java.awt.Font getLineNumberFont(java.awt.Font);
}

SettingsEditorAction$EditorFontDialog$6

package mars.venus;
synchronized class SettingsEditorAction$EditorFontDialog$6 implements javax.swing.event.ChangeListener {
void SettingsEditorAction$EditorFontDialog$6(SettingsEditorAction$EditorFontDialog);
public void stateChanged(javax.swing.event.ChangeEvent);
}

MessagesPane$Asker$4

package mars.venus;
synchronized class MessagesPane$Asker$4 implements Runnable {
void MessagesPane$Asker$4(MessagesPane$Asker);
public void run();
}

mars/venus/AbstractFontSettingDialog.java
mars/venus/AbstractFontSettingDialog.java   package mars.venus;
   import mars.simulator.*;
   import mars.*;
   import mars.util.*;
   import java.util.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.text.*;
   import javax.swing.border.*;
   import javax.swing.event.*;
   import java.io.*;
    
    /*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
   /**
    * Abstract class for a font selection dialog.
    */
    public abstract class AbstractFontSettingDialog extends JDialog  {
    
      JDialog editorDialog;
      JComboBox fontFamilySelector, fontStyleSelector;
      JSlider fontSizeSelector;
      JSpinner fontSizeSpinSelector;
      JLabel fontSample;
      protected Font currentFont;
    
    // Used to determine upon OK, whether or not anything has changed.
      String initialFontFamily, initialFontStyle, initialFontSize; 
      
      /**
       *  Create a new font chooser.  Has pertinent JDialog parameters.
        *  Will do everything except make it visible.
        */
       public AbstractFontSettingDialog(Frame owner, String title, boolean modality, Font currentFont) {
         super(owner, title, modality);
         this.currentFont = currentFont;
            JPanel overallPanel = new JPanel(new BorderLayout());
            overallPanel.setBorder(new EmptyBorder(10,10,10,10));
            overallPanel.add(buildDialogPanel(), BorderLayout.CENTER);
            overallPanel.add(buildControlPanel(), BorderLayout.SOUTH);
         this.setContentPane(overallPanel);
         this.setDefaultCloseOperation(
                        JDialog.DO_NOTHING_ON_CLOSE);
         this.addWindowListener(
                new WindowAdapter() {
                   public void windowClosing(WindowEvent we) {
                     closeDialog();
                  }
               });
         this.pack();
         this.setLocationRelativeTo(owner);
      }
     
      // The dialog area, not including control buttons at bottom
       protected JPanel buildDialogPanel() {
         JPanel contents = new JPanel(new BorderLayout(20,20));
         contents.setBorder(new EmptyBorder(10,10,10,10));
        
         //Font currentFont = Globals.getSettings().getEditorFont();
         initialFontFamily = currentFont.getFamily();
         initialFontStyle = EditorFont.styleIntToStyleString(currentFont.getStyle());
         initialFontSize = EditorFont.sizeIntToSizeString(currentFont.getSize());
         String[] commonFontFamilies = EditorFont.getCommonFamilies();
         String[] allFontFamilies = EditorFont.getAllFamilies();
        // The makeVectorData() method will combine these two into one Vector
        // with a horizontal line separating the two groups.
         String[][] fullList = { commonFontFamilies, allFontFamilies };
        
         fontFamilySelector = new JComboBox(makeVectorData(fullList));
         fontFamilySelector.setRenderer(new ComboBoxRenderer());
         fontFamilySelector.addActionListener(new BlockComboListener(fontFamilySelector));
         fontFamilySelector.setSelectedItem(currentFont.getFamily());
         fontFamilySelector.setEditable(false);
         fontFamilySelector.setMaximumRowCount(commonFontFamilies.length);
         fontFamilySelector.setToolTipText(“Short list of common font families followed by complete list.”);
        
         String[] fontStyles = EditorFont.getFontStyleStrings();
         fontStyleSelector = new JComboBox(fontStyles);
         fontStyleSelector.setSelectedItem(EditorFont.styleIntToStyleString(currentFont.getStyle()));
         fontStyleSelector.setEditable(false);
         fontStyleSelector.setToolTipText(“List of available font styles.”);
      
         fontSizeSelector = new JSlider(EditorFont.MIN_SIZE, EditorFont.MAX_SIZE, currentFont.getSize());
         fontSizeSelector.setToolTipText(“Use slider to select font size from “+EditorFont.MIN_SIZE+” to “+EditorFont.MAX_SIZE+”.”);
         fontSizeSelector.addChangeListener(
                new ChangeListener() {
                   public void stateChanged(ChangeEvent e) {
                     Integer value = new Integer(((JSlider)e.getSource()).getValue());
                     fontSizeSpinSelector.setValue(value);
                     fontSample.setFont(getFont());
                  }
               });  
         SpinnerNumberModel fontSizeSpinnerModel = new SpinnerNumberModel(currentFont.getSize(), EditorFont.MIN_SIZE, EditorFont.MAX_SIZE, 1); 
         fontSizeSpinSelector = new JSpinner(fontSizeSpinnerModel);
         fontSizeSpinSelector.setToolTipText(“Current font size in points.”);
         fontSizeSpinSelector.addChangeListener(
                new ChangeListener() {
                   public void stateChanged(ChangeEvent e) {
                     Object value = ((JSpinner)e.getSource()).getValue();
                     fontSizeSelector.setValue(((Integer)value).intValue());
                     fontSample.setFont(getFont());
                  }
               });  
            // Action listener to update sample when family or style selected
         ActionListener updateSample = 
             new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  fontSample.setFont(getFont());
               }
            };  
         fontFamilySelector.addActionListener(updateSample);
         fontStyleSelector.addActionListener(updateSample);
        
         JPanel familyStyleComponents = new JPanel(new GridLayout(2,2,4,4));
         familyStyleComponents.add(new JLabel(“Font Family”));
         familyStyleComponents.add(new JLabel(“Font Style”));
         familyStyleComponents.add(fontFamilySelector);
         familyStyleComponents.add(fontStyleSelector);
            
         fontSample = new JLabel(“Sample of this font”, SwingConstants.CENTER);
         fontSample.setBorder(new LineBorder(Color.BLACK));
         fontSample.setFont(getFont()); 
        fontSample.setToolTipText(“Dynamically updated font sample based on current settings”);
         JPanel sizeComponents = new JPanel();
         sizeComponents.add(new JLabel(“Font Size “));
         sizeComponents.add(fontSizeSelector);
         sizeComponents.add(fontSizeSpinSelector);
           JPanel sizeAndSample = new JPanel(new GridLayout(2,1,4,8));
            sizeAndSample.add(sizeComponents);
            sizeAndSample.add(fontSample);
         contents.add(familyStyleComponents, BorderLayout.NORTH);
         contents.add(sizeAndSample, BorderLayout.CENTER);
         return contents;
      }  

       // Build component containing the buttons for dialog control
     // Such as OK, Cancel, Reset, Apply, etc.  These may vary
     // by application   
       protected abstract Component buildControlPanel();

   
       public Font getFont() {
         return EditorFont.createFontFromStringValues(
                     (String) fontFamilySelector.getSelectedItem(), 
                        (String) fontStyleSelector.getSelectedItem(), 
                        fontSizeSpinSelector.getValue().toString() );
      }
    
    // User has clicked “Apply” or “Apply and Close” button.
       protected void performApply() {
         apply(this.getFont());
      }
            
    // We’re finished with this modal dialog.
       protected void closeDialog() {
         this.setVisible(false);
         this.dispose();
      }
    
    // Reset font to its initial setting
       protected void reset() {
         fontFamilySelector.setSelectedItem(initialFontFamily);
         fontStyleSelector.setSelectedItem(initialFontStyle);
         fontSizeSelector.setValue(EditorFont.sizeStringToSizeInt(initialFontSize));
         fontSizeSpinSelector.setValue(new Integer(EditorFont.sizeStringToSizeInt(initialFontSize)));
      }
     
    /**
     *  Apply the given font.  Left for the client to define.
     *
     *  @param font a font to be applied by the client.
     */
       protected abstract void apply(Font font);
    
   
   /////////////////////////////////////////////////////////////////////
   //
   // Method and two classes to permit one or more horizontal separators
   // within a combo box list.  I obtained this code on 13 July 2007 
   // from http://www.codeguru.com/java/articles/164.shtml.  Author
   // is listed: Nobuo Tamemasa.  Code is old, 1999, but fine for this.
   // I will use it to separate the short list of “common” font
   // families from the very long list of all font families.  No attempt
   // to keep a list of recently-used fonts like Word does.  The list
   // of common font families is static.
   //
   /////////////////////////////////////////////////////////////////////
   
      private static String SEPARATOR = “___SEPARATOR____”;
   
   // Given an array of string arrays, will produce a Vector contenating
   // the arrays with a separator between each.
       private Vector makeVectorData(String[][] str) {
         boolean needSeparator = false;
         Vector data = new Vector();
         for (int i=0;i MAX_DISPLAYED_CHARS) {
                  name = name.substring(0,MAX_DISPLAYED_CHARS-3)+”…”;
               }
                // To get left-justified, put file name into first slot of horizontal Box, then glue.
               JLabel nameLab = new JLabel(name,JLabel.LEFT);
               Box nameLabel = Box.createHorizontalBox();
               nameLabel.add(nameLab);
               nameLabel.add(Box.createHorizontalGlue());
               nameLabel.add(Box.createHorizontalStrut(1));
               tableNames.add(nameLabel);
               allSymtabTables.add(nameLabel);
               JTable table = symtab.generateLabelTable();
               tableHeader = table.getTableHeader();
                // The following is selfish on my part.  Column re-ordering doesn’t work correctly when
                // displaying multiple symbol tables; the headers re-order but the columns do not.
                // Given the low perceived benefit of reordering displayed symbol table information
                // versus the perceived effort to make reordering work for multiple symbol tables,
                // I am taking the easy way out here.  PS 19 July 2007.
               tableHeader.setReorderingAllowed(false);
               table.setSelectionBackground(table.getBackground());
               // Sense click on label/address and scroll Text/Data segment display to it.
               table.addMouseListener(new LabelDisplayMouseListener());
               allSymtabTables.add(table);
            }
         }
         JScrollPane labelScrollPane = new JScrollPane(allSymtabTables,
                                               ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, 
                                                          ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        // Set file name label’s max width to scrollpane’s viewport width, max height to small.
        // Does it do any good?  Addressing problem that occurs when label (filename) is wider than
        // the table beneath it — the table column widths are stretched to attain the same width and
        // the address information requires scrolling to see.  All because of a long file name.
         for (int i=0;i= 0 && addrB >= 0 || addrA < 0 && addrB < 0) ? addrA-addrB : addrB ;          }       }                   ////////////////////////////////////////////////////////////////////////////     //     //  Comparator class used to sort in descending order a List of symbols.  It will     //  sort either alphabetically by name or numerically by address, depending on the     //  Comparator object provided as the argument constructor.  This works because it     //  is implemented by returning the result of the Ascending comparator when     //  arguments are reversed.        private class DescendingComparator implements java.util.Comparator {          private Comparator opposite;           private DescendingComparator(Comparator opposite) {             this.opposite = opposite;          }           public int compare(Object a, Object b) {             return opposite.compare(b,a);          }       }             }          MessagesPane$1 package mars.venus; synchronized class MessagesPane$1 implements java.awt.event.ActionListener { void MessagesPane$1(MessagesPane); public void actionPerformed(java.awt.event.ActionEvent); } Coprocessor1Window$RegisterCellRenderer package mars.venus; synchronized class Coprocessor1Window$RegisterCellRenderer extends javax.swing.table.DefaultTableCellRenderer { private java.awt.Font font; private int alignment; public void Coprocessor1Window$RegisterCellRenderer(Coprocessor1Window, java.awt.Font, int); public java.awt.Component getTableCellRendererComponent(javax.swing.JTable, Object, boolean, boolean, int, int); } mars/ext/game/GameScreen.java mars/ext/game/GameScreen.javapackage mars.ext.game; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.*; import javax.swing.*; /**  * This class is the GUI component of the game.  *   * @author jasonwangm  *   */ public class GameScreen extends JFrame {     private int timer; // the timer of the level     private int quota; // the quota of the level     private int balance; // the current balance of the level     private int dynamiteLeft; // the number of simple bombs left     private Font font = new Font("Serif", Font.BOLD, 24);     // the vector of game objects     private Hashtable gameObjs;
    private boolean[][] grids;
    private int gridObjects;
    private SoundPlayer soundPlayer;
    private MMIOInput keyListener; // the memeory mapped IO
    private GameImage bgImage;
    private ScreenPanel panel;

    private int level; // the level of the game

    private static GameScreen instance;

    public static GameScreen getInstance()
    {
        return instance;
    }

    public static synchronized GameScreen createIntance(String title,
            int width, int height)
    {
        if (instance == null)
        {
            instance = new GameScreen(title, width, height);
        }
        return instance;
    }

    private class ScreenPanel extends JPanel
    {
        public ScreenPanel()
        {
        }

        public void paintComponent(Graphics g)
        {
            Graphics2D g2 = (Graphics2D) g;
            if (bgImage != null)
            {
                bgImage.paint(g);
            }
            for (Map.Entry entry : gameObjs.entrySet())
            {
                GameObject obj = entry.getValue();
                obj.paint(g);
            }
            g2.setFont(font);
            g2.setColor(Color.white);
            g2.drawString(“Level: ” +  Integer.toString(level), 150, 40);
            g2.drawString(Integer.toString(timer/1000), 200, 82);
            g2.drawString(Integer.toString(quota), 680, 40);
            g2.drawString(Integer.toString(balance), 680, 82);
            g2.drawString(Integer.toString(dynamiteLeft), 478, 38);
        }
    }

    private GameScreen(String title, int width, int height)
    {
        this.level = 1;
        this.balance = 0;
        this.dynamiteLeft = 0;
        this.bgImage = new GameImage(-1, GameConfigFile.BACKGROUND);
        this.gameObjs = new Hashtable();
        this.gridObjects = 0;
        this.soundPlayer = new SoundPlayer();
        this.setTitle(title);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setSize(width, height);
        this.setResizable(false);

        this.addWindowListener(new WindowAdapter()
        {
            public void windowClosed(WindowEvent e)
            {
                keyListener.destroy();
                soundPlayer.stopAll();
                bgImage = null;
                gameObjs.clear();
                instance = null;
            }
        });
        this.panel = new ScreenPanel();
        this.getContentPane().add(panel);
        this.keyListener = new MMIOInput(true);
        this.addKeyListener(keyListener);
        this.setVisible(true);
    }
    
    public void playSound(int soundId, boolean toLoop)
    {
        this.soundPlayer.play(soundId, toLoop);
    }
    
    public void stopSound(int soundId)
    {
        this.soundPlayer.stopSound(soundId);
    }
    
    public void addGameObject(int id, GameObject obj)
    {
        this.gameObjs.put(id, obj);
    }

    public GameObject getGameObject(int id)
    {
        if (!gameObjs.containsKey(id))
        {
            return null;
        }
        return gameObjs.get(id);
    }

    public void destroyGameObject(int id)
    {
        if (gameObjs.containsKey(id))
        {
            gameObjs.remove(id);
        }
    }

    public void refreshScreen()
    {
        this.panel.repaint();
    }

    public void setLevel(int level)
    {
        this.level = level;
        //reset grids
        this.grids = new boolean[8][6];
        this.grids[3][0] = this.grids[4][0] = true; // these two grids are too close to the hook
        this.gridObjects = 0;
    }

    public void setTimer(int timer)
    {
        this.timer = timer;
    }

    public void setQuota(int quota)
    {
        this.quota = quota;
    }

    public void setBalance(int balance)
    {
        this.balance = balance;
    }

    public void setDynamiteInfo(int dLeft)
    {
        this.dynamiteLeft = dLeft;
    }
    
    public int[] getLevelObjectLocation()
    {
        int x = -1, y = -1;
        if (gridObjects >= 46) {
            return new int[] {x, y};
        }
        while(true) {
            Random r = new Random();
            x = r.nextInt(8);
            y = r.nextInt(6);
            if (!grids[x][y]) {
                gridObjects++;
                grids[x][y] = true;
                return new int[] {x*100, 125+y*75};
            }
        }
    }
}

mars/ext/game/GameImage.java
mars/ext/game/GameImage.javapackage mars.ext.game;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;

public class GameImage extends GameObject
{
    private Image image;

    public GameImage(int id, int x, int y, String imgName)
    {
        super(id, x, y);
        URL im = this.getClass().getResource(imgName);
        if (im == null)
        {
            System.err.println(“Internal Error: images folder or file not found”);
            System.exit(0);
        }
        image = Toolkit.getDefaultToolkit().getImage(im);
    }

    public GameImage(int id, String imgName)
    {
        this(id, 0, 0, imgName);
    }

    @Override
    public void paint(Graphics graph)
    {
        Graphics2D g2 = (Graphics2D) graph;
        g2.drawImage(image, this.getXLoc(), this.getYLoc(), null);
    }

}

mars/ext/game/GameConfigFile.java
mars/ext/game/GameConfigFile.javapackage mars.ext.game;

public final class GameConfigFile
{
    public static final String BACKGROUND = “/images/game_bg.png”;
    public static final String HOOK = “/images/game_hook.png”;
    public static final String GOLD = “/images/game_gold.png”;
    public static final String GEM = “/images/game_gem.png”;
    public static final String ROCK = “/images/game_rock.png”;
    public static final String DYNAMITE = “/images/game_dynamite.png”;

    public static final String SOUND_END = “/sounds/end.wav”;
    public static final String SOUND_BOMB = “/sounds/bomb.wav”;
    public static final String SOUND_KEY = “/sounds/key.wav”;
    public static final String SOUND_BACKGROUND = “/sounds/background.wav”;

    private GameConfigFile()
    {
        // TODO Auto-generated constructor stub
    }
}

mars/ext/game/MMIOInput.java
mars/ext/game/MMIOInput.javapackage mars.ext.game;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Observable;
import java.util.Observer;

import mars.Globals;
import mars.mips.hardware.AccessNotice;
import mars.mips.hardware.Coprocessor0;
import mars.mips.hardware.Memory;
import mars.mips.hardware.MemoryAccessNotice;
import mars.simulator.Exceptions;
import mars.util.SystemIO;

/**
 * MMIOInput is modified from “mars.tools.KeyboardAndDisplaySimulator.java”. 
 * 
 * @author jasonwangm
 * 
 */
public class MMIOInput implements KeyListener, Observer {
    public static int RECEIVER_CONTROL; // keyboard Ready in low-order bit
    public static int RECEIVER_DATA; // keyboard character in low-order byte
    private MMIOThread mmioThread;
    private boolean noRepeatedKeyEvents = true; // no repeated keyPress events
                                                // of
    // key-heldDown are processed after the
    // second (repeated) one, then
    // keyRelease event is processed
    private int keyPressNum = 0;
    private boolean acceptClearInput = true;

    // Set the MMIO addresses. Prior to MARS 3.7 these were final because
    // MIPS address space was final as well. Now we will get MMIO base address
    // each time to reflect possible change in memory configuration. DPS
    // 6-Aug-09
    public MMIOInput(boolean noRepeatedKeyEvents) {

        // 0xffff0000; keyboard Ready in low-order bit;
        RECEIVER_CONTROL = Memory.memoryMapBaseAddress; 
        // 0xffff004; keyboard character in low-order byte;
        RECEIVER_DATA = Memory.memoryMapBaseAddress + 4; 
        this.noRepeatedKeyEvents = noRepeatedKeyEvents;
        // Create memory updating thread that must be different from memory observer
        // thread to avoid the deadlock on MIPS-Memory lock.
        mmioThread = new MMIOThread(this); 
        mmioThread.start();
        addAsObserver();
    }

    /**
     * destroy any used resources.
     */
    public void destroy() {
        Globals.memory.deleteObserver(this);
        mmioThread.stopProcess();
    }

    /**
     * Registers us as an Observer over the static data segment (starting
     * address 0x10010000) only.
     * 
     * When user enters keystroke, set RECEIVER_CONTROL and RECEIVER_DATA using
     * the action listener. When user loads word (lw) from RECEIVER_DATA (we are
     * notified of the read), then clear RECEIVER_CONTROL.
     */
    void addAsObserver() {
        try {
            // We want to be an observer only of MIPS reads from RECEIVER_DATA
            Globals.memory.addObserver(this, RECEIVER_DATA, RECEIVER_DATA);
        } catch (Exception aee) {
            SystemIO.printString(“\nMMIO error: adding observer of incorrect MMIO address!\n”);
        }
    }

    /**
     * We get the notification of access to MIPS memory or registers. Here, it
     * corresponds to the keystoke.
     * 
     * Default implementation of method required by Observer interface. This
     * method will filter out notices originating from the MARS GUI or from
     * direct user editing of memory or register displays. Only notices arising
     * from MIPS program access are allowed in.
     * 
     * @param memory
     *            the attached memory
     * @param arg
     *            information provided by memory in MemoryAccessNotice object
     */
    public void update(Observable memory, Object arg) {

        AccessNotice accessNotice = (AccessNotice) arg;
        MemoryAccessNotice notice = (MemoryAccessNotice) accessNotice;
        // If MIPS program has just read (loaded) the receiver (keyboard) data
        // register, then clear the Ready bit to indicate there is no longer a
        // keystroke available.
        // If Ready bit was initially clear, they’ll get the old keystroke —
        // serves ’em right for not checking!
        if (notice.accessIsFromMIPS() && notice.getAddress() == RECEIVER_DATA
                && notice.getAccessType() == AccessNotice.READ) {
            synchronized (this) {
                if (!noRepeatedKeyEvents || acceptClearInput) { 
                    clearInput();
                }
            }
        }
    }

    // Update the MMIO Control register memory cell.
    private void updateMMIOControl(int addr, int intValue) {
        updateMMIOControlAndData(addr, intValue, 0, 0, true);
    }

    // Update the MMIO Control and Data register pair — 2 memory cells.
    private void updateMMIOControlAndData(int controlAddr, int controlValue,
            int dataAddr, int dataValue) {
        updateMMIOControlAndData(controlAddr, controlValue, dataAddr,
                dataValue, false);
    }

    /**
     * Update the MMIO Control and optionally the Data register as well
     * 
     * controlOnly: TRUE means update only the MMIO Control register; FALSE
     * means update both Control and Data.
     */
    private void updateMMIOControlAndData(int controlAddr, int controlValue,
            int dataAddr, int dataValue, boolean controlOnly) {
        synchronized (Globals.memoryAndRegistersLock) {
            try {
                Globals.memory.setRawWord(controlAddr, controlValue);
                if (noRepeatedKeyEvents && (controlValue & 1) == 1) // set input
                    synchronized (this) {
                        if (keyPressNum >= 2)
                            acceptClearInput = false;
                    }
                if (!controlOnly)
                    Globals.memory.setRawWord(dataAddr, dataValue);
            } catch (Exception aee) {
                SystemIO.printString(“\nMMIO error: updating data of incorrect MMIO address!\n”);
            }
        }
        // HERE’S A HACK!!
        // Want to immediately display the updated memory value in MARS,
        // but that code was not written for event-driven update (e.g.
        // Observer).
        // It was written to poll the memory cells for their values.
        // So we force it to do so.
        if (Globals.getGui() != null
                && Globals.getGui().getMainPane().getExecutePane()
                        .getTextSegmentWindow().getCodeHighlighting()) {
            Globals.getGui().getMainPane().getExecutePane()
                    .getDataSegmentWindow().updateValues();
        }
    }

    // ///////////////////////////////////////////////////////////////////
    // Return value of the given MMIO control register after ready (low order)
    // bit set (to 1).
    // Have to preserve the value of Interrupt Enable bit (bit 1)
    private boolean isReadyBitSet(int mmioControlRegister) {
        try {
            return (Globals.memory.get(mmioControlRegister,
                    Memory.WORD_LENGTH_BYTES) & 1) == 1;
        } catch (Exception aee) {
            SystemIO.printString(“\nMMIO error: accessing incorrect MMIO address!\n”);

        }
        return false; // to satisfy the compiler — this will never happen.
    }

    // ///////////////////////////////////////////////////////////////////
    // Return value of the given MMIO control register after ready (low order)
    // bit set (to 1).
    // Have to preserve the value of Interrupt Enable bit (bit 1)
    private int readyBitSet(int mmioControlRegister) {
        try {
            return Globals.memory.get(mmioControlRegister,
                    Memory.WORD_LENGTH_BYTES) | 1;
        } catch (Exception aee) {
            SystemIO.printString(“\nMMIO error: accessing incorrect MMIO address!\n”);

        }
        return 1; // to satisfy the compiler — this will never happen.
    }

    // ///////////////////////////////////////////////////////////////////
    // Return value of the given MMIO control register after ready (low order)
    // bit cleared (to 0).
    // Have to preserve the value of Interrupt Enable bit (bit 1). Bits 2 and
    // higher don’t matter.
    private int readyBitCleared(int mmioControlRegister) {
        try {
            return Globals.memory.get(mmioControlRegister,
                    Memory.WORD_LENGTH_BYTES) & 2;
        } catch (Exception aee) {
            SystemIO.printString(“\nMMIO error: accessing incorrect MMIO address!\n”);

        }
        return 0; // to satisfy the compiler — this will never happen.
    }

    // /////////////////////////////////////////////////////////////////////////////////
    //
    // grab keystrokes going to keyboard echo area and send them to MMIO area
    //
    public void writeInput(char key) {
        int updatedReceiverControl = readyBitSet(RECEIVER_CONTROL);
        updateMMIOControlAndData(RECEIVER_CONTROL, updatedReceiverControl,
                RECEIVER_DATA, key & 0x00000ff);
        if (updatedReceiverControl != 1
                && (Coprocessor0.getValue(Coprocessor0.STATUS) & 2) == 0
                && (Coprocessor0.getValue(Coprocessor0.STATUS) & 1) == 1) {
            // interrupt-enabled bit is set in both Receiver Control and in
            // Coprocessor0 Status register, and Interrupt Level Bit is 0, so
            // trigger external interrupt.
            mars.simulator.Simulator.externalInterruptingDevice = Exceptions.EXTERNAL_INTERRUPT_KEYBOARD;
        }
    }

    public void clearInput() {
        updateMMIOControl(RECEIVER_CONTROL, readyBitCleared(RECEIVER_CONTROL));
    }

    public void keyTyped(KeyEvent e) {
        // SystemIO.printString(“type ‘” + (char) e.getKeyChar()
        // +e.getWhen()+”‘\n” );
        // mmioThread.add(1, e);
    }

    public synchronized void processKeyPress(char key) {
        if (noRepeatedKeyEvents) {
            if (keyPressNum >= 2)
                return;
            else
                keyPressNum++;
        }
        mmioThread.add(1, new Character(key));
    }

    public synchronized void keyPressed(KeyEvent e) {
        // SystemIO.printString(“type ‘” + (char) e.getKeyChar()
        // +e.getWhen()+”‘\n” );
        processKeyPress(e.getKeyChar());
    }

    public synchronized void processKeyRelease() {

        if (noRepeatedKeyEvents) {
            acceptClearInput = true;
            keyPressNum = 0;
        }
    }

    public synchronized void keyReleased(KeyEvent e) {
        // SystemIO.printString(“release ‘” + (char) e.getKeyChar()
        // +e.getWhen()+”‘\n” );
        processKeyRelease();
    }

}

GameObjectDynamite

package mars.ext.game;
public synchronized class GameObjectDynamite extends GameObject implements ActiveElementInterface {
public static final int WIDTH = 30;
public static final int HEIGHT = 45;
private java.awt.Image image;
private int speed;
private int direction;
private int price;
public void GameObjectDynamite(int, int, int, String);
public void GameObjectDynamite(int, String);
public void paint(java.awt.Graphics);
public void setPrice(int);
public int getPrice();
public void setDirection(int);
public void updateDirection(int);
public int getDirection();
public void setSpeed(int);
public int getSpeed();
public void updateLocation();
public boolean isHooked();
public void toggleIsHooked();
}

mars/ext/game/GameObjectText.java
mars/ext/game/GameObjectText.javapackage mars.ext.game;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;

/**
 * This class represents the Text Object, to be drawn in the game.
 * 
 * @author jasonwangm
 * 
 */
public class GameObjectText extends GameObject
{
    private String text;
    private Font font;
    private Color color;

    public GameObjectText(int id, int x, int y)
    {
        super(id, x, y);
        text = “”;
        font = new Font(“SansSerif”, Font.BOLD, 28);
        color = Color.red;
    }

    public GameObjectText(int id)
    {
        this(id, 0, 0);
    }

    @Override
    public void paint(Graphics graph)
    {
        Graphics2D g2 = (Graphics2D) graph;
        g2.setColor(color);
        g2.setFont(font);
        g2.drawString(text, (int)xLoc, (int)yLoc);
    }

    public void setText(String text)
    {
        this.text = text;
    }

    public void setFont(String fontName, int size, boolean isBold)
            throws GameException
    {
        if (size < 1)         {             throw new GameException("Invalid font size: " + size + "\n");         }         int style = isBold ? Font.BOLD : Font.PLAIN;         try         {             font = new Font(fontName, style, size);         }         catch (Exception e)         {             throw new GameException("Invalid font name: " + fontName + "\n");         }     }     public void setColor(int colorNum) throws GameException     {         try         {             this.color = new Color(colorNum);         }         catch (Exception e)         {             throw new GameException("Invalid color number: 0x"                     + Integer.toHexString(colorNum) + "\n");         }     } } SoundPlayer package mars.ext.game; public synchronized class SoundPlayer { private static String SOUND_DIR; private static final String[] soundFNms; private java.util.HashMap soundsMap; private java.util.ArrayList loopSounds; static void ();
public void SoundPlayer();
private void loadSounds() throws javax.sound.sampled.LineUnavailableException;
private void loadSound(javax.sound.sampled.Clip, int);
public void play(int, boolean);
public void stopSound(int);
public void stopAll();
public static void main(String[]);
}

GameObjectHook

package mars.ext.game;
public synchronized class GameObjectHook extends GameObject implements ActiveElementInterface {
public static final int WIDTH = 22;
public static final int HEIGHT = 32;
public static final int HOOK_ANCHOR_Y = 3;
public static final int WINCH_X = 400;
public static final int WINCH_Y = 80;
public static final int RADIUS = 20;
private java.awt.Image image;
private int speed;
private int direction;
private int price;
private boolean isShoot;
private boolean isHooked;
private boolean isClockwise;
public void GameObjectHook(int, int, int, String);
public void GameObjectHook(int, String);
public void paint(java.awt.Graphics);
public void setPrice(int);
public int getPrice();
public void setDirection(int);
public void updateDirection(int);
public int getDirection();
public void setSpeed(int);
public int getSpeed();
public boolean isShoot();
public void toggleIsShoot();
public boolean isHooked();
public void toggleIsHooked();
public boolean isClockwise();
public void toggleIsClockwise();
public void updateLocation();
}

MMIOThread

package mars.ext.game;
public synchronized class MMIOThread extends Thread {
private MMIOInput mmioInput;
private java.util.Vector events;
boolean isFinish;
public void MMIOThread(MMIOInput);
public synchronized void stopProcess();
public synchronized Object[] getEvent();
public synchronized void add(int, Character);
public void run();
}

ActiveElementInterface

package mars.ext.game;
public abstract interface ActiveElementInterface {
public abstract void setPrice(int);
public abstract int getPrice();
public abstract void setDirection(int);
public abstract void updateDirection(int);
public abstract int getDirection();
public abstract void setSpeed(int);
public abstract int getSpeed();
public abstract void updateLocation();
public abstract boolean isHooked();
public abstract void toggleIsHooked();
}

GameScreen$1

package mars.ext.game;
synchronized class GameScreen$1 extends java.awt.event.WindowAdapter {
void GameScreen$1(GameScreen);
public void windowClosed(java.awt.event.WindowEvent);
}

GameScreen$ScreenPanel

package mars.ext.game;
synchronized class GameScreen$ScreenPanel extends javax.swing.JPanel {
public void GameScreen$ScreenPanel(GameScreen);
public void paintComponent(java.awt.Graphics);
}

GameObjectText

package mars.ext.game;
public synchronized class GameObjectText extends GameObject {
private String text;
private java.awt.Font font;
private java.awt.Color color;
public void GameObjectText(int, int, int);
public void GameObjectText(int);
public void paint(java.awt.Graphics);
public void setText(String);
public void setFont(String, int, boolean) throws GameException;
public void setColor(int) throws GameException;
}

mars/ext/game/GameException.java
mars/ext/game/GameException.javapackage mars.ext.game;

/**
 * Represent the exception information within Game.
 * 
 * @author jasonwangm
 * 
 */
public class GameException extends Exception {
    public GameException(String message) {
        super(message);
    }
}

GameObject

package mars.ext.game;
public abstract synchronized class GameObject {
protected int id;
protected double xLoc;
protected double yLoc;
public void GameObject(int);
public void GameObject(int, double, double);
public abstract void paint(java.awt.Graphics);
public int getId();
public void setXLoc(int);
public int getXLoc();
public void setYLoc(int);
public int getYLoc();
public void setLocations(double, double);
}

MMIOInput

package mars.ext.game;
public synchronized class MMIOInput implements java.awt.event.KeyListener, java.util.Observer {
public static int RECEIVER_CONTROL;
public static int RECEIVER_DATA;
private MMIOThread mmioThread;
private boolean noRepeatedKeyEvents;
private int keyPressNum;
private boolean acceptClearInput;
public void MMIOInput(boolean);
public void destroy();
void addAsObserver();
public void update(java.util.Observable, Object);
private void updateMMIOControl(int, int);
private void updateMMIOControlAndData(int, int, int, int);
private void updateMMIOControlAndData(int, int, int, int, boolean);
private boolean isReadyBitSet(int);
private int readyBitSet(int);
private int readyBitCleared(int);
public void writeInput(char);
public void clearInput();
public void keyTyped(java.awt.event.KeyEvent);
public synchronized void processKeyPress(char);
public synchronized void keyPressed(java.awt.event.KeyEvent);
public synchronized void processKeyRelease();
public synchronized void keyReleased(java.awt.event.KeyEvent);
}

GameObjectMineral

package mars.ext.game;
public synchronized class GameObjectMineral extends GameObject implements ActiveElementInterface {
private int width;
private int height;
private java.awt.Image image;
private int speed;
private int direction;
private int price;
private boolean isHooked;
public void GameObjectMineral(int, int, int, int, int, String);
public void GameObjectMineral(int, int, int, String);
public void paint(java.awt.Graphics);
public void setPrice(int);
public int getPrice();
public void setDirection(int);
public void updateDirection(int);
public int getDirection();
public void setSpeed(int);
public int getSpeed();
public boolean isHooked();
public void toggleIsHooked();
public void updateLocation();
}

mars/ext/game/GameObject.java
mars/ext/game/GameObject.javapackage mars.ext.game;

import java.awt.Graphics;

/**
 * This is the Abstract Base Class of all types of objects to be used in the
 * course project of COMP2611 in HKUST.
 * 
 * @author jasonwong
 * 
 */
public abstract class GameObject {
    protected int id; // each GameObject has a unique non-negative id
    protected double xLoc; // the x-coordinate
    protected double yLoc; // the y-coordinate

    public GameObject(int id) {
        this(id, -1, -1);
    }

    public GameObject(int id, double x, double y) {
        this.id = id;
        this.xLoc = x;
        this.yLoc = y;
    }

    /**
     * A concrete type of GameObject has its own implementation of how to paint
     * itself on the Graphics.
     * 
     * @param graph
     */
    public abstract void paint(Graphics graph);

    public int getId() {
        return this.id;
    }

    public void setXLoc(int x) {
        this.xLoc = x;
    }

    public int getXLoc() {
        return (int) this.xLoc;
    }

    public void setYLoc(int y) {
        this.yLoc = y;
    }

    public int getYLoc() {
        return (int) this.yLoc;
    }
    
    public void setLocations(double x, double y) {
        this.xLoc = x;
        this.yLoc = y;
    }
}

mars/ext/game/GameObjectMineral.java
mars/ext/game/GameObjectMineral.javapackage mars.ext.game;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;

/**
* Mineral Object used in the Gold Miner. This is a super-class for gold nuggets, gems, and rocks.

* @author jasonwong

*/

public class GameObjectMineral extends GameObject implements ActiveElementInterface
{
    private int width;
    private int height;
    private Image image = null;
    private int speed;
    private int direction;
    private int price;
    private boolean isHooked;
    
    public GameObjectMineral(int id, int width, int height, int x, int y, String imgFileName)
    {
        super(id, x, y);
        this.width = width;
        this.height = height;
        speed = 0;
        direction = 0;
        price = 0;
        isHooked = false;
        URL im = this.getClass().getResource(imgFileName);
        if (im == null)
        {
            System.err.println(“Internal Error: images folder or file not found”);
            System.exit(0);
        }
        image = Toolkit.getDefaultToolkit().getImage(im);
    }
    
    public GameObjectMineral(int id, int width, int height, String imgFileName)
    {
        this(id, width, height, 0, 0, imgFileName);
    }
    
    @Override
    public void paint(Graphics graph)
    {
        Graphics2D g2 = (Graphics2D) graph;
        
        //Draw the rotated mineral
        AffineTransform at = AffineTransform.getTranslateInstance(this.getXLoc(), this.getYLoc());
        if ( this.isHooked ) {
            at.translate(Math.sin(Math.toRadians(direction+270))*width/2, Math.cos(Math.toRadians(direction+270))*height/10);
            at.rotate(Math.toRadians(direction), width/2, height/10);
            g2.drawImage(image, at, null);
        } else {
            g2.drawImage(image, at, null);
        }
    }
    
    @Override
    public void setPrice(int price)
    {
        this.price = price;
    }
    
    @Override
    public int getPrice()
    {
        return price;
    }

    @Override
    public void setDirection(int d)
    {
        direction = d;
    }
    
    @Override
    public void updateDirection(int d)
    {
        direction += d;
    }
    
    @Override
    public int getDirection()
    {
        return this.direction;
    }
    
    @Override
    public void setSpeed(int v)
    {
        this.speed = v;
    }
    
    @Override
    public int getSpeed()
    {
        return this.speed;
    }
    
    @Override
    public boolean isHooked()
    {
        return this.isHooked;
    }
    
    @Override
    public void toggleIsHooked()
    {
        this.isHooked = !this.isHooked;
    }
    
    @Override
    public void updateLocation()
    {
        xLoc += Math.cos(Math.toRadians(direction+270))*speed;
        yLoc += Math.sin(Math.toRadians(direction+270))*speed;
    }
}

GameImage

package mars.ext.game;
public synchronized class GameImage extends GameObject {
private java.awt.Image image;
public void GameImage(int, int, int, String);
public void GameImage(int, String);
public void paint(java.awt.Graphics);
}

mars/ext/game/MMIOThread.java
mars/ext/game/MMIOThread.javapackage mars.ext.game;

import java.util.Vector;
import mars.util.SystemIO;

/**
 * 
 * @author jasonwangm
 * 
 */
public class MMIOThread extends Thread {
    private MMIOInput mmioInput;
    private Vector events;
    boolean isFinish;

    public MMIOThread(MMIOInput mmioInput) {
        super();
        this.mmioInput = mmioInput;
        this.events = new Vector();
        this.isFinish = false;
    }

    public synchronized void stopProcess() {
        this.isFinish = true;
    }

    public synchronized Object[] getEvent() {
        Object[] event = null;
        if (isFinish || events.size() <= 0) {             return null;         }         event = new Object[2];         event[0] = events.remove(0);         if (((Integer) event[0]).intValue() == 1)             event[1] = events.remove(0);         return event;     }     public synchronized void add(int action, Character e) {         try {             events.addElement(new Integer(action));             if (e != null)                 events.addElement(e);             notify();         } catch (Exception ex) {             SystemIO.printString("\nMMIO error: problems in processing input keys!\n");         }     }     public void run() {         try {             Object[] event = null;             while (!isFinish) {                 synchronized (this) {                     event = getEvent();                     if (event == null) {                         wait(100); // even if no events, wake up periodically to                                     // check whether isFinish is true                         // event = getEvent(); // get the event immediately while                                             // holding the lock                     }                 }                 if (event != null)                     switch (((Integer) event[0]).intValue()) {                     case 1:                         mmioInput.writeInput(((Character) event[1]).charValue());                         break;                     case 2:                         mmioInput.clearInput();                         break;                     }             }         } catch (Exception e) {             SystemIO.printString("\nMMIO error: problems in processing input keys!\n");         }     } } mars/ext/game/ActiveElementInterface.java mars/ext/game/ActiveElementInterface.javapackage mars.ext.game; public interface ActiveElementInterface {     public void setPrice(int p);     public int getPrice();     public void setDirection(int d);     public void updateDirection(int d);     public int getDirection();     public void setSpeed(int v);     public int getSpeed();     public void updateLocation();     public boolean isHooked();     public void toggleIsHooked(); } mars/ext/game/GameObjectHook.java mars/ext/game/GameObjectHook.javapackage mars.ext.game; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Color; import java.awt.BasicStroke; import java.awt.geom.AffineTransform; import java.awt.Image; import java.awt.Toolkit; import java.net.URL; /** * Hook Object used in the Gold Miner *  * @author jasonwong *  */ public class GameObjectHook extends GameObject implements ActiveElementInterface {     public static final int WIDTH = 22;     public static final int HEIGHT = 32;     public static final int HOOK_ANCHOR_Y = 3;     public static final int WINCH_X = 400;     public static final int WINCH_Y = 80;     public static final int RADIUS = 20;     private Image image = null;     private int speed;     private int direction;     private int price;     private boolean isShoot;     private boolean isHooked;     private boolean isClockwise;          public GameObjectHook(int id, int x, int y, String imgFileName)     {         super(id, x, y);         speed = 0;         direction = 0;         price = 0;         isShoot = false;         isHooked = false;         isClockwise = true;         URL im = this.getClass().getResource(imgFileName);         if (im == null)         {             System.err.println("Internal Error: images folder or file not found");             System.exit(0);         }         image = Toolkit.getDefaultToolkit().getImage(im);     }          public GameObjectHook(int id, String imgFileName)     {         this(id, 0, 0, imgFileName);     }          @Override     public void paint(Graphics graph)     {         Graphics2D g2 = (Graphics2D) graph;                  //Draw the rotated hook         AffineTransform at = AffineTransform.getTranslateInstance(this.getXLoc(), this.getYLoc());         at.rotate(Math.toRadians(direction), WIDTH/2, HOOK_ANCHOR_Y);         g2.drawImage(image, at, null);                  //Draw the line that connects the hook and the winch         g2.setColor(new Color(255, 255, 255));         g2.setStroke(new BasicStroke(2.0f));         g2.drawLine(this.getXLoc()+WIDTH/2, this.getYLoc()+HOOK_ANCHOR_Y, WINCH_X, WINCH_Y);     }          @Override     public void setPrice(int price)     {         this.price = price;     }          @Override     public int getPrice()     {         return price;     }          @Override     public void setDirection(int d)     {         direction = d;     }          @Override     public void updateDirection(int d)     {         // move backward in the direction         xLoc += Math.cos(Math.toRadians(direction+270)) * RADIUS;         yLoc += Math.sin(Math.toRadians(direction+270)) * RADIUS;         direction = (direction + d) % 360 == 0? 0: (direction + d);         // move forward in the direction         xLoc -= Math.cos(Math.toRadians(direction+270)) * RADIUS;         yLoc -= Math.sin(Math.toRadians(direction+270)) * RADIUS;     }          @Override     public int getDirection()     {         return direction;     }          @Override     public void setSpeed(int v)     {         speed = v;     }          @Override     public int getSpeed()     {         return speed;     }          public boolean isShoot()     {         return isShoot;     }          public void toggleIsShoot()     {         isShoot = !isShoot;     }          public boolean isHooked()     {         return isHooked;     }          public void toggleIsHooked()     {         isHooked = !isHooked;     }          public boolean isClockwise()     {         return isClockwise;     }          public void toggleIsClockwise()     {         isClockwise = !isClockwise;     }          @Override     public void updateLocation()     {         if (isHooked) {             xLoc += Math.cos(Math.toRadians(direction+270))*speed;             yLoc += Math.sin(Math.toRadians(direction+270))*speed;         } else {             xLoc -= Math.cos(Math.toRadians(direction+270))*speed;             yLoc -= Math.sin(Math.toRadians(direction+270))*speed;         }     } } mars/ext/game/GameObjectDynamite.java mars/ext/game/GameObjectDynamite.javapackage mars.ext.game; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.Image; import java.awt.Toolkit; import java.net.URL; /** * Dynamite Object used in the Gold Miner *  * @author jasonwong *  */ public class GameObjectDynamite extends GameObject implements ActiveElementInterface {     public static final int WIDTH = 30;     public static final int HEIGHT = 45;     private Image image = null;     private int speed;     private int direction;     private int price;          public GameObjectDynamite(int id, int x, int y, String imgFileName)     {         super(id, x, y);         speed = 0;         direction = 0;         price = 0;         URL im = this.getClass().getResource(imgFileName);         if (im == null)         {             System.err.println("Internal Error: images folder or file not found");             System.exit(0);         }         image = Toolkit.getDefaultToolkit().getImage(im);     }     public GameObjectDynamite(int id, String imgFileName)     {         this(id, 0, 0, imgFileName);     }          @Override     public void paint(Graphics graph)     {         Graphics2D g2 = (Graphics2D) graph;                  //Draw the rotated dynamite         AffineTransform at = AffineTransform.getTranslateInstance(this.getXLoc(), this.getYLoc());         at.translate(Math.sin(Math.toRadians(direction+270))*WIDTH/2, Math.cos(Math.toRadians(direction+270))*HEIGHT/10);         at.rotate(Math.toRadians(direction), WIDTH/2, HEIGHT/10);         g2.drawImage(image, at, null);     }          @Override     public void setPrice(int price)     {         this.price = price;     }          @Override     public int getPrice()     {         return price;     }          @Override     public void setDirection(int d)     {         direction = d;     }          @Override     public void updateDirection(int d)     {         direction += d;     }          @Override     public int getDirection()     {         return this.direction;     }          @Override     public void setSpeed(int v)     {         this.speed = v;     }          @Override     public int getSpeed()     {         return this.speed;     }          @Override     public void updateLocation()     {         xLoc -= Math.cos(Math.toRadians(direction+270))*speed;         yLoc -= Math.sin(Math.toRadians(direction+270))*speed;     }          @Override     public boolean isHooked()     {         return false;     }          @Override     public void toggleIsHooked()     {     } } GameScreen package mars.ext.game; public synchronized class GameScreen extends javax.swing.JFrame { private int timer; private int quota; private int balance; private int dynamiteLeft; private java.awt.Font font; private java.util.Hashtable gameObjs; private boolean[][] grids; private int gridObjects; private SoundPlayer soundPlayer; private MMIOInput keyListener; private GameImage bgImage; private GameScreen$ScreenPanel panel; private int level; private static GameScreen instance; public static GameScreen getInstance(); public static synchronized GameScreen createIntance(String, int, int); private void GameScreen(String, int, int); public void playSound(int, boolean); public void stopSound(int); public void addGameObject(int, GameObject); public GameObject getGameObject(int); public void destroyGameObject(int); public void refreshScreen(); public void setLevel(int); public void setTimer(int); public void setQuota(int); public void setBalance(int); public void setDynamiteInfo(int); public int[] getLevelObjectLocation(); } GameException package mars.ext.game; public synchronized class GameException extends Exception { public void GameException(String); } GameConfigFile package mars.ext.game; public final synchronized class GameConfigFile { public static final String BACKGROUND = /images/game_bg.png; public static final String HOOK = /images/game_hook.png; public static final String GOLD = /images/game_gold.png; public static final String GEM = /images/game_gem.png; public static final String ROCK = /images/game_rock.png; public static final String DYNAMITE = /images/game_dynamite.png; public static final String SOUND_END = /sounds/end.wav; public static final String SOUND_BOMB = /sounds/bomb.wav; public static final String SOUND_KEY = /sounds/key.wav; public static final String SOUND_BACKGROUND = /sounds/background.wav; private void GameConfigFile(); } mars/ext/game/SoundPlayer.java mars/ext/game/SoundPlayer.javapackage mars.ext.game; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class SoundPlayer {     private static String SOUND_DIR = "/sounds/";     private static final String[] soundFNms = {         "background.mid",          "win.wav",          "lose.wav",          "emit.wav",          "hit.wav"     };     private HashMap soundsMap; 
    private ArrayList loopSounds;
    public SoundPlayer()
    {
        loopSounds = new ArrayList();
        try
        {
            loadSounds();
        }
        catch (Exception ex)
        {
            System.out.println(ex);
        }
    }
    
    private void loadSounds() throws LineUnavailableException
    {
        soundsMap = new HashMap();
        for (int i = 0; i < soundFNms.length; i++)         {             Clip clip = AudioSystem.getClip();             loadSound(clip, i);             soundsMap.put(i, clip);         }     }          private void loadSound(Clip clip, int i)     {         URL url = getClass().getResource(SOUND_DIR + soundFNms[i]);         if (url == null)         {             System.out.println("Url is null!");         }         try         {             AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);             clip.open(audioInputStream);         }         catch (Exception ex)         {             System.out.println(ex);             System.out.println("Problem loading " + SOUND_DIR + soundFNms[i]);         }     }          public void play(int soundId, boolean toLoop)     {         Clip clip = (Clip) soundsMap.get(soundId);         if (clip == null)         {             System.out.println("No clip for " + soundId);             return;         }         clip.stop();         clip.close();         loadSound(clip, soundId);         if (toLoop)         {             clip.loop(Clip.LOOP_CONTINUOUSLY);             clip.start();             loopSounds.add(soundId);         }         else         {             clip.loop(0);             clip.start();         }     }          public void stopSound(int soundId)     {         Clip clip = soundsMap.get(soundId);         if (clip == null)         {             System.out.println("No clip for " + soundId);             return;         }         clip.stop();         clip.close();         loadSound(clip, soundId);         if (loopSounds.contains(soundId))         {             loopSounds.remove(soundId);         }     }          public void stopAll()     {         for (int i = 0; i < loopSounds.size(); ++i)         {             int id = loopSounds.get(i);             if (soundsMap.containsKey(id))             {                 stopSound(id);             }         }         loopSounds.clear();     }          public static void main(String args[])     {         SoundPlayer player = new SoundPlayer();         Scanner sc = new Scanner(System.in);                  while (true)         {             int c = sc.nextInt();             player.play(c, false);             if (c == 9)             break;         }         sc.close();     } } mars/ProcessingException.java mars/ProcessingException.java   package mars;    import mars.util.*;    import mars.mips.hardware.*;    import mars.mips.instructions.Instruction;    import mars.simulator.*; /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Class to represent error that occurs while assembling or running a MIPS program.  *   * @author Pete Sanderson  * @version August 2003  **/    public class ProcessingException extends Exception {         private ErrorList errs;        /**     * Constructor for ProcessingException.     *      * @param e An ErrorList which is an ArrayList of ErrorMessage objects.  Each ErrorMessage     * represents one processing error.     **/       public ProcessingException(ErrorList e) {          errs = e;       }        /**     * Constructor for ProcessingException to handle runtime exceptions     *      * @param ps a ProgramStatement of statement causing runtime exception     * @param m a String containing specialized error message     **/       public ProcessingException(ProgramStatement ps, String m) {          errs = new ErrorList();          errs.add(new ErrorMessage(ps, "Runtime exception at "+             Binary.intToHexString(RegisterFile.getProgramCounter()-Instruction.INSTRUCTION_LENGTH)+              ": "+m));             // Stopped using ps.getAddress() because of pseudo-instructions.  All instructions in             // the macro expansion point to the same ProgramStatement, and thus all will return the             // same value for getAddress(). But only the first such expanded instruction will              // be stored at that address.  So now I use the program counter (which has already             // been incremented).       }            /**     * Constructor for ProcessingException to handle runtime exceptions     *      * @param ps a ProgramStatement of statement causing runtime exception     * @param m a String containing specialized error message     * @param cause exception cause (see Exceptions class for list)     **/       public ProcessingException(ProgramStatement ps, String m, int cause) {          this(ps,m);          Exceptions.setRegisters(cause);       }            /**     * Constructor for ProcessingException to handle address runtime exceptions     *      * @param ps a ProgramStatement of statement causing runtime exception     * @param aee AddressErrorException object containing specialized error message, cause, address     **/           public ProcessingException(ProgramStatement ps, AddressErrorException aee) {          this(ps, aee.getMessage());          Exceptions.setRegisters(aee.getType(), aee.getAddress());       }        /**     * Constructor for ProcessingException.     *      * No parameter and thus no error list.  Use this for normal MIPS     * program termination (e.g. syscall 10 for exit).     **/       public ProcessingException() {          errs = null;       }        /**     * Produce the list of error messages.     *      * @return Returns ErrorList of error messages.     * @see ErrorList     * @see ErrorMessage     **/            public ErrorList errors() {          return errs;       }    } ProgramStatement$BasicStatementList$ListElement package mars; synchronized class ProgramStatement$BasicStatementList$ListElement { int type; String sValue; int iValue; void ProgramStatement$BasicStatementList$ListElement(ProgramStatement$BasicStatementList, int, String, int); } ErrorList package mars; public synchronized class ErrorList { private java.util.ArrayList messages; private int errorCount; private int warningCount; public static final String ERROR_MESSAGE_PREFIX = Error; public static final String WARNING_MESSAGE_PREFIX = Warning; public static final String FILENAME_PREFIX = in ; public static final String LINE_PREFIX = line ; public static final String POSITION_PREFIX = column ; public static final String MESSAGE_SEPARATOR = : ; public void ErrorList(); public java.util.ArrayList getErrorMessages(); public boolean errorsOccurred(); public boolean warningsOccurred(); public void add(ErrorMessage); public void add(ErrorMessage, int); public int errorCount(); public int warningCount(); public boolean errorLimitExceeded(); public int getErrorLimit(); public String generateErrorReport(); public String generateWarningReport(); public String generateErrorAndWarningReport(); private String generateReport(boolean); } mars/ErrorList.java mars/ErrorList.java   package mars;    import java.util.*;    import java.io.*; /* Copyright (c) 2003-2012,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */   /**  * Maintains list of generated error messages, regardless of source (tokenizing, parsing,  * assembly, execution).  *   * @author Pete Sanderson  * @version August 2003  **/     public class ErrorList {       private ArrayList messages;       private int errorCount;       private int warningCount;       public static final String ERROR_MESSAGE_PREFIX = "Error";       public static final String WARNING_MESSAGE_PREFIX = "Warning";       public static final String FILENAME_PREFIX = " in ";       public static final String LINE_PREFIX = " line ";       public static final String POSITION_PREFIX = " column ";       public static final String MESSAGE_SEPARATOR = ": ";             /**     * Constructor for ErrorList    **/            public ErrorList() {          messages = new ArrayList();          errorCount = 0;          warningCount = 0;       }        /**     *  Get ArrayList of error messages.     *  @return ArrayList of ErrorMessage objects     */        public ArrayList getErrorMessages() {          return messages;       }           /**    * Determine whether error has occured or not.    * @return true if an error has occurred (does not include warnings), false otherwise.
   **/
       public boolean errorsOccurred() {
         return (errorCount != 0 );
      }
   
   /**
   * Determine whether warning has occured or not.
   * @return true if an warning has occurred, false otherwise.
   **/
       public boolean warningsOccurred() {
         return (warningCount != 0 );
      }
   
   /** Add new error message to end of list.
   * @param mess ErrorMessage object to be added to end of error list.
   **/
       public void add(ErrorMessage mess){
         add(mess, messages.size());
      }
   
   /** Add new error message at specified index position.
   * @param mess ErrorMessage object to be added to end of error list.
   * @param index position in error list
   **/       
       public void add(ErrorMessage mess, int index) {
         if (errorCount > getErrorLimit()) {
            return;
         }
         if (errorCount == getErrorLimit()) {
            messages.add(new ErrorMessage((MIPSprogram)null, mess.getLine(), mess.getPosition(),”Error Limit of “+getErrorLimit()+” exceeded.”));
            errorCount++; // subsequent errors will not be added; see if statement above
            return;
         }
         messages.add(index, mess);
         if (mess.isWarning()) {
            warningCount++;
         } 
         else {
            errorCount++;
         }
      }
       
   
   /**
   * Count of number of error messages in list.
   * @return Number of error messages in list.
   **/
   
       public int errorCount() {
         return this.errorCount;
      }
   
   /**
   * Count of number of warning messages in list.
   * @return Number of warning messages in list.
   **/
   
       public int warningCount() {
         return this.warningCount;
      }
   
   /**
   * Check to see if error limit has been exceeded.
   * @return True if error limit exceeded, false otherwise.
   **/
   
       public boolean errorLimitExceeded() {
         return this.errorCount > getErrorLimit();
      }
   
   /**
   * Get limit on number of error messages to be generated
   * by one assemble operation.
   * @return error limit.
   **/
   
       public int getErrorLimit() {
         return Globals.maximumErrorMessages;
      }
   
   /**
   * Produce error report.
      * @return String containing report.
   **/
       public String generateErrorReport() {
         return generateReport(ErrorMessage.ERROR);
      }
   
   /**
   * Produce warning report.
   * @return String containing report.
   **/
       public String generateWarningReport() {
         return generateReport(ErrorMessage.WARNING);
      } 
   
   /**
   * Produce report containing both warnings and errors, warnings first.
   * @return String containing report.
   **/      
       public String generateErrorAndWarningReport() {
         return generateWarningReport()+generateErrorReport();
      }
    
   // Produces either error or warning report.
       private String generateReport(boolean isWarning) {
         StringBuffer report = new StringBuffer(“”);
         String reportLine;
         for (int i = 0; i < messages.size(); i++) {             ErrorMessage m = (ErrorMessage) messages.get(i);             if  ((isWarning && m.isWarning()) || (!isWarning && !m.isWarning())) {                reportLine = ((isWarning) ? WARNING_MESSAGE_PREFIX : ERROR_MESSAGE_PREFIX) + FILENAME_PREFIX;                if (m.getFilename().length() > 0) 
                  reportLine = reportLine + (new File(m.getFilename()).getPath()); //.getName());
               if (m.getLine() > 0)
                  reportLine = reportLine + LINE_PREFIX  +m.getMacroExpansionHistory()+ m.getLine();
               if (m.getPosition() > 0)
                  reportLine = reportLine + POSITION_PREFIX + m.getPosition();
               reportLine = reportLine + MESSAGE_SEPARATOR + m.getMessage() + “\n”;
               report.append(reportLine);
            }
         }
         return report.toString();
      }
   }  // ErrorList

InstructionSet$62

package mars.mips.instructions;
synchronized class InstructionSet$62 implements SimulationCode {
void InstructionSet$62(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$27

package mars.mips.instructions;
synchronized class InstructionSet$27 implements SimulationCode {
void InstructionSet$27(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$143

package mars.mips.instructions;
synchronized class InstructionSet$143 implements SimulationCode {
void InstructionSet$143(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$106

package mars.mips.instructions;
synchronized class InstructionSet$106 implements SimulationCode {
void InstructionSet$106(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$46

package mars.mips.instructions;
synchronized class InstructionSet$46 implements SimulationCode {
void InstructionSet$46(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$122

package mars.mips.instructions;
synchronized class InstructionSet$122 implements SimulationCode {
void InstructionSet$122(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$86

package mars.mips.instructions;
synchronized class InstructionSet$86 implements SimulationCode {
void InstructionSet$86(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$84

package mars.mips.instructions;
synchronized class InstructionSet$84 implements SimulationCode {
void InstructionSet$84(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$79

package mars.mips.instructions;
synchronized class InstructionSet$79 implements SimulationCode {
void InstructionSet$79(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$44

package mars.mips.instructions;
synchronized class InstructionSet$44 implements SimulationCode {
void InstructionSet$44(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$120

package mars.mips.instructions;
synchronized class InstructionSet$120 implements SimulationCode {
void InstructionSet$120(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$60

package mars.mips.instructions;
synchronized class InstructionSet$60 implements SimulationCode {
void InstructionSet$60(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$25

package mars.mips.instructions;
synchronized class InstructionSet$25 implements SimulationCode {
void InstructionSet$25(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$141

package mars.mips.instructions;
synchronized class InstructionSet$141 implements SimulationCode {
void InstructionSet$141(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$104

package mars.mips.instructions;
synchronized class InstructionSet$104 implements SimulationCode {
void InstructionSet$104(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$139

package mars.mips.instructions;
synchronized class InstructionSet$139 implements SimulationCode {
void InstructionSet$139(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$18

package mars.mips.instructions;
synchronized class InstructionSet$18 implements SimulationCode {
void InstructionSet$18(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$145

package mars.mips.instructions;
synchronized class InstructionSet$145 implements SimulationCode {
void InstructionSet$145(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$100

package mars.mips.instructions;
synchronized class InstructionSet$100 implements SimulationCode {
void InstructionSet$100(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$64

package mars.mips.instructions;
synchronized class InstructionSet$64 implements SimulationCode {
void InstructionSet$64(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$21

package mars.mips.instructions;
synchronized class InstructionSet$21 implements SimulationCode {
void InstructionSet$21(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$99

package mars.mips.instructions;
synchronized class InstructionSet$99 implements SimulationCode {
void InstructionSet$99(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$59

package mars.mips.instructions;
synchronized class InstructionSet$59 implements SimulationCode {
void InstructionSet$59(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$38

package mars.mips.instructions;
synchronized class InstructionSet$38 implements SimulationCode {
void InstructionSet$38(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$80

package mars.mips.instructions;
synchronized class InstructionSet$80 implements SimulationCode {
void InstructionSet$80(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$119

package mars.mips.instructions;
synchronized class InstructionSet$119 implements SimulationCode {
void InstructionSet$119(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$124

package mars.mips.instructions;
synchronized class InstructionSet$124 implements SimulationCode {
void InstructionSet$124(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$40

package mars.mips.instructions;
synchronized class InstructionSet$40 implements SimulationCode {
void InstructionSet$40(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallLoader

package mars.mips.instructions;
synchronized class SyscallLoader {
private static final String CLASS_PREFIX = mars.mips.instructions.syscalls.;
private static final String SYSCALLS_DIRECTORY_PATH = mars/mips/instructions/syscalls;
private static final String SYSCALL_INTERFACE = Syscall.class;
private static final String SYSCALL_ABSTRACT = AbstractSyscall.class;
private static final String CLASS_EXTENSION = class;
private java.util.ArrayList syscallList;
void SyscallLoader();
void loadSyscalls();
private java.util.ArrayList processSyscallNumberOverrides(java.util.ArrayList);
syscalls.Syscall findSyscall(int);
}

ExtendedInstruction

package mars.mips.instructions;
public synchronized class ExtendedInstruction extends Instruction {
private java.util.ArrayList translationStrings;
private java.util.ArrayList compactTranslationStrings;
public void ExtendedInstruction(String, String, String, String);
public void ExtendedInstruction(String, String, String);
public void ExtendedInstruction(String, String);
public int getInstructionLength();
public java.util.ArrayList getBasicIntructionTemplateList();
public int getCompactInstructionLength();
public boolean hasCompactTranslation();
public java.util.ArrayList getCompactBasicIntructionTemplateList();
public static String makeTemplateSubstitutions(mars.MIPSprogram, String, mars.assembler.TokenList);
private static String substitute(String, String, String);
private static String substituteFirst(String, String, String);
private java.util.ArrayList buildTranslationList(String);
private int getInstructionLength(java.util.ArrayList);
}

InstructionSet$126

package mars.mips.instructions;
synchronized class InstructionSet$126 implements SimulationCode {
void InstructionSet$126(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$42

package mars.mips.instructions;
synchronized class InstructionSet$42 implements SimulationCode {
void InstructionSet$42(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$82

package mars.mips.instructions;
synchronized class InstructionSet$82 implements SimulationCode {
void InstructionSet$82(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$147

package mars.mips.instructions;
synchronized class InstructionSet$147 implements SimulationCode {
void InstructionSet$147(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$102

package mars.mips.instructions;
synchronized class InstructionSet$102 implements SimulationCode {
void InstructionSet$102(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

BasicInstructionFormat

package mars.mips.instructions;
public synchronized class BasicInstructionFormat {
public static final BasicInstructionFormat R_FORMAT;
public static final BasicInstructionFormat I_FORMAT;
public static final BasicInstructionFormat I_BRANCH_FORMAT;
public static final BasicInstructionFormat J_FORMAT;
static void ();
private void BasicInstructionFormat();
}

InstructionSet$9

package mars.mips.instructions;
synchronized class InstructionSet$9 implements SimulationCode {
void InstructionSet$9(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$66

package mars.mips.instructions;
synchronized class InstructionSet$66 implements SimulationCode {
void InstructionSet$66(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$23

package mars.mips.instructions;
synchronized class InstructionSet$23 implements SimulationCode {
void InstructionSet$23(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$121

package mars.mips.instructions;
synchronized class InstructionSet$121 implements SimulationCode {
void InstructionSet$121(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$45

package mars.mips.instructions;
synchronized class InstructionSet$45 implements SimulationCode {
void InstructionSet$45(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$85

package mars.mips.instructions;
synchronized class InstructionSet$85 implements SimulationCode {
void InstructionSet$85(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$78

package mars.mips.instructions;
synchronized class InstructionSet$78 implements SimulationCode {
void InstructionSet$78(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$19

package mars.mips.instructions;
synchronized class InstructionSet$19 implements SimulationCode {
void InstructionSet$19(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$138

package mars.mips.instructions;
synchronized class InstructionSet$138 implements SimulationCode {
void InstructionSet$138(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$105

package mars.mips.instructions;
synchronized class InstructionSet$105 implements SimulationCode {
void InstructionSet$105(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$140

package mars.mips.instructions;
synchronized class InstructionSet$140 implements SimulationCode {
void InstructionSet$140(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$24

package mars.mips.instructions;
synchronized class InstructionSet$24 implements SimulationCode {
void InstructionSet$24(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$61

package mars.mips.instructions;
synchronized class InstructionSet$61 implements SimulationCode {
void InstructionSet$61(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$107

package mars.mips.instructions;
synchronized class InstructionSet$107 implements SimulationCode {
void InstructionSet$107(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$142

package mars.mips.instructions;
synchronized class InstructionSet$142 implements SimulationCode {
void InstructionSet$142(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$26

package mars.mips.instructions;
synchronized class InstructionSet$26 implements SimulationCode {
void InstructionSet$26(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$63

package mars.mips.instructions;
synchronized class InstructionSet$63 implements SimulationCode {
void InstructionSet$63(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$87

package mars.mips.instructions;
synchronized class InstructionSet$87 implements SimulationCode {
void InstructionSet$87(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SimulationCode

package mars.mips.instructions;
public abstract interface SimulationCode {
public abstract void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/SimulationCode.java
mars/mips/instructions/SimulationCode.javapackage mars.mips.instructions;
import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Interface to represent the method for simulating the execution of a specific MIPS basic
 * instruction.  It will be implemented by the anonymous class created in the last
 * argument to the BasicInstruction constructor.
 * 
 * @author Pete Sanderson 
 * @version August 2003
 * 
 */

public interface SimulationCode {

    /**
     * Method to simulate the execution of a specific MIPS basic instruction.
     * 
     * @param statement A ProgramStatement representing the MIPS instruction to simulate. 
     * @throws ProcessingException This is a run-time exception generated during simulation.
     **/
     
    public void simulate(ProgramStatement statement) throws ProcessingException;
}

InstructionSet$123

package mars.mips.instructions;
synchronized class InstructionSet$123 implements SimulationCode {
void InstructionSet$123(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$47

package mars.mips.instructions;
synchronized class InstructionSet$47 implements SimulationCode {
void InstructionSet$47(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$83

package mars.mips.instructions;
synchronized class InstructionSet$83 implements SimulationCode {
void InstructionSet$83(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$43

package mars.mips.instructions;
synchronized class InstructionSet$43 implements SimulationCode {
void InstructionSet$43(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$127

package mars.mips.instructions;
synchronized class InstructionSet$127 implements SimulationCode {
void InstructionSet$127(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$22

package mars.mips.instructions;
synchronized class InstructionSet$22 implements SimulationCode {
void InstructionSet$22(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$67

package mars.mips.instructions;
synchronized class InstructionSet$67 implements SimulationCode {
void InstructionSet$67(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$103

package mars.mips.instructions;
synchronized class InstructionSet$103 implements SimulationCode {
void InstructionSet$103(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$146

package mars.mips.instructions;
synchronized class InstructionSet$146 implements SimulationCode {
void InstructionSet$146(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$8

package mars.mips.instructions;
synchronized class InstructionSet$8 implements SimulationCode {
void InstructionSet$8(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

BasicInstruction

package mars.mips.instructions;
public synchronized class BasicInstruction extends Instruction {
private String instructionName;
private BasicInstructionFormat instructionFormat;
private String operationMask;
private SimulationCode simulationCode;
public void BasicInstruction(String, String, BasicInstructionFormat, String, SimulationCode);
public void BasicInstruction(String, BasicInstructionFormat, String, SimulationCode);
public String getOperationMask();
public BasicInstructionFormat getInstructionFormat();
public SimulationCode getSimulationCode();
}

InstructionSet$58

package mars.mips.instructions;
synchronized class InstructionSet$58 implements SimulationCode {
void InstructionSet$58(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

Instruction

package mars.mips.instructions;
public abstract synchronized class Instruction {
public static final int INSTRUCTION_LENGTH = 4;
public static final int INSTRUCTION_LENGTH_BITS = 32;
public static char[] operandMask;
protected String mnemonic;
protected String exampleFormat;
protected String description;
protected mars.assembler.TokenList tokenList;
static void ();
public void Instruction();
public String getName();
public String getExampleFormat();
public String getDescription();
public mars.assembler.TokenList getTokenList();
public int getInstructionLength();
protected String extractOperator(String);
protected void createExampleTokenList();
}

InstructionSet$20

package mars.mips.instructions;
synchronized class InstructionSet$20 implements SimulationCode {
void InstructionSet$20(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$65

package mars.mips.instructions;
synchronized class InstructionSet$65 implements SimulationCode {
void InstructionSet$65(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$98

package mars.mips.instructions;
synchronized class InstructionSet$98 implements SimulationCode {
void InstructionSet$98(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$101

package mars.mips.instructions;
synchronized class InstructionSet$101 implements SimulationCode {
void InstructionSet$101(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$144

package mars.mips.instructions;
synchronized class InstructionSet$144 implements SimulationCode {
void InstructionSet$144(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$41

package mars.mips.instructions;
synchronized class InstructionSet$41 implements SimulationCode {
void InstructionSet$41(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$125

package mars.mips.instructions;
synchronized class InstructionSet$125 implements SimulationCode {
void InstructionSet$125(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$118

package mars.mips.instructions;
synchronized class InstructionSet$118 implements SimulationCode {
void InstructionSet$118(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$39

package mars.mips.instructions;
synchronized class InstructionSet$39 implements SimulationCode {
void InstructionSet$39(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/ExtendedInstruction.java
mars/mips/instructions/ExtendedInstruction.java   package mars.mips.instructions;
   import mars.*;
   import mars.util.*;
   import mars.assembler.*;
   import mars.mips.hardware.*;
   import java.util.*;
    
    /*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
/**
 * ExtendedInstruction represents a MIPS extended (a.k.a pseudo) instruction.  This
 * assembly language instruction does not have a corresponding machine instruction.  Instead
 * it is translated by the extended assembler into one or more basic instructions (operations
 * that have a corresponding machine instruction).  The TranslationCode object is 
 * responsible for performing the translation.
 * 
 * @author Pete Sanderson 
 * @version August 2003
 */
    public class ExtendedInstruction extends Instruction {
   
      private ArrayList translationStrings, compactTranslationStrings;
    /**
     * Constructor for ExtendedInstruction.
     * 
     * @param example A String containing example use of the MIPS extended instruction.
     * @param translation Specifications for translating this instruction into a sequence
     * of one or more MIPS basic instructions.
     * @param compactTranslation Alternative translation that can be used if running under
     * a compact (16 bit) memory configuration.
     * @param description a helpful description to be included on help requests
     *
     * The presence of an alternative “compact translation” can optimize code generation
     * by assuming that data label addresses are 16 bits instead of 32
     **/
     
       public ExtendedInstruction(String example, String translation, String compactTranslation, String description) {
         this.exampleFormat = example;
         this.description = description;
         this.mnemonic = this.extractOperator(example);
         this.createExampleTokenList();
         this.translationStrings = buildTranslationList(translation);
         this.compactTranslationStrings = buildTranslationList(compactTranslation);
      }
   
    /**
     * Constructor for ExtendedInstruction.  No compact translation is provided.
     * 
     * @param example A String containing example use of the MIPS extended instruction.
     * @param translation Specifications for translating this instruction into a sequence
     * of one or more MIPS basic instructions.
     * @param description a helpful description to be included on help requests
     **/
     
       public ExtendedInstruction(String example, String translation, String description) {
         this.exampleFormat = example;
         this.description = description;
         this.mnemonic = this.extractOperator(example);
         this.createExampleTokenList();
         this.translationStrings = buildTranslationList(translation);
         this.compactTranslationStrings = null;
      }
   
     /**
     * Constructor for ExtendedInstruction, where no instruction description or 
     * compact translation is provided.
     * 
     * @param example A String containing example use of the MIPS extended instruction.
     * @param translation Specifications for translating this instruction into a sequence
     * of one or more MIPS basic instructions.
     **/
     
       public ExtendedInstruction(String example, String translation) {
         this(example, translation, “”);
      }  
    
    /**
     * Get length in bytes that this extended instruction requires in its 
     * binary form. The answer depends on how many basic instructions it 
     * expands to.  This may vary, if expansion includes a nop, depending on
     * whether or not delayed branches are enabled. Each requires 4 bytes.
     * @return int length in bytes of corresponding binary instruction(s).
     */
   
       public int getInstructionLength() {
         return getInstructionLength(translationStrings);
      }

   
    /**
     * Get ArrayList of Strings that represent list of templates for
     * basic instructions generated by this extended instruction. 
     * @return ArrayList of Strings.
     */
    
       public ArrayList getBasicIntructionTemplateList() {
         return translationStrings;
      }
   
    /**
     * Get length in bytes that this extended instruction requires in its 
     * binary form if it includes an alternative expansion for compact 
     * memory (16 bit addressing) configuration. The answer depends on 
     * how many basic instructions it expands to.  This may vary, if 
     * expansion includes a nop, depending on whether or not delayed 
     * branches are enabled. Each requires 4 bytes.
     * @return int length in bytes of corresponding binary instruction(s).
     * Returns 0 if an alternative expansion is not defined for this
     * instruction.
     */
     
       public int getCompactInstructionLength() {
         return getInstructionLength(compactTranslationStrings);
      }
   
   
     /**
      * Determine whether or not this pseudo-instruction has a second
        * translation optimized for 16 bit address space: a compact version.
      */
      public boolean hasCompactTranslation() {
      return compactTranslationStrings != null;
    }

   
    /**
     * Get ArrayList of Strings that represent list of templates for
     * basic instructions generated by the “compact” or 16-bit version
      * of this extended instruction. 
     * @return ArrayList of Strings.  Returns null if the instruction does not
      * have a compact alternative.
     */
    
       public ArrayList getCompactBasicIntructionTemplateList() {
         return compactTranslationStrings;
      }
           
      /**
     * Given a basic instruction template and the list of tokens from an extended
     * instruction statement, substitute operands from the token list appropriately into the 
     * template to generate the basic statement.  Assumes the extended instruction statement has
     * been translated from source form to basic assembly form (e.g. register mnemonics
     * translated to corresponding register numbers).
     * Operand format of source statement is already verified correct.
     * Assume the template has correct number and positions of operands.
     * Template is String with special markers.  In the list below, n represents token position (1,2,3,etc)
     * in source statement (operator is token 0, parentheses count but commas don’t):
     * 


           * 
  • RGn means substitute register found in n’th token of source statement
           * 
  • NRn means substitute next higher register than the one in n’th token of source code
           * 
  • OPn means substitute n’th token of source code as is
           * 
  • LLn means substitute low order 16 bits from label address in source token n.
           * 
  • LLnU means substitute low order 16 bits (unsigned) from label address in source token n.
           * 
  • LLnPm (m=1,2,3,4) means substitute low order 16 bits from label address in source token n, after adding m.
           * 
  • LHn means substitute high order 16 bits from label address in source token n. Must add 1 if address bit 15 is 1. 
           * 
  • LHnPm (m=1,2,3,4) means substitute high order 16 bits from label address in source token n, after adding m. Must then add 1 if bit 15 is 1. 
           * 
  • VLn means substitute low order 16 bits from 32 bit value in source token n.
           * 
  • VLnU means substitute low order 16 bits (unsigned) from 32 bit value in source token n.
           * 
  • VLnPm (m=1,2,3,4) means substitute low order 16 bits from 32 bit value in source token n, after adding m to value.
           * 
  • VLnPmU (m=1,2,3,4) means substitute low order 16 bits (unsigned) from 32 bit value in source token n, after adding m to value.
         * 
  • VHLn means substitute high order 16 bits from 32 bit value in source token n.  Use this if later combined with low order 16 bits using “ori $1,$1,VLn”. See logical and branch operations.
           * 
  • VHn means substitute high order 16 bits from 32 bit value in source token n, then add 1 if value’s bit 15 is 1.  Use this only if later instruction uses VLn($1) to calculate 32 bit address.  See loads and stores.
           * 
  • VHLnPm (m=1,2,3,4) means substitute high order 16 bits from 32 bit value in source token n, after adding m.  See VHLn.
           * 
  • VHnPm (m=1,2,3,4) means substitute high order 16 bits from 32 bit value in source token n, after adding m. Must then add 1 if bit 15 is 1. See VHn.
           * 
  • LLP is similar to LLn, but is needed for “label+100000” address offset. Immediate is added before taking low order 16. 
           * 
  • LLPU is similar to LLnU, but is needed for “label+100000” address offset. Immediate is added before taking low order 16 (unsigned). 
           * 
  • LLPPm (m=1,2,3,4) is similar to LLP except m is added along with mmediate before taking low order 16. 
           * 
  • LHPA is similar to LHn, but is needed for “label+100000” address offset. Immediate is added before taking high order 16.
           * 
  • LHPN is similar to LHPA, used only by “la” instruction. Address resolved by “ori” so do not add 1 if bit 15 is 1.
           * 
  • LHPAPm (m=1,2,3,4) is similar to LHPA except value m is added along with immediate before taking high order 16.
           * 
  • LHL means substitute high order 16 bits from label address in token 2 of “la” (load address) source statement.
           * 
  • LAB means substitute textual label from last token of source statement.  Used for various branches.
           * 
  • S32 means substitute the result of subtracting the constant value in last token from 32.  Used by “ror”, “rol”.
         * 
  • DBNOP means Delayed Branching NOP – generate a “nop” instruction but only if delayed branching is enabled. Added in 3.4.1 release.
           * 
  • BROFFnm means substitute n if delayed branching is NOT enabled otherwise substitute m.  n and m are single digit numbers indicating constant branch offset (in words).  Added in 3.4.1 release.
         * 

     * @param template a String containing template for basic statement.
     * @param tokenList a TokenList containing tokens from extended instruction.
     * @return String representing basic assembler statement.
     */
   
       public static String makeTemplateSubstitutions(MIPSprogram program, String template, TokenList theTokenList) {
         String instruction = template;
         int index;
         // Added 22 Jan 2008 by DPS.  The DBNOP template means to generate a “nop” instruction if delayed branching
        // is enabled and generate no instruction otherwise.  
        
        //This is the goal, but it leads to a cascade of 
        // additional changes, so for now I will generate “nop” in either case, then come back to it for the
        // next major release.
         if (instruction.indexOf(“DBNOP”)>=0) {
            return Globals.getSettings().getDelayedBranchingEnabled() ? “nop” : “”;
         }
        // substitute first operand token for template’s RG1 or OP1, second for RG2 or OP2, etc
         for (int op=1; op=0) {
            // Label, last operand, has already been translated to address by symtab lookup
               String label = theTokenList.get(op).getValue();
               int addr = 0;
               int add = instruction.charAt(index+4)-48; // extract the digit following P
               try {
                  addr = Binary.stringToInt(label) + add;    // KENV   1/6/05
               } 
                   catch (NumberFormatException e) {
                   // this won’t happen…
                  }
                    // If bit 15 is 1, that means lower 16 bits will become a negative offset!  To
                // compensate if that is the case, we need to add 1 to the high 16 bits.
               int extra = Binary.bitValue(addr,15);
               instruction = substitute(instruction,”LH”+op+”P”+add,String.valueOf((addr >> 16)+extra));
            }
         // substitute upper 16 bits of label address
         // NOTE: form LHnPm will not match here since it is discovered and substituted above.
            if (instruction.indexOf(“LH”+op)>=0) {
            // Label, last operand, has already been translated to address by symtab lookup
               String label = theTokenList.get(op).getValue();
               int addr = 0;
               try {
                  addr = Binary.stringToInt(label);    // KENV   1/6/05
               } 
                   catch (NumberFormatException e) {
                   // this won’t happen…
                  }
                    // If bit 15 is 1, that means lower 16 bits will become a negative offset!  To
                // compensate if that is the case, we need to add 1 to the high 16 bits.
               int extra = Binary.bitValue(addr,15);
               instruction = substitute(instruction,”LH”+op,String.valueOf((addr >> 16)+extra));
            }
         // substitute lower 16 bits of label address, after adding single digit that follows P
            if ((index=instruction.indexOf(“LL”+op+”P”))>=0) {
            // label has already been translated to address by symtab lookup.
               String label = theTokenList.get(op).getValue();
               int addr = 0;
               int add = instruction.charAt(index+4)-48; // digit that follows P
               try {
                  addr = Binary.stringToInt(label) + add;     // KENV   1/6/05
               } 
                   catch (NumberFormatException e) {
                   // this won’t happen…
                  }
               instruction = substitute(instruction,”LL”+op+”P”+add,String.valueOf(addr << 16 >> 16));//addr & 0xffff));
            }   
         // substitute lower 16 bits of label address. 
         // NOTE: form LLnPm will not match here since it is discovered and substituted above.
            if ((index=instruction.indexOf(“LL”+op))>=0) {
            // label has already been translated to address by symtab lookup.
               String label = theTokenList.get(op).getValue();
               int addr = 0;
               try {
                  addr = Binary.stringToInt(label);     // KENV   1/6/05
               } 
                   catch (NumberFormatException e) {
                   // this won’t happen…
                  }
               if ((instruction.length() > index+3) && (instruction.charAt(index+3) == ‘U’)) {
                  instruction = substitute(instruction,”LL”+op+”U”,String.valueOf(addr & 0xffff));
               } 
               else {
                  instruction = substitute(instruction,”LL”+op,String.valueOf(addr << 16 >> 16));//addr & 0xffff));
               }
            }
         // Substitute upper 16 bits of value after adding 1,2,3,4, (any single digit)
         // Added by DPS on 22 Jan 2008 to fix “ble” and “bgt” bug [do not adjust for bit 15==1]
            if ((index=instruction.indexOf(“VHL”+op+”P”))>=0) {
               String value = theTokenList.get(op).getValue();
               int val = 0;
               int add = instruction.charAt(index+5)-‘0’; // amount to add: 1,2,3,4 (any single digit)
               try { // KENV 1/6/05
                  val = Binary.stringToInt(value) + add;
               } 
                   catch (NumberFormatException e) {
                   // this won’t happen…
                  }
               instruction = substitute(instruction,”VHL”+op+”P”+add,String.valueOf(val >> 16));
            }            
         // substitute upper 16 bits of value after adding 1,2,3,4, then adjust
         // if necessary, if resulting bit 15 is 1 (see “extra” below)
            if ((index=instruction.indexOf(“VH”+op+”P”))>=0) {
               String value = theTokenList.get(op).getValue();
               int val = 0;
               int add = instruction.charAt(index+4)-‘0’; // amount to add: 1,2,3,4 (any single digit)
               try { // KENV 1/6/05
                  val = Binary.stringToInt(value) + add;
               } 
                   catch (NumberFormatException e) {
                   // this won’t happen…
                  }
                // If bit 15 is 1, that means lower 16 bits will become a negative offset!  To
                // compensate if that is the case, we need to add 1 to the high 16 bits.
               int extra = Binary.bitValue(val,15);
               instruction = substitute(instruction,”VH”+op+”P”+add,String.valueOf((val >> 16)+extra));
            }
         // substitute upper 16 bits of value, adjusted if necessary (see “extra” below)
         // NOTE: if VHnPm appears it will not match here; already substituted by code above
            if (instruction.indexOf(“VH”+op)>=0) {
               String value = theTokenList.get(op).getValue();
               int val = 0;
               try {
                  val = Binary.stringToInt(value);      // KENV   1/6/05
               } 
                   catch (NumberFormatException e) {
                   // this won’t happen…
                  }
                // If bit 15 is 1, that means lower 16 bits will become a negative offset!  To
                // compensate if that is the case, we need to add 1 to the high 16 bits.
               int extra = Binary.bitValue(val,15);
               instruction = substitute(instruction,”VH”+op,String.valueOf((val >> 16)+extra));
            }   
         // substitute lower 16 bits of value after adding specified amount (1,2,3,4)
            if ((index=instruction.indexOf(“VL”+op+”P”))>=0) {
               String value = theTokenList.get(op).getValue();
               int val = 0;
               int add = instruction.charAt(index+4)-‘0’; // P is followed by 1,2,3,4(any single digit OK)
               try {  // KENV 1/6/05
                  val = Binary.stringToInt(value) + add;
               } 
                   catch (NumberFormatException e) {
                   // this won’t happen…
                  }
               if ((instruction.length() > index+5) && (instruction.charAt(index+5) == ‘U’)) {
                  instruction = substitute(instruction,”VL”+op+”P”+add+”U”,String.valueOf(val & 0xffff));
               }
               else {
                  instruction = substitute(instruction,”VL”+op+”P”+add,String.valueOf(val << 16 >> 16));//val & 0xffff));
               }
            }
         // substitute lower 16 bits of value.  NOTE: VLnPm already substituted by above code.
            if ((index=instruction.indexOf(“VL”+op))>=0) {
               String value = theTokenList.get(op).getValue();
               int val = 0;
               try {
                  val = Binary.stringToInt(value);      // KENV   1/6/05
               } 
                   catch (NumberFormatException e) {
                   // this won’t happen…
                  }
               if ((instruction.length() > index+3) && (instruction.charAt(index+3) == ‘U’)) {
                  instruction = substitute(instruction,”VL”+op+”U”,String.valueOf(val & 0xffff));
               }
               else {
                  instruction = substitute(instruction,”VL”+op,String.valueOf(val << 16 >> 16));//val & 0xffff));
               }
            }
            // substitute upper 16 bits of 32 bit value
            if (instruction.indexOf(“VHL”+op)>=0) {
            // value has to be second operand token.
               String value = theTokenList.get(op).getValue(); // has to be token 2 position
               int val = 0;
               try {
                  val = Binary.stringToInt(value);      // KENV   1/6/05
               } 
                   catch (NumberFormatException e) {
                   // this won’t happen…
                  }
               instruction = substitute(instruction,”VHL”+op,String.valueOf(val >> 16));
            }
         }
         // substitute upper 16 bits of label address for “la”
         if (instruction.indexOf(“LHL”)>=0) {
            // Label has already been translated to address by symtab lookup
            String label = theTokenList.get(2).getValue();  // has to be token 2 position
            int addr = 0;
            try {
               addr = Binary.stringToInt(label);    // KENV   1/6/05
            } 
                catch (NumberFormatException e) {
                   // this won’t happen…
               }
            instruction = substitute(instruction,”LHL”,String.valueOf(addr >> 16));
         }  
      
         // substitute upper 16 bits of label address after adding the digit that follows “P” and
        // also adding the immediate e.g. here+44($s0)
        // Address will be resolved using addition, so need to add 1 to upper half if bit 15 is 1.
         if ((index=instruction.indexOf(“LHPAP”))>=0) {
               // Label has already been translated to address by symtab lookup
            String label = theTokenList.get(2).getValue();  // 2 is only possible token position
            String addend= theTokenList.get(4).getValue();  // 4 is only possible token position
            int addr = 0;
            int add = instruction.charAt(index+5)-48; // extract digit following P
            try {
               addr = Binary.stringToInt(label) +    // KENV   1/6/05
                                Binary.stringToInt(addend) + add;
            } 
                catch (NumberFormatException e) {
                   // this won’t happen…
               }
                // If bit 15 is 1, that means lower 16 bits will become a negative offset!  To
                // compensate if that is the case, we need to add 1 to the high 16 bits.
            int extra = Binary.bitValue(addr,15);
            instruction = substitute(instruction,”LHPAP”+add,String.valueOf((addr >> 16) + extra));
         }      
         // substitute upper 16 bits of label address after adding constant e.g. here+4($s0)
        // Address will be resolved using addition, so need to add 1 to upper half if bit 15 is 1.
        // NOTE: format LHPAPm is recognized and substituted by the code above.
         if (instruction.indexOf(“LHPA”)>=0) {
               // Label has already been translated to address by symtab lookup
            String label = theTokenList.get(2).getValue();  // 2 is only possible token position
            String addend= theTokenList.get(4).getValue();  // 4 is only possible token position
            int addr = 0;
            try {
               addr = Binary.stringToInt(label) +    // KENV   1/6/05
                                Binary.stringToInt(addend);
            } 
                catch (NumberFormatException e) {
                   // this won’t happen…
               }
                // If bit 15 is 1, that means lower 16 bits will become a negative offset!  To
                // compensate if that is the case, we need to add 1 to the high 16 bits.
            int extra = Binary.bitValue(addr,15);
            instruction = substitute(instruction,”LHPA”,String.valueOf((addr >> 16) + extra));
         }  
         // substitute upper 16 bits of label address after adding constant e.g. here+4($s0)
        // Address will be resolved using “ori”, so DO NOT adjust upper 16 if bit 15 is 1.
        // This only happens in the “la” (load address) instruction.
         if (instruction.indexOf(“LHPN”)>=0) {
               // Label has already been translated to address by symtab lookup
            String label = theTokenList.get(2).getValue();  // 2 is only possible token position
            String addend= theTokenList.get(4).getValue();  // 4 is only possible token position
            int addr = 0;
            try {
               addr = Binary.stringToInt(label) +    // KENV   1/6/05
                                Binary.stringToInt(addend);
            } 
                catch (NumberFormatException e) {
                   // this won’t happen…
               }
            instruction = substitute(instruction,”LHPN”,String.valueOf(addr >> 16));
         }  
         // substitute lower 16 bits of label address after adding immediate value e.g. here+44($s0)
        // and also adding the digit following LLPP in the spec.
         if ((index=instruction.indexOf(“LLPP”))>=0) {
            // label has already been translated to address by symtab lookup.
            String label = theTokenList.get(2).getValue(); // 2 is only possible token position
            String addend= theTokenList.get(4).getValue(); // 4 is only possible token position
            int addr = 0;
            int add = instruction.charAt(index+4)-48; // extract digit following P
            try {
               addr = Binary.stringToInt(label) +    // KENV   1/6/05
                                Binary.stringToInt(addend) + add;
                
            } 
                catch (NumberFormatException e) {
                   // this won’t happen…
               }
            instruction = substitute(instruction,”LLPP”+add,String.valueOf(addr << 16 >> 16));//addr & 0xffff));
         }
         // substitute lower 16 bits of label address after adding immediate value e.g. here+44($s0)
        // NOTE: format LLPPm is recognized and substituted by the code above
         if ((index=instruction.indexOf(“LLP”))>=0) {
            // label has already been translated to address by symtab lookup.
            String label = theTokenList.get(2).getValue(); // 2 is only possible token position
            String addend= theTokenList.get(4).getValue(); // 4 is only possible token position
            int addr = 0;
            try {
               addr = Binary.stringToInt(label) +    // KENV   1/6/05
                                Binary.stringToInt(addend);
                
            } 
                catch (NumberFormatException e) {
                   // this won’t happen…
               }
            if ((instruction.length() > index+3) && (instruction.charAt(index+3) == ‘U’)) {
               instruction = substitute(instruction,”LLPU”,String.valueOf(addr & 0xffff));
            }
            else {
               instruction = substitute(instruction,”LLP”,String.valueOf(addr << 16 >> 16));//addr & 0xffff));
            }
         }
        // 23-Jan-2008 DPS.  Substitute correct constant branch offset depending on whether or not
        // delayed branching is enabled. BROFF is followed by 2 digits.  The first is branch offset
        // to substitute if delayed branching is DISABLED, second is offset if ENABLED.
         if ((index=instruction.indexOf(“BROFF”))>=0) {
            try {
               String disabled = instruction.substring(index+5, index+6);
               String enabled  = instruction.substring(index+6, index+7);
               instruction = substitute(instruction,”BROFF”+disabled+enabled,
                          Globals.getSettings().getDelayedBranchingEnabled() ? enabled : disabled );
            } 
                catch (IndexOutOfBoundsException iooe) {
                  instruction = substitute(instruction,”BROFF”, “BAD_PSEUDO_OP_SPEC”);
               }
         }
        // substitute Next higher Register for registers in token list (for “mfc1.d”,”mtc1.d”)
         if (instruction.indexOf(“NR”)>=0) {
            for (int op=1; op=0) {
                     instruction = substitute(instruction, “NR”+op,”$”+(regNumber+1));
                  } 
               }
                   catch (NullPointerException e) { // not in RegisterFile, must be Coprocessor1 register
                     regNumber = Coprocessor1.getRegisterNumber(token);
                     if (regNumber>=0) {
                        instruction = substitute(instruction, “NR”+op,”$f”+(regNumber+1));
                     }
                  }
            }              
         }
      
        // substitute result of subtracting last token from 32 (rol and ror constant rotate amount)
         if (instruction.indexOf(“S32″)>=0) {
            String value = theTokenList.get(theTokenList.size()-1).getValue();
            int val = 0;
            try {
               val = Binary.stringToInt(value);      // KENV   1/6/05
            } 
                catch (NumberFormatException e) {
                 // this won’t happen…
               }
            instruction = substitute(instruction,”S32”,Integer.toString(32-val));
         }

        // substitute label if necessary
         if (instruction.indexOf(“LAB”)>=0) {
            // label has to be last token.  It has already been translated to address
            // by symtab lookup, so I need to get the text label back so parseLine() won’t puke.
            String label = theTokenList.get(theTokenList.size()-1).getValue();
            Symbol sym = program.getLocalSymbolTable().getSymbolGivenAddressLocalOrGlobal(label);
            if (sym!=null) { 
               // should never be null, since there would not be an address if label were not in symtab!
                // DPS 9 Dec 2007: The “substitute()” method will substitute for ALL matches.  Here
                // we want to substitute only for the first match, for two reasons: (1) a statement
                // can only contain one label reference, its last operand, and (2) If the user’s label
                // contains the substring “LAB”, then substitute() will go into an infinite loop because
                // it will keep matching the substituted string!
               instruction = substituteFirst(instruction,”LAB”,sym.getName());
            }
         }
         return instruction;
      }
   
        // Performs a String substitution.  Java 1.5 adds an overloaded String.replace method to 
    // do this directly but I wanted to stay 1.4 compatible.
    // Modified 12 July 2006 to “substitute all occurances”, not just the first.
       private static String substitute(String original, String find, String replacement) { 
         if (original.indexOf(find)<0 || find.equals(replacement)) {             return original;  // second condition prevents infinite loop below          }          int i;          String modified = original;          while ((i=modified.indexOf(find))>=0) {
            modified = modified.substring(0, i) + replacement + modified.substring(i + find.length());
         }
         return modified;
      }
    
        // Performs a String substitution, but will only substitute for the first match.
    // Java 1.5 adds an overloaded String.replace method to do this directly but I 
    // wanted to stay 1.4 compatible.
       private static String substituteFirst(String original, String find, String replacement) { 
         if (original.indexOf(find)<0 || find.equals(replacement)) {             return original;  // second condition prevents infinite loop below          }          int i;          String modified = original;          if ((i=modified.indexOf(find))>=0) {
            modified = modified.substring(0, i) + replacement + modified.substring(i + find.length());
         }
         return modified;
      }
   
   
    // Takes list of basic instructions that this extended instruction
    // expands to, which is a string, and breaks out into separate
    // instructions.  They are separated by ‘\n’ character.
    
       private ArrayList buildTranslationList(String translation) {
         if (translation == null || translation.length() == 0) {
            return null;
         }
         ArrayList translationList = new ArrayList();
         StringTokenizer st = new StringTokenizer(translation,”\n”);
         while (st.hasMoreTokens()) {
            translationList.add(st.nextToken());
         }      
         return translationList;
      }
      
    
       
    /*
     * Get length in bytes that this extended instruction requires in its 
     * binary form. The answer depends on how many basic instructions it 
     * expands to.  This may vary, if expansion includes a nop, depending on
     * whether or not delayed branches are enabled. Each requires 4 bytes.
     * Returns length in bytes of corresponding binary instruction(s).
     * Returns 0 if the ArrayList is null or empty.
     */   
       private int getInstructionLength(ArrayList translationList) {
         if (translationList == null || translationList.size() == 0) {
            return 0;
         }
       // If instruction template is DBNOP, that means generate a “nop” instruction but only
       // if Delayed branching is enabled.  Otherwise generate nothing.  If generating nothing,
       // then don’t count the nop in the instruction length.   DPS 23-Jan-2008
         int instructionCount = 0;
         for (int i=0; i=0 && !Globals.getSettings().getDelayedBranchingEnabled()) 
               continue;
            instructionCount++;
         }
         return 4 * instructionCount;
      }
      
   }

InstructionSet$81

package mars.mips.instructions;
synchronized class InstructionSet$81 implements SimulationCode {
void InstructionSet$81(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$151

package mars.mips.instructions;
synchronized class InstructionSet$151 implements SimulationCode {
void InstructionSet$151(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$114

package mars.mips.instructions;
synchronized class InstructionSet$114 implements SimulationCode {
void InstructionSet$114(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$70

package mars.mips.instructions;
synchronized class InstructionSet$70 implements SimulationCode {
void InstructionSet$70(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$35

package mars.mips.instructions;
synchronized class InstructionSet$35 implements SimulationCode {
void InstructionSet$35(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$129

package mars.mips.instructions;
synchronized class InstructionSet$129 implements SimulationCode {
void InstructionSet$129(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$69

package mars.mips.instructions;
synchronized class InstructionSet$69 implements SimulationCode {
void InstructionSet$69(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$94

package mars.mips.instructions;
synchronized class InstructionSet$94 implements SimulationCode {
void InstructionSet$94(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$6

package mars.mips.instructions;
synchronized class InstructionSet$6 implements SimulationCode {
void InstructionSet$6(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$148

package mars.mips.instructions;
synchronized class InstructionSet$148 implements SimulationCode {
void InstructionSet$148(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$130

package mars.mips.instructions;
synchronized class InstructionSet$130 implements SimulationCode {
void InstructionSet$130(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$54

package mars.mips.instructions;
synchronized class InstructionSet$54 implements SimulationCode {
void InstructionSet$54(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$11

package mars.mips.instructions;
synchronized class InstructionSet$11 implements SimulationCode {
void InstructionSet$11(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$132

package mars.mips.instructions;
synchronized class InstructionSet$132 implements SimulationCode {
void InstructionSet$132(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$56

package mars.mips.instructions;
synchronized class InstructionSet$56 implements SimulationCode {
void InstructionSet$56(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$13

package mars.mips.instructions;
synchronized class InstructionSet$13 implements SimulationCode {
void InstructionSet$13(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$96

package mars.mips.instructions;
synchronized class InstructionSet$96 implements SimulationCode {
void InstructionSet$96(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$4

package mars.mips.instructions;
synchronized class InstructionSet$4 implements SimulationCode {
void InstructionSet$4(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$153

package mars.mips.instructions;
synchronized class InstructionSet$153 implements SimulationCode {
void InstructionSet$153(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$116

package mars.mips.instructions;
synchronized class InstructionSet$116 implements SimulationCode {
void InstructionSet$116(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/BasicInstructionFormat.java
mars/mips/instructions/BasicInstructionFormat.javapackage mars.mips.instructions;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * These are the MIPS-defined formats of basic machine instructions.  The R-format indicates
 * the instruction works only with registers.  The I-format indicates the instruction
 * works with an immediate value (e.g. constant).  The J-format indicates this is a Jump
 * instruction.  The I-branch-format is defined by me, not MIPS, to to indicate this is
 * a Branch instruction, specifically to distinguish immediate
 * values used as target addresses.
 * 
 * @author Pete Sanderson 
 * @version August 2003
 */
public class BasicInstructionFormat {
    public static final BasicInstructionFormat R_FORMAT = new BasicInstructionFormat();
    public static final BasicInstructionFormat I_FORMAT = new BasicInstructionFormat();
    public static final BasicInstructionFormat I_BRANCH_FORMAT = new BasicInstructionFormat();
    public static final BasicInstructionFormat J_FORMAT = new BasicInstructionFormat();
    
    // private default constructor prevents objects of this class other than those above.
    private BasicInstructionFormat() {
    }
}

InstructionSet$72

package mars.mips.instructions;
synchronized class InstructionSet$72 implements SimulationCode {
void InstructionSet$72(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$37

package mars.mips.instructions;
synchronized class InstructionSet$37 implements SimulationCode {
void InstructionSet$37(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$76

package mars.mips.instructions;
synchronized class InstructionSet$76 implements SimulationCode {
void InstructionSet$76(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$33

package mars.mips.instructions;
synchronized class InstructionSet$33 implements SimulationCode {
void InstructionSet$33(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$112

package mars.mips.instructions;
synchronized class InstructionSet$112 implements SimulationCode {
void InstructionSet$112(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$52

package mars.mips.instructions;
synchronized class InstructionSet$52 implements SimulationCode {
void InstructionSet$52(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$17

package mars.mips.instructions;
synchronized class InstructionSet$17 implements SimulationCode {
void InstructionSet$17(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$136

package mars.mips.instructions;
synchronized class InstructionSet$136 implements SimulationCode {
void InstructionSet$136(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$92

package mars.mips.instructions;
synchronized class InstructionSet$92 implements SimulationCode {
void InstructionSet$92(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$109

package mars.mips.instructions;
synchronized class InstructionSet$109 implements SimulationCode {
void InstructionSet$109(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$2

package mars.mips.instructions;
synchronized class InstructionSet$2 implements SimulationCode {
void InstructionSet$2(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$90

package mars.mips.instructions;
synchronized class InstructionSet$90 implements SimulationCode {
void InstructionSet$90(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$28

package mars.mips.instructions;
synchronized class InstructionSet$28 implements SimulationCode {
void InstructionSet$28(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$50

package mars.mips.instructions;
synchronized class InstructionSet$50 implements SimulationCode {
void InstructionSet$50(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$15

package mars.mips.instructions;
synchronized class InstructionSet$15 implements SimulationCode {
void InstructionSet$15(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$134

package mars.mips.instructions;
synchronized class InstructionSet$134 implements SimulationCode {
void InstructionSet$134(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet

package mars.mips.instructions;
public synchronized class InstructionSet {
private java.util.ArrayList instructionList;
private SyscallLoader syscallLoader;
public void InstructionSet();
public java.util.ArrayList getInstructionList();
public void populate();
private void addPseudoInstructions();
public java.util.ArrayList matchOperator(String);
public java.util.ArrayList prefixMatchOperator(String);
private void findAndSimulateSyscall(int, mars.ProgramStatement) throws mars.ProcessingException;
private void processBranch(int);
private void processJump(int);
private void processReturnAddress(int);
}

InstructionSet$89

package mars.mips.instructions;
synchronized class InstructionSet$89 implements SimulationCode {
void InstructionSet$89(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$74

package mars.mips.instructions;
synchronized class InstructionSet$74 implements SimulationCode {
void InstructionSet$74(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$31

package mars.mips.instructions;
synchronized class InstructionSet$31 implements SimulationCode {
void InstructionSet$31(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$155

package mars.mips.instructions;
synchronized class InstructionSet$155 implements SimulationCode {
void InstructionSet$155(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$110

package mars.mips.instructions;
synchronized class InstructionSet$110 implements SimulationCode {
void InstructionSet$110(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$49

package mars.mips.instructions;
synchronized class InstructionSet$49 implements SimulationCode {
void InstructionSet$49(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$5

package mars.mips.instructions;
synchronized class InstructionSet$5 implements SimulationCode {
void InstructionSet$5(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$97

package mars.mips.instructions;
synchronized class InstructionSet$97 implements SimulationCode {
void InstructionSet$97(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$12

package mars.mips.instructions;
synchronized class InstructionSet$12 implements SimulationCode {
void InstructionSet$12(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$57

package mars.mips.instructions;
synchronized class InstructionSet$57 implements SimulationCode {
void InstructionSet$57(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$133

package mars.mips.instructions;
synchronized class InstructionSet$133 implements SimulationCode {
void InstructionSet$133(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$36

package mars.mips.instructions;
synchronized class InstructionSet$36 implements SimulationCode {
void InstructionSet$36(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$73

package mars.mips.instructions;
synchronized class InstructionSet$73 implements SimulationCode {
void InstructionSet$73(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$117

package mars.mips.instructions;
synchronized class InstructionSet$117 implements SimulationCode {
void InstructionSet$117(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$152

package mars.mips.instructions;
synchronized class InstructionSet$152 implements SimulationCode {
void InstructionSet$152(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$128

package mars.mips.instructions;
synchronized class InstructionSet$128 implements SimulationCode {
void InstructionSet$128(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/Instruction.java
mars/mips/instructions/Instruction.javapackage mars.mips.instructions;
import mars.assembler.*;
import mars.*;
import java.util.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Base class to represent member of MIPS instruction set.
 * 
 * @author Pete Sanderson and Ken Vollmar
 * @version August 2003
 */

public abstract class Instruction {
  /**
   *  Length in bytes of a machine instruction.  MIPS is a RISC architecture
    *  so all instructions are the same length.  Currently set to 4.
    */
    public static final int INSTRUCTION_LENGTH       =  4;
    public static final int INSTRUCTION_LENGTH_BITS  = 32;
    /** Characters used in instruction mask to indicate bit positions
     *  for ‘f’irst, ‘s’econd, and ‘t’hird operands.
     **/
    public static char[] operandMask = { ‘f’, ‘s’, ‘t’};  
    /** The instruction name. **/
    protected String mnemonic;
    /** Example usage of this instruction.  Is provided as subclass constructor argument.  **/
    protected String exampleFormat;
    /** Description of instruction for display to user **/
    protected String description;
    /** List of tokens generated by tokenizing example usage (see exampleFormat). **/
    protected TokenList tokenList;

    /**
     * Get operation mnemonic
     *
     * @return operation mnemonic (e.g. addi, sw)
     */
    public String getName() {
        return mnemonic;
    }

    /**
     * Get string descriptor of instruction’s format.  This is an example MIPS
     * assembler instruction usage which contains the operator and all operands.
     * Operands are separated by commas, an operand that begins with a ‘$’
     * represents a register, and an integer operand represents an immediate value
     * or address.  Here are two examples: “nor $1,$2,$3” and “sw $1,100($2)”
     *
     * @return String representing example instruction format.
     */
    public String getExampleFormat() {
        return exampleFormat;
    }

    /**
     * Get string describing the instruction.  This is not used internally by
      * MARS, but is for display to the user.
     *
     * @return String describing the instruction.
     */
    public String getDescription() {
        return description;
    }
    
    /**
     * Get TokenList corresponding to correct instruction syntax.
     * For example, the instruction with format “sw $1,100($2)” yields token list
     * 
     *
     * @return TokenList object representing correct instruction usage.
     */

    public TokenList getTokenList() {
        return tokenList;
    }
    
    
    /**
     * Get length in bytes that this instruction requires in its binary form.
      * Default is 4 (holds for all basic instructions), but can be overridden 
      * in subclass.
     * @return int length in bytes of corresponding binary instruction(s).
     */

    public int getInstructionLength() {
        return INSTRUCTION_LENGTH;
    }
     
    /** Used by subclass constructors to extract operator mnemonic from the
     instruction example. **/

    protected String extractOperator(String example) {
        StringTokenizer st = new StringTokenizer(example, ” ,\t”);
        return st.nextToken();
    }
    
    /** Used to build a token list from the example instruction
    provided as constructor argument.  Parser uses this for syntax checking.  **/
    protected void createExampleTokenList() {
        try {
            tokenList = ((new Tokenizer()).tokenizeExampleInstruction(exampleFormat));
        } catch (ProcessingException pe) {
            System.out.println(“CONFIGURATION ERROR: Instruction example \””+exampleFormat+”\” contains invalid token(s).”);
        }
    }
}

mars/mips/instructions/SyscallLoader.java
mars/mips/instructions/SyscallLoader.java   package mars.mips.instructions;
   import mars.mips.instructions.syscalls.*;
   import mars.*;
    import mars.util.*;
   import java.util.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

    
    /****************************************************************************/
    /* This class provides functionality to bring external Syscall definitions
     * into MARS.  This permits anyone with knowledge of the Mars public interfaces, 
     * in particular of the Memory and Register classes, to write custom MIPS syscall
     * functions. This is adapted from the ToolLoader class, which is in turn adapted
     * from Bret Barker’s GameServer class from the book “Developing Games In Java”.
     */
    
    class SyscallLoader {
      
      private static final String CLASS_PREFIX = “mars.mips.instructions.syscalls.”;
      private static final String SYSCALLS_DIRECTORY_PATH = “mars/mips/instructions/syscalls”;
      private static final String SYSCALL_INTERFACE = “Syscall.class”;
      private static final String SYSCALL_ABSTRACT = “AbstractSyscall.class”;
      private static final String CLASS_EXTENSION = “class”;
      
      private ArrayList syscallList;
    
   /*
      *  Dynamically loads Syscalls into an ArrayList.  This method is adapted from
      *  the loadGameControllers() method in Bret Barker’s GameServer class.
      *  Barker ( ) is co-author of the book “Developing Games
      *  in Java”.  Also see the “loadMarsTools()” method from ToolLoader class.
      */
       void loadSyscalls() {
         syscallList = new ArrayList();
         // grab all class files in the same directory as Syscall
         ArrayList candidates = FilenameFinder.getFilenameList(this.getClass( ).getClassLoader(),
                                              SYSCALLS_DIRECTORY_PATH, CLASS_EXTENSION);
           HashMap syscalls = new HashMap();
         for( int i = 0; i < candidates.size(); i++) {             String file = (String) candidates.get(i);                  // Do not add class if already encountered (happens if run in MARS development directory)                 if (syscalls.containsKey(file)) {                   continue;                 } else {                    syscalls.put(file,file);                 }             if ((!file.equals(SYSCALL_INTERFACE)) &&                   (!file.equals(SYSCALL_ABSTRACT)) ) {                try {                   // grab the class, make sure it implements Syscall, instantiate, add to list                   String syscallClassName = CLASS_PREFIX+file.substring(0, file.indexOf(CLASS_EXTENSION)-1);                   Class clas = Class.forName(syscallClassName);                   if (!Syscall.class.isAssignableFrom(clas)) {                      continue;                   }                   Syscall syscall = (Syscall) clas.newInstance();                   if (findSyscall(syscall.getNumber()) == null) {                      syscallList.add(syscall);                   }                    else {                      throw new Exception("Duplicate service number: "+syscall.getNumber()+                             " already registered to "+                             findSyscall(syscall.getNumber()).getName());                   }                }                     catch (Exception e) {                      System.out.println("Error instantiating Syscall from file " + file + ": "+e);                      System.exit(0);                   }             }          }          syscallList = processSyscallNumberOverrides(syscallList);          return;       }                  // Will get any syscall number override specifications from MARS config file and        // process them.  This will alter syscallList entry for affected names.        private ArrayList processSyscallNumberOverrides(ArrayList syscallList) {          ArrayList overrides = new Globals().getSyscallOverrides();          SyscallNumberOverride override;          Syscall syscall;          for (int index=0; index < overrides.size(); index++) {             override = (SyscallNumberOverride) overrides.get(index);             boolean match = false;              for (int i=0; i < syscallList.size(); i++) {                syscall = (Syscall) syscallList.get(i);                if (override.getName().equals(syscall.getName())) {                       // we have a match to service name, assign new number                   syscall.setNumber(override.getNumber());                   match = true;                }              }             if (!match) {                System.out.println("Error: syscall name '"+override.getName()+                      "' in config file does not match any name in syscall list");                System.exit(0);             }          }             // Wait until end to check for duplicate numbers.  To do so earlier             // would disallow for instance the exchange of numbers between two             // services.  This is N-squared operation but N is small.             // This will also detect duplicates that accidently occur from addition             // of a new Syscall subclass to the collection, even if the config file             // does not contain any overrides.          Syscall syscallA, syscallB;          boolean duplicates = false;          for (int i = 0; i < syscallList.size(); i++) {             syscallA = (Syscall)syscallList.get(i);             for (int j = i+1; j < syscallList.size(); j++) {                syscallB = (Syscall)syscallList.get(j);                if ( syscallA.getNumber() == syscallB.getNumber()) {                   System.out.println("Error: syscalls "+syscallA.getName()+" and "+                         syscallB.getName()+" are both assigned same number "+syscallA.getNumber());                   duplicates = true;                }             }          }          if (duplicates) {             System.exit(0);          }          return syscallList;       }            /*      * Method to find Syscall object associated with given service number.      * Returns null if no associated object found.      */        Syscall findSyscall(int number) {          // linear search is OK since number of syscalls is small.          Syscall service, match = null;          if (syscallList==null) {             loadSyscalls();          }          for (int index=0; index < syscallList.size(); index++) {             service = (Syscall) syscallList.get(index);             if (service.getNumber() == number) {                match = service;             }          }          return match;       }    } InstructionSet$34 package mars.mips.instructions; synchronized class InstructionSet$34 implements SimulationCode { void InstructionSet$34(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$71 package mars.mips.instructions; synchronized class InstructionSet$71 implements SimulationCode { void InstructionSet$71(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$115 package mars.mips.instructions; synchronized class InstructionSet$115 implements SimulationCode { void InstructionSet$115(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$150 package mars.mips.instructions; synchronized class InstructionSet$150 implements SimulationCode { void InstructionSet$150(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$10 package mars.mips.instructions; synchronized class InstructionSet$10 implements SimulationCode { void InstructionSet$10(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$55 package mars.mips.instructions; synchronized class InstructionSet$55 implements SimulationCode { void InstructionSet$55(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$131 package mars.mips.instructions; synchronized class InstructionSet$131 implements SimulationCode { void InstructionSet$131(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$7 package mars.mips.instructions; synchronized class InstructionSet$7 implements SimulationCode { void InstructionSet$7(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$149 package mars.mips.instructions; synchronized class InstructionSet$149 implements SimulationCode { void InstructionSet$149(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$68 package mars.mips.instructions; synchronized class InstructionSet$68 implements SimulationCode { void InstructionSet$68(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$95 package mars.mips.instructions; synchronized class InstructionSet$95 implements SimulationCode { void InstructionSet$95(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$135 package mars.mips.instructions; synchronized class InstructionSet$135 implements SimulationCode { void InstructionSet$135(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$14 package mars.mips.instructions; synchronized class InstructionSet$14 implements SimulationCode { void InstructionSet$14(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$51 package mars.mips.instructions; synchronized class InstructionSet$51 implements SimulationCode { void InstructionSet$51(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$91 package mars.mips.instructions; synchronized class InstructionSet$91 implements SimulationCode { void InstructionSet$91(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$29 package mars.mips.instructions; synchronized class InstructionSet$29 implements SimulationCode { void InstructionSet$29(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$108 package mars.mips.instructions; synchronized class InstructionSet$108 implements SimulationCode { void InstructionSet$108(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$3 package mars.mips.instructions; synchronized class InstructionSet$3 implements SimulationCode { void InstructionSet$3(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$48 package mars.mips.instructions; synchronized class InstructionSet$48 implements SimulationCode { void InstructionSet$48(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/InstructionSet.java mars/mips/instructions/InstructionSet.java   package mars.mips.instructions;    import mars.simulator.*;    import mars.mips.hardware.*;    import mars.mips.instructions.syscalls.*;    import mars.*;    import mars.util.*;    import java.util.*;    import java.io.*;          /* Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * The list of Instruction objects, each of which represents a MIPS instruction.  * The instruction may either be basic (translates into binary machine code) or  * extended (translates into sequence of one or more basic instructions).  *  * @author Pete Sanderson and Ken Vollmar  * @version August 2003-5  */     public class InstructionSet    {       private ArrayList instructionList;       private SyscallLoader syscallLoader;     /**      * Creates a new InstructionSet object.      */        public InstructionSet()       {          instructionList = new ArrayList();              }     /**      * Retrieve the current instruction set.      */        public ArrayList getInstructionList()       {          return instructionList;              }     /**      * Adds all instructions to the set.  A given extended instruction may have      * more than one Instruction object, depending on how many formats it can have.      * @see Instruction      * @see BasicInstruction      * @see ExtendedInstruction      */        public void populate()       {         /* Here is where the parade begins.  Every instruction is added to the set here.*/                // ////////////////////////////////////   BASIC INSTRUCTIONS START HERE ////////////////////////////////                 instructionList.add(                 new BasicInstruction("nop",                  "Null operation : machine code is all zeroes",                 BasicInstructionFormat.R_FORMAT,                 "000000 00000 00000 00000 00000 000000",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                     // Hey I like this so far!                   }                }));          instructionList.add(                 new BasicInstruction("add $t1,$t2,$t3",                  "Addition with overflow : set $t1 to ($t2 plus $t3)",                 BasicInstructionFormat.R_FORMAT,                 "000000 sssss ttttt fffff 00000 100000",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      int add1 = RegisterFile.getValue(operands[1]);                      int add2 = RegisterFile.getValue(operands[2]);                      int sum = add1 + add2;                   // overflow on A+B detected when A and B have same sign and A+B has other sign.                      if ((add1 >= 0 && add2 >= 0 && sum < 0)                         || (add1 < 0 && add2 < 0 && sum >= 0))
                     {
                        throw new ProcessingException(statement,
                            “arithmetic overflow”,Exceptions.ARITHMETIC_OVERFLOW_EXCEPTION);
                     }
                     RegisterFile.updateRegister(operands[0], sum);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“sub $t1,$t2,$t3”,
                 “Subtraction with overflow : set $t1 to ($t2 minus $t3)”,
                BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttttt fffff 00000 100010”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     int sub1 = RegisterFile.getValue(operands[1]);
                     int sub2 = RegisterFile.getValue(operands[2]);
                     int dif = sub1 – sub2;
                  // overflow on A-B detected when A and B have opposite signs and A-B has B’s sign
                     if ((sub1 >= 0 && sub2 < 0 && dif < 0)                         || (sub1 < 0 && sub2 >= 0 && dif >= 0))
                     {
                        throw new ProcessingException(statement,
                            “arithmetic overflow”,Exceptions.ARITHMETIC_OVERFLOW_EXCEPTION);
                     }
                     RegisterFile.updateRegister(operands[0], dif);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“addi $t1,$t2,-100”,
                 “Addition immediate with overflow : set $t1 to ($t2 plus signed 16-bit immediate)”,
                BasicInstructionFormat.I_FORMAT,
                “001000 sssss fffff tttttttttttttttt”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     int add1 = RegisterFile.getValue(operands[1]);
                     int add2 = operands[2] << 16 >> 16;
                     int sum = add1 + add2;
                  // overflow on A+B detected when A and B have same sign and A+B has other sign.
                     if ((add1 >= 0 && add2 >= 0 && sum < 0)                         || (add1 < 0 && add2 < 0 && sum >= 0))
                     {
                        throw new ProcessingException(statement,
                            “arithmetic overflow”,Exceptions.ARITHMETIC_OVERFLOW_EXCEPTION);
                     }
                     RegisterFile.updateRegister(operands[0], sum);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“addu $t1,$t2,$t3”,
                 “Addition unsigned without overflow : set $t1 to ($t2 plus $t3), no overflow”,
                BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttttt fffff 00000 100001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1])
                        + RegisterFile.getValue(operands[2]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“subu $t1,$t2,$t3”,
                 “Subtraction unsigned without overflow : set $t1 to ($t2 minus $t3), no overflow”,
                BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttttt fffff 00000 100011”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1])
                        – RegisterFile.getValue(operands[2]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“addiu $t1,$t2,-100”,
                 “Addition immediate unsigned without overflow : set $t1 to ($t2 plus signed 16-bit immediate), no overflow”,
                BasicInstructionFormat.I_FORMAT,
                “001001 sssss fffff tttttttttttttttt”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1])
                        + (operands[2] << 16 >> 16));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“mult $t1,$t2”,
                 “Multiplication : Set hi to high-order 32 bits, lo to low-order 32 bits of the product of $t1 and $t2 (use mfhi to access hi, mflo to access lo)”,
                BasicInstructionFormat.R_FORMAT,
                “000000 fffff sssss 00000 00000 011000”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     long product = (long) RegisterFile.getValue(operands[0])
                        * (long) RegisterFile.getValue(operands[1]);
                  // Register 33 is HIGH and 34 is LOW
                     RegisterFile.updateRegister(33, (int) (product >> 32));
                     RegisterFile.updateRegister(34, (int) ((product << 32) >> 32));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“multu $t1,$t2”,
                 “Multiplication unsigned : Set HI to high-order 32 bits, LO to low-order 32 bits of the product of unsigned $t1 and $t2 (use mfhi to access HI, mflo to access LO)”,
                BasicInstructionFormat.R_FORMAT,
                “000000 fffff sssss 00000 00000 011001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     long product = (((long) RegisterFile.getValue(operands[0]))<<32>>>32)
                        * (((long) RegisterFile.getValue(operands[1]))<<32>>>32);
                  // Register 33 is HIGH and 34 is LOW
                     RegisterFile.updateRegister(33, (int) (product >> 32));
                     RegisterFile.updateRegister(34, (int) ((product << 32) >> 32));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“mul $t1,$t2,$t3”,
                 “Multiplication without overflow  : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of the product of $t2 and $t3 (use mfhi to access HI, mflo to access LO)”,
                BasicInstructionFormat.R_FORMAT,
                “011100 sssss ttttt fffff 00000 000010”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     long product = (long) RegisterFile.getValue(operands[1])
                        * (long) RegisterFile.getValue(operands[2]);
                     RegisterFile.updateRegister(operands[0],
                        (int) ((product << 32) >> 32));
                  // Register 33 is HIGH and 34 is LOW.  Not required by MIPS; SPIM does it.
                     RegisterFile.updateRegister(33, (int) (product >> 32));
                     RegisterFile.updateRegister(34, (int) ((product << 32) >> 32));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“madd $t1,$t2”,
                 “Multiply add : Multiply $t1 by $t2 then increment HI by high-order 32 bits of product, increment LO by low-order 32 bits of product (use mfhi to access HI, mflo to access LO)”,
                BasicInstructionFormat.R_FORMAT,
                “011100 fffff sssss 00000 00000 000000”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     long product = (long) RegisterFile.getValue(operands[0])
                        * (long) RegisterFile.getValue(operands[1]);
                     // Register 33 is HIGH and 34 is LOW. 
                     long contentsHiLo = Binary.twoIntsToLong(
                        RegisterFile.getValue(33), RegisterFile.getValue(34));
                     long sum = contentsHiLo + product;
                     RegisterFile.updateRegister(33, Binary.highOrderLongToInt(sum));
                     RegisterFile.updateRegister(34, Binary.lowOrderLongToInt(sum));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“maddu $t1,$t2”,
                 “Multiply add unsigned : Multiply $t1 by $t2 then increment HI by high-order 32 bits of product, increment LO by low-order 32 bits of product, unsigned (use mfhi to access HI, mflo to access LO)”,
                BasicInstructionFormat.R_FORMAT,
                “011100 fffff sssss 00000 00000 000001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     long product = (((long) RegisterFile.getValue(operands[0]))<<32>>>32)
                        * (((long) RegisterFile.getValue(operands[1]))<<32>>>32);
                     // Register 33 is HIGH and 34 is LOW. 
                     long contentsHiLo = Binary.twoIntsToLong(
                        RegisterFile.getValue(33), RegisterFile.getValue(34));
                     long sum = contentsHiLo + product;
                     RegisterFile.updateRegister(33, Binary.highOrderLongToInt(sum));
                     RegisterFile.updateRegister(34, Binary.lowOrderLongToInt(sum));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“msub $t1,$t2”,
                 “Multiply subtract : Multiply $t1 by $t2 then decrement HI by high-order 32 bits of product, decrement LO by low-order 32 bits of product (use mfhi to access HI, mflo to access LO)”,
                BasicInstructionFormat.R_FORMAT,
                “011100 fffff sssss 00000 00000 000100”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     long product = (long) RegisterFile.getValue(operands[0])
                        * (long) RegisterFile.getValue(operands[1]);
                     // Register 33 is HIGH and 34 is LOW. 
                     long contentsHiLo = Binary.twoIntsToLong(
                        RegisterFile.getValue(33), RegisterFile.getValue(34));
                     long diff = contentsHiLo – product;
                     RegisterFile.updateRegister(33, Binary.highOrderLongToInt(diff));
                     RegisterFile.updateRegister(34, Binary.lowOrderLongToInt(diff));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“msubu $t1,$t2”,
                 “Multiply subtract unsigned : Multiply $t1 by $t2 then decrement HI by high-order 32 bits of product, decement LO by low-order 32 bits of product, unsigned (use mfhi to access HI, mflo to access LO)”,
                BasicInstructionFormat.R_FORMAT,
                “011100 fffff sssss 00000 00000 000101”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     long product = (((long) RegisterFile.getValue(operands[0]))<<32>>>32)
                        * (((long) RegisterFile.getValue(operands[1]))<<32>>>32);
                     // Register 33 is HIGH and 34 is LOW. 
                     long contentsHiLo = Binary.twoIntsToLong(
                        RegisterFile.getValue(33), RegisterFile.getValue(34));
                     long diff = contentsHiLo – product;
                     RegisterFile.updateRegister(33, Binary.highOrderLongToInt(diff));
                     RegisterFile.updateRegister(34, Binary.lowOrderLongToInt(diff));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“div $t1,$t2”,
                 “Division with overflow : Divide $t1 by $t2 then set LO to quotient and HI to remainder (use mfhi to access HI, mflo to access LO)”,
                BasicInstructionFormat.R_FORMAT,
                “000000 fffff sssss 00000 00000 011010”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[1]) == 0)
                     {
                     // Note: no exceptions and undefined results for zero div
                     // COD3 Appendix A says “with overflow” but MIPS 32 instruction set
                     // specification says “no arithmetic exception under any circumstances”.
                        return;
                     }
                  
                  // Register 33 is HIGH and 34 is LOW
                     RegisterFile.updateRegister(33,
                        RegisterFile.getValue(operands[0])
                        % RegisterFile.getValue(operands[1]));
                     RegisterFile.updateRegister(34,
                        RegisterFile.getValue(operands[0])
                        / RegisterFile.getValue(operands[1]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“divu $t1,$t2”,
                 “Division unsigned without overflow : Divide unsigned $t1 by $t2 then set LO to quotient and HI to remainder (use mfhi to access HI, mflo to access LO)”,
                BasicInstructionFormat.R_FORMAT,
                “000000 fffff sssss 00000 00000 011011”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[1]) == 0)
                     {
                     // Note: no exceptions, and undefined results for zero divide
                        return;
                     }
                     long oper1 = ((long)RegisterFile.getValue(operands[0])) << 32 >>> 32; 
                     long oper2 = ((long)RegisterFile.getValue(operands[1])) << 32 >>> 32; 
                  // Register 33 is HIGH and 34 is LOW
                     RegisterFile.updateRegister(33,
                        (int) (((oper1 % oper2) << 32) >> 32));
                     RegisterFile.updateRegister(34,
                        (int) (((oper1 / oper2) << 32) >> 32));                  
                  }
               }));
         instructionList.add(
                new BasicInstruction(“mfhi $t1”, 
                 “Move from HI register : Set $t1 to contents of HI (see multiply and divide operations)”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 00000 00000 fffff 00000 010000”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(33));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“mflo $t1”, 
                 “Move from LO register : Set $t1 to contents of LO (see multiply and divide operations)”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 00000 00000 fffff 00000 010010”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(34));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“mthi $t1”, 
                 “Move to HI registerr : Set HI to contents of $t1 (see multiply and divide operations)”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 fffff 00000 00000 00000 010001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(33,
                        RegisterFile.getValue(operands[0]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“mtlo $t1”, 
                 “Move to LO register : Set LO to contents of $t1 (see multiply and divide operations)”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 fffff 00000 00000 00000 010011”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(34,
                        RegisterFile.getValue(operands[0]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“and $t1,$t2,$t3”,
                 “Bitwise AND : Set $t1 to bitwise AND of $t2 and $t3”,
                BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttttt fffff 00000 100100”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1])
                        & RegisterFile.getValue(operands[2]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“or $t1,$t2,$t3”,
                 “Bitwise OR : Set $t1 to bitwise OR of $t2 and $t3”,
                BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttttt fffff 00000 100101”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1])
                        | RegisterFile.getValue(operands[2]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“andi $t1,$t2,100”,
                 “Bitwise AND immediate : Set $t1 to bitwise AND of $t2 and zero-extended 16-bit immediate”,
                BasicInstructionFormat.I_FORMAT,
                “001100 sssss fffff tttttttttttttttt”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                  // ANDing with 0x0000FFFF zero-extends the immediate (high 16 bits always 0).
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1])
                        & (operands[2] & 0x0000FFFF));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“ori $t1,$t2,100”,
                 “Bitwise OR immediate : Set $t1 to bitwise OR of $t2 and zero-extended 16-bit immediate”,
                BasicInstructionFormat.I_FORMAT,
                “001101 sssss fffff tttttttttttttttt”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                  // ANDing with 0x0000FFFF zero-extends the immediate (high 16 bits always 0).
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1])
                        | (operands[2] & 0x0000FFFF));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“nor $t1,$t2,$t3”,
                 “Bitwise NOR : Set $t1 to bitwise NOR of $t2 and $t3”,
                BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttttt fffff 00000 100111”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        ~(RegisterFile.getValue(operands[1])
                        | RegisterFile.getValue(operands[2])));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“xor $t1,$t2,$t3”,
                 “Bitwise XOR (exclusive OR) : Set $t1 to bitwise XOR of $t2 and $t3”,
                BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttttt fffff 00000 100110”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1])
                        ^ RegisterFile.getValue(operands[2]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“xori $t1,$t2,100”,
                 “Bitwise XOR immediate : Set $t1 to bitwise XOR of $t2 and zero-extended 16-bit immediate”,
                BasicInstructionFormat.I_FORMAT,
                “001110 sssss fffff tttttttttttttttt”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                  // ANDing with 0x0000FFFF zero-extends the immediate (high 16 bits always 0).
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1])
                        ^ (operands[2] & 0x0000FFFF));
                  }
               }));                 
         instructionList.add(
                new BasicInstruction(“sll $t1,$t2,10”,
                 “Shift left logical : Set $t1 to result of shifting $t2 left by number of bits specified by immediate”,
                BasicInstructionFormat.R_FORMAT,
                “000000 00000 sssss fffff ttttt 000000”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1]) << operands[2]);                   }                }));          instructionList.add(                 new BasicInstruction("sllv $t1,$t2,$t3",                  "Shift left logical variable : Set $t1 to result of shifting $t2 left by number of bits specified by value in low-order 5 bits of $t3",                 BasicInstructionFormat.R_FORMAT,                 "000000 ttttt sssss fffff 00000 000100",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                   // Mask all but low 5 bits of register containing shamt.                      RegisterFile.updateRegister(operands[0],                         RegisterFile.getValue(operands[1]) <<                          (RegisterFile.getValue(operands[2]) & 0x0000001F));                   }                }));          instructionList.add(                 new BasicInstruction("srl $t1,$t2,10",                  "Shift right logical : Set $t1 to result of shifting $t2 right by number of bits specified by immediate",                 BasicInstructionFormat.R_FORMAT,                 "000000 00000 sssss fffff ttttt 000010",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                   // must zero-fill, so use ">>>” instead of “>>”.
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1]) >>> operands[2]);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“sra $t1,$t2,10”,
                “Shift right arithmetic : Set $t1 to result of sign-extended shifting $t2 right by number of bits specified by immediate”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 00000 sssss fffff ttttt 000011”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                  // must sign-fill, so use “>>”.
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1]) >> operands[2]);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“srav $t1,$t2,$t3”,
                 “Shift right arithmetic variable : Set $t1 to result of sign-extended shifting $t2 right by number of bits specified by value in low-order 5 bits of $t3”,
                BasicInstructionFormat.R_FORMAT,
                “000000 ttttt sssss fffff 00000 000111”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                  // Mask all but low 5 bits of register containing shamt.Use “>>” to sign-fill.
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1]) >> 
                        (RegisterFile.getValue(operands[2]) & 0x0000001F));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“srlv $t1,$t2,$t3”,
                 “Shift right logical variable : Set $t1 to result of shifting $t2 right by number of bits specified by value in low-order 5 bits of $t3”,
                BasicInstructionFormat.R_FORMAT,
                “000000 ttttt sssss fffff 00000 000110”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                  // Mask all but low 5 bits of register containing shamt.Use “>>>” to zero-fill.
                     RegisterFile.updateRegister(operands[0],
                        RegisterFile.getValue(operands[1]) >>> 
                        (RegisterFile.getValue(operands[2]) & 0x0000001F));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“lw $t1,-100($t2)”,
                 “Load word : Set $t1 to contents of effective memory word address”,
                BasicInstructionFormat.I_FORMAT,
                “100011 ttttt fffff ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     try
                     {
                        RegisterFile.updateRegister(operands[0],
                            Globals.memory.getWord(
                            RegisterFile.getValue(operands[2]) + operands[1]));
                     } 
                         catch (AddressErrorException e)
                        {
                           throw new ProcessingException(statement, e);
                        }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“ll $t1,-100($t2)”,
                “Load linked : Paired with Store Conditional (sc) to perform atomic read-modify-write.  Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors.”,
                 BasicInstructionFormat.I_FORMAT,
                “110000 ttttt fffff ssssssssssssssss”,
                 // The ll (load link) command is supposed to be the front end of an atomic
                 // operation completed by sc (store conditional), with success or failure
                 // of the store depending on whether the memory block containing the
                 // loaded word is modified in the meantime by a different processor.
                 // Since MARS, like SPIM simulates only a single processor, the store
                 // conditional will always succeed so there is no need to do anything
                 // special here.  In that case, ll is same as lw.  And sc does the same
                 // thing as sw except in addition it writes 1 into the source register.
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     try
                     {
                        RegisterFile.updateRegister(operands[0],
                            Globals.memory.getWord(
                            RegisterFile.getValue(operands[2]) + operands[1]));
                     } 
                         catch (AddressErrorException e)
                        {
                           throw new ProcessingException(statement, e);
                        }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“lwl $t1,-100($t2)”,
                “Load word left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word”,
                 BasicInstructionFormat.I_FORMAT,
                “100010 ttttt fffff ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     try
                     {
                        int address = RegisterFile.getValue(operands[2]) + operands[1];
                        int result = RegisterFile.getValue(operands[0]);
                        for (int i=0; i<=address % Globals.memory.WORD_LENGTH_BYTES; i++) {                            result = Binary.setByte(result,3-i,Globals.memory.getByte(address-i));                         }                         RegisterFile.updateRegister(operands[0], result);                      }                           catch (AddressErrorException e)                         {                            throw new ProcessingException(statement, e);                         }                   }                }));          instructionList.add(                 new BasicInstruction("lwr $t1,-100($t2)",                 "Load word right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word",                  BasicInstructionFormat.I_FORMAT,                 "100110 ttttt fffff ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      try                      {                         int address = RegisterFile.getValue(operands[2]) + operands[1];                         int result = RegisterFile.getValue(operands[0]);                         for (int i=0; i<=3-(address % Globals.memory.WORD_LENGTH_BYTES); i++) {                            result = Binary.setByte(result,i,Globals.memory.getByte(address+i));                         }                         RegisterFile.updateRegister(operands[0], result);                      }                           catch (AddressErrorException e)                         {                            throw new ProcessingException(statement, e);                         }                   }                }));          instructionList.add(                 new BasicInstruction("sw $t1,-100($t2)",                 "Store word : Store contents of $t1 into effective memory word address",                  BasicInstructionFormat.I_FORMAT,                 "101011 ttttt fffff ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      try                      {                         Globals.memory.setWord(                             RegisterFile.getValue(operands[2]) + operands[1],                             RegisterFile.getValue(operands[0]));                      }                           catch (AddressErrorException e)                         {                            throw new ProcessingException(statement, e);                         }                   }                }));          instructionList.add(                 new BasicInstruction("sc $t1,-100($t2)",                 "Store conditional : Paired with Load Linked (ll) to perform atomic read-modify-write.  Stores $t1 value into effective address, then sets $t1 to 1 for success.  Always succeeds because MARS does not simulate multiple processors.",                  BasicInstructionFormat.I_FORMAT,                 "111000 ttttt fffff ssssssssssssssss",                  // See comments with "ll" instruction above.  "sc" is implemented                  // like "sw", except that 1 is placed in the source register.                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      try                      {                         Globals.memory.setWord(                             RegisterFile.getValue(operands[2]) + operands[1],                             RegisterFile.getValue(operands[0]));                      }                           catch (AddressErrorException e)                         {                            throw new ProcessingException(statement, e);                         }                      RegisterFile.updateRegister(operands[0],1); // always succeeds                   }                }));          instructionList.add(                 new BasicInstruction("swl $t1,-100($t2)",                 "Store word left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective byte address and continuing through the low-order byte of its word",                  BasicInstructionFormat.I_FORMAT,                 "101010 ttttt fffff ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      try                      {                         int address = RegisterFile.getValue(operands[2]) + operands[1];                         int source = RegisterFile.getValue(operands[0]);                         for (int i=0; i<=address % Globals.memory.WORD_LENGTH_BYTES; i++) {                            Globals.memory.setByte(address-i,Binary.getByte(source,3-i));                         }                      }                           catch (AddressErrorException e)                         {                            throw new ProcessingException(statement, e);                         }                   }                }));          instructionList.add(                 new BasicInstruction("swr $t1,-100($t2)",                 "Store word right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective byte address and continuing through that byte address",                  BasicInstructionFormat.I_FORMAT,                 "101110 ttttt fffff ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      try                      {                         int address = RegisterFile.getValue(operands[2]) + operands[1];                         int source = RegisterFile.getValue(operands[0]);                         for (int i=0; i<=3-(address % Globals.memory.WORD_LENGTH_BYTES); i++) {                            Globals.memory.setByte(address+i,Binary.getByte(source,i));                         }                      }                           catch (AddressErrorException e)                         {                            throw new ProcessingException(statement, e);                         }                   }                }));          instructionList.add(                 new BasicInstruction("lui $t1,100",                 "Load upper immediate : Set high-order 16 bits of $t1 to 16-bit immediate and low-order 16 bits to 0",                  BasicInstructionFormat.I_FORMAT,                 "001111 00000 fffff ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      RegisterFile.updateRegister(operands[0], operands[1] << 16);                   }                }));          instructionList.add(                 new BasicInstruction("beq $t1,$t2,label",                 "Branch if equal : Branch to statement at label's address if $t1 and $t2 are equal",                  BasicInstructionFormat.I_BRANCH_FORMAT,                 "000100 fffff sssss tttttttttttttttt",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                                         if (RegisterFile.getValue(operands[0])                         == RegisterFile.getValue(operands[1]))                      {                         processBranch(operands[2]);                      }                   }                }));          instructionList.add(                 new BasicInstruction("bne $t1,$t2,label",                 "Branch if not equal : Branch to statement at label's address if $t1 and $t2 are not equal",                  BasicInstructionFormat.I_BRANCH_FORMAT,                 "000101 fffff sssss tttttttttttttttt",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      if (RegisterFile.getValue(operands[0])                         != RegisterFile.getValue(operands[1]))                      {                         processBranch(operands[2]);                      }                   }                }));          instructionList.add(                 new BasicInstruction("bgez $t1,label",                 "Branch if greater than or equal to zero : Branch to statement at label's address if $t1 is greater than or equal to zero",                  BasicInstructionFormat.I_BRANCH_FORMAT,                 "000001 fffff 00001 ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      if (RegisterFile.getValue(operands[0]) >= 0)
                     {
                        processBranch(operands[1]);
                     }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“bgezal $t1,label”,
                “Branch if greater then or equal to zero and link : If $t1 is greater than or equal to zero, then set $ra to the Program Counter and branch to statement at label’s address”,
                 BasicInstructionFormat.I_BRANCH_FORMAT,
                “000001 fffff 10001 ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[0]) >= 0)
                     {  // the “and link” part
                        processReturnAddress(31);//RegisterFile.updateRegister(“$ra”,RegisterFile.getProgramCounter());
                        processBranch(operands[1]);
                     }
                  } 
               }));
         instructionList.add(
                new BasicInstruction(“bgtz $t1,label”,
                “Branch if greater than zero : Branch to statement at label’s address if $t1 is greater than zero”,
                 BasicInstructionFormat.I_BRANCH_FORMAT,
                “000111 fffff 00000 ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[0]) > 0)
                     {
                        processBranch(operands[1]);
                     }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“blez $t1,label”,
                “Branch if less than or equal to zero : Branch to statement at label’s address if $t1 is less than or equal to zero”,
                 BasicInstructionFormat.I_BRANCH_FORMAT,
                “000110 fffff 00000 ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[0]) <= 0)                      {                         processBranch(operands[1]);                      }                   }                }));          instructionList.add(                 new BasicInstruction("bltz $t1,label",                 "Branch if less than zero : Branch to statement at label's address if $t1 is less than zero",                  BasicInstructionFormat.I_BRANCH_FORMAT,                 "000001 fffff 00000 ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      if (RegisterFile.getValue(operands[0]) < 0)                      {                         processBranch(operands[1]);                      }                   }                }));          instructionList.add(                 new BasicInstruction("bltzal $t1,label",                 "Branch if less than zero and link : If $t1 is less than or equal to zero, then set $ra to the Program Counter and branch to statement at label's address",                  BasicInstructionFormat.I_BRANCH_FORMAT,                 "000001 fffff 10000 ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      if (RegisterFile.getValue(operands[0]) < 0)                      {  // the "and link" part                         processReturnAddress(31);//RegisterFile.updateRegister("$ra",RegisterFile.getProgramCounter());                         processBranch(operands[1]);                      }                   }                }));          instructionList.add(                 new BasicInstruction("slt $t1,$t2,$t3",                 "Set less than : If $t2 is less than $t3, then set $t1 to 1 else set $t1 to 0",                  BasicInstructionFormat.R_FORMAT,                 "000000 sssss ttttt fffff 00000 101010",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      RegisterFile.updateRegister(operands[0],                         (RegisterFile.getValue(operands[1])                         < RegisterFile.getValue(operands[2]))                                 ? 1                                 : 0);                   }                }));          instructionList.add(                 new BasicInstruction("sltu $t1,$t2,$t3",                 "Set less than unsigned : If $t2 is less than $t3 using unsigned comparision, then set $t1 to 1 else set $t1 to 0",                  BasicInstructionFormat.R_FORMAT,                 "000000 sssss ttttt fffff 00000 101011",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      int first = RegisterFile.getValue(operands[1]);                      int second = RegisterFile.getValue(operands[2]);                      if (first >= 0 && second >= 0 || first < 0 && second < 0)                      {                         RegisterFile.updateRegister(operands[0],                             (first < second) ? 1 : 0);                      }                       else                      {                         RegisterFile.updateRegister(operands[0],                             (first >= 0) ? 1 : 0);
                     }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“slti $t1,$t2,-100”,
                “Set less than immediate : If $t2 is less than sign-extended 16-bit immediate, then set $t1 to 1 else set $t1 to 0”,
                 BasicInstructionFormat.I_FORMAT,
                “001010 sssss fffff tttttttttttttttt”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                  // 16 bit immediate value in operands[2] is sign-extended
                     RegisterFile.updateRegister(operands[0],
                        (RegisterFile.getValue(operands[1])
                        < (operands[2] << 16 >> 16))
                                ? 1
                                : 0);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“sltiu $t1,$t2,-100”,
                “Set less than immediate unsigned : If $t2 is less than  sign-extended 16-bit immediate using unsigned comparison, then set $t1 to 1 else set $t1 to 0”,
                 BasicInstructionFormat.I_FORMAT,
                “001011 sssss fffff tttttttttttttttt”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     int first = RegisterFile.getValue(operands[1]);
                  // 16 bit immediate value in operands[2] is sign-extended
                     int second = operands[2] << 16 >> 16;
                     if (first >= 0 && second >= 0 || first < 0 && second < 0)                      {                         RegisterFile.updateRegister(operands[0],                             (first < second) ? 1 : 0);                      }                       else                      {                         RegisterFile.updateRegister(operands[0],                             (first >= 0) ? 1 : 0);
                     }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“movn $t1,$t2,$t3”,
                “Move conditional not zero : Set $t1 to $t2 if $t3 is not zero”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttttt fffff 00000 001011”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[2])!=0)
                        RegisterFile.updateRegister(operands[0], RegisterFile.getValue(operands[1]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“movz $t1,$t2,$t3”,
                “Move conditional zero : Set $t1 to $t2 if $t3 is zero”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttttt fffff 00000 001010”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[2])==0)
                        RegisterFile.updateRegister(operands[0], RegisterFile.getValue(operands[1]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“movf $t1,$t2”,
                “Move if FP condition flag 0 false : Set $t1 to $t2 if FPU (Coprocessor 1) condition flag 0 is false (zero)”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 sssss 000 00 fffff 00000 000001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (Coprocessor1.getConditionFlag(0)==0)
                        RegisterFile.updateRegister(operands[0], RegisterFile.getValue(operands[1]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“movf $t1,$t2,1”,
                “Move if specified FP condition flag false : Set $t1 to $t2 if FPU (Coprocessor 1) condition flag specified by the immediate is false (zero)”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttt 00 fffff 00000 000001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (Coprocessor1.getConditionFlag(operands[2])==0)
                        RegisterFile.updateRegister(operands[0], RegisterFile.getValue(operands[1]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“movt $t1,$t2”,
                 “Move if FP condition flag 0 true : Set $t1 to $t2 if FPU (Coprocessor 1) condition flag 0 is true (one)”,
                BasicInstructionFormat.R_FORMAT,
                “000000 sssss 000 01 fffff 00000 000001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (Coprocessor1.getConditionFlag(0)==1)
                        RegisterFile.updateRegister(operands[0], RegisterFile.getValue(operands[1]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“movt $t1,$t2,1”,
                 “Move if specfied FP condition flag true : Set $t1 to $t2 if FPU (Coprocessor 1) condition flag specified by the immediate is true (one)”,
                BasicInstructionFormat.R_FORMAT,
                “000000 sssss ttt 01 fffff 00000 000001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (Coprocessor1.getConditionFlag(operands[2])==1)
                        RegisterFile.updateRegister(operands[0], RegisterFile.getValue(operands[1]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“break 100”, 
                 “Break execution with code : Terminate program execution with specified exception code”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 ffffffffffffffffffff 001101”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {  // At this time I don’t have exception processing or trap handlers
                     // so will just halt execution with a message.
                     int[] operands = statement.getOperands();
                     throw new ProcessingException(statement, “break instruction executed; code = “+
                          operands[0]+”.”, Exceptions.BREAKPOINT_EXCEPTION);
                  }
               })); 
         instructionList.add(
                new BasicInstruction(“break”, 
                 “Break execution : Terminate program execution with exception”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 00000 00000 00000 00000 001101”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {  // At this time I don’t have exception processing or trap handlers
                     // so will just halt execution with a message.
                     throw new ProcessingException(statement, “break instruction executed; no code given.”,
                        Exceptions.BREAKPOINT_EXCEPTION);
                  }
               }));                 
         instructionList.add(
                new BasicInstruction(“syscall”, 
                 “Issue a system call : Execute the system call specified by value in $v0”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 00000 00000 00000 00000 001100”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     findAndSimulateSyscall(RegisterFile.getValue(2),statement);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“j target”, 
                 “Jump unconditionally : Jump to statement at target address”,
                 BasicInstructionFormat.J_FORMAT,
                “000010 ffffffffffffffffffffffffff”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     processJump(
                        ((RegisterFile.getProgramCounter() & 0xF0000000)
                                | (operands[0] << 2)));                               }                }));          instructionList.add(                 new BasicInstruction("jr $t1",                   "Jump register unconditionally : Jump to statement whose address is in $t1",                  BasicInstructionFormat.R_FORMAT,                 "000000 fffff 00000 00000 00000 001000",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      processJump(RegisterFile.getValue(operands[0]));                   }                }));          instructionList.add(                 new BasicInstruction("jal target",                 "Jump and link : Set $ra to Program Counter (return address) then jump to statement at target address",                  BasicInstructionFormat.J_FORMAT,                 "000011 ffffffffffffffffffffffffff",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      processReturnAddress(31);// RegisterFile.updateRegister(31, RegisterFile.getProgramCounter());                      processJump(                         (RegisterFile.getProgramCounter() & 0xF0000000)                                 | (operands[0] << 2));                   }                }));          instructionList.add(                 new BasicInstruction("jalr $t1,$t2",                 "Jump and link register : Set $t1 to Program Counter (return address) then jump to statement whose address is in $t2",                  BasicInstructionFormat.R_FORMAT,                 "000000 sssss 00000 fffff 00000 001001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      processReturnAddress(operands[0]);//RegisterFile.updateRegister(operands[0], RegisterFile.getProgramCounter());                      processJump(RegisterFile.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("jalr $t1",                 "Jump and link register : Set $ra to Program Counter (return address) then jump to statement whose address is in $t1",                  BasicInstructionFormat.R_FORMAT,                 "000000 fffff 00000 11111 00000 001001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      processReturnAddress(31);//RegisterFile.updateRegister(31, RegisterFile.getProgramCounter());                       processJump(RegisterFile.getValue(operands[0]));                   }                }));          instructionList.add(                 new BasicInstruction("lb $t1,-100($t2)",                 "Load byte : Set $t1 to sign-extended 8-bit value from effective memory byte address",                  BasicInstructionFormat.I_FORMAT,                 "100000 ttttt fffff ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      try                      {                         RegisterFile.updateRegister(operands[0],                             Globals.memory.getByte(                             RegisterFile.getValue(operands[2])                                     + (operands[1] << 16 >> 16))
                                            << 24                                             >> 24);
                     } 
                         catch (AddressErrorException e)
                        {
                           throw new ProcessingException(statement, e);
                        }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“lh $t1,-100($t2)”,
                “Load halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address”,
                 BasicInstructionFormat.I_FORMAT,
                “100001 ttttt fffff ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     try
                     {
                        RegisterFile.updateRegister(operands[0],
                            Globals.memory.getHalf(
                            RegisterFile.getValue(operands[2])
                                    + (operands[1] << 16 >> 16))
                                            << 16                                             >> 16);
                     } 
                         catch (AddressErrorException e)
                        {
                           throw new ProcessingException(statement, e);
                        }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“lhu $t1,-100($t2)”,
                “Load halfword unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address”,
                 BasicInstructionFormat.I_FORMAT,
                “100101 ttttt fffff ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     try
                     {
                     // offset is sign-extended and loaded halfword value is zero-extended
                        RegisterFile.updateRegister(operands[0],
                            Globals.memory.getHalf(
                            RegisterFile.getValue(operands[2])
                                    + (operands[1] << 16 >> 16))
                                            & 0x0000ffff);
                     } 
                         catch (AddressErrorException e)
                        {
                           throw new ProcessingException(statement, e);
                        }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“lbu $t1,-100($t2)”,
                “Load byte unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address”,
                 BasicInstructionFormat.I_FORMAT,
                “100100 ttttt fffff ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     try
                     {
                        RegisterFile.updateRegister(operands[0],
                            Globals.memory.getByte(
                            RegisterFile.getValue(operands[2])
                                    + (operands[1] << 16 >> 16))
                                            & 0x000000ff);
                     } 
                         catch (AddressErrorException e)
                        {
                           throw new ProcessingException(statement, e);
                        }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“sb $t1,-100($t2)”,
                “Store byte : Store the low-order 8 bits of $t1 into the effective memory byte address”,
                 BasicInstructionFormat.I_FORMAT,
                “101000 ttttt fffff ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     try
                     {
                        Globals.memory.setByte(
                            RegisterFile.getValue(operands[2])
                                    + (operands[1] << 16 >> 16),
                                    RegisterFile.getValue(operands[0])
                                            & 0x000000ff);
                     } 
                         catch (AddressErrorException e)
                        {
                           throw new ProcessingException(statement, e);
                        }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“sh $t1,-100($t2)”,
                “Store halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address”,
                 BasicInstructionFormat.I_FORMAT,
                “101001 ttttt fffff ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     try
                     {
                        Globals.memory.setHalf(
                            RegisterFile.getValue(operands[2])
                                    + (operands[1] << 16 >> 16),
                                    RegisterFile.getValue(operands[0])
                                            & 0x0000ffff);
                     } 
                         catch (AddressErrorException e)
                        {
                           throw new ProcessingException(statement, e);
                        }
                  }
               }));             
         instructionList.add(        
                new BasicInstruction(“clo $t1,$t2”, 
                 “Count number of leading ones : Set $t1 to the count of leading one bits in $t2 starting at most significant bit position”,
                 BasicInstructionFormat.R_FORMAT,
                 // MIPS32 requires rd (first) operand to appear twice in machine code.
                 // It has to be same as rt (third) operand in machine code, but the
                 // source statement does not have or permit third operand.
                 // In the machine code, rd and rt are adjacent, but my mask
                 // substitution cannot handle adjacent placement of the same source
                 // operand (e.g. “… sssss fffff fffff …”) because it would interpret
                 // the mask to be the total length of both (10 bits).  I could code it
                 // to have 3 operands then define a pseudo-instruction of two operands
                 // to translate into this, but then both would show up in instruction set
                 // list and I don’t want that.  So I will use the convention of Computer
                 // Organization and Design 3rd Edition, Appendix A, and code the rt bits
                 // as 0’s.  The generated code does not match SPIM and would not run 
                 // on a real MIPS machine but since I am providing no means of storing
                 // the binary code that is not really an issue.
                “011100 sssss 00000 fffff 00000 100001”,
                new SimulationCode()
               {   
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     int value = RegisterFile.getValue(operands[1]);
                     int leadingOnes = 0;
                     int bitPosition = 31;
                     while (Binary.bitValue(value,bitPosition)==1 && bitPosition>=0) {
                        leadingOnes++;
                        bitPosition–;
                     }
                     RegisterFile.updateRegister(operands[0], leadingOnes);
                  }
               })); 
         instructionList.add(        
                new BasicInstruction(“clz $t1,$t2”, 
                 “Count number of leading zeroes : Set $t1 to the count of leading zero bits in $t2 starting at most significant bit positio”,
                 BasicInstructionFormat.R_FORMAT,
                 // See comments for “clo” instruction above.  They apply here too.
                “011100 sssss 00000 fffff 00000 100000”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     int value = RegisterFile.getValue(operands[1]);
                     int leadingZeros = 0;
                     int bitPosition = 31;
                     while (Binary.bitValue(value,bitPosition)==0 && bitPosition>=0) {
                        leadingZeros++;
                        bitPosition–;
                     }
                     RegisterFile.updateRegister(operands[0], leadingZeros);
                  }
               }));             
         instructionList.add(        
                new BasicInstruction(“mfc0 $t1,$8”, 
                 “Move from Coprocessor 0 : Set $t1 to the value stored in Coprocessor 0 register $8”,
                 BasicInstructionFormat.R_FORMAT,
                “010000 00000 fffff sssss 00000 000000”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     RegisterFile.updateRegister(operands[0],
                        Coprocessor0.getValue(operands[1]));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“mtc0 $t1,$8”, 
                 “Move to Coprocessor 0 : Set Coprocessor 0 register $8 to value stored in $t1”,
                 BasicInstructionFormat.R_FORMAT,
                “010000 00100 fffff sssss 00000 000000”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     Coprocessor0.updateRegister(operands[1],
                        RegisterFile.getValue(operands[0]));
                  }
               }));
                
        /////////////////////// Floating Point Instructions Start Here ////////////////
         instructionList.add(
                new BasicInstruction(“add.s $f0,$f1,$f3”,
                “Floating point addition single precision : Set $f0 to single-precision floating point value of $f1 plus $f3”, 
                 BasicInstructionFormat.R_FORMAT,
                “010001 10000 ttttt sssss fffff 000000″,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     float add1 = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));
                     float add2 = Float.intBitsToFloat(Coprocessor1.getValue(operands[2]));
                     float sum = add1 + add2;
                  // overflow detected when sum is positive or negative infinity.
                  /*
                  if (sum == Float.NEGATIVE_INFINITY || sum == Float.POSITIVE_INFINITY) {
                    throw new ProcessingException(statement,”arithmetic overflow”);
                  }
                  */
                     Coprocessor1.updateRegister(operands[0], Float.floatToIntBits(sum));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“sub.s $f0,$f1,$f3”,
                “Floating point subtraction single precision : Set $f0 to single-precision floating point value of $f1  minus $f3”,
                 BasicInstructionFormat.R_FORMAT,
                “010001 10000 ttttt sssss fffff 000001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     float sub1 = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));
                     float sub2 = Float.intBitsToFloat(Coprocessor1.getValue(operands[2]));
                     float diff = sub1 – sub2;
                     Coprocessor1.updateRegister(operands[0], Float.floatToIntBits(diff));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“mul.s $f0,$f1,$f3”,
                “Floating point multiplication single precision : Set $f0 to single-precision floating point value of $f1 times $f3”,
                 BasicInstructionFormat.R_FORMAT,
                “010001 10000 ttttt sssss fffff 000010”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     float mul1 = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));
                     float mul2 = Float.intBitsToFloat(Coprocessor1.getValue(operands[2]));
                     float prod = mul1 * mul2;
                     Coprocessor1.updateRegister(operands[0], Float.floatToIntBits(prod));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“div.s $f0,$f1,$f3”,
                “Floating point division single precision : Set $f0 to single-precision floating point value of $f1 divided by $f3”,
                 BasicInstructionFormat.R_FORMAT,
                “010001 10000 ttttt sssss fffff 000011”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     float div1 = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));
                     float div2 = Float.intBitsToFloat(Coprocessor1.getValue(operands[2]));
                     float quot = div1 / div2;
                     Coprocessor1.updateRegister(operands[0], Float.floatToIntBits(quot));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“sqrt.s $f0,$f1”,
                 “Square root single precision : Set $f0 to single-precision floating point square root of $f1”,
                BasicInstructionFormat.R_FORMAT,
                “010001 10000 00000 sssss fffff 000100”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     float value = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));
                     int floatSqrt = 0;
                     if (value < 0.0f) {                         // This is subject to refinement later.  Release 4.0 defines floor, ceil, trunc, round                         // to act silently rather than raise Invalid Operation exception, so sqrt should do the                         // same.  An intermediate step would be to define a setting for FCSR Invalid Operation                         // flag, but the best solution is to simulate the FCSR register itself.                         // FCSR = Floating point unit Control and Status Register.  DPS 10-Aug-2010                         floatSqrt = Float.floatToIntBits( Float.NaN);                         //throw new ProcessingException(statement, "Invalid Operation: sqrt of negative number");                      }                       else {                         floatSqrt = Float.floatToIntBits( (float) Math.sqrt(value));                      }                      Coprocessor1.updateRegister(operands[0], floatSqrt);                   }                }));          instructionList.add(                 new BasicInstruction("floor.w.s $f0,$f1",                 "Floor single precision to word : Set $f0 to 32-bit integer floor of single-precision float in $f1",                  BasicInstructionFormat.R_FORMAT,                 "010001 10000 00000 sssss fffff 001111",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      float floatValue = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));                         int floor = (int) Math.floor(floatValue);                     // DPS 28-July-2010: Since MARS does not simulate the FSCR, I will take the default                     // action of setting the result to 2^31-1, if the value is outside the 32 bit range.                      if ( Float.isNaN(floatValue)                            || Float.isInfinite(floatValue)                           || floatValue < (float) Integer.MIN_VALUE                            || floatValue > (float) Integer.MAX_VALUE ) {                         
                        floor = Integer.MAX_VALUE;
                     }
                     Coprocessor1.updateRegister(operands[0], floor);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“ceil.w.s $f0,$f1”,
                 “Ceiling single precision to word : Set $f0 to 32-bit integer ceiling of single-precision float in $f1”,
                BasicInstructionFormat.R_FORMAT,
                “010001 10000 00000 sssss fffff 001110”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     float floatValue = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));   
                     int ceiling = (int) Math.ceil(floatValue);
                    // DPS 28-July-2010: Since MARS does not simulate the FSCR, I will take the default
                    // action of setting the result to 2^31-1, if the value is outside the 32 bit range.
                     if ( Float.isNaN(floatValue) 
                          || Float.isInfinite(floatValue)
                          || floatValue < (float) Integer.MIN_VALUE                            || floatValue > (float) Integer.MAX_VALUE ) {                         
                        ceiling = Integer.MAX_VALUE;
                     }
                     Coprocessor1.updateRegister(operands[0], ceiling);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“round.w.s $f0,$f1”,
                “Round single precision to word : Set $f0 to 32-bit integer round of single-precision float in $f1”,
                 BasicInstructionFormat.R_FORMAT,
                “010001 10000 00000 sssss fffff 001100”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { // MIPS32 documentation (and IEEE 754) states that round rounds to the nearest but when
                    // both are equally near it rounds to the even one!  SPIM rounds -4.5, -5.5,
                    // 4.5 and 5.5 to (-4, -5, 5, 6).  Curiously, it rounds -5.1 to -4 and -5.6 to -5. 
                    // Until MARS 3.5, I used Math.round, which rounds to nearest but when both are
                    // equal it rounds toward positive infinity.  With Release 3.5, I painstakingly
                    // carry out the MIPS and IEEE 754 standard.
                     int[] operands = statement.getOperands();
                     float floatValue = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));
                     int below=0, above=0, round = Math.round(floatValue);
                    // According to MIPS32 spec, if any of these conditions is true, set
                    // Invalid Operation in the FCSR (Floating point Control/Status Register) and
                    // set result to be 2^31-1.  MARS does not implement this register (as of release 3.4.1).
                    // It also mentions the “Invalid Operation Enable bit” in FCSR, that, if set, results
                    // in immediate exception instead of default value.  
                     if ( Float.isNaN(floatValue) 
                          || Float.isInfinite(floatValue)
                          || floatValue < (float) Integer.MIN_VALUE                            || floatValue > (float) Integer.MAX_VALUE ) {
                        round = Integer.MAX_VALUE;
                     } 
                     else {
                        Float floatObj = new Float(floatValue);
                        // If we are EXACTLY in the middle, then round to even!  To determine this,
                        // find next higher integer and next lower integer, then see if distances 
                        // are exactly equal.
                        if (floatValue < 0.0F) {                            above = floatObj.intValue(); // truncates                            below = above - 1;                         }                          else {                            below = floatObj.intValue(); // truncates                            above = below + 1;                         }                         if (floatValue - below == above - floatValue) { // exactly in the middle?                            round = (above%2 == 0) ? above : below;                         }                      }                      Coprocessor1.updateRegister(operands[0], round);                   }                }));          instructionList.add(                 new BasicInstruction("trunc.w.s $f0,$f1",                 "Truncate single precision to word : Set $f0 to 32-bit integer truncation of single-precision float in $f1",                  BasicInstructionFormat.R_FORMAT,                 "010001 10000 00000 sssss fffff 001101",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      float floatValue = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));                         int truncate = (int) floatValue;// Typecasting will round toward zero, the correct action                     // DPS 28-July-2010: Since MARS does not simulate the FSCR, I will take the default                     // action of setting the result to 2^31-1, if the value is outside the 32 bit range.                      if ( Float.isNaN(floatValue)                            || Float.isInfinite(floatValue)                           || floatValue < (float) Integer.MIN_VALUE                            || floatValue > (float) Integer.MAX_VALUE ) {                         
                        truncate = Integer.MAX_VALUE;
                     }
                     Coprocessor1.updateRegister(operands[0], truncate);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“add.d $f2,$f4,$f6”,
                 “Floating point addition double precision : Set $f2 to double-precision floating point value of $f4 plus $f6”,
                 BasicInstructionFormat.R_FORMAT,
                “010001 10001 ttttt sssss fffff 000000”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (operands[0]%2==1 || operands[1]%2==1 || operands[2]%2==1) {
                        throw new ProcessingException(statement, “all registers must be even-numbered”);
                     }
                     double add1 = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));
                     double add2 = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[2]+1),Coprocessor1.getValue(operands[2])));
                     double sum  = add1 + add2;
                     long longSum = Double.doubleToLongBits(sum);
                     Coprocessor1.updateRegister(operands[0]+1, Binary.highOrderLongToInt(longSum));
                     Coprocessor1.updateRegister(operands[0], Binary.lowOrderLongToInt(longSum));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“sub.d $f2,$f4,$f6”,
                 “Floating point subtraction double precision : Set $f2 to double-precision floating point value of $f4 minus $f6”,
                BasicInstructionFormat.R_FORMAT,
                “010001 10001 ttttt sssss fffff 000001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (operands[0]%2==1 || operands[1]%2==1 || operands[2]%2==1) {
                        throw new ProcessingException(statement, “all registers must be even-numbered”);
                     }
                     double sub1 = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));
                     double sub2 = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[2]+1),Coprocessor1.getValue(operands[2])));
                     double diff = sub1 – sub2;
                     long longDiff = Double.doubleToLongBits(diff);
                     Coprocessor1.updateRegister(operands[0]+1, Binary.highOrderLongToInt(longDiff));
                     Coprocessor1.updateRegister(operands[0], Binary.lowOrderLongToInt(longDiff));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“mul.d $f2,$f4,$f6”,
                 “Floating point multiplication double precision : Set $f2 to double-precision floating point value of $f4 times $f6”,
                BasicInstructionFormat.R_FORMAT,
                “010001 10001 ttttt sssss fffff 000010”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (operands[0]%2==1 || operands[1]%2==1 || operands[2]%2==1) {
                        throw new ProcessingException(statement, “all registers must be even-numbered”);
                     }
                     double mul1 = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));
                     double mul2 = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[2]+1),Coprocessor1.getValue(operands[2])));
                     double prod  = mul1 * mul2;
                     long longProd = Double.doubleToLongBits(prod);
                     Coprocessor1.updateRegister(operands[0]+1, Binary.highOrderLongToInt(longProd));
                     Coprocessor1.updateRegister(operands[0], Binary.lowOrderLongToInt(longProd));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“div.d $f2,$f4,$f6”,
                 “Floating point division double precision : Set $f2 to double-precision floating point value of $f4 divided by $f6”,
                BasicInstructionFormat.R_FORMAT,
                “010001 10001 ttttt sssss fffff 000011”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (operands[0]%2==1 || operands[1]%2==1 || operands[2]%2==1) {
                        throw new ProcessingException(statement, “all registers must be even-numbered”);
                     }
                     double div1 = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));
                     double div2 = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[2]+1),Coprocessor1.getValue(operands[2])));
                     double quot  = div1 / div2;
                     long longQuot = Double.doubleToLongBits(quot);
                     Coprocessor1.updateRegister(operands[0]+1, Binary.highOrderLongToInt(longQuot));
                     Coprocessor1.updateRegister(operands[0], Binary.lowOrderLongToInt(longQuot));
                  }
               }));
         instructionList.add(
                new BasicInstruction(“sqrt.d $f2,$f4”,
                 “Square root double precision : Set $f2 to double-precision floating point square root of $f4”,
                BasicInstructionFormat.R_FORMAT,
                “010001 10001 00000 sssss fffff 000100”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (operands[0]%2==1 || operands[1]%2==1 || operands[2]%2==1) {
                        throw new ProcessingException(statement, “both registers must be even-numbered”);
                     }
                     double value = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));
                     long longSqrt = 0;              
                     if (value < 0.0) {                         // This is subject to refinement later.  Release 4.0 defines floor, ceil, trunc, round                         // to act silently rather than raise Invalid Operation exception, so sqrt should do the                         // same.  An intermediate step would be to define a setting for FCSR Invalid Operation                         // flag, but the best solution is to simulate the FCSR register itself.                         // FCSR = Floating point unit Control and Status Register.  DPS 10-Aug-2010                         longSqrt = Double.doubleToLongBits(Double.NaN);                         //throw new ProcessingException(statement, "Invalid Operation: sqrt of negative number");                      }                       else {                         longSqrt = Double.doubleToLongBits(Math.sqrt(value));                      }                      Coprocessor1.updateRegister(operands[0]+1, Binary.highOrderLongToInt(longSqrt));                      Coprocessor1.updateRegister(operands[0], Binary.lowOrderLongToInt(longSqrt));                   }                }));          instructionList.add(                 new BasicInstruction("floor.w.d $f1,$f2",                  "Floor double precision to word : Set $f1 to 32-bit integer floor of double-precision float in $f2",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 00000 sssss fffff 001111",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[1]%2==1) {                         throw new ProcessingException(statement, "second register must be even-numbered");                      }                      double doubleValue = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));                     // DPS 27-July-2010: Since MARS does not simulate the FSCR, I will take the default                     // action of setting the result to 2^31-1, if the value is outside the 32 bit range.                      int floor = (int) Math.floor(doubleValue);                      if ( Double.isNaN(doubleValue)                            || Double.isInfinite(doubleValue)                           || doubleValue < (double) Integer.MIN_VALUE                            || doubleValue > (double) Integer.MAX_VALUE ) {
                        floor = Integer.MAX_VALUE;
                     } 
                     Coprocessor1.updateRegister(operands[0], floor);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“ceil.w.d $f1,$f2”,
                 “Ceiling double precision to word : Set $f1 to 32-bit integer ceiling of double-precision float in $f2”,
                BasicInstructionFormat.R_FORMAT,
                “010001 10001 00000 sssss fffff 001110”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (operands[1]%2==1) {
                        throw new ProcessingException(statement, “second register must be even-numbered”);
                     }
                     double doubleValue = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));
                    // DPS 27-July-2010: Since MARS does not simulate the FSCR, I will take the default
                    // action of setting the result to 2^31-1, if the value is outside the 32 bit range.
                     int ceiling = (int) Math.ceil(doubleValue);
                     if ( Double.isNaN(doubleValue) 
                          || Double.isInfinite(doubleValue)
                          || doubleValue < (double) Integer.MIN_VALUE                            || doubleValue > (double) Integer.MAX_VALUE ) {
                        ceiling = Integer.MAX_VALUE;
                     } 
                     Coprocessor1.updateRegister(operands[0], ceiling);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“round.w.d $f1,$f2”,
                 “Round double precision to word : Set $f1 to 32-bit integer round of double-precision float in $f2”,
                BasicInstructionFormat.R_FORMAT,
                “010001 10001 00000 sssss fffff 001100”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { // See comments in round.w.s above, concerning MIPS and IEEE 754 standard. 
                    // Until MARS 3.5, I used Math.round, which rounds to nearest but when both are
                    // equal it rounds toward positive infinity.  With Release 3.5, I painstakingly
                    // carry out the MIPS and IEEE 754 standard (round to nearest/even).
                     int[] operands = statement.getOperands();
                     if (operands[1]%2==1) {
                        throw new ProcessingException(statement, “second register must be even-numbered”);
                     }
                     double doubleValue = Double.longBitsToDouble(Binary.twoIntsToLong(
                              Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));
                     int below=0, above=0; 
                     int round = (int) Math.round(doubleValue);
                    // See comments in round.w.s above concerning FSCR…  
                     if ( Double.isNaN(doubleValue) 
                          || Double.isInfinite(doubleValue)
                          || doubleValue < (double) Integer.MIN_VALUE                            || doubleValue > (double) Integer.MAX_VALUE ) {
                        round = Integer.MAX_VALUE;
                     } 
                     else {
                        Double doubleObj = new Double(doubleValue);
                        // If we are EXACTLY in the middle, then round to even!  To determine this,
                        // find next higher integer and next lower integer, then see if distances 
                        // are exactly equal.
                        if (doubleValue < 0.0) {                            above = doubleObj.intValue(); // truncates                            below = above - 1;                         }                          else {                            below = doubleObj.intValue(); // truncates                            above = below + 1;                         }                         if (doubleValue - below == above - doubleValue) { // exactly in the middle?                            round = (above%2 == 0) ? above : below;                         }                      }                      Coprocessor1.updateRegister(operands[0], round);                   }                }));          instructionList.add(                 new BasicInstruction("trunc.w.d $f1,$f2",                  "Truncate double precision to word : Set $f1 to 32-bit integer truncation of double-precision float in $f2",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 00000 sssss fffff 001101",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[1]%2==1) {                         throw new ProcessingException(statement, "second register must be even-numbered");                      }                      double doubleValue = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));                     // DPS 27-July-2010: Since MARS does not simulate the FSCR, I will take the default                     // action of setting the result to 2^31-1, if the value is outside the 32 bit range.                      int truncate = (int) doubleValue; // Typecasting will round toward zero, the correct action.                      if ( Double.isNaN(doubleValue)                            || Double.isInfinite(doubleValue)                           || doubleValue < (double) Integer.MIN_VALUE                            || doubleValue > (double) Integer.MAX_VALUE ) {
                        truncate = Integer.MAX_VALUE;
                     } 
                     Coprocessor1.updateRegister(operands[0], truncate);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“bc1t label”,
                 “Branch if FP condition flag 0 true (BC1T, not BCLT) : If Coprocessor 1 condition flag 0 is true (one) then branch to statement at label’s address”,
                BasicInstructionFormat.I_BRANCH_FORMAT,
                “010001 01000 00001 ffffffffffffffff”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (Coprocessor1.getConditionFlag(0)==1)
                     {
                        processBranch(operands[0]);
                     }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“bc1t 1,label”,
                “Branch if specified FP condition flag true (BC1T, not BCLT) : If Coprocessor 1 condition flag specified by immediate is true (one) then branch to statement at label’s address”,
                 BasicInstructionFormat.I_BRANCH_FORMAT,
                “010001 01000 fff 01 ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (Coprocessor1.getConditionFlag(operands[0])==1)
                     {
                        processBranch(operands[1]);
                     }
                  }
               }));
         instructionList.add(
                new BasicInstruction(“bc1f label”,
                “Branch if FP condition flag 0 false (BC1F, not BCLF) : If Coprocessor 1 condition flag 0 is false (zero) then branch to statement at label’s address”,
                 BasicInstructionFormat.I_BRANCH_FORMAT,
                “010001 01000 00000 ffffffffffffffff”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (Coprocessor1.getConditionFlag(0)==0)
                     {
                        processBranch(operands[0]);
                     }
                  
                  }
               }));
         instructionList.add(
                new BasicInstruction(“bc1f 1,label”,
                “Branch if specified FP condition flag false (BC1F, not BCLF) : If Coprocessor 1 condition flag specified by immediate is false (zero) then branch to statement at label’s address”,
                 BasicInstructionFormat.I_BRANCH_FORMAT,
                “010001 01000 fff 00 ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (Coprocessor1.getConditionFlag(operands[0])==0)
                     {
                        processBranch(operands[1]);
                     }
                  
                  }
               }));
         instructionList.add(
                new BasicInstruction(“c.eq.s $f0,$f1”,
                “Compare equal single precision : If $f0 is equal to $f1, set Coprocessor 1 condition flag 0 true else set it false”,
                 BasicInstructionFormat.R_FORMAT,
                “010001 10000 sssss fffff 00000 110010”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     float op1 = Float.intBitsToFloat(Coprocessor1.getValue(operands[0]));
                     float op2 = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));
                     if (op1 == op2) 
                        Coprocessor1.setConditionFlag(0);
                     else
                        Coprocessor1.clearConditionFlag(0);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“c.eq.s 1,$f0,$f1”,
                 “Compare equal single precision : If $f0 is equal to $f1, set Coprocessor 1 condition flag specied by immediate to true else set it to false”,
               BasicInstructionFormat.R_FORMAT,
                “010001 10000 ttttt sssss fff 00 11 0010”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     float op1 = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));
                     float op2 = Float.intBitsToFloat(Coprocessor1.getValue(operands[2]));
                     if (op1 == op2) 
                        Coprocessor1.setConditionFlag(operands[0]);
                     else
                        Coprocessor1.clearConditionFlag(operands[0]);
                  }
               }));
         instructionList.add(
                new BasicInstruction(“c.le.s $f0,$f1”,
                 “Compare less or equal single precision : If $f0 is less than or equal to $f1, set Coprocessor 1 condition flag 0 true else set it false”,
                BasicInstructionFormat.R_FORMAT,
                “010001 10000 sssss fffff 00000 111110”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     float op1 = Float.intBitsToFloat(Coprocessor1.getValue(operands[0]));
                     float op2 = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));
                     if (op1 <= op2)                          Coprocessor1.setConditionFlag(0);                      else                         Coprocessor1.clearConditionFlag(0);                   }                }));          instructionList.add(                 new BasicInstruction("c.le.s 1,$f0,$f1",                  "Compare less or equal single precision : If $f0 is less than or equal to $f1, set Coprocessor 1 condition flag specified by immediate to true else set it to false",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 ttttt sssss fff 00 111110",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      float op1 = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));                      float op2 = Float.intBitsToFloat(Coprocessor1.getValue(operands[2]));                      if (op1 <= op2)                          Coprocessor1.setConditionFlag(operands[0]);                      else                         Coprocessor1.clearConditionFlag(operands[0]);                   }                }));          instructionList.add(                 new BasicInstruction("c.lt.s $f0,$f1",                  "Compare less than single precision : If $f0 is less than $f1, set Coprocessor 1 condition flag 0 true else set it false",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 sssss fffff 00000 111100",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      float op1 = Float.intBitsToFloat(Coprocessor1.getValue(operands[0]));                      float op2 = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));                      if (op1 < op2)                          Coprocessor1.setConditionFlag(0);                      else                         Coprocessor1.clearConditionFlag(0);                   }                }));          instructionList.add(                 new BasicInstruction("c.lt.s 1,$f0,$f1",                 "Compare less than single precision : If $f0 is less than $f1, set Coprocessor 1 condition flag specified by immediate to true else set it to false",                  BasicInstructionFormat.R_FORMAT,                 "010001 10000 ttttt sssss fff 00 111100",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      float op1 = Float.intBitsToFloat(Coprocessor1.getValue(operands[1]));                      float op2 = Float.intBitsToFloat(Coprocessor1.getValue(operands[2]));                      if (op1 < op2)                          Coprocessor1.setConditionFlag(operands[0]);                      else                         Coprocessor1.clearConditionFlag(operands[0]);                   }                }));          instructionList.add(                 new BasicInstruction("c.eq.d $f2,$f4",                  "Compare equal double precision : If $f2 is equal to $f4 (double-precision), set Coprocessor 1 condition flag 0 true else set it false",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 sssss fffff 00000 110010",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      double op1 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[0]+1),Coprocessor1.getValue(operands[0])));                      double op2 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));                      if (op1 == op2)                          Coprocessor1.setConditionFlag(0);                      else                         Coprocessor1.clearConditionFlag(0);                   }                }));          instructionList.add(                 new BasicInstruction("c.eq.d 1,$f2,$f4",                  "Compare equal double precision : If $f2 is equal to $f4 (double-precision), set Coprocessor 1 condition flag specified by immediate to true else set it to false",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 ttttt sssss fff 00 110010",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[1]%2==1 || operands[2]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      double op1 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));                      double op2 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[2]+1),Coprocessor1.getValue(operands[2])));                      if (op1 == op2)                          Coprocessor1.setConditionFlag(operands[0]);                      else                         Coprocessor1.clearConditionFlag(operands[0]);                   }                }));          instructionList.add(                 new BasicInstruction("c.le.d $f2,$f4",                  "Compare less or equal double precision : If $f2 is less than or equal to $f4 (double-precision), set Coprocessor 1 condition flag 0 true else set it false",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 sssss fffff 00000 111110",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      double op1 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[0]+1),Coprocessor1.getValue(operands[0])));                      double op2 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));                      if (op1 <= op2)                          Coprocessor1.setConditionFlag(0);                      else                         Coprocessor1.clearConditionFlag(0);                   }                }));          instructionList.add(                 new BasicInstruction("c.le.d 1,$f2,$f4",                  "Compare less or equal double precision : If $f2 is less than or equal to $f4 (double-precision), set Coprocessor 1 condition flag specfied by immediate true else set it false",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 ttttt sssss fff 00 111110",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      if (operands[1]%2==1 || operands[2]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      double op1 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));                      double op2 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[2]+1),Coprocessor1.getValue(operands[2])));                      if (op1 <= op2)                          Coprocessor1.setConditionFlag(operands[0]);                      else                         Coprocessor1.clearConditionFlag(operands[0]);                   }                }));          instructionList.add(                 new BasicInstruction("c.lt.d $f2,$f4",                  "Compare less than double precision : If $f2 is less than $f4 (double-precision), set Coprocessor 1 condition flag 0 true else set it false",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 sssss fffff 00000 111100",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      double op1 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[0]+1),Coprocessor1.getValue(operands[0])));                      double op2 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));                      if (op1 < op2)                          Coprocessor1.setConditionFlag(0);                      else                         Coprocessor1.clearConditionFlag(0);                   }                }));          instructionList.add(                 new BasicInstruction("c.lt.d 1,$f2,$f4",                  "Compare less than double precision : If $f2 is less than $f4 (double-precision), set Coprocessor 1 condition flag specified by immediate to true else set it to false",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 ttttt sssss fff 00 111100",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[1]%2==1 || operands[2]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      double op1 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));                      double op2 = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[2]+1),Coprocessor1.getValue(operands[2])));                      if (op1 < op2)                          Coprocessor1.setConditionFlag(operands[0]);                      else                         Coprocessor1.clearConditionFlag(operands[0]);                   }                }));          instructionList.add(                 new BasicInstruction("abs.s $f0,$f1",                  "Floating point absolute value single precision : Set $f0 to absolute value of $f1, single precision",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 00000 sssss fffff 000101",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                     // I need only clear the high order bit!                      Coprocessor1.updateRegister(operands[0],                                           Coprocessor1.getValue(operands[1]) & Integer.MAX_VALUE);                   }                }));          instructionList.add(                 new BasicInstruction("abs.d $f2,$f4",                  "Floating point absolute value double precision : Set $f2 to absolute value of $f4, double precision",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 00000 sssss fffff 000101",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                     // I need only clear the high order bit of high word register!                      Coprocessor1.updateRegister(operands[0]+1,                                           Coprocessor1.getValue(operands[1]+1) & Integer.MAX_VALUE);                      Coprocessor1.updateRegister(operands[0],                                           Coprocessor1.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("cvt.d.s $f2,$f1",                  "Convert from single precision to double precision : Set $f2 to double precision equivalent of single precision value in $f1",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 00000 sssss fffff 100001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1) {                         throw new ProcessingException(statement, "first register must be even-numbered");                      }                     // convert single precision in $f1 to double stored in $f2                      long result = Double.doubleToLongBits(                           (double)Float.intBitsToFloat(Coprocessor1.getValue(operands[1])));                      Coprocessor1.updateRegister(operands[0]+1, Binary.highOrderLongToInt(result));                      Coprocessor1.updateRegister(operands[0], Binary.lowOrderLongToInt(result));                   }                }));          instructionList.add(                 new BasicInstruction("cvt.d.w $f2,$f1",                  "Convert from word to double precision : Set $f2 to double precision equivalent of 32-bit integer value in $f1",                 BasicInstructionFormat.R_FORMAT,                 "010001 10100 00000 sssss fffff 100001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1) {                         throw new ProcessingException(statement, "first register must be even-numbered");                      }                     // convert integer to double (interpret $f1 value as int?)                      long result = Double.doubleToLongBits(                           (double)Coprocessor1.getValue(operands[1]));                      Coprocessor1.updateRegister(operands[0]+1, Binary.highOrderLongToInt(result));                      Coprocessor1.updateRegister(operands[0], Binary.lowOrderLongToInt(result));                   }                }));          instructionList.add(                 new BasicInstruction("cvt.s.d $f1,$f2",                 "Convert from double precision to single precision : Set $f1 to single precision equivalent of double precision value in $f2",                  BasicInstructionFormat.R_FORMAT,                 "010001 10001 00000 sssss fffff 100000",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                     // convert double precision in $f2 to single stored in $f1                      if (operands[1]%2==1) {                         throw new ProcessingException(statement, "second register must be even-numbered");                      }                      double val = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));                      Coprocessor1.updateRegister(operands[0], Float.floatToIntBits((float)val));                   }                }));          instructionList.add(                 new BasicInstruction("cvt.s.w $f0,$f1",                  "Convert from word to single precision : Set $f0 to single precision equivalent of 32-bit integer value in $f2",                 BasicInstructionFormat.R_FORMAT,                 "010001 10100 00000 sssss fffff 100000",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                     // convert integer to single (interpret $f1 value as int?)                      Coprocessor1.updateRegister(operands[0],                           Float.floatToIntBits((float)Coprocessor1.getValue(operands[1])));                   }                }));          instructionList.add(                 new BasicInstruction("cvt.w.d $f1,$f2",                  "Convert from double precision to word : Set $f1 to 32-bit integer equivalent of double precision value in $f2",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 00000 sssss fffff 100100",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                     // convert double precision in $f2 to integer stored in $f1                      if (operands[1]%2==1) {                         throw new ProcessingException(statement, "second register must be even-numbered");                      }                      double val = Double.longBitsToDouble(Binary.twoIntsToLong(                               Coprocessor1.getValue(operands[1]+1),Coprocessor1.getValue(operands[1])));                      Coprocessor1.updateRegister(operands[0], (int) val);                   }                }));          instructionList.add(                 new BasicInstruction("cvt.w.s $f0,$f1",                  "Convert from single precision to word : Set $f0 to 32-bit integer equivalent of single precision value in $f1",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 00000 sssss fffff 100100",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                     // convert single precision in $f1 to integer stored in $f0                      Coprocessor1.updateRegister(operands[0],                               (int)Float.intBitsToFloat(Coprocessor1.getValue(operands[1])));                   }                }));          instructionList.add(                 new BasicInstruction("mov.d $f2,$f4",                  "Move floating point double precision : Set double precision $f2 to double precision value in $f4",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 00000 sssss fffff 000110",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                      Coprocessor1.updateRegister(operands[0]+1, Coprocessor1.getValue(operands[1]+1));                   }                }));          instructionList.add(                 new BasicInstruction("movf.d $f2,$f4",                  "Move floating point double precision : If condition flag 0 false, set double precision $f2 to double precision value in $f4",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 000 00 sssss fffff 010001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      if (Coprocessor1.getConditionFlag(0)==0) {                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                         Coprocessor1.updateRegister(operands[0]+1, Coprocessor1.getValue(operands[1]+1));                      }                   }                }));          instructionList.add(                 new BasicInstruction("movf.d $f2,$f4,1",                  "Move floating point double precision : If condition flag specified by immediate is false, set double precision $f2 to double precision value in $f4",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 ttt 00 sssss fffff 010001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      if (Coprocessor1.getConditionFlag(operands[2])==0) {                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                         Coprocessor1.updateRegister(operands[0]+1, Coprocessor1.getValue(operands[1]+1));                      }                   }                }));          instructionList.add(                 new BasicInstruction("movt.d $f2,$f4",                  "Move floating point double precision : If condition flag 0 true, set double precision $f2 to double precision value in $f4",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 000 01 sssss fffff 010001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      if (Coprocessor1.getConditionFlag(0)==1) {                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                         Coprocessor1.updateRegister(operands[0]+1, Coprocessor1.getValue(operands[1]+1));                      }                   }                }));          instructionList.add(                 new BasicInstruction("movt.d $f2,$f4,1",                  "Move floating point double precision : If condition flag specified by immediate is true, set double precision $f2 to double precision value in $f4e",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 ttt 01 sssss fffff 010001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      if (Coprocessor1.getConditionFlag(operands[2])==1) {                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                         Coprocessor1.updateRegister(operands[0]+1, Coprocessor1.getValue(operands[1]+1));                      }                   }                }));          instructionList.add(                 new BasicInstruction("movn.d $f2,$f4,$t3",                  "Move floating point double precision : If $t3 is not zero, set double precision $f2 to double precision value in $f4",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 ttttt sssss fffff 010011",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      if (RegisterFile.getValue(operands[2])!=0) {                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                         Coprocessor1.updateRegister(operands[0]+1, Coprocessor1.getValue(operands[1]+1));                      }                   }                }));          instructionList.add(                 new BasicInstruction("movz.d $f2,$f4,$t3",                  "Move floating point double precision : If $t3 is zero, set double precision $f2 to double precision value in $f4",                 BasicInstructionFormat.R_FORMAT,                 "010001 10001 ttttt sssss fffff 010010",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                      if (RegisterFile.getValue(operands[2])==0) {                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                         Coprocessor1.updateRegister(operands[0]+1, Coprocessor1.getValue(operands[1]+1));                      }                   }                }));          instructionList.add(                 new BasicInstruction("mov.s $f0,$f1",                  "Move floating point single precision : Set single precision $f0 to single precision value in $f1",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 00000 sssss fffff 000110",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("movf.s $f0,$f1",                  "Move floating point single precision : If condition flag 0 is false, set single precision $f0 to single precision value in $f1",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 000 00 sssss fffff 010001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (Coprocessor1.getConditionFlag(0)==0)                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("movf.s $f0,$f1,1",                  "Move floating point single precision : If condition flag specified by immediate is false, set single precision $f0 to single precision value in $f1e",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 ttt 00 sssss fffff 010001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (Coprocessor1.getConditionFlag(operands[2])==0)                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("movt.s $f0,$f1",                  "Move floating point single precision : If condition flag 0 is true, set single precision $f0 to single precision value in $f1e",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 000 01 sssss fffff 010001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (Coprocessor1.getConditionFlag(0)==1)                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("movt.s $f0,$f1,1",                  "Move floating point single precision : If condition flag specified by immediate is true, set single precision $f0 to single precision value in $f1e",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 ttt 01 sssss fffff 010001",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (Coprocessor1.getConditionFlag(operands[2])==1)                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("movn.s $f0,$f1,$t3",                  "Move floating point single precision : If $t3 is not zero, set single precision $f0 to single precision value in $f1",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 ttttt sssss fffff 010011",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (RegisterFile.getValue(operands[2])!=0)                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("movz.s $f0,$f1,$t3",                  "Move floating point single precision : If $t3 is zero, set single precision $f0 to single precision value in $f1",                 BasicInstructionFormat.R_FORMAT,                 "010001 10000 ttttt sssss fffff 010010",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (RegisterFile.getValue(operands[2])==0)                         Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("mfc1 $t1,$f1",                 "Move from Coprocessor 1 (FPU) : Set $t1 to value in Coprocessor 1 register $f1",                  BasicInstructionFormat.R_FORMAT,                 "010001 00000 fffff sssss 00000 000000",                  new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      RegisterFile.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("mtc1 $t1,$f1",                 "Move to Coprocessor 1 (FPU) : Set Coprocessor 1 register $f1 to value in $t1",                  BasicInstructionFormat.R_FORMAT,                 "010001 00100 fffff sssss 00000 000000",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      Coprocessor1.updateRegister(operands[1], RegisterFile.getValue(operands[0]));                   }                }));          instructionList.add(                 new BasicInstruction("neg.d $f2,$f4",                 "Floating point negate double precision : Set double precision $f2 to negation of double precision value in $f4",                  BasicInstructionFormat.R_FORMAT,                 "010001 10001 00000 sssss fffff 000111",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1 || operands[1]%2==1) {                         throw new ProcessingException(statement, "both registers must be even-numbered");                      }                     // flip the sign bit of the second register (high order word) of the pair                      int value = Coprocessor1.getValue(operands[1]+1);                      Coprocessor1.updateRegister(operands[0]+1,                            ((value < 0) ? (value & Integer.MAX_VALUE) : (value | Integer.MIN_VALUE)));                      Coprocessor1.updateRegister(operands[0], Coprocessor1.getValue(operands[1]));                   }                }));          instructionList.add(                 new BasicInstruction("neg.s $f0,$f1",                 "Floating point negate single precision : Set single precision $f0 to negation of single precision value in $f1",                  BasicInstructionFormat.R_FORMAT,                 "010001 10000 00000 sssss fffff 000111",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      int value = Coprocessor1.getValue(operands[1]);                     // flip the sign bit                      Coprocessor1.updateRegister(operands[0],                            ((value < 0) ? (value & Integer.MAX_VALUE) : (value | Integer.MIN_VALUE)));                   }                }));          instructionList.add(                 new BasicInstruction("lwc1 $f1,-100($t2)",                 "Load word into Coprocessor 1 (FPU) : Set $f1 to 32-bit value from effective memory word address",                  BasicInstructionFormat.I_FORMAT,                 "110001 ttttt fffff ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      try                      {                         Coprocessor1.updateRegister(operands[0],                             Globals.memory.getWord(                             RegisterFile.getValue(operands[2]) + operands[1]));                      }                           catch (AddressErrorException e)                         {                            throw new ProcessingException(statement, e);                         }                   }                }));                instructionList.add(// no printed reference, got opcode from SPIM                 new BasicInstruction("ldc1 $f2,-100($t2)",                  "Load double word Coprocessor 1 (FPU)) : Set $f2 to 64-bit value from effective memory doubleword address",                 BasicInstructionFormat.I_FORMAT,                 "110101 ttttt fffff ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1) {                         throw new ProcessingException(statement, "first register must be even-numbered");                      }                     // IF statement added by DPS 13-July-2011.                      if (!Globals.memory.doublewordAligned(RegisterFile.getValue(operands[2]) + operands[1])) {                         throw new ProcessingException(statement,                            new AddressErrorException("address not aligned on doubleword boundary ",                            Exceptions.ADDRESS_EXCEPTION_LOAD, RegisterFile.getValue(operands[2]) + operands[1]));                      }                                                           try                      {                         Coprocessor1.updateRegister(operands[0],                             Globals.memory.getWord(                             RegisterFile.getValue(operands[2]) + operands[1]));                         Coprocessor1.updateRegister(operands[0]+1,                             Globals.memory.getWord(                             RegisterFile.getValue(operands[2]) + operands[1] + 4));                      }                           catch (AddressErrorException e)                         {                            throw new ProcessingException(statement, e);                         }                   }                }));            instructionList.add(                 new BasicInstruction("swc1 $f1,-100($t2)",                  "Store word from Coprocesor 1 (FPU) : Store 32 bit value in $f1 to effective memory word address",                 BasicInstructionFormat.I_FORMAT,                 "111001 ttttt fffff ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      try                      {                         Globals.memory.setWord(                             RegisterFile.getValue(operands[2]) + operands[1],                             Coprocessor1.getValue(operands[0]));                      }                           catch (AddressErrorException e)                         {                            throw new ProcessingException(statement, e);                         }                   }                }));          instructionList.add( // no printed reference, got opcode from SPIM                 new BasicInstruction("sdc1 $f2,-100($t2)",                  "Store double word from Coprocessor 1 (FPU)) : Store 64 bit value in $f2 to effective memory doubleword address",                 BasicInstructionFormat.I_FORMAT,                 "111101 ttttt fffff ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (operands[0]%2==1) {                         throw new ProcessingException(statement, "first register must be even-numbered");                      }                     // IF statement added by DPS 13-July-2011.                      if (!Globals.memory.doublewordAligned(RegisterFile.getValue(operands[2]) + operands[1])) {                         throw new ProcessingException(statement,                            new AddressErrorException("address not aligned on doubleword boundary ",                            Exceptions.ADDRESS_EXCEPTION_STORE, RegisterFile.getValue(operands[2]) + operands[1]));                      }                      try                      {                         Globals.memory.setWord(                             RegisterFile.getValue(operands[2]) + operands[1],                             Coprocessor1.getValue(operands[0]));                         Globals.memory.setWord(                             RegisterFile.getValue(operands[2]) + operands[1] + 4,                             Coprocessor1.getValue(operands[0]+1));                      }                           catch (AddressErrorException e)                         {                            throw new ProcessingException(statement, e);                         }                   }                }));         ////////////////////////////  THE TRAP INSTRUCTIONS & ERET  ////////////////////////////          instructionList.add(                 new BasicInstruction("teq $t1,$t2",                 "Trap if equal : Trap if $t1 is equal to $t2",                  BasicInstructionFormat.R_FORMAT,                 "000000 fffff sssss 00000 00000 110100",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (RegisterFile.getValue(operands[0]) == RegisterFile.getValue(operands[1]))                      {                         throw new ProcessingException(statement,                             "trap",Exceptions.TRAP_EXCEPTION);                      }                                          }                }));          instructionList.add(                 new BasicInstruction("teqi $t1,-100",                  "Trap if equal to immediate : Trap if $t1 is equal to sign-extended 16 bit immediate",                 BasicInstructionFormat.I_FORMAT,                 "000001 fffff 01100 ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      if (RegisterFile.getValue(operands[0]) == (operands[1] << 16 >> 16)) 
                     {
                        throw new ProcessingException(statement,
                            “trap”,Exceptions.TRAP_EXCEPTION);
                     }                
                  }
               }));
         instructionList.add(
                new BasicInstruction(“tne $t1,$t2”,
                “Trap if not equal : Trap if $t1 is not equal to $t2”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 fffff sssss 00000 00000 110110”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[0]) != RegisterFile.getValue(operands[1]))
                     {
                        throw new ProcessingException(statement,
                            “trap”,Exceptions.TRAP_EXCEPTION);
                     }                      
                  }
               }));        
         instructionList.add(
                new BasicInstruction(“tnei $t1,-100”,
                 “Trap if not equal to immediate : Trap if $t1 is not equal to sign-extended 16 bit immediate”,
                BasicInstructionFormat.I_FORMAT,
                “000001 fffff 01110 ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[0]) != (operands[1] << 16 >> 16)) 
                     {
                        throw new ProcessingException(statement,
                            “trap”,Exceptions.TRAP_EXCEPTION);
                     }                     
                  }
               }));
         instructionList.add(
                new BasicInstruction(“tge $t1,$t2”,
                “Trap if greater or equal : Trap if $t1 is greater than or equal to $t2”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 fffff sssss 00000 00000 110000”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[0]) >= RegisterFile.getValue(operands[1]))
                     {
                        throw new ProcessingException(statement,
                            “trap”,Exceptions.TRAP_EXCEPTION);
                     }                       
                  }
               }));
         instructionList.add(
                new BasicInstruction(“tgeu $t1,$t2”,
                “Trap if greater or equal unsigned : Trap if $t1 is greater than or equal to $t2 using unsigned comparision”,
                 BasicInstructionFormat.R_FORMAT,
                “000000 fffff sssss 00000 00000 110001”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  { 
                     int[] operands = statement.getOperands();
                     int first = RegisterFile.getValue(operands[0]);
                     int second = RegisterFile.getValue(operands[1]);
                    // if signs same, do straight compare; if signs differ & first negative then first greater else second
                     if ((first >= 0 && second >= 0 || first < 0 && second < 0) ? (first >= second) : (first < 0) )                       {                         throw new ProcessingException(statement,                             "trap",Exceptions.TRAP_EXCEPTION);                      }                                         }                }));          instructionList.add(                 new BasicInstruction("tgei $t1,-100",                  "Trap if greater than or equal to immediate : Trap if $t1 greater than or equal to sign-extended 16 bit immediate",                 BasicInstructionFormat.I_FORMAT,                 "000001 fffff 01000 ssssssssssssssss",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                      int[] operands = statement.getOperands();                      if (RegisterFile.getValue(operands[0]) >= (operands[1] << 16 >> 16)) 
                     {
                        throw new ProcessingException(statement,
                            “trap”,Exceptions.TRAP_EXCEPTION);
                     }                    
                  }
               }));
         instructionList.add(
                new BasicInstruction(“tgeiu $t1,-100”,
                “Trap if greater or equal to immediate unsigned : Trap if $t1 greater than or equal to sign-extended 16 bit immediate, unsigned comparison”,
                 BasicInstructionFormat.I_FORMAT,
                “000001 fffff 01001 ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     int first = RegisterFile.getValue(operands[0]);
                     // 16 bit immediate value in operands[1] is sign-extended
                     int second = operands[1] << 16 >> 16;
                    // if signs same, do straight compare; if signs differ & first negative then first greater else second
                     if ((first >= 0 && second >= 0 || first < 0 && second < 0) ? (first >= second) : (first < 0) )                       {                         throw new ProcessingException(statement,                             "trap",Exceptions.TRAP_EXCEPTION);                      }                                   }                }));          instructionList.add(                 new BasicInstruction("tlt $t1,$t2",                 "Trap if less than: Trap if $t1 less than $t2",                  BasicInstructionFormat.R_FORMAT,                 "000000 fffff sssss 00000 00000 110010",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      if (RegisterFile.getValue(operands[0]) < RegisterFile.getValue(operands[1]))                      {                         throw new ProcessingException(statement,                             "trap",Exceptions.TRAP_EXCEPTION);                      }                                          }                }));          instructionList.add(                 new BasicInstruction("tltu $t1,$t2",                 "Trap if less than unsigned : Trap if $t1 less than $t2, unsigned comparison",                  BasicInstructionFormat.R_FORMAT,                 "000000 fffff sssss 00000 00000 110011",                 new SimulationCode()                {                    public void simulate(ProgramStatement statement) throws ProcessingException                   {                       int[] operands = statement.getOperands();                      int first = RegisterFile.getValue(operands[0]);                      int second = RegisterFile.getValue(operands[1]);                     // if signs same, do straight compare; if signs differ & first positive then first is less else second                      if ((first >= 0 && second >= 0 || first < 0 && second < 0) ? (first < second) : (first >= 0) ) 
                     {
                        throw new ProcessingException(statement,
                            “trap”,Exceptions.TRAP_EXCEPTION);
                     }                    
                  }
               }));
         instructionList.add(
                new BasicInstruction(“tlti $t1,-100”,
                 “Trap if less than immediate : Trap if $t1 less than sign-extended 16-bit immediate”,
                BasicInstructionFormat.I_FORMAT,
                “000001 fffff 01010 ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     if (RegisterFile.getValue(operands[0]) < (operands[1] << 16 >> 16)) 
                     {
                        throw new ProcessingException(statement,
                            “trap”,Exceptions.TRAP_EXCEPTION);
                     }                       
                  }
               }));
         instructionList.add(
                new BasicInstruction(“tltiu $t1,-100”,
                “Trap if less than immediate unsigned : Trap if $t1 less than sign-extended 16-bit immediate, unsigned comparison”,
                 BasicInstructionFormat.I_FORMAT,
                “000001 fffff 01011 ssssssssssssssss”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     int[] operands = statement.getOperands();
                     int first = RegisterFile.getValue(operands[0]);
                     // 16 bit immediate value in operands[1] is sign-extended
                     int second = operands[1] << 16 >> 16;
                    // if signs same, do straight compare; if signs differ & first positive then first is less else second
                     if ((first >= 0 && second >= 0 || first < 0 && second < 0) ? (first < second) : (first >= 0) ) 
                     {
                        throw new ProcessingException(statement,
                            “trap”,Exceptions.TRAP_EXCEPTION);
                     }                   
                  }
               }));
         instructionList.add(
                new BasicInstruction(“eret”, 
                 “Exception return : Set Program Counter to Coprocessor 0 EPC register value, set Coprocessor Status register bit 1 (exception level) to zero”,
                 BasicInstructionFormat.R_FORMAT,
                “010000 1 0000000000000000000 011000”,
                new SimulationCode()
               {
                   public void simulate(ProgramStatement statement) throws ProcessingException
                  {
                     // set EXL bit (bit 1) in Status register to 0 and set PC to EPC
                     Coprocessor0.updateRegister(Coprocessor0.STATUS, 
                                                 Binary.clearBit(Coprocessor0.getValue(Coprocessor0.STATUS), Coprocessor0.EXCEPTION_LEVEL));
                     RegisterFile.setProgramCounter(Coprocessor0.getValue(Coprocessor0.EPC));
                  }
               }));
                
        ////////////// READ PSEUDO-INSTRUCTION SPECS FROM DATA FILE AND ADD //////////////////////
         addPseudoInstructions();
        
        ////////////// GET AND CREATE LIST OF SYSCALL FUNCTION OBJECTS ////////////////////
         syscallLoader = new SyscallLoader();
         syscallLoader.loadSyscalls();
        
        // Initialization step.  Create token list for each instruction example.  This is
        // used by parser to determine user program correct syntax.
         for (int i = 0; i < instructionList.size(); i++)          {             Instruction inst = (Instruction) instructionList.get(i);             inst.createExampleTokenList();          }              }               /*  METHOD TO ADD PSEUDO-INSTRUCTIONS     */            private void addPseudoInstructions()       {          InputStream is = null;          BufferedReader in = null;          try          {             // leading "/" prevents package name being prepended to filepath.             is = this.getClass().getResourceAsStream("/PseudoOps.txt");             in = new BufferedReader(new InputStreamReader(is));          }               catch (NullPointerException e)             {                System.out.println(                     "Error: MIPS pseudo-instruction file PseudoOps.txt not found.");                System.exit(0);             }          try          {             String line, pseudoOp, template, firstTemplate, token;             String description;             StringTokenizer tokenizer;             while ((line = in.readLine()) != null) {                 // skip over: comment lines, empty lines, lines starting with blank.                if (!line.startsWith("#") && !line.startsWith(" ")                         && line.length() > 0)  {  
                  description = “”;
                  tokenizer = new StringTokenizer(line, “\t”);
                  pseudoOp = tokenizer.nextToken();
                  template = “”;
                  firstTemplate = null;
                  while (tokenizer.hasMoreTokens()) {
                     token = tokenizer.nextToken();
                     if (token.startsWith(“#”)) {  
                        // Optional description must be last token in the line.
                        description = token.substring(1);
                        break;
                     }
                     if (token.startsWith(“COMPACT”)) {
                        // has second template for Compact (16-bit) memory config — added DPS 3 Aug 2009
                        firstTemplate = template;
                        template = “”;
                        continue;
                     } 
                     template = template + token;
                     if (tokenizer.hasMoreTokens()) {
                        template = template + “\n”;
                     }
                  }
                  ExtendedInstruction inst = (firstTemplate == null)
                         ? new ExtendedInstruction(pseudoOp, template, description)
                         : new ExtendedInstruction(pseudoOp, firstTemplate, template, description);
                  instructionList.add(inst);
                //if (firstTemplate != null) System.out.println(“\npseudoOp: “+pseudoOp+”\ndefault template:\n”+firstTemplate+”\ncompact template:\n”+template);
               }
            }
            in.close();
         } 
             catch (IOException ioe)
            {
               System.out.println(
                    “Internal Error: MIPS pseudo-instructions could not be loaded.”);
               System.exit(0);
            } 
             catch (Exception ioe)
            {
               System.out.println(
                    “Error: Invalid MIPS pseudo-instruction specification.”);
               System.exit(0);
            }
      
      }
    
    /**
     *  Given an operator mnemonic, will return the corresponding Instruction object(s)
     *  from the instruction set.  Uses straight linear search technique.
     *  @param name operator mnemonic (e.g. addi, sw,…)
     *  @return list of corresponding Instruction object(s), or null if not found.
     */
       public ArrayList matchOperator(String name)
      {
         ArrayList matchingInstructions = null;
        // Linear search for now….
         for (int i = 0; i < instructionList.size(); i++)          {             if (((Instruction) instructionList.get(i)).getName().equalsIgnoreCase(name))             {                if (matchingInstructions == null)                    matchingInstructions = new ArrayList();                matchingInstructions.add(instructionList.get(i));             }          }          return matchingInstructions;       }             /**      *  Given a string, will return the Instruction object(s) from the instruction      *  set whose operator mnemonic prefix matches it.  Case-insensitive.  For example      *  "s" will match "sw", "sh", "sb", etc.  Uses straight linear search technique.      *  @param name a string      *  @return list of matching Instruction object(s), or null if none match.      */        public ArrayList prefixMatchOperator(String name)       {          ArrayList matchingInstructions = null;         // Linear search for now....          if (name != null) {             for (int i = 0; i < instructionList.size(); i++)             {                if (((Instruction) instructionList.get(i)).getName().toLowerCase().startsWith(name.toLowerCase()))                {                   if (matchingInstructions == null)                       matchingInstructions = new ArrayList();                   matchingInstructions.add(instructionList.get(i));                }             }          }          return matchingInstructions;       }          /*      * Method to find and invoke a syscall given its service number.  Each syscall      * function is represented by an object in an array list.  Each object is of      * a class that implements Syscall or extends AbstractSyscall.      */              private void findAndSimulateSyscall(int number, ProgramStatement statement)                                                          throws ProcessingException {          Syscall service = syscallLoader.findSyscall(number);          if (service != null) {             service.simulate(statement);             return;          }          throw new ProcessingException(statement,               "invalid or unimplemented syscall service: " +               number + " ", Exceptions.SYSCALL_EXCEPTION);       }          /*      * Method to process a successful branch condition.  DO NOT USE WITH JUMP      * INSTRUCTIONS!  The branch operand is a relative displacement in words      * whereas the jump operand is an absolute address in bytes.      *      * The parameter is displacement operand from instruction.      *      * Handles delayed branching if that setting is enabled.      */      // 4 January 2008 DPS:  The subtraction of 4 bytes (instruction length) after      // the shift has been removed.  It is left in as commented-out code below.      // This has the effect of always branching as if delayed branching is enabled,       // even if it isn't.  This mod must work in conjunction with      // ProgramStatement.java, buildBasicStatementFromBasicInstruction() method near      // the bottom (currently line 194, heavily commented).              private void processBranch(int displacement) {          if (Globals.getSettings().getDelayedBranchingEnabled()) {             // Register the branch target address (absolute byte address).             DelayedBranch.register(RegisterFile.getProgramCounter() + (displacement << 2));          }           else {             // Decrement needed because PC has already been incremented             RegisterFile.setProgramCounter(                 RegisterFile.getProgramCounter()                   + (displacement << 2)); // - Instruction.INSTRUCTION_LENGTH);           }          }         /*      * Method to process a jump.  DO NOT USE WITH BRANCH INSTRUCTIONS!        * The branch operand is a relative displacement in words      * whereas the jump operand is an absolute address in bytes.      *      * The parameter is jump target absolute byte address.      *      * Handles delayed branching if that setting is enabled.      */              private void processJump(int targetAddress) {          if (Globals.getSettings().getDelayedBranchingEnabled()) {             DelayedBranch.register(targetAddress);          }           else {             RegisterFile.setProgramCounter(targetAddress);          }          }         /*      * Method to process storing of a return address in the given      * register.  This is used only by the "and link"      * instructions: jal, jalr, bltzal, bgezal.  If delayed branching      * setting is off, the return address is the address of the      * next instruction (e.g. the current PC value).  If on, the      * return address is the instruction following that, to skip over      * the delay slot.      *      * The parameter is register number to receive the return address.      */              private void processReturnAddress(int register) {          RegisterFile.updateRegister(register, RegisterFile.getProgramCounter() +                  ((Globals.getSettings().getDelayedBranchingEnabled()) ?                    Instruction.INSTRUCTION_LENGTH : 0) );            }         } InstructionSet$111 package mars.mips.instructions; synchronized class InstructionSet$111 implements SimulationCode { void InstructionSet$111(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$154 package mars.mips.instructions; synchronized class InstructionSet$154 implements SimulationCode { void InstructionSet$154(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$88 package mars.mips.instructions; synchronized class InstructionSet$88 implements SimulationCode { void InstructionSet$88(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$30 package mars.mips.instructions; synchronized class InstructionSet$30 implements SimulationCode { void InstructionSet$30(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$75 package mars.mips.instructions; synchronized class InstructionSet$75 implements SimulationCode { void InstructionSet$75(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$113 package mars.mips.instructions; synchronized class InstructionSet$113 implements SimulationCode { void InstructionSet$113(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$32 package mars.mips.instructions; synchronized class InstructionSet$32 implements SimulationCode { void InstructionSet$32(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } InstructionSet$77 package mars.mips.instructions; synchronized class InstructionSet$77 implements SimulationCode { void InstructionSet$77(InstructionSet); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } SyscallInputDialogDouble package mars.mips.instructions.syscalls; public synchronized class SyscallInputDialogDouble extends AbstractSyscall { public void SyscallInputDialogDouble(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } SyscallClose package mars.mips.instructions.syscalls; public synchronized class SyscallClose extends AbstractSyscall { public void SyscallClose(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallGameIsShoot.java mars/mips/instructions/syscalls/SyscallGameIsShoot.javapackage mars.mips.instructions.syscalls; import mars.ProcessingException; import mars.ProgramStatement; import mars.ext.game.GameObject; import mars.ext.game.GameObjectHook; import mars.ext.game.GameScreen; import mars.mips.hardware.RegisterFile; import mars.util.SystemIO; public class SyscallGameIsShoot extends AbstractSyscall {     public SyscallGameIsShoot()     {         super(120, "Get isShoot");     }     @Override     public void simulate(ProgramStatement statement) throws ProcessingException     {         int id = RegisterFile.getValue(4);         GameScreen game = GameScreen.getInstance();         if (game == null)         {             SystemIO.printString("GameScreen has not been created!");             throw new ProcessingException();         }         GameObject obj = game.getGameObject(id);         if (obj == null)         {             SystemIO.printString("GameObject: id=" + id + " does not exist!");             throw new ProcessingException();         }         if (obj instanceof GameObjectHook)         {             GameObjectHook hook = (GameObjectHook) obj;             RegisterFile.updateRegister(2, hook.isShoot()? 1: 0);         }     } } SyscallGameCreateObject package mars.mips.instructions.syscalls; public synchronized class SyscallGameCreateObject extends AbstractSyscall { public void SyscallGameCreateObject(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallGameUpdateObjLocation.java mars/mips/instructions/syscalls/SyscallGameUpdateObjLocation.javapackage mars.mips.instructions.syscalls; import mars.ProcessingException; import mars.ProgramStatement; import mars.ext.game.ActiveElementInterface; import mars.ext.game.GameObject; import mars.ext.game.GameScreen; import mars.mips.hardware.RegisterFile; import mars.util.SystemIO; public class SyscallGameUpdateObjLocation extends AbstractSyscall {     public SyscallGameUpdateObjLocation()     {         super(110, "Update Object Location");     }     @Override     public void simulate(ProgramStatement statement) throws ProcessingException     {         int id = RegisterFile.getValue(4);         GameScreen game = GameScreen.getInstance();         if (game == null)         {             SystemIO.printString("GameScreen has not been created!");             throw new ProcessingException();         }         GameObject obj = game.getGameObject(id);         if (obj == null)         {             SystemIO.printString("GameObject: id=" + id + " does not exist!");             throw new ProcessingException();         }         ActiveElementInterface ele = (ActiveElementInterface) obj;         ele.updateLocation();     } } mars/mips/instructions/syscalls/SyscallGameUpdateObjDirection.java mars/mips/instructions/syscalls/SyscallGameUpdateObjDirection.javapackage mars.mips.instructions.syscalls; import mars.ProcessingException; import mars.ProgramStatement; import mars.ext.game.ActiveElementInterface; import mars.ext.game.GameObject; import mars.ext.game.GameScreen; import mars.mips.hardware.RegisterFile; import mars.util.SystemIO; public class SyscallGameUpdateObjDirection extends AbstractSyscall {     public SyscallGameUpdateObjDirection()     {         super(115, "Update Object Direction");     }     @Override     public void simulate(ProgramStatement statement) throws ProcessingException     {         int id = RegisterFile.getValue(4);         int degree = RegisterFile.getValue(5);         GameScreen game = GameScreen.getInstance();         if (game == null)         {             SystemIO.printString("GameScreen has not been created!");             throw new ProcessingException();         }         GameObject obj = game.getGameObject(id);         if (obj == null)         {             SystemIO.printString("GameObject: id=" + id + " does not exist!");             throw new ProcessingException();         }         ActiveElementInterface ele = (ActiveElementInterface) obj;         ele.updateDirection(degree);     } } mars/mips/instructions/syscalls/SyscallPrintString.java mars/mips/instructions/syscalls/SyscallPrintString.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.mips.hardware.*;     import mars.*; /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**   * Service to display string stored starting at address in $a0 onto the console.    */       public class SyscallPrintString extends AbstractSyscall {    /**     * Build an instance of the Print String syscall.  Default service number     * is 4 and name is "PrintString".     */        public SyscallPrintString() {          super(4, "PrintString");       }           /**    * Performs syscall function to print string stored starting at address in $a0.    */        public void simulate(ProgramStatement statement) throws ProcessingException {          int byteAddress = RegisterFile.getValue(4);          char ch = 0;          try          {             ch = (char) Globals.memory.getByte(byteAddress);                               // won't stop until NULL byte reached!             while (ch != 0)             {                SystemIO.printString(new Character(ch).toString());                byteAddress++;                ch = (char) Globals.memory.getByte(byteAddress);             }          }               catch (AddressErrorException e)             {                throw new ProcessingException(statement, e);             }       }    } mars/mips/instructions/syscalls/SyscallPrintIntBinary.java mars/mips/instructions/syscalls/SyscallPrintIntBinary.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.mips.hardware.*;    import mars.*; /* Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**   * Service to display integer stored in $a0 on the console.  *  */       public class SyscallPrintIntBinary extends AbstractSyscall {    /**     * Build an instance of the Print Integer syscall.  Default service number     * is 1 and name is "PrintInt".     */        public SyscallPrintIntBinary() {          super(35, "PrintIntBinary");       }           /**    * Performs syscall function to print on the console the integer stored in $a0, in hexadecimal format.    */        public void simulate(ProgramStatement statement) throws ProcessingException {          SystemIO.printString(Binary.intToBinaryString(RegisterFile.getValue(4)));       }    } mars/mips/instructions/syscalls/SyscallMidiOut.java mars/mips/instructions/syscalls/SyscallMidiOut.java   package mars.mips.instructions.syscalls;         import mars.util.*;    import mars.mips.hardware.*;    import mars.simulator.*;    import mars.*; /* Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Service to output simulated MIDI tone to sound card.  The call returns  * immediately upon generating the tone.  By contrast, syscall 33  * (MidiOutSync) does not return until tone duration has elapsed.  */     public class SyscallMidiOut extends AbstractSyscall {          // Endpoints of ranges for the three "byte" parameters.  The duration     // parameter is limited at the high end only by the int range.       static final int rangeLowEnd = 0;       static final int rangeHighEnd = 127;         /**     * Build an instance of the MIDI (simulated) out syscall.  Default service number     * is 31 and name is "MidiOut".     */        public SyscallMidiOut() {          super(31, "MidiOut");       }           /**    * Performs syscall function to send MIDI output to sound card.  This requires    * four arguments in registers $a0 through $a3.
   * $a0 – pitch (note).  Integer value from 0 to 127, with 60 being middle-C on a piano.
   * $a1 – duration. Integer value in milliseconds.
   * $a2 – instrument.  Integer value from 0 to 127, with 0 being acoustic grand piano.
   * $a3 – volume.  Integer value from 0 to 127.
   * Default values, in case any parameters are outside the above ranges, are $a0=60, $a1=1000,
   * $a2=0, $a3=100.
   * See MARS documentation elsewhere or www.midi.org for more information.  Note that the pitch,
   * instrument and volume value ranges 0-127 are from javax.sound.midi; actual MIDI instruments
   * use the range 1-128.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         int pitch      = RegisterFile.getValue(4); // $a0
         int duration   = RegisterFile.getValue(5); // $a1
         int instrument = RegisterFile.getValue(6); // $a2
         int volume     = RegisterFile.getValue(7); // $a3
         if (pitch < rangeLowEnd || pitch > rangeHighEnd) pitch = ToneGenerator.DEFAULT_PITCH;
         if (duration < 0) duration = ToneGenerator.DEFAULT_DURATION;          if (instrument < rangeLowEnd || instrument > rangeHighEnd) instrument = ToneGenerator.DEFAULT_INSTRUMENT;
         if (volume < rangeLowEnd || volume > rangeHighEnd) volume = ToneGenerator.DEFAULT_VOLUME;
         new ToneGenerator().generateTone( (byte) pitch, duration, (byte) instrument, (byte) volume);
      }

   }
    

SyscallRandInt

package mars.mips.instructions.syscalls;
public synchronized class SyscallRandInt extends AbstractSyscall {
public void SyscallRandInt();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallGameGetObjDirection.java
mars/mips/instructions/syscalls/SyscallGameGetObjDirection.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.ActiveElementInterface;
import mars.ext.game.GameObject;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameGetObjDirection extends AbstractSyscall
{

    public SyscallGameGetObjDirection()
    {
        super(113, “Get Direction”);
    }

    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int id = RegisterFile.getValue(4);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“GameScreen has not been created!”);
            throw new ProcessingException();
        }
        GameObject obj = game.getGameObject(id);
        if (obj == null)
        {
            SystemIO.printString(“GameObject: id=” + id
                    + ” does not exist!”);
            throw new ProcessingException();
        }
        ActiveElementInterface ele = (ActiveElementInterface) obj;
        RegisterFile.updateRegister(2, ele.getDirection());
    }

}

SyscallMidiOutSync

package mars.mips.instructions.syscalls;
public synchronized class SyscallMidiOutSync extends AbstractSyscall {
static final int rangeLowEnd = 0;
static final int rangeHighEnd = 127;
public void SyscallMidiOutSync();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallGameSetObjSpeed

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameSetObjSpeed extends AbstractSyscall {
public void SyscallGameSetObjSpeed();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallReadInt

package mars.mips.instructions.syscalls;
public synchronized class SyscallReadInt extends AbstractSyscall {
public void SyscallReadInt();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallSbrk

package mars.mips.instructions.syscalls;
public synchronized class SyscallSbrk extends AbstractSyscall {
public void SyscallSbrk();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallPrintString

package mars.mips.instructions.syscalls;
public synchronized class SyscallPrintString extends AbstractSyscall {
public void SyscallPrintString();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallGameCreateObject.java
mars/mips/instructions/syscalls/SyscallGameCreateObject.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.GameConfigFile;
import mars.ext.game.GameObject;
import mars.ext.game.GameObjectDynamite;
import mars.ext.game.GameObjectHook;
import mars.ext.game.GameScreen;
import mars.ext.game.GameObjectMineral;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameCreateObject extends AbstractSyscall
{
    
    public SyscallGameCreateObject()
    {
        super(105, “Create Game Object”);
    }
    
    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        // $a0: id
        // $a1: type
        // $a2: x_loc
        // $a3: y_loc
        int id = RegisterFile.getValue(4);
        int type = RegisterFile.getValue(5);
        int x_loc = RegisterFile.getValue(6);
        int y_loc = RegisterFile.getValue(7);
        
        GameObject obj;
        int width, height;
        
        switch (type) {
            case 0: //Hook
            obj = new GameObjectHook(id, x_loc, y_loc, GameConfigFile.HOOK);
            break;
            case 1: //Gold
            width = 60;
            height = 45;
            obj = new GameObjectMineral(id, width, height, x_loc, y_loc, GameConfigFile.GOLD);
            break;
            case 2: //Gem
            width = 30;
            height = 18;
            obj = new GameObjectMineral(id, width, height, x_loc, y_loc, GameConfigFile.GEM);
            break;
            case 3: //Rock
            width = 100;
            height = 75;
            obj = new GameObjectMineral(id, width, height, x_loc, y_loc, GameConfigFile.ROCK);
            break;
            case 4: //Dynamite
            obj = new GameObjectDynamite(id, x_loc, y_loc, GameConfigFile.DYNAMITE);
            break;
            default: //ignore invalid type
            return;
        }
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“In Creating Mineral, but GameScreen has not been created first!”);
            throw new ProcessingException();
        }
        game.addGameObject(id, obj);
    }
    
}

Syscall

package mars.mips.instructions.syscalls;
public abstract interface Syscall {
public abstract String getName();
public abstract void setNumber(int);
public abstract int getNumber();
public abstract void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallGameSetObjSpeed.java
mars/mips/instructions/syscalls/SyscallGameSetObjSpeed.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.ActiveElementInterface;
import mars.ext.game.GameObject;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameSetObjSpeed extends AbstractSyscall
{

    public SyscallGameSetObjSpeed()
    {
        super(112, “Set Object Speed”);
    }

    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int id = RegisterFile.getValue(4);
        int speed = RegisterFile.getValue(5);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“GameScreen has not been created!”);
            throw new ProcessingException();
        }
        GameObject obj = game.getGameObject(id);
        if (obj == null)
        {
            SystemIO.printString(“GameObject: id=” + id + ” does not exist!”);
            throw new ProcessingException();
        }
        ActiveElementInterface ele = (ActiveElementInterface) obj;
        ele.setSpeed(speed);
    }

}

mars/mips/instructions/syscalls/SyscallCreateGame.java
mars/mips/instructions/syscalls/SyscallCreateGame.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;

public class SyscallCreateGame extends AbstractSyscall
{
    public SyscallCreateGame()
    {
        super(100, “Create Game”);
    }

    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        // $a0: base address of the string of the game’s title
        // $a1: width
        // $a2: height
        String title = SyscallGameHelper.getStringFromMIPS(RegisterFile.getValue(4));
        int width = RegisterFile.getValue(5);
        int height = RegisterFile.getValue(6);
        GameScreen.createIntance(title, width, height);
    }

}

SyscallMessageDialogString

package mars.mips.instructions.syscalls;
public synchronized class SyscallMessageDialogString extends AbstractSyscall {
public void SyscallMessageDialogString();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallExit.java
mars/mips/instructions/syscalls/SyscallExit.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to exit the MIPS program.
 *
 */
 
    public class SyscallExit extends AbstractSyscall {
   /**
    * Build an instance of the Exit syscall.  Default service number
    * is 10 and name is “Exit”.
    */
       public SyscallExit() {
         super(10, “Exit”);
      }
      
   /**
   * Performs syscall function to exit the MIPS program.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         throw new ProcessingException();  // empty exception list.
      }
   }

SyscallWrite

package mars.mips.instructions.syscalls;
public synchronized class SyscallWrite extends AbstractSyscall {
public void SyscallWrite();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallInputDialogInt.java
mars/mips/instructions/syscalls/SyscallInputDialogInt.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
    import mars.simulator.*;
   import mars.*;
import javax.swing.JOptionPane;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Service to input data.
 *
 */

    public class SyscallInputDialogInt extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallInputDialogInt() {
         super(51, “InputDialogInt”);
      }

   /**
   * System call to input data.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Input arguments: $a0 = address of null-terminated string that is the message to user
          // Outputs:
          //    $a0 contains value of int read
          //    $a1 contains status value
          //       0: valid input data, correctly parsed
          //       -1: input data cannot be correctly parsed
          //       -2: Cancel was chosen
          //       -3: OK was chosen but no data had been input into field

         String message = new String(); // = “”;
         int byteAddress = RegisterFile.getValue(4);
         char ch[] = { ‘ ‘}; // Need an array to convert to String
         try
         {
            ch[0] = (char) Globals.memory.getByte(byteAddress);
            while (ch[0] != 0) // only uses single location ch[0]
            {
               message = message.concat(new String(ch)); // parameter to String constructor is a char[] array
               byteAddress++;
               ch[0] = (char) Globals.memory.getByte(byteAddress);
            }
         }
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }

            // Values returned by Java’s InputDialog:
            // A null return value means that “Cancel” was chosen rather than OK.
            // An empty string returned (that is, inputValue.length() of zero)
            // means that OK was chosen but no string was input.
            String inputValue = null;
            inputValue = JOptionPane.showInputDialog(message);
            if (inputValue == null)  // Cancel was chosen
            {
               RegisterFile.updateRegister(4, 0 );  // set $a0 to zero
               RegisterFile.updateRegister(5, -2 );  // set $a1 to -2 flag
            }
            else if (inputValue.length() == 0)  // OK was chosen but there was no input
            {
               RegisterFile.updateRegister(4, 0 );  // set $a0 to zero
               RegisterFile.updateRegister(5, -3 );  // set $a1 to -3 flag
            }
            else
            {
               try
               {
                   int i = Integer.parseInt(inputValue);
                   
                   // Successful parse of valid input data
                   RegisterFile.updateRegister(4, i );  // set $a0 to the data read
                   RegisterFile.updateRegister(5, 0 );  // set $a1 to valid flag
               }
               catch ( NumberFormatException e)
               {
                   // Unsuccessful parse of input data
                   RegisterFile.updateRegister(4, 0 );  // set $a0 to zero
                   RegisterFile.updateRegister(5, -1 );  // set $a1 to -1 flag

               }
               
            } // end else

       }

   }

SyscallGameUpdateObjDirection

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameUpdateObjDirection extends AbstractSyscall {
public void SyscallGameUpdateObjDirection();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallMessageDialogInt.java
mars/mips/instructions/syscalls/SyscallMessageDialogInt.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
    import mars.simulator.*;
   import mars.*;
import javax.swing.JOptionPane;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Service to display a message to user.
 *
 */

    public class SyscallMessageDialogInt extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallMessageDialogInt() {
         super(56, “MessageDialogInt”);
      }

   /**
   * System call to display a message to user.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Input arguments:
          //   $a0 = address of null-terminated string that is an information-type message to user
          //   $a1 = int value to display in string form after the first message
          // Output: none

         String message = new String(); // = “”;
         int byteAddress = RegisterFile.getValue(4);
         char ch[] = { ‘ ‘}; // Need an array to convert to String
         try
         {
            ch[0] = (char) Globals.memory.getByte(byteAddress);
            while (ch[0] != 0) // only uses single location ch[0]
            {
               message = message.concat(new String(ch)); // parameter to String constructor is a char[] array
               byteAddress++;
               ch[0] = (char) Globals.memory.getByte(byteAddress);
            }
         }
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }

            // Display the dialog.
            JOptionPane.showMessageDialog(null,
                  message + Integer.toString(RegisterFile.getValue(5)),
                  null,
                  JOptionPane.INFORMATION_MESSAGE );
            

       }

   }

SyscallConfirmDialog

package mars.mips.instructions.syscalls;
public synchronized class SyscallConfirmDialog extends AbstractSyscall {
public void SyscallConfirmDialog();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallOpen.java
mars/mips/instructions/syscalls/SyscallOpen.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
    import mars.simulator.*;
   import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to open file name specified by $a0. File descriptor returned in $v0.
 * (this was changed from $a0 in MARS 3.7 for SPIM compatibility.  The table
 * in COD erroneously shows $a0).
 *
 */
 
    public class SyscallOpen extends AbstractSyscall {
   /**
    * Build an instance of the Open file syscall.  Default service number
    * is 13 and name is “Open”.
    */
       public SyscallOpen() {
         super(13, “Open”);
      }
      
   /**
   * Performs syscall function to open file name specified by $a0. File descriptor returned
    * in $v0.  Only supported flags ($a1) are read-only (0), write-only (1) and 
    * write-append (9). write-only flag creates file if it does not exist, so it is technically
    * write-create.  write-append will start writing at end of existing file.
    * Mode ($a2) is ignored. 
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
            // NOTE: with MARS 3.7, return changed from $a0 to $v0 and the terminology
             // of ‘flags’ and ‘mode’ was corrected (they had been reversed).
             //
          // Arguments: $a0 = filename (string), $a1 = flags, $a2 = mode
          // Result: file descriptor (in $v0)
          // This code implements the flags:
          // Read          flag = 0
          // Write         flag = 1
          // Read/Write    NOT IMPLEMENTED
             // Write/append  flag = 9
          // This code implements the modes:
          // NO MODES IMPLEMENTED  — MODE IS IGNORED
          // Returns in $v0: a “file descriptor” in the range 0 to SystemIO.SYSCALL_MAXFILES-1,
          // or -1 if error
         String filename = new String(); // = “”;
         int byteAddress = RegisterFile.getValue(4);
         char ch[] = { ‘ ‘}; // Need an array to convert to String
         try
         {
            ch[0] = (char) Globals.memory.getByte(byteAddress);
            while (ch[0] != 0) // only uses single location ch[0]
            {
               filename = filename.concat(new String(ch)); // parameter to String constructor is a char[] array
               byteAddress++;
               ch[0] = (char) Globals.memory.getByte(
                                        byteAddress);
            }
         } 
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }
         int retValue = SystemIO.openFile(filename,
                                 RegisterFile.getValue(5));
         RegisterFile.updateRegister(2, retValue); // set returned fd value in register
            
            // GETTING RID OF PROCESSING EXCEPTION.  IT IS THE RESPONSIBILITY OF THE
            // USER PROGRAM TO CHECK FOR BAD FILE OPEN.  MARS SHOULD NOT PRE-EMPTIVELY
            // TERMINATE MIPS EXECUTION BECAUSE OF IT.  Thanks to UCLA student
            // Duy Truong for pointing this out.  DPS 28-July-2009.
         /*
            if (retValue < 0) // some error in opening file          {             throw new ProcessingException(statement,                 SystemIO.getFileErrorMessage()+" (syscall "+this.getNumber()+")",                       Exceptions.SYSCALL_EXCEPTION);          }              */       }    } mars/mips/instructions/syscalls/SyscallReadChar.java mars/mips/instructions/syscalls/SyscallReadChar.java   package mars.mips.instructions.syscalls;    import mars.*;    import mars.util.*;    import mars.mips.hardware.*;    import mars.simulator.*; /* Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**   * Service to read a character from input console into $a0.  *  */       public class SyscallReadChar extends AbstractSyscall {    /**     * Build an instance of the Read Char syscall.  Default service number     * is 12 and name is "ReadChar".     */        public SyscallReadChar() {          super(12, "ReadChar");       }           /**    * Performs syscall function to read a character from input console into $a0    */        public void simulate(ProgramStatement statement) throws ProcessingException {          int value = 0;          try          {             value = SystemIO.readChar(this.getNumber());          }               catch (IndexOutOfBoundsException e) // means null input             {                throw new ProcessingException(statement,                      "invalid char input (syscall "+this.getNumber()+")",                     Exceptions.SYSCALL_EXCEPTION);             }             // DPS 20 June 2008: changed from 4 ($a0) to 2 ($v0)          RegisterFile.updateRegister(2, value);        }        } SyscallGameSetLevelInfo package mars.mips.instructions.syscalls; public synchronized class SyscallGameSetLevelInfo extends AbstractSyscall { public void SyscallGameSetLevelInfo(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallReadFloat.java mars/mips/instructions/syscalls/SyscallReadFloat.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.simulator.*;    import mars.mips.hardware.*;    import mars.*; /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**   * Service to read the bits of input float into $f0  */       public class SyscallReadFloat extends AbstractSyscall {    /**     * Build an instance of the Read Float syscall.  Default service number     * is 6 and name is "ReadFloat".     */        public SyscallReadFloat() {          super(6, "ReadFloat");       }           /**    * Performs syscall function to read the bits of input float into $f0    */        public void simulate(ProgramStatement statement) throws ProcessingException {          float floatValue = 0;          try          {             floatValue = SystemIO.readFloat(this.getNumber());          }               catch (NumberFormatException e)             {                throw new ProcessingException(statement,                   "invalid float input (syscall "+this.getNumber()+")",                         Exceptions.SYSCALL_EXCEPTION);             }          Coprocessor1.updateRegister(0, Float.floatToRawIntBits(floatValue));       }    } mars/mips/instructions/syscalls/SyscallGameGetObjPrice.java mars/mips/instructions/syscalls/SyscallGameGetObjPrice.javapackage mars.mips.instructions.syscalls; import mars.ProcessingException; import mars.ProgramStatement; import mars.ext.game.ActiveElementInterface; import mars.ext.game.GameObject; import mars.ext.game.GameScreen; import mars.mips.hardware.RegisterFile; import mars.util.SystemIO; public class SyscallGameGetObjPrice extends AbstractSyscall {     public SyscallGameGetObjPrice()     {         super(116, "Get Price");     }     @Override     public void simulate(ProgramStatement statement) throws ProcessingException     {         int id = RegisterFile.getValue(4);         GameScreen game = GameScreen.getInstance();         if (game == null)         {             SystemIO.printString("GameScreen has not been created!");             throw new ProcessingException();         }         GameObject obj = game.getGameObject(id);         if (obj == null)         {             SystemIO.printString("GameObject: id=" + id + " does not exist!");             throw new ProcessingException();         }         ActiveElementInterface ele = (ActiveElementInterface) obj;         RegisterFile.updateRegister(2, ele.getPrice());     } } SyscallMidiOut package mars.mips.instructions.syscalls; public synchronized class SyscallMidiOut extends AbstractSyscall { static final int rangeLowEnd = 0; static final int rangeHighEnd = 127; public void SyscallMidiOut(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } SyscallGameCreateObjectText package mars.mips.instructions.syscalls; public synchronized class SyscallGameCreateObjectText extends AbstractSyscall { public void SyscallGameCreateObjectText(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallMessageDialog.java mars/mips/instructions/syscalls/SyscallMessageDialog.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.mips.hardware.*;     import mars.simulator.*;    import mars.*; import javax.swing.JOptionPane; /* Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Service to display a message to user.  *  */     public class SyscallMessageDialog extends AbstractSyscall {    /**     * Build an instance of the syscall with its default service number and name.     */        public SyscallMessageDialog() {          super(55, "MessageDialog");       }    /**    * System call to display a message to user.    */        public void simulate(ProgramStatement statement) throws ProcessingException {           // Input arguments:           //   $a0 = address of null-terminated string that is the message to user           //   $a1 = the type of the message to the user, which is one of:           //       1: error message           //       2: information message           //       3: warning message           //       4: question message           //       other: plain message           // Output: none          String message = new String(); // = "";          int byteAddress = RegisterFile.getValue(4);          char ch[] = { ' '}; // Need an array to convert to String          try          {             ch[0] = (char) Globals.memory.getByte(byteAddress);             while (ch[0] != 0) // only uses single location ch[0]             {                message = message.concat(new String(ch)); // parameter to String constructor is a char[] array                byteAddress++;                ch[0] = (char) Globals.memory.getByte(byteAddress);             }          }              catch (AddressErrorException e)             {                throw new ProcessingException(statement, e);             }             // Display the dialog.             int msgType = RegisterFile.getValue(5);             if (msgType < 0 || msgType > 3) msgType = -1; // See values in http://java.sun.com/j2se/1.5.0/docs/api/constant-values.html
            JOptionPane.showMessageDialog(null, message, null, msgType );
            

       }

   }

SyscallTime

package mars.mips.instructions.syscalls;
public synchronized class SyscallTime extends AbstractSyscall {
public void SyscallTime();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallReadString

package mars.mips.instructions.syscalls;
public synchronized class SyscallReadString extends AbstractSyscall {
public void SyscallReadString();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallGameSetObjDirection.java
mars/mips/instructions/syscalls/SyscallGameSetObjDirection.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.ActiveElementInterface;
import mars.ext.game.GameObject;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameSetObjDirection extends AbstractSyscall
{

    public SyscallGameSetObjDirection()
    {
        super(114, “Set Object Direction”);
    }

    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int id = RegisterFile.getValue(4);
        int direction = RegisterFile.getValue(5);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“GameScreen has not been created!”);
            throw new ProcessingException();
        }
        GameObject obj = game.getGameObject(id);
        if (obj == null)
        {
            SystemIO.printString(“GameObject: id=” + id + ” does not exist!”);
            throw new ProcessingException();
        }
        ActiveElementInterface ele = (ActiveElementInterface) obj;
        ele.setDirection(direction);
    }

}

mars/mips/instructions/syscalls/SyscallRandDouble.java
mars/mips/instructions/syscalls/SyscallRandDouble.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.simulator.*;
   import mars.*;
   import java.util.Random;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Service to return a random floating point value.
 *
 */

    public class SyscallRandDouble extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallRandDouble() {
         super(44, “RandDouble”);
      }
      
   /**
   * System call to the random number generator.
   * Return in $f0 the next pseudorandom, uniformly distributed double value between 0.0 and 1.0
   * from this random number generator’s sequence.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Input arguments: $a0 = index of pseudorandom number generator
          // Return: $f0 = the next pseudorandom, uniformly distributed double value between 0.0 and 1.0
          // from this random number generator’s sequence.
         Integer index = new Integer(RegisterFile.getValue(4));
         Random stream = (Random) RandomStreams.randomStreams.get(index);
         if (stream == null) {
            stream = new Random(); // create a non-seeded stream
            RandomStreams.randomStreams.put(index, stream);
         } 
         try {
            Coprocessor1.setRegisterPairToDouble(0, stream.nextDouble( ));
         }     
             catch (InvalidRegisterAccessException e) {   // register ID error in this method
               throw new ProcessingException(statement,
                       “Internal error storing double to register (syscall “+this.getNumber()+”)”,
                             Exceptions.SYSCALL_EXCEPTION);
            }
      }
   
   }

SyscallGameToggleIsHooked

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameToggleIsHooked extends AbstractSyscall {
public void SyscallGameToggleIsHooked();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallPrintIntUnsigned.java
mars/mips/instructions/syscalls/SyscallPrintIntUnsigned.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.*;

/*
Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to display integer stored in $a0 on the console as unsigned decimal.
 *
 */
 
    public class SyscallPrintIntUnsigned extends AbstractSyscall {
   /**
    * Build an instance of the Print Integer Unsigned syscall.  Default service number
    * is 36 and name is “PrintIntUnsigned”.
    */
       public SyscallPrintIntUnsigned() {
         super(36, “PrintIntUnsigned”);
      }
      
   /**
   * Performs syscall function to print on the console the integer stored in $a0.
   * The value is treated as unsigned.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         SystemIO.printString(
                    Binary.unsignedIntToIntString(RegisterFile.getValue(4)));
      }
   }

mars/mips/instructions/syscalls/SyscallPrintFloat.java
mars/mips/instructions/syscalls/SyscallPrintFloat.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to display on the console float whose bits are stored in $f12
 */
 
    public class SyscallPrintFloat extends AbstractSyscall {
   /**
    * Build an instance of the Print Float syscall.  Default service number
    * is 2 and name is “PrintFloat”.
    */
       public SyscallPrintFloat() {
         super(2, “PrintFloat”);
      }
      
   /**
   * Performs syscall function to display float whose bits are stored in $f12
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         SystemIO.printString(new Float(Float.intBitsToFloat(
                                Coprocessor1.getValue(12))).toString());
      }
   }

mars/mips/instructions/syscalls/SyscallGameToggleIsShoot.java
mars/mips/instructions/syscalls/SyscallGameToggleIsShoot.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.GameObject;
import mars.ext.game.GameObjectHook;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameToggleIsShoot extends AbstractSyscall
{
    
    public SyscallGameToggleIsShoot()
    {
        super(121, “Toggle isShoot”);
    }
    
    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int id = RegisterFile.getValue(4);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“GameScreen has not been created!”);
            throw new ProcessingException();
        }
        GameObject obj = game.getGameObject(id);
        if (obj == null)
        {
            SystemIO.printString(“GameObject: id=” + id + ” does not exist!”);
            throw new ProcessingException();
        }
        
        if (obj instanceof GameObjectHook)
        {
            GameObjectHook hook = (GameObjectHook) obj;
            hook.toggleIsShoot();
        }
    }
}

mars/mips/instructions/syscalls/SyscallSbrk.java
mars/mips/instructions/syscalls/SyscallSbrk.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
    import mars.simulator.*;
   import mars.mips.hardware.*;
   import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to allocate amount of heap memory specified in $a0, putting address into $v0.
 *
 */
 
    public class SyscallSbrk extends AbstractSyscall {
   /**
    * Build an instance of the Sbrk syscall.  Default service number
    * is 9 and name is “Sbrk”.
    */
       public SyscallSbrk() {
         super(9, “Sbrk”);
      }
      
   /**
   * Performs syscall function to allocate amount of heap memory specified in $a0, putting address into $v0.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         int address = 0;
         try {
            address = Globals.memory.allocateBytesFromHeap(RegisterFile.getValue(4));
         } 
             catch (IllegalArgumentException iae) {
               throw new ProcessingException(statement,
                                       iae.getMessage()+” (syscall “+this.getNumber()+”)”,
                                       Exceptions.SYSCALL_EXCEPTION);
            }
         RegisterFile.updateRegister(2, address);
      }
   }

AbstractSyscall

package mars.mips.instructions.syscalls;
public abstract synchronized class AbstractSyscall implements Syscall {
private int serviceNumber;
private String serviceName;
public void AbstractSyscall(int, String);
public String getName();
public void setNumber(int);
public int getNumber();
public abstract void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallMessageDialogString.java
mars/mips/instructions/syscalls/SyscallMessageDialogString.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
    import mars.simulator.*;
   import mars.*;
import javax.swing.JOptionPane;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Service to display a message to user.
 *
 */

    public class SyscallMessageDialogString extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallMessageDialogString() {
         super(59, “MessageDialogString”);
      }

   /**
   * System call to display a message to user.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Input arguments:
          //   $a0 = address of null-terminated string that is an information-type message to user
          //   $a1 = address of null-terminated string to display after the first message
          // Output: none

         String message = new String(); // = “”;
         int byteAddress = RegisterFile.getValue(4);
         char ch[] = { ‘ ‘}; // Need an array to convert to String
         try
         {
            ch[0] = (char) Globals.memory.getByte(byteAddress);
            while (ch[0] != 0) // only uses single location ch[0]
            {
               message = message.concat(new String(ch)); // parameter to String constructor is a char[] array
               byteAddress++;
               ch[0] = (char) Globals.memory.getByte(byteAddress);
            }
         }
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }

         String message2 = new String(); // = “”;
         byteAddress = RegisterFile.getValue(5);
         try
         {
            ch[0] = (char) Globals.memory.getByte(byteAddress);
            while (ch[0] != 0) // only uses single location ch[0]
            {
               message2 = message2.concat(new String(ch)); // parameter to String constructor is a char[] array
               byteAddress++;
               ch[0] = (char) Globals.memory.getByte(byteAddress);
            }
         }
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }

            // Display the dialog.
            JOptionPane.showMessageDialog(null,
                  message + message2,
                  null,
                  JOptionPane.INFORMATION_MESSAGE );
            

       }

   }

mars/mips/instructions/syscalls/SyscallInputDialogFloat.java
mars/mips/instructions/syscalls/SyscallInputDialogFloat.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
    import mars.simulator.*;
   import mars.*;
import javax.swing.JOptionPane;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Service to input data.
 *
 */

    public class SyscallInputDialogFloat extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallInputDialogFloat() {
         super(52, “InputDialogFloat”);
      }

   /**
   * System call to input data.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Input arguments: $a0 = address of null-terminated string that is the message to user
          // Outputs:
          //    $f0 contains value of float read
          //    $a1 contains status value
          //       0: valid input data, correctly parsed
          //       -1: input data cannot be correctly parsed
          //       -2: Cancel was chosen
          //       -3: OK was chosen but no data had been input into field

         String message = new String(); // = “”;
         int byteAddress = RegisterFile.getValue(4);
         char ch[] = { ‘ ‘}; // Need an array to convert to String
         try
         {
            ch[0] = (char) Globals.memory.getByte(byteAddress);
            while (ch[0] != 0) // only uses single location ch[0]
            {
               message = message.concat(new String(ch)); // parameter to String constructor is a char[] array
               byteAddress++;
               ch[0] = (char) Globals.memory.getByte(byteAddress);
            }
         }
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }

            // Values returned by Java’s InputDialog:
            // A null return value means that “Cancel” was chosen rather than OK.
            // An empty string returned (that is, inputValue.length() of zero)
            // means that OK was chosen but no string was input.
            String inputValue = null;
            inputValue = JOptionPane.showInputDialog(message);

            try
            {
                 Coprocessor1.setRegisterToFloat(0, (float)0.0);  // set $f0 to zero
              if (inputValue == null)  // Cancel was chosen
              {
                 RegisterFile.updateRegister(5, -2 );  // set $a1 to -2 flag
              }
              else if (inputValue.length() == 0)  // OK was chosen but there was no input
              {
                 RegisterFile.updateRegister(5, -3 );  // set $a1 to -3 flag
              }
              else
              {

                   float floatValue = Float.parseFloat(inputValue);

                   //System.out.println(“SyscallInputDialogFloat: floatValue is ” + floatValue);
                   
                   // Successful parse of valid input data
                   Coprocessor1.setRegisterToFloat(0, floatValue);  // set $f0 to input data
                   RegisterFile.updateRegister(5, 0 );  // set $a1 to valid flag

              }

            } // end try block

               catch ( NumberFormatException e)    // Unsuccessful parse of input data
               {
                   RegisterFile.updateRegister(5, -1 );  // set $a1 to -1 flag

                   /*  Don’t throw exception because returning a status flag
                   throw new ProcessingException(statement,
                      “invalid float input (syscall “+this.getNumber()+”)”,
                                  Exceptions.SYSCALL_EXCEPTION);
                   */

               }

       }

   }

SyscallGameGetObjDirection

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameGetObjDirection extends AbstractSyscall {
public void SyscallGameGetObjDirection();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/AbstractSyscall.java
mars/mips/instructions/syscalls/AbstractSyscall.java   package mars.mips.instructions.syscalls;
   import mars.*;
/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 *  Abstract class that a MIPS syscall system service may extend.  A qualifying service
 *  must be a class in the mars.mips.instructions.syscalls package that 
 *  implements the Syscall interface, must be compiled into a .class file, 
 *  and its .class file must be in the same folder as Syscall.class.
 *  Mars will detect a qualifying syscall upon startup, create an instance 
 *  using its no-argument constructor and add it to its syscall list.  
 *  When its service is invoked at runtime (“syscall” instruction
 *  with its service number stored in register $v0), its simulate()
 *  method will be invoked.
 *
 */
 
    public abstract class AbstractSyscall implements Syscall {
      private int serviceNumber;
      private String serviceName;
     
   /**
    * Constructor is provided so subclass may initialize instance variables.
    * @param number default assigned service number
    * @param name service name which may be used for reference independent of number
    */
       public AbstractSyscall(int number, String name) {
         serviceNumber = number;
         serviceName   = name;
      }
    
   /**
   *  Return the name you have chosen for this syscall.  This can be used by a MARS
   *  user to refer to the service when choosing to override its default service
   *  number in the configuration file.
   *  @return service name as a string
   */
       public String getName() {
         return serviceName;
      }
   
   /**
   * Set the service number.  This is provided to allow MARS implementer or user
   * to override the default service number.
   * @param num specified service number to override the default.
   */
       public void setNumber(int num) {
         serviceNumber = num;
      }
   
   /**
   * Return the assigned service number.  This is the number the MIPS programmer
   * must store into $v0 before issuing the SYSCALL instruction.
   * @return assigned service number
   */
       public int getNumber() {
         return serviceNumber;
      }
   
   /**
   * Performs syscall function.  It will be invoked when the service is invoked
   * at simulation time.  Service is identified by value stored in $v0.
    * @param statement ProgramStatement object for this syscall instruction.
   */
       public abstract void simulate(ProgramStatement statement)
            throws ProcessingException;
   }

mars/mips/instructions/syscalls/SyscallGameToggleIsClockwise.java
mars/mips/instructions/syscalls/SyscallGameToggleIsClockwise.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.GameObject;
import mars.ext.game.GameObjectHook;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameToggleIsClockwise extends AbstractSyscall
{

    public SyscallGameToggleIsClockwise()
    {
        super(123, “Toggle isClockwise”);
    }

    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int id = RegisterFile.getValue(4);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“GameScreen has not been created!”);
            throw new ProcessingException();
        }
        GameObject obj = game.getGameObject(id);
        if (obj == null)
        {
            SystemIO.printString(“GameObject: id=” + id
                    + ” does not exist!”);
            throw new ProcessingException();
        }
        
        if (obj instanceof GameObjectHook)
        {
            GameObjectHook hook = (GameObjectHook) obj;
            hook.toggleIsClockwise();
        }
    }

}

mars/mips/instructions/syscalls/RandomStreams.java
mars/mips/instructions/syscalls/RandomStreams.java   package mars.mips.instructions.syscalls;
    import java.util.HashMap;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * This small class serves only to hold a static HashMap for storing
 * random number generators for use by all the random number generator
 * syscalls.
 */
 
    public class RandomStreams {
      /** Collection of pseudorandom number streams available for use in Rand-type syscalls.
       * The streams are by default not seeded. */
         static final HashMap randomStreams = new HashMap();
   }

SyscallRandFloat

package mars.mips.instructions.syscalls;
public synchronized class SyscallRandFloat extends AbstractSyscall {
public void SyscallRandFloat();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallReadChar

package mars.mips.instructions.syscalls;
public synchronized class SyscallReadChar extends AbstractSyscall {
public void SyscallReadChar();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallReadString.java
mars/mips/instructions/syscalls/SyscallReadString.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to read console input string into buffer starting at address in $a0.  
 */
 
    public class SyscallReadString extends AbstractSyscall {
   /**
    * Build an instance of the Read String syscall.  Default service number
    * is 8 and name is “ReadString”.
    */
       public SyscallReadString() {
         super(8, “ReadString”);
      }
      
   /**
   * Performs syscall function to read console input string into buffer starting at address in $a0.
   * Follows semantics of UNIX ‘fgets’.  For specified length n,
   * string can be no longer than n-1. If less than that, add
   * newline to end.  In either case, then pad with null byte.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
      
         String inputString = “”;
         int buf = RegisterFile.getValue(4); // buf addr in $a0
         int maxLength = RegisterFile.getValue(5) – 1; // $a1
            boolean addNullByte = true;
        // Guard against negative maxLength.  DPS 13-July-2011
         if (maxLength < 0)           {             maxLength = 0;                 addNullByte = false;          }          inputString = SystemIO.readString(this.getNumber(), maxLength);          int stringLength = Math.min(maxLength, inputString.length());          try          {             for (int index = 0; index < stringLength; index++)             {                Globals.memory.setByte(buf + index,                                        inputString.charAt(index));             }                         if (stringLength < maxLength)             {                Globals.memory.setByte(buf + stringLength, '\n');                stringLength++;             }             if (addNullByte) Globals.memory.setByte(buf + stringLength, 0);          }               catch (AddressErrorException e)             {                throw new ProcessingException(statement, e);             }       }    } mars/mips/instructions/syscalls/SyscallInputDialogString.java mars/mips/instructions/syscalls/SyscallInputDialogString.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.mips.hardware.*;    import mars.simulator.*;    import mars.*;    import javax.swing.JOptionPane; /* Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Service to input data.  *  */     public class SyscallInputDialogString extends AbstractSyscall {    /**     * Build an instance of the syscall with its default service number and name.     */        public SyscallInputDialogString() {          super(54, "InputDialogString");       }        /**    * System call to input data.    */        public void simulate(ProgramStatement statement) throws ProcessingException {           // Input arguments:           //    $a0 = address of null-terminated string that is the message to user           //    $a1 = address of input buffer for the input string           //    $a2 = maximum number of characters to read           // Outputs:           //    $a1 contains status value           //       0: valid input data, correctly parsed           //       -1: input data cannot be correctly parsed           //       -2: Cancel was chosen           //       -3: OK was chosen but no data had been input into field                        String message = new String(); // = "";          int byteAddress = RegisterFile.getValue(4); // byteAddress of string is in $a0          char ch[] = { ' '}; // Need an array to convert to String          try          {             ch[0] = (char) Globals.memory.getByte(byteAddress);             while (ch[0] != 0) // only uses single location ch[0]             {                message = message.concat(new String(ch)); // parameter to String constructor is a char[] array                byteAddress++;                ch[0] = (char) Globals.memory.getByte(byteAddress);             }          }              catch (AddressErrorException e)             {                throw new ProcessingException(statement, e);             }                    // Values returned by Java's InputDialog:             // A null return value means that "Cancel" was chosen rather than OK.             // An empty string returned (that is, inputString.length() of zero)             // means that OK was chosen but no string was input.          String inputString = null;          inputString = JOptionPane.showInputDialog(message);          byteAddress = RegisterFile.getValue(5); // byteAddress of string is in $a1          int maxLength = RegisterFile.getValue(6); // input buffer size for input string is in $a2                 try          {             if (inputString == null)  // Cancel was chosen             {                RegisterFile.updateRegister(5, -2 );  // set $a1 to -2 flag             }             else if (inputString.length() == 0)  // OK was chosen but there was no input             {                RegisterFile.updateRegister(5, -3 );  // set $a1 to -3 flag             }             else             {                     // The buffer will contain characters, a '\n' character, and the null character                     // Copy the input data to buffer as space permits                for (int index = 0; (index < inputString.length()) && (index < maxLength - 1); index++)                {                   Globals.memory.setByte(byteAddress + index,                                        inputString.charAt(index));                }                if (inputString.length() < maxLength-1)                      {                   Globals.memory.setByte(byteAddress + (int)Math.min(inputString.length(), maxLength-2), '\n');  // newline at string end                }                Globals.memory.setByte(byteAddress + (int)Math.min((inputString.length()+1), maxLength-1), 0);  // null char to end string                                     if (inputString.length() > maxLength – 1)
               {
                    //  length of the input string exceeded the specified maximum
                  RegisterFile.updateRegister(5, -4 );  // set $a1 to -4 flag
               }
               else
               {
                  RegisterFile.updateRegister(5, 0 );  // set $a1 to 0 flag
               }
            } // end else
               
         } // end try
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }
      
            
      }
   
   }

mars/mips/instructions/syscalls/SyscallGameHelper.java
mars/mips/instructions/syscalls/SyscallGameHelper.javapackage mars.mips.instructions.syscalls;

import mars.Globals;
import mars.mips.hardware.AddressErrorException;
import mars.mips.hardware.Memory;

/**
 * Provide some common functionalities for other syscalls for the Game!
 * 
 * @author jasonwangm
 * 
 */
public final class SyscallGameHelper
{
    public static String getStringFromMIPS(int baseAddress)
    {
        StringBuffer buffer = new StringBuffer();
        try
        {
            Memory mem = Globals.memory;
            char ch = ‘\0’;
            ch = (char) (mem.getByte(baseAddress) & 0xFF);
            baseAddress++;
            while (ch != ‘\0’)
            {
                buffer.append(ch);
                ch = (char) (mem.getByte(baseAddress) & 0xFF);
                baseAddress++;
            }
        }
        catch (AddressErrorException e)
        {
            System.err.println(“Invalid byte address for the string!”);
            e.printStackTrace();
        }
        return buffer.toString();
    }

    private SyscallGameHelper()
    {
        // TODO Auto-generated constructor stub
    }

}

EndOfTrackListener

package mars.mips.instructions.syscalls;
synchronized class EndOfTrackListener implements javax.sound.midi.MetaEventListener {
private boolean endedYet;
void EndOfTrackListener();
public synchronized void meta(javax.sound.midi.MetaMessage);
public synchronized void awaitEndOfTrack() throws InterruptedException;
}

Tone

package mars.mips.instructions.syscalls;
synchronized class Tone implements Runnable {
public static final int TEMPO = 1000;
public static final int DEFAULT_CHANNEL = 0;
private byte pitch;
private int duration;
private byte instrument;
private byte volume;
private static java.util.concurrent.locks.Lock openLock;
static void ();
public void Tone(byte, int, byte, byte);
public void run();
private void playTone();
}

SyscallPrintChar

package mars.mips.instructions.syscalls;
public synchronized class SyscallPrintChar extends AbstractSyscall {
public void SyscallPrintChar();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallReadDouble

package mars.mips.instructions.syscalls;
public synchronized class SyscallReadDouble extends AbstractSyscall {
public void SyscallReadDouble();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallGameCreateObjectText.java
mars/mips/instructions/syscalls/SyscallGameCreateObjectText.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.GameScreen;
import mars.ext.game.GameObjectText;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameCreateObjectText extends AbstractSyscall
{

    public SyscallGameCreateObjectText()
    {
        super(106, “Create Text”);
    }

    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int id = RegisterFile.getValue(4);
        int x_loc = RegisterFile.getValue(5);
        int y_loc = RegisterFile.getValue(6);
        String text = SyscallGameHelper.getStringFromMIPS(RegisterFile.getValue(7));
        GameObjectText obj = new GameObjectText(id, x_loc, y_loc);
        obj.setText(text);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“In Creating Ship, but GameScreen has not been created first!”);
            throw new ProcessingException();
        }
        game.addGameObject(id, obj);
    }

}

mars/mips/instructions/syscalls/SyscallPrintChar.java
mars/mips/instructions/syscalls/SyscallPrintChar.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to display character stored in $a0 on the console.
 *
 */
 
    public class SyscallPrintChar extends AbstractSyscall {
   /**
    * Build an instance of the Print Char syscall.  Default service number
    * is 11 and name is “PrintChar”.
    */
       public SyscallPrintChar() {
         super(11, “PrintChar”);
      }
      
   /**
   * Performs syscall function to print on the console the character stored in $a0.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         // mask off the lower byte of register $a0.
         // Convert to a one-character string and use the string technique.
         char t = (char) (RegisterFile.getValue(4) & 0x000000ff);
         SystemIO.printString(new Character(t).toString());
      }
   
   }

SyscallGameToggleIsShoot

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameToggleIsShoot extends AbstractSyscall {
public void SyscallGameToggleIsShoot();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallGameSetLevelInfo.java
mars/mips/instructions/syscalls/SyscallGameSetLevelInfo.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameSetLevelInfo extends AbstractSyscall
{
    
    public SyscallGameSetLevelInfo()
    {
        super(103, “Set Game Level Information”);
    }
    
    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int infoType = RegisterFile.getValue(4);
        int value = RegisterFile.getValue(5);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“GameScreen has not been created!”);
            throw new ProcessingException();
        }
        switch (infoType) {
            case 0: // game level
            game.setLevel(value);
            break;
            case 1: // level timer
            game.setTimer(value);
            break;
            case 2: // level quota
            game.setQuota(value);
            break;
            case 3: // level balance
            game.setBalance(value);
            break;
            case 4: // available dynamites
            game.setDynamiteInfo(value);
            break;
            default:
            break;
        }
    }
    
}

SyscallMessageDialog

package mars.mips.instructions.syscalls;
public synchronized class SyscallMessageDialog extends AbstractSyscall {
public void SyscallMessageDialog();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallGameSetObjLocation.java
mars/mips/instructions/syscalls/SyscallGameSetObjLocation.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.GameObject;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameSetObjLocation extends AbstractSyscall
{

    public SyscallGameSetObjLocation()
    {
        super(109, “Set Object Location”);
    }

    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int id = RegisterFile.getValue(4);
        int x_loc = RegisterFile.getValue(5);
        int y_loc = RegisterFile.getValue(6);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“GameScreen has not been created!”);
            throw new ProcessingException();
        }
        GameObject obj = game.getGameObject(id);
        if (obj == null)
        {
            SystemIO.printString(“GameObject: id=” + id + ” does not exist!”);
            throw new ProcessingException();
        }

        obj.setLocations(x_loc, y_loc);
    }

}

SyscallInputDialogString

package mars.mips.instructions.syscalls;
public synchronized class SyscallInputDialogString extends AbstractSyscall {
public void SyscallInputDialogString();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallRandIntRange.java
mars/mips/instructions/syscalls/SyscallRandIntRange.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.simulator.*;
   import mars.*;
   import java.util.Random;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to return a random integer in a specified range.
 *
 */
 
    public class SyscallRandIntRange extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallRandIntRange() {
         super(42, “RandIntRange”);
      }
      
   /**
   * System call to the random number generator, with an upper range specified.
   * Return in $a0 the next pseudorandom, uniformly distributed int value between 0 (inclusive)
   * and the specified value (exclusive), drawn from this random number generator’s sequence.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Input arguments:
          //    $a0 = index of pseudorandom number generator
          //    $a1 = the upper bound of range of returned values.
          // Return: $a0 = the next pseudorandom, uniformly distributed int value from this
          // random number generator’s sequence.
         Integer index = new Integer(RegisterFile.getValue(4));
         Random stream = (Random) RandomStreams.randomStreams.get(index);
         if (stream == null) {
            stream = new Random(); // create a non-seeded stream
            RandomStreams.randomStreams.put(index, stream);
         } 
         try {
            RegisterFile.updateRegister(4, stream.nextInt( RegisterFile.getValue(5) ) );
         } 
             catch (IllegalArgumentException iae) {
               throw new ProcessingException(statement,
                       “Upper bound of range cannot be negative (syscall “+this.getNumber()+”)”,
                             Exceptions.SYSCALL_EXCEPTION);          
            }
      }
   
   }

SyscallGameGetObjSpeed

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameGetObjSpeed extends AbstractSyscall {
public void SyscallGameGetObjSpeed();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallGameSetObjDirection

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameSetObjDirection extends AbstractSyscall {
public void SyscallGameSetObjDirection();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallRandIntRange

package mars.mips.instructions.syscalls;
public synchronized class SyscallRandIntRange extends AbstractSyscall {
public void SyscallRandIntRange();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallSleep

package mars.mips.instructions.syscalls;
public synchronized class SyscallSleep extends AbstractSyscall {
public void SyscallSleep();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallGameIsClockwise

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameIsClockwise extends AbstractSyscall {
public void SyscallGameIsClockwise();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallGameToggleIsHooked.java
mars/mips/instructions/syscalls/SyscallGameToggleIsHooked.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.ActiveElementInterface;
import mars.ext.game.GameObject;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameToggleIsHooked extends AbstractSyscall
{
    
    public SyscallGameToggleIsHooked()
    {
        super(119, “Toggle isHooked”);
    }
    
    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int id = RegisterFile.getValue(4);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“GameScreen has not been created!”);
            throw new ProcessingException();
        }
        GameObject obj = game.getGameObject(id);
        if (obj == null)
        {
            SystemIO.printString(“GameObject: id=” + id + ” does not exist!”);
            throw new ProcessingException();
        }
        ActiveElementInterface ele = (ActiveElementInterface) obj;
        ele.toggleIsHooked();
    }
    
}

mars/mips/instructions/syscalls/Syscall.java
mars/mips/instructions/syscalls/Syscall.java   package mars.mips.instructions.syscalls;
    import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 *  Interface for any MIPS syscall system service.  A qualifying service
 *   must be a class in the mars.mips.instructions.syscalls package that 
 *  implements the Syscall interface, must be compiled into a .class file, 
 *  and its .class file must be in the same folder as Syscall.class.
 *  Mars will detect a qualifying syscall upon startup, create an instance 
 *  using its no-argument constructor and add it to its syscall list.  
 *  When its service is invoked at runtime (“syscall” instruction
 *  with its service number stored in register $v0), its simulate()
 *  method will be invoked.
 *
 */
 
    public interface Syscall {
   /**
   *  Return a name you have chosen for this syscall.  This can be used by a MARS
   *  user to refer to the service when choosing to override its default service
   *  number in the configuration file.
   *  @return service name as a string
   */
       public abstract String getName();
   
   /**
   * Set the service number.  This is provided to allow MARS implementer or user
   * to override the default service number.
   * @param num specified service number to override the default.
   */
       public abstract void setNumber(int num);
   
   /**
   * Return the assigned service number.  This is the number the MIPS programmer
   * must store into $v0 before issuing the SYSCALL instruction.
   * @return assigned service number
   */
       public abstract int getNumber();
   
   /**
   * Performs syscall function.  It will be invoked when the service is invoked
   * at simulation time.  Service is identified by value stored in $v0.
   * @param statement ProgramStatement for this syscall statement.
   */
       public abstract void simulate(ProgramStatement statement)
            throws ProcessingException;
   }

SyscallPrintIntUnsigned

package mars.mips.instructions.syscalls;
public synchronized class SyscallPrintIntUnsigned extends AbstractSyscall {
public void SyscallPrintIntUnsigned();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallPrintDouble

package mars.mips.instructions.syscalls;
public synchronized class SyscallPrintDouble extends AbstractSyscall {
public void SyscallPrintDouble();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallGameRefreshScreen.java
mars/mips/instructions/syscalls/SyscallGameRefreshScreen.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.GameScreen;
import mars.util.SystemIO;

public class SyscallGameRefreshScreen extends AbstractSyscall
{

    public SyscallGameRefreshScreen()
    {
        super(101, “Refresh Screen”);
    }

    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“In Creating Ship, but GameScreen has not been created first!”);
            throw new ProcessingException();
        }
        game.refreshScreen();
    }

}

SyscallPrintInt

package mars.mips.instructions.syscalls;
public synchronized class SyscallPrintInt extends AbstractSyscall {
public void SyscallPrintInt();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallRandSeed

package mars.mips.instructions.syscalls;
public synchronized class SyscallRandSeed extends AbstractSyscall {
public void SyscallRandSeed();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallGameHelper

package mars.mips.instructions.syscalls;
public final synchronized class SyscallGameHelper {
public static String getStringFromMIPS(int);
private void SyscallGameHelper();
}

SyscallMessageDialogDouble

package mars.mips.instructions.syscalls;
public synchronized class SyscallMessageDialogDouble extends AbstractSyscall {
public void SyscallMessageDialogDouble();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/ToneGenerator.java
mars/mips/instructions/syscalls/ToneGenerator.java
   package mars.mips.instructions.syscalls;
    

   import javax.sound.midi.*;
   import java.util.concurrent.locks.Lock;
   import java.util.concurrent.locks.ReentrantLock;
   import java.util.concurrent.Executor;
   import java.util.concurrent.Executors;

/*
Copyright (c) 2003-2007,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

    
  /////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  //
  //  The ToneGenerator and Tone classes were developed by Otterbein College
  //  student Tony Brock in July 2007.  They simulate MIDI output through the
  //  computers soundcard using classes and methods of the javax.sound.midi
  //  package.
  //
  //  Max Hailperin < > changed the interface of the
  //  ToneGenerator class 2009-10-19 in order to
  //  (1) provide a reliable way to wait for the completion of a
  //       synchronous tone,
  //  and while he was at it,
  //  (2) improve the efficiency of asynchronous tones by using a thread
  //      pool executor, and
  //  (3) simplify the interface by removing all the unused versions
  //       that provided default values for various parameters
  /////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////
  
  
   /*
    * Creates a Tone object and passes it to a thread to “play” it using MIDI.
    */
    class ToneGenerator {
      
      /**
      * The default pitch value for the tone: 60 / middle C.
      */    
      public final static byte DEFAULT_PITCH = 60;
      
      /**
      * The default duration of the tone: 1000 milliseconds.
      */    
      public final static int DEFAULT_DURATION = 1000;
      
      /**
      * The default instrument of the tone: 0 / piano.
      */          
      public final static byte DEFAULT_INSTRUMENT = 0;
      
      /**
      * The default volume of the tone: 100 (of 127).
      */          
      public final static byte DEFAULT_VOLUME = 100;

       private static Executor threadPool = Executors.newCachedThreadPool();
      
      /**
      * Produces a Tone with the specified pitch, duration, and instrument,
      * and volume.
      *
      * @param pitch the desired pitch in semitones – 0-127 where 60 is 
      * middle C.
      * @param duration the desired duration in milliseconds.
      * @param instrument the desired instrument (or patch) represented
      * by a positive byte value (0-127).  See the general 
      * MIDI instrument patch map for more instruments associated with
      * each value.
      * @param volume the desired volume of the initial attack of the 
      * Tone (MIDI velocity) represented by a positive byte value (0-127).
      */   
       public void generateTone(byte pitch, int duration,
                byte instrument, byte volume) {
         Runnable tone = new Tone(pitch, duration, instrument, volume);
         threadPool.execute(tone);
      }

      /**
      * Produces a Tone with the specified pitch, duration, and instrument,
      * and volume, waiting for it to finish playing.
      *
      * @param pitch the desired pitch in semitones – 0-127 where 60 is 
      * middle C.
      * @param duration the desired duration in milliseconds.
      * @param instrument the desired instrument (or patch) represented
      * by a positive byte value (0-127).  See the general 
      * MIDI instrument patch map for more instruments associated with
      * each value.
      * @param volume the desired volume of the initial attack of the 
      * Tone (MIDI velocity) represented by a positive byte value (0-127).
      */   
       public void generateToneSynchronously(byte pitch, int duration,
                         byte instrument, byte volume) {
         Runnable tone = new Tone(pitch, duration, instrument, volume);
         tone.run();
      }
      
   }
   
   
   /**
    * Contains important variables for a MIDI Tone: pitch, duration
    * instrument (patch), and volume.  The tone can be passed to a thread
    * and will be played using MIDI.
    */
    class Tone implements Runnable {
      
      /**
      * Tempo of the tone is in milliseconds: 1000 beats per second.
      */
      
      public final static int TEMPO = 1000;
      /**
      * The default MIDI channel of the tone: 0 (channel 1).
      */      
      public final static int DEFAULT_CHANNEL = 0;
      
      private byte pitch;
      private int duration;
      private byte instrument;
      private byte volume;
      
      /**
      * Instantiates a new Tone object, initializing the tone’s pitch,
      * duration, instrument (patch), and volume.
      *
      * @param pitch the pitch in semitones.  Pitch is represented by 
      * a positive byte value – 0-127 where 60 is middle C.
      * @param duration the duration of the tone in milliseconds.
      * @param instrument a positive byte value (0-127) which represents
      * the instrument (or patch) of the tone.  See the general 
      * MIDI instrument patch map for more instruments associated with
      * each value.
      * @param volume a positive byte value (0-127) which represents the
      * volume of the initial attack of the note (MIDI velocity).  127 being
      * loud, and 0 being silent.
      */ 
       public Tone(byte pitch, int duration, byte instrument, byte volume) {
         this.pitch = pitch;
         this.duration = duration;
         this.instrument = instrument;
         this.volume = volume;
      }
      
      /**
      * Plays the tone.
      */
       public void run() {
         playTone();
      }
      
       /* The following lock and the code which locks and unlocks it
    * around the opening of the Sequencer were added 2009-10-19 by
    * Max Hailperin < > in order to work around a
    * bug in Sun’s JDK which causes crashing if two threads race:
    * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6888117 .
    * This routinely manifested native-code crashes when tones
    * were played asynchronously, on dual-core machines with Sun’s
    * JDK (but not on one core or with OpenJDK).  Even when tones
    * were played only synchronously, crashes sometimes occurred.
    * This is likely due to the fact that Thread.sleep was used
    * for synchronization, a role it cannot reliably serve.  In
    * any case, this one lock seems to make all the crashes go
    * away, and the sleeps are being eliminated (since they can
    * cause other, less severe, problems), so that case should be
    * double covered. */ 

       private static Lock openLock = new ReentrantLock();

       private void playTone() {
         
         try {
        Sequencer player = null;
        openLock.lock();
        try {
           player = MidiSystem.getSequencer();
           player.open();
        } finally {
           openLock.unlock();
        }
            
            Sequence seq = new Sequence(Sequence.PPQ, 1);
            player.setTempoInMPQ(TEMPO);
            Track   t = seq.createTrack();
            
            //select instrument
            ShortMessage inst = new ShortMessage();
            inst.setMessage(ShortMessage.PROGRAM_CHANGE, DEFAULT_CHANNEL, instrument, 0);
            MidiEvent instChange = new MidiEvent(inst, 0);
            t.add(instChange);
              
            ShortMessage on = new ShortMessage();
            on.setMessage(ShortMessage.NOTE_ON, DEFAULT_CHANNEL, pitch, volume);
            MidiEvent noteOn = new MidiEvent(on, 0);
            t.add(noteOn);
               
            ShortMessage off = new ShortMessage();
            off.setMessage(ShortMessage.NOTE_OFF, DEFAULT_CHANNEL, pitch, volume);
            MidiEvent noteOff = new MidiEvent(off, duration);
            t.add(noteOff);
            
            player.setSequence(seq);

        /* The EndOfTrackListener was added 2009-10-19 by Max
         * Hailperin < > so that its
         * awaitEndOfTrack method could be used as a more reliable
         * replacement for Thread.sleep.  (Given that the tone
         * might not start playing right away, the sleep could end
         * before the tone, clipping off the end of the tone.) */
        EndOfTrackListener eot = new EndOfTrackListener();
        player.addMetaEventListener(eot);
            
            player.start();
            
            try {
               eot.awaitEndOfTrack();
            } 
                catch (InterruptedException ex) {
               }
            finally {
               player.close();
            }
            
         } 
             catch (MidiUnavailableException mue) {
               mue.printStackTrace();   
            } 
             catch (InvalidMidiDataException imde) {
               imde.printStackTrace();
            }
      }
   }

class EndOfTrackListener implements javax.sound.midi.MetaEventListener {

   private boolean endedYet = false;
   
   public synchronized void meta(javax.sound.midi.MetaMessage m){
      if(m.getType() == 47){
     endedYet = true;
     notifyAll();
      }
   }

   public synchronized void awaitEndOfTrack() throws InterruptedException {
      while(!endedYet){
     wait();
      }
   }
}

mars/mips/instructions/syscalls/SyscallTime.java
mars/mips/instructions/syscalls/SyscallTime.java   package mars.mips.instructions.syscalls;
   import mars.*;
   import mars.util.*;
    import mars.mips.hardware.*;

/*
Copyright (c) 2003-2007,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to read a character from input console into $a0.
 *
 */
 
    public class SyscallTime extends AbstractSyscall {
   /**
    * Build an instance of the Read Char syscall.  Default service number
    * is 12 and name is “ReadChar”.
    */
       public SyscallTime() {
         super(30, “Time”);
      }
      
   /**
   * Performs syscall function to place current system time into $a0 (low order 32 bits)
    * and $a1 (high order 32 bits).
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
            long value = new java.util.Date().getTime();
         RegisterFile.updateRegister(4, Binary.lowOrderLongToInt(value)); // $a0 
            RegisterFile.updateRegister(5, Binary.highOrderLongToInt(value)); // $a1
      }
   
   }

mars/mips/instructions/syscalls/SyscallPrintIntHex.java
mars/mips/instructions/syscalls/SyscallPrintIntHex.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.*;

/*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to display integer stored in $a0 on the console.
 *
 */
 
    public class SyscallPrintIntHex extends AbstractSyscall {
   /**
    * Build an instance of the Print Integer syscall.  Default service number
    * is 1 and name is “PrintInt”.
    */
       public SyscallPrintIntHex() {
         super(34, “PrintIntHex”);
      }
      
   /**
   * Performs syscall function to print on the console the integer stored in $a0, in hexadecimal format.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         SystemIO.printString(Binary.intToHexString(RegisterFile.getValue(4)));
      }
   }

mars/mips/instructions/syscalls/SyscallRandSeed.java
mars/mips/instructions/syscalls/SyscallRandSeed.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
    import mars.simulator.*;
   import mars.*;
   import java.util.Random;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to set seed for the underlying Java pseudorandom number generator. No values are returned.
 *
 */
 
    public class SyscallRandSeed extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallRandSeed() {
         super(40, “RandSeed”);
      }

   /**
   * Set the seed of the underlying Java pseudorandom number generator.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Arguments: $a0 = index of pseudorandom number generator
          //   $a1 = seed for pseudorandom number generator.
          // Result: No values are returned. Sets the seed of the underlying Java pseudorandom number generator.

          Integer index = new Integer(RegisterFile.getValue(4));
             Random stream = (Random) RandomStreams.randomStreams.get(index);
          if (stream == null) {
                RandomStreams.randomStreams.put(index, new Random(RegisterFile.getValue(5)));
             } else {
                stream.setSeed(RegisterFile.getValue(5));
             }
       }

   }

SyscallPrintFloat

package mars.mips.instructions.syscalls;
public synchronized class SyscallPrintFloat extends AbstractSyscall {
public void SyscallPrintFloat();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallGameSetObjPrice

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameSetObjPrice extends AbstractSyscall {
public void SyscallGameSetObjPrice();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallPrintInt.java
mars/mips/instructions/syscalls/SyscallPrintInt.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to display integer stored in $a0 on the console.
 *
 */
 
    public class SyscallPrintInt extends AbstractSyscall {
   /**
    * Build an instance of the Print Integer syscall.  Default service number
    * is 1 and name is “PrintInt”.
    */
       public SyscallPrintInt() {
         super(1, “PrintInt”);
      }
      
   /**
   * Performs syscall function to print on the console the integer stored in $a0.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         SystemIO.printString(
             new Integer(RegisterFile.getValue(4)).toString());
      }
   }

ToneGenerator

package mars.mips.instructions.syscalls;
synchronized class ToneGenerator {
public static final byte DEFAULT_PITCH = 60;
public static final int DEFAULT_DURATION = 1000;
public static final byte DEFAULT_INSTRUMENT = 0;
public static final byte DEFAULT_VOLUME = 100;
private static java.util.concurrent.Executor threadPool;
static void ();
void ToneGenerator();
public void generateTone(byte, int, byte, byte);
public void generateToneSynchronously(byte, int, byte, byte);
}

SyscallGameDestroyObject

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameDestroyObject extends AbstractSyscall {
public void SyscallGameDestroyObject();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

RandomStreams

package mars.mips.instructions.syscalls;
public synchronized class RandomStreams {
static final java.util.HashMap randomStreams;
static void ();
public void RandomStreams();
}

mars/mips/instructions/syscalls/SyscallMessageDialogDouble.java
mars/mips/instructions/syscalls/SyscallMessageDialogDouble.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
    import mars.simulator.*;
   import mars.*;
import javax.swing.JOptionPane;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Service to display a message to user.
 *
 */

    public class SyscallMessageDialogDouble extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallMessageDialogDouble() {
         super(58, “MessageDialogDouble”);
      }

   /**
   * System call to display a message to user.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Input arguments:
          //   $a0 = address of null-terminated string that is an information-type message to user
          //   $f12 = double value to display in string form after the first message
          // Output: none

         String message = new String(); // = “”;
         int byteAddress = RegisterFile.getValue(4);
         char ch[] = { ‘ ‘}; // Need an array to convert to String
         try
         {
            ch[0] = (char) Globals.memory.getByte(byteAddress);
            while (ch[0] != 0) // only uses single location ch[0]
            {
               message = message.concat(new String(ch)); // parameter to String constructor is a char[] array
               byteAddress++;
               ch[0] = (char) Globals.memory.getByte(byteAddress);
            }
         }
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }

            // Display the dialog.
            try
            {
            JOptionPane.showMessageDialog(null,
                  message + Double.toString(  Coprocessor1.getDoubleFromRegisterPair(“$f12”) ),
                  null,
                  JOptionPane.INFORMATION_MESSAGE );
            }
            
               catch (InvalidRegisterAccessException e)   // register ID error in this method
               {
                  RegisterFile.updateRegister(5, -1 );  // set $a1 to -1 flag
                   throw new ProcessingException(statement,
                       “invalid int reg. access during double input (syscall “+this.getNumber()+”)”,
                                   Exceptions.SYSCALL_EXCEPTION);
               }

       }

   }

SyscallGameSoundControl

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameSoundControl extends AbstractSyscall {
public void SyscallGameSoundControl();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallConfirmDialog.java
mars/mips/instructions/syscalls/SyscallConfirmDialog.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
    import mars.simulator.*;
   import mars.*;
import javax.swing.JOptionPane;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Service to display a message to user.
 *
 */

    public class SyscallConfirmDialog extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallConfirmDialog() {
         super(50, “ConfirmDialog”);
      }

   /**
   * System call to display a message to user.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Input arguments: $a0 = address of null-terminated string that is the message to user
          // Output: $a0 contains value of user-chosen option
          //   0: Yes
          //   1: No
          //   2: Cancel

         String message = new String(); // = “”;
         int byteAddress = RegisterFile.getValue(4);
         char ch[] = { ‘ ‘}; // Need an array to convert to String
         try
         {
            ch[0] = (char) Globals.memory.getByte(byteAddress);
            while (ch[0] != 0) // only uses single location ch[0]
            {
               message = message.concat(new String(ch)); // parameter to String constructor is a char[] array
               byteAddress++;
               ch[0] = (char) Globals.memory.getByte(byteAddress);
            }
         }
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }

            // update register $a0 with the value from showConfirmDialog.
            // showConfirmDialog returns an int with one of three possible values:
            //    0 —> meaning Yes
            //    1 —> meaning No
            //    2 —> meaning Cancel
            RegisterFile.updateRegister(4, JOptionPane.showConfirmDialog(null, message) );

       }

   }

SyscallExit

package mars.mips.instructions.syscalls;
public synchronized class SyscallExit extends AbstractSyscall {
public void SyscallExit();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallMessageDialogFloat.java
mars/mips/instructions/syscalls/SyscallMessageDialogFloat.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
    import mars.simulator.*;
   import mars.*;
import javax.swing.JOptionPane;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Service to display a message to user.
 *
 */

    public class SyscallMessageDialogFloat extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallMessageDialogFloat() {
         super(57, “MessageDialogFloat”);
      }

   /**
   * System call to display a message to user.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Input arguments:
          //   $a0 = address of null-terminated string that is an information-type message to user
          //   $f12 = float value to display in string form after the first message
          // Output: none

         String message = new String(); // = “”;
         int byteAddress = RegisterFile.getValue(4);
         char ch[] = { ‘ ‘}; // Need an array to convert to String
         try
         {
            ch[0] = (char) Globals.memory.getByte(byteAddress);
            while (ch[0] != 0) // only uses single location ch[0]
            {
               message = message.concat(new String(ch)); // parameter to String constructor is a char[] array
               byteAddress++;
               ch[0] = (char) Globals.memory.getByte(byteAddress);
            }
         }
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }

            // Display the dialog.
            JOptionPane.showMessageDialog(null,
                  message + Float.toString(  Coprocessor1.getFloatFromRegister(“$f12”) ),
                  null,
                  JOptionPane.INFORMATION_MESSAGE );
            

       }

   }

SyscallExit2

package mars.mips.instructions.syscalls;
public synchronized class SyscallExit2 extends AbstractSyscall {
public void SyscallExit2();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallReadInt.java
mars/mips/instructions/syscalls/SyscallReadInt.java   package mars.mips.instructions.syscalls;
    import mars.*;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.simulator.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to read an integer from input console into $v0.
 *
 */
 
    public class SyscallReadInt extends AbstractSyscall {
   /**
    * Build an instance of the Read Integer syscall.  Default service number
    * is 5 and name is “ReadInt”.
    */
       public SyscallReadInt() {
         super(5, “ReadInt”);
      }
      
   /**
   * Performs syscall function to read an integer from input console into $v0
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         int value = 0;
         try
         {
            value = SystemIO.readInteger(this.getNumber());
         } 
             catch (NumberFormatException e)
            {
               throw new ProcessingException(statement,
                 “invalid integer input (syscall “+this.getNumber()+”)”,
                      Exceptions.SYSCALL_EXCEPTION);
            }
         RegisterFile.updateRegister(2, value);
      }
   
   }

SyscallGameIsHooked

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameIsHooked extends AbstractSyscall {
public void SyscallGameIsHooked();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallInputDialogDouble.java
mars/mips/instructions/syscalls/SyscallInputDialogDouble.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
    import mars.simulator.*;
   import mars.*;
import javax.swing.JOptionPane;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Service to input data.
 *
 */

    public class SyscallInputDialogDouble extends AbstractSyscall {
   /**
    * Build an instance of the syscall with its default service number and name.
    */
       public SyscallInputDialogDouble() {
         super(53, “InputDialogDouble”);
      }

   /**
   * System call to input data.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
          // Input arguments: $a0 = address of null-terminated string that is the message to user
          // Outputs:
          //    $f0 and $f1 contains value of double read. $f1 contains high order word of the double.
          //    $a1 contains status value
          //       0: valid input data, correctly parsed
          //       -1: input data cannot be correctly parsed
          //       -2: Cancel was chosen
          //       -3: OK was chosen but no data had been input into field

         String message = new String(); // = “”;
         int byteAddress = RegisterFile.getValue(4);
         char ch[] = { ‘ ‘}; // Need an array to convert to String
         try
         {
            ch[0] = (char) Globals.memory.getByte(byteAddress);
            while (ch[0] != 0) // only uses single location ch[0]
            {
               message = message.concat(new String(ch)); // parameter to String constructor is a char[] array
               byteAddress++;
               ch[0] = (char) Globals.memory.getByte(byteAddress);
            }
         }
             catch (AddressErrorException e)
            {
               throw new ProcessingException(statement, e);
            }

            // Values returned by Java’s InputDialog:
            // A null return value means that “Cancel” was chosen rather than OK.
            // An empty string returned (that is, inputValue.length() of zero)
            // means that OK was chosen but no string was input.
            String inputValue = null;
            inputValue = JOptionPane.showInputDialog(message);
            
            try
            {
              Coprocessor1.setRegisterPairToDouble(0, 0.0);  // set $f0 to zero
              if (inputValue == null)  // Cancel was chosen
              {
                 RegisterFile.updateRegister(5, -2 );  // set $a1 to -2 flag
              }
              else if (inputValue.length() == 0)  // OK was chosen but there was no input
              {
                 RegisterFile.updateRegister(5, -3 );  // set $a1 to -3 flag
              }
              else
              {
                   double doubleValue = Double.parseDouble(inputValue);

                   // Successful parse of valid input data
                   Coprocessor1.setRegisterPairToDouble(0, doubleValue);  // set $f0 to input data
                   RegisterFile.updateRegister(5, 0 );  // set $a1 to valid flag
                   
              }

            } // end try block

               catch (InvalidRegisterAccessException e)   // register ID error in this method
               {
                  RegisterFile.updateRegister(5, -1 );  // set $a1 to -1 flag
                   throw new ProcessingException(statement,
                       “invalid int reg. access during double input (syscall “+this.getNumber()+”)”,
                                   Exceptions.SYSCALL_EXCEPTION);
               }

               catch ( NumberFormatException e)    // Unsuccessful parse of input data
               {
                   RegisterFile.updateRegister(5, -1 );  // set $a1 to -1 flag
                   /*  Don’t throw exception because returning a status flag
                   throw new ProcessingException(statement,
                      “invalid float input (syscall “+this.getNumber()+”)”,
                                  Exceptions.SYSCALL_EXCEPTION);
                   */
               }

       }

   }

SyscallGameGetLevelObjLocation

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameGetLevelObjLocation extends AbstractSyscall {
public void SyscallGameGetLevelObjLocation();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallExit2.java
mars/mips/instructions/syscalls/SyscallExit2.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.*;
   import mars.mips.hardware.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to exit the MIPS program with return value given in $a0.  Ignored if running from GUI.
 *
 */
 
    public class SyscallExit2 extends AbstractSyscall {
   /**
    * Build an instance of the Exit2 syscall.  Default service number
    * is 17 and name is “Exit2”.
    */
       public SyscallExit2() {
         super(17, “Exit2”);
      }
      
   /**
   * Performs syscall function to exit the MIPS program with return value given in $a0.
   * If running in command mode, MARS will exit with that value.  If running under GUI,
   * return value is ignored.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         if (Globals.getGui()==null) {
            Globals.exitCode = RegisterFile.getValue(4);
         }
         throw new ProcessingException(); // empty error list
      }
   }

mars/mips/instructions/syscalls/SyscallReadDouble.java
mars/mips/instructions/syscalls/SyscallReadDouble.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
    import mars.simulator.*;
   import mars.mips.hardware.*;
   import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to read the bits of console input double into $f0 and $f1.  
 * $f1 contains high order word of the double.
 */
 
    public class SyscallReadDouble extends AbstractSyscall {
   /**
    * Build an instance of the Read Double syscall.  Default service number
    * is 7 and name is “ReadDouble”.
    */
       public SyscallReadDouble() {
         super(7, “ReadDouble”);
      }
      
   /**
   * Performs syscall function to read the bits of input double into $f0 and $f1.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
      //  Higher numbered reg contains high order word so order is $f1 – $f0.
         double doubleValue = 0;
         try
         {
            doubleValue = SystemIO.readDouble(this.getNumber());
         } 
             catch (NumberFormatException e)
            {
               throw new ProcessingException(statement,
                   “invalid double input (syscall “+this.getNumber()+”)”,
                         Exceptions.SYSCALL_EXCEPTION);
            }
         long longValue = Double.doubleToRawLongBits(doubleValue);  
         Coprocessor1.updateRegister(1, Binary.highOrderLongToInt(longValue));
         Coprocessor1.updateRegister(0, Binary.lowOrderLongToInt(longValue));
      }
   }

SyscallPrintIntHex

package mars.mips.instructions.syscalls;
public synchronized class SyscallPrintIntHex extends AbstractSyscall {
public void SyscallPrintIntHex();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallWrite.java
mars/mips/instructions/syscalls/SyscallWrite.java   package mars.mips.instructions.syscalls;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.simulator.*;
   import mars.*;

/*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to write to file descriptor given in $a0.  $a1 specifies buffer
 * and $a2 specifies length.  Number of characters written is returned in $v0
 * (this was changed from $a0 in MARS 3.7 for SPIM compatibility.  The table
 * in COD erroneously shows $a0).
 *
 */
 
    public class SyscallWrite extends AbstractSyscall {
   /**
    * Build an instance of the Write file syscall.  Default service number
    * is 15 and name is “Write”.
    */
       public SyscallWrite() {
         super(15, “Write”);
      }
      
   /**
   * Performs syscall function to write to file descriptor given in $a0.  $a1 specifies buffer
   * and $a2 specifies length.  Number of characters written is returned in $v0, starting in MARS 3.7. 
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         int byteAddress = RegisterFile.getValue(5); // source of characters to write to file
         byte b = 0;
         int reqLength = RegisterFile.getValue(6); // user-requested length
         int index = 0;
         byte myBuffer[] = new byte[RegisterFile.getValue(6) + 1]; // specified length plus null termination
         try
         {
            b = (byte) Globals.memory.getByte(byteAddress);                            
            while (index < reqLength) // Stop at requested length. Null bytes are included.                                  // while (index < reqLength && b != 0) // Stop at requested length OR null byte             {                myBuffer[index++] = b;                byteAddress++;                b = (byte) Globals.memory.getByte(byteAddress);             }                                            myBuffer[index] = 0; // Add string termination          } // end try              catch (AddressErrorException e)             {                throw new ProcessingException(statement, e);             }          int retValue = SystemIO.writeToFile(                                  RegisterFile.getValue(4), // fd                                  myBuffer, // buffer                                  RegisterFile.getValue(6)); // length          RegisterFile.updateRegister(2, retValue); // set returned value in register          // Getting rid of processing exception.  It is the responsibility of the             // user program to check the syscall's return value.  MARS should not             // re-emptively terminate MIPS execution because of it.  Thanks to             // UCLA student Duy Truong for pointing this out.  DPS 28-July-2009          /*          if (retValue < 0) // some error in opening file          {             throw new ProcessingException(statement,                                     SystemIO.getFileErrorMessage());          }             */       }    } SyscallMessageDialogInt package mars.mips.instructions.syscalls; public synchronized class SyscallMessageDialogInt extends AbstractSyscall { public void SyscallMessageDialogInt(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } SyscallGameToggleIsClockwise package mars.mips.instructions.syscalls; public synchronized class SyscallGameToggleIsClockwise extends AbstractSyscall { public void SyscallGameToggleIsClockwise(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallGameSoundControl.java mars/mips/instructions/syscalls/SyscallGameSoundControl.javapackage mars.mips.instructions.syscalls; import mars.ProcessingException; import mars.ProgramStatement; import mars.ext.game.GameScreen; import mars.mips.hardware.RegisterFile; import mars.util.SystemIO; public class SyscallGameSoundControl extends AbstractSyscall {          public SyscallGameSoundControl()     {         super(102, "Sound Control");     }          @Override     public void simulate(ProgramStatement statement) throws ProcessingException     {         int soundId = RegisterFile.getValue(4);         int control = RegisterFile.getValue(5);         GameScreen game = GameScreen.getInstance();         if (game == null)         {             SystemIO.printString("GameScreen has not been created!");             throw new ProcessingException();         }         switch (control) {             case 0: // play             game.playSound(soundId, false);             break;             case 1: // loop indefinitely             game.playSound(soundId, true);             break;             case 2: // stop             game.stopSound(soundId);             break;             default:             break;         }     } } SyscallRandDouble package mars.mips.instructions.syscalls; public synchronized class SyscallRandDouble extends AbstractSyscall { public void SyscallRandDouble(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallClose.java mars/mips/instructions/syscalls/SyscallClose.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.mips.hardware.*;    import mars.*; /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**   * Service to close file descriptor given in $a0.  *  */       public class SyscallClose extends AbstractSyscall {    /**     * Build an instance of the Close syscall.  Default service number     * is 16 and name is "Close".     */        public SyscallClose() {          super(16, "Close");       }           /**    * Performs syscall function to close file descriptor given in $a0.    */        public void simulate(ProgramStatement statement) throws ProcessingException {          SystemIO.closeFile(RegisterFile.getValue(4));        }    } SyscallGameRefreshScreen package mars.mips.instructions.syscalls; public synchronized class SyscallGameRefreshScreen extends AbstractSyscall { public void SyscallGameRefreshScreen(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallSleep.java mars/mips/instructions/syscalls/SyscallSleep.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.mips.hardware.*;     import mars.simulator.*;    import mars.*; /* Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Service to cause the MARS Java thread to sleep for (at least) the specified number of milliseconds.  * This timing will not be precise as the Java implementation will add some overhead.  *  */     public class SyscallSleep extends AbstractSyscall {    /**     * Build an instance of the syscall with its default service number and name.     */        public SyscallSleep() {          super(32, "Sleep");       }    /**    * System call to cause the MARS Java thread to sleep for (at least) the specified number of milliseconds.    * This timing will not be precise as the Java implementation will add some overhead.    */        public void simulate(ProgramStatement statement) throws ProcessingException {           // Input arguments: $a0 is the length of time to sleep in milliseconds.                try                {                   Thread.sleep(RegisterFile.getValue(4)); // units of milliseconds  1000 millisec = 1 sec.                }                catch (InterruptedException e)                {                    return; // no exception handling                }        }    } SyscallGameSetObjLocation package mars.mips.instructions.syscalls; public synchronized class SyscallGameSetObjLocation extends AbstractSyscall { public void SyscallGameSetObjLocation(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } SyscallOpen package mars.mips.instructions.syscalls; public synchronized class SyscallOpen extends AbstractSyscall { public void SyscallOpen(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallRandInt.java mars/mips/instructions/syscalls/SyscallRandInt.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.mips.hardware.*;     import mars.simulator.*;    import mars.*;    import java.util.Random; /* Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Service to return a random integer.  *  */     public class SyscallRandInt extends AbstractSyscall {    /**     * Build an instance of the syscall with its default service number and name.     */        public SyscallRandInt() {          super(41, "RandInt");       }           /**    * System call to the random number generator.    * Return in $a0 the next pseudorandom, uniformly distributed int value from this random number generator's sequence.    */        public void simulate(ProgramStatement statement) throws ProcessingException {           // Input arguments: $a0 = index of pseudorandom number generator           // Return: $a0 = the next pseudorandom, uniformly distributed int value from this random number generator's sequence.           Integer index = new Integer(RegisterFile.getValue(4));              Random stream = (Random) RandomStreams.randomStreams.get(index);           if (stream == null) {                 stream = new Random(); // create a non-seeded stream                 RandomStreams.randomStreams.put(index, stream);              }               RegisterFile.updateRegister(4, stream.nextInt() );        }    } mars/mips/instructions/syscalls/SyscallGameGetLevelObjLocation.java mars/mips/instructions/syscalls/SyscallGameGetLevelObjLocation.javapackage mars.mips.instructions.syscalls; import mars.ProcessingException; import mars.ProgramStatement; import mars.ext.game.GameScreen; import mars.mips.hardware.RegisterFile; import mars.util.SystemIO; public class SyscallGameGetLevelObjLocation extends AbstractSyscall {     public SyscallGameGetLevelObjLocation()     {         super(104, "Get Game Level Object Location");     }     @Override     public void simulate(ProgramStatement statement) throws ProcessingException     {         GameScreen game = GameScreen.getInstance();         if (game == null)         {             SystemIO.printString("GameScreen has not been created!");             throw new ProcessingException();         }         int[] loc = game.getLevelObjectLocation();         RegisterFile.updateRegister(2, loc[0]);         RegisterFile.updateRegister(3, loc[1]);     } } SyscallMessageDialogFloat package mars.mips.instructions.syscalls; public synchronized class SyscallMessageDialogFloat extends AbstractSyscall { public void SyscallMessageDialogFloat(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } SyscallPrintIntBinary package mars.mips.instructions.syscalls; public synchronized class SyscallPrintIntBinary extends AbstractSyscall { public void SyscallPrintIntBinary(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } SyscallGameIsShoot package mars.mips.instructions.syscalls; public synchronized class SyscallGameIsShoot extends AbstractSyscall { public void SyscallGameIsShoot(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallGameSetObjPrice.java mars/mips/instructions/syscalls/SyscallGameSetObjPrice.javapackage mars.mips.instructions.syscalls; import mars.ProcessingException; import mars.ProgramStatement; import mars.ext.game.ActiveElementInterface; import mars.ext.game.GameObject; import mars.ext.game.GameScreen; import mars.mips.hardware.RegisterFile; import mars.util.SystemIO; public class SyscallGameSetObjPrice extends AbstractSyscall {     public SyscallGameSetObjPrice()     {         super(117, "Set Object Price");     }     @Override     public void simulate(ProgramStatement statement) throws ProcessingException     {         int id = RegisterFile.getValue(4);         int price = RegisterFile.getValue(5);         GameScreen game = GameScreen.getInstance();         if (game == null)         {             SystemIO.printString("GameScreen has not been created!");             throw new ProcessingException();         }         GameObject obj = game.getGameObject(id);         if (obj == null)         {             SystemIO.printString("GameObject: id=" + id + " does not exist!");             throw new ProcessingException();         }         ActiveElementInterface ele = (ActiveElementInterface) obj;         ele.setPrice(price);     } } SyscallReadFloat package mars.mips.instructions.syscalls; public synchronized class SyscallReadFloat extends AbstractSyscall { public void SyscallReadFloat(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } SyscallInputDialogInt package mars.mips.instructions.syscalls; public synchronized class SyscallInputDialogInt extends AbstractSyscall { public void SyscallInputDialogInt(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } SyscallInputDialogFloat package mars.mips.instructions.syscalls; public synchronized class SyscallInputDialogFloat extends AbstractSyscall { public void SyscallInputDialogFloat(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallGameGetObjSpeed.java mars/mips/instructions/syscalls/SyscallGameGetObjSpeed.javapackage mars.mips.instructions.syscalls; import mars.ProcessingException; import mars.ProgramStatement; import mars.ext.game.ActiveElementInterface; import mars.ext.game.GameObject; import mars.ext.game.GameScreen; import mars.mips.hardware.RegisterFile; import mars.util.SystemIO; public class SyscallGameGetObjSpeed extends AbstractSyscall {     public SyscallGameGetObjSpeed()     {         super(111, "Get Speed");     }     @Override     public void simulate(ProgramStatement statement) throws ProcessingException     {         int id = RegisterFile.getValue(4);         GameScreen game = GameScreen.getInstance();         if (game == null)         {             SystemIO.printString("GameScreen has not been created!");             throw new ProcessingException();         }         GameObject obj = game.getGameObject(id);         if (obj == null)         {             SystemIO.printString("GameObject: id=" + id + " does not exist!");             throw new ProcessingException();         }         ActiveElementInterface ele = (ActiveElementInterface) obj;         RegisterFile.updateRegister(2, ele.getSpeed());     } } mars/mips/instructions/syscalls/SyscallPrintDouble.java mars/mips/instructions/syscalls/SyscallPrintDouble.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.mips.hardware.*;    import mars.*; /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**   * Service to display double whose bits are stored in $f12 & $f13 onto the console.    * $f13 contains high order word of the double.  */       public class SyscallPrintDouble extends AbstractSyscall {    /**     * Build an instance of the Print Double syscall.  Default service number     * is 3 and name is "PrintDouble".     */        public SyscallPrintDouble() {          super(3, "PrintDouble");       }           /**    * Performs syscall function to print double whose bits are stored in $f12 & $f13.    */        public void simulate(ProgramStatement statement) throws ProcessingException {          // Note: Higher numbered reg contains high order word so concat 13-12.          SystemIO.printString(new Double(Double.longBitsToDouble(              Binary.twoIntsToLong(Coprocessor1.getValue(13),Coprocessor1.getValue(12))              )).toString());       }    } mars/mips/instructions/syscalls/SyscallRead.java mars/mips/instructions/syscalls/SyscallRead.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.mips.hardware.*;    import mars.simulator.*;    import mars.*; /* Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**   * Service to read from file descriptor given in $a0.  $a1 specifies buffer  * and $a2 specifies length.  Number of characters read is returned in $v0.  * (this was changed from $a0 in MARS 3.7 for SPIM compatibility.  The table  * in COD erroneously shows $a0). *  */       public class SyscallRead extends AbstractSyscall {    /**     * Build an instance of the Read file syscall.  Default service number     * is 14 and name is "Read".     */        public SyscallRead() {          super(14, "Read");       }           /**    * Performs syscall function to read from file descriptor given in $a0.  $a1 specifies buffer    * and $a2 specifies length.  Number of characters read is returned in $v0 (starting MARS 3.7).     */        public void simulate(ProgramStatement statement) throws ProcessingException {          int byteAddress = RegisterFile.getValue(5); // destination of characters read from file          byte b = 0;          int index = 0;          byte myBuffer[] = new byte[RegisterFile.getValue(6)]; // specified length          // Call to SystemIO.xxxx.read(xxx,xxx,xxx)  returns actual length          int retLength = SystemIO.readFromFile(                                  RegisterFile.getValue(4), // fd                                  myBuffer, // buffer                                  RegisterFile.getValue(6)); // length          RegisterFile.updateRegister(2, retLength); // set returned value in register          // Getting rid of processing exception.  It is the responsibility of the             // user program to check the syscall's return value.  MARS should not             // re-emptively terminate MIPS execution because of it.  Thanks to             // UCLA student Duy Truong for pointing this out.  DPS 28-July-2009          /*          if (retLength < 0) // some error in opening file          {             throw new ProcessingException(statement,                                     SystemIO.getFileErrorMessage()+" (syscall 14)",                                     Exceptions.SYSCALL_EXCEPTION);          }             */                          // copy bytes from returned buffer into MARS memory          try          {             while (index < retLength)             {                Globals.memory.setByte(byteAddress++,                                         myBuffer[index++]);             }          }               catch (AddressErrorException e)             {                throw new ProcessingException(statement, e);             }       }    } mars/mips/instructions/syscalls/SyscallGameIsClockwise.java mars/mips/instructions/syscalls/SyscallGameIsClockwise.javapackage mars.mips.instructions.syscalls; import mars.ProcessingException; import mars.ProgramStatement; import mars.ext.game.GameObject; import mars.ext.game.GameObjectHook; import mars.ext.game.GameScreen; import mars.mips.hardware.RegisterFile; import mars.util.SystemIO; public class SyscallGameIsClockwise extends AbstractSyscall {     public SyscallGameIsClockwise()     {         super(122, "Get isClockwise");     }     @Override     public void simulate(ProgramStatement statement) throws ProcessingException     {         int id = RegisterFile.getValue(4);         GameScreen game = GameScreen.getInstance();         if (game == null)         {             SystemIO.printString("GameScreen has not been created!");             throw new ProcessingException();         }         GameObject obj = game.getGameObject(id);         if (obj == null)         {             SystemIO.printString("GameObject: id=" + id                     + " does not exist!");             throw new ProcessingException();         }         if (obj instanceof GameObjectHook)         {             GameObjectHook hook = (GameObjectHook) obj;             RegisterFile.updateRegister(2, hook.isClockwise()? 1: 0);         }     } } mars/mips/instructions/syscalls/SyscallNumberOverride.java mars/mips/instructions/syscalls/SyscallNumberOverride.java   package mars.mips.instructions.syscalls;    import java.util.*;     import mars.util.*; /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Represents User override of default syscall number assignment.  * Such overrides are specified in the config.txt file read when  * MARS starts up.  */     public class SyscallNumberOverride {       private String serviceName;       private int newServiceNumber;                /**       * Constructor is called with two strings: service name and desired       * number.  Will throw an exception is number is malformed, but does        * not check validity of the service name or number.       * @param serviceName a String containing syscall service mnemonic.           * @param value a String containing its reassigned syscall service number.          * If this number is previously assigned to a different syscall which does not       * also receive a new number, then an error for duplicate numbers will       * be issued at MARS launch.       */                  public SyscallNumberOverride(String serviceName, String value) {          this.serviceName = serviceName;          try {             this.newServiceNumber = Integer.parseInt(value.trim());          }               catch (NumberFormatException e) {                System.out.println("Error processing Syscall number override: '"+value.trim()+"' is not a valid integer");                System.exit(0);                       }        }                   /**      * Get the service name as a String.      * @return the service name      */        public String getName() {          return serviceName;       }          /**      * Get the new service number as an int.      * @return the service number      */        public int getNumber() {          return newServiceNumber;       }        }             SyscallRead package mars.mips.instructions.syscalls; public synchronized class SyscallRead extends AbstractSyscall { public void SyscallRead(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } SyscallCreateGame package mars.mips.instructions.syscalls; public synchronized class SyscallCreateGame extends AbstractSyscall { public void SyscallCreateGame(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallGameDestroyObject.java mars/mips/instructions/syscalls/SyscallGameDestroyObject.javapackage mars.mips.instructions.syscalls; import mars.ProcessingException; import mars.ProgramStatement; import mars.ext.game.GameScreen; import mars.mips.hardware.RegisterFile; import mars.util.SystemIO; public class SyscallGameDestroyObject extends AbstractSyscall {     public SyscallGameDestroyObject()     {         super(107, "Destroy Object");     }     @Override     public void simulate(ProgramStatement statement) throws ProcessingException     {         int id = RegisterFile.getValue(4);         GameScreen game = GameScreen.getInstance();         if (game == null)         {             SystemIO.printString("GameScreen has not been created!");             throw new ProcessingException();         }         game.destroyGameObject(id);     } } SyscallNumberOverride package mars.mips.instructions.syscalls; public synchronized class SyscallNumberOverride { private String serviceName; private int newServiceNumber; public void SyscallNumberOverride(String, String); public String getName(); public int getNumber(); } SyscallGameGetObjLocation package mars.mips.instructions.syscalls; public synchronized class SyscallGameGetObjLocation extends AbstractSyscall { public void SyscallGameGetObjLocation(); public void simulate(mars.ProgramStatement) throws mars.ProcessingException; } mars/mips/instructions/syscalls/SyscallRandFloat.java mars/mips/instructions/syscalls/SyscallRandFloat.java   package mars.mips.instructions.syscalls;    import mars.util.*;    import mars.mips.hardware.*;    import mars.simulator.*;    import mars.*;    import java.util.Random; /* Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Service to return a random floating point value.  *  */     public class SyscallRandFloat extends AbstractSyscall {    /**     * Build an instance of the syscall with its default service number and name.     */        public SyscallRandFloat() {          super(43, "RandFloat");       }           /**    * System call to the random number generator.    * Return in $f0 the next pseudorandom, uniformly distributed float value between 0.0 and 1.0    * from this random number generator's sequence.    */        public void simulate(ProgramStatement statement) throws ProcessingException {           // Input arguments: $a0 = index of pseudorandom number generator           // Return: $f0 = the next pseudorandom, uniformly distributed float value between 0.0 and 1.0           // from this random number generator's sequence.          Integer index = new Integer(RegisterFile.getValue(4));          Random stream = (Random) RandomStreams.randomStreams.get(index);          if (stream == null) {             stream = new Random(); // create a non-seeded stream             RandomStreams.randomStreams.put(index, stream);          }           Coprocessor1.setRegisterToFloat(0, stream.nextFloat( ));       }    } mars/mips/instructions/syscalls/SyscallMidiOutSync.java mars/mips/instructions/syscalls/SyscallMidiOutSync.java   package mars.mips.instructions.syscalls;         import mars.util.*;    import mars.mips.hardware.*;    import mars.simulator.*;    import mars.*; /* Copyright (c) 2003-2007,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Modified 2009-10-19 by Max Hailperin < >
to use a specific method for synchronously generating
a tone, rather than using an asyncronous method followed
by a Thread.sleep, because sleeping isn’t a reliable
synchronization method — depending on thread scheduling,
the actual tone generation could have been delayed, in
which case the tone might still be playing when the
sleep ended.

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/** 
 * Service to output simulated MIDI tone to sound card.  The call does
 * not return until the tone duration has elapsed.  By contrast, syscall 31
 * (MidiOut) returns immediately upon generating the tone.
 *
 */
 
    public class SyscallMidiOutSync extends AbstractSyscall {
    
    // Endpoints of ranges for the three “byte” parameters.  The duration
    // parameter is limited at the high end only by the int range.
      static final int rangeLowEnd = 0;
      static final int rangeHighEnd = 127;
    
   /**
    * Build an instance of the MIDI (simulated) out syscall.  Default service number
    * is 33 and name is “MidiOutSync”.
    */
       public SyscallMidiOutSync() {
         super(33, “MidiOutSync”);
      }
      
   /**
   * Performs syscall function to send MIDI output to sound card.  The syscall does not
   * return until after the duration period ($a1) has elapsed.  This requires
   * four arguments in registers $a0 through $a3.
   * $a0 – pitch (note).  Integer value from 0 to 127, with 60 being middle-C on a piano.
   * $a1 – duration. Integer value in milliseconds.
   * $a2 – instrument.  Integer value from 0 to 127, with 0 being acoustic grand piano.
   * $a3 – volume.  Integer value from 0 to 127.
   * Default values, in case any parameters are outside the above ranges, are $a0=60, $a1=1000,
   * $a2=0, $a3=100.
   * See MARS documentation elsewhere or www.midi.org for more information.  Note that the pitch,
   * instrument and volume value ranges 0-127 are from javax.sound.midi; actual MIDI instruments
   * use the range 1-128.
   */
       public void simulate(ProgramStatement statement) throws ProcessingException {
         int pitch      = RegisterFile.getValue(4); // $a0
         int duration   = RegisterFile.getValue(5); // $a1
         int instrument = RegisterFile.getValue(6); // $a2
         int volume     = RegisterFile.getValue(7); // $a3
         if (pitch < rangeLowEnd || pitch > rangeHighEnd) pitch = ToneGenerator.DEFAULT_PITCH;
         if (duration < 0) duration = ToneGenerator.DEFAULT_DURATION;          if (instrument < rangeLowEnd || instrument > rangeHighEnd) instrument = ToneGenerator.DEFAULT_INSTRUMENT;
         if (volume < rangeLowEnd || volume > rangeHighEnd) volume = ToneGenerator.DEFAULT_VOLUME;
         new ToneGenerator().generateToneSynchronously( (byte) pitch, duration, (byte) instrument, (byte) volume);
      }
   
   }
    

mars/mips/instructions/syscalls/SyscallGameGetObjLocation.java
mars/mips/instructions/syscalls/SyscallGameGetObjLocation.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.GameObject;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameGetObjLocation extends AbstractSyscall
{

    public SyscallGameGetObjLocation()
    {
        super(108, “Get Object Location”);
    }

    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int id = RegisterFile.getValue(4);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“GameScreen has not been created!”);
            throw new ProcessingException();
        }
        GameObject obj = game.getGameObject(id);
        if (obj == null)
        {
            SystemIO.printString(“GameObject: id=” + id + ” does not exist!”);
            throw new ProcessingException();
        }
        RegisterFile.updateRegister(2, obj.getXLoc());
        RegisterFile.updateRegister(3, obj.getYLoc());
    }

}

SyscallGameGetObjPrice

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameGetObjPrice extends AbstractSyscall {
public void SyscallGameGetObjPrice();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

SyscallGameUpdateObjLocation

package mars.mips.instructions.syscalls;
public synchronized class SyscallGameUpdateObjLocation extends AbstractSyscall {
public void SyscallGameUpdateObjLocation();
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/instructions/syscalls/SyscallGameIsHooked.java
mars/mips/instructions/syscalls/SyscallGameIsHooked.javapackage mars.mips.instructions.syscalls;

import mars.ProcessingException;
import mars.ProgramStatement;
import mars.ext.game.ActiveElementInterface;
import mars.ext.game.GameObject;
import mars.ext.game.GameScreen;
import mars.mips.hardware.RegisterFile;
import mars.util.SystemIO;

public class SyscallGameIsHooked extends AbstractSyscall
{

    public SyscallGameIsHooked()
    {
        super(118, “Get isHooked”);
    }

    @Override
    public void simulate(ProgramStatement statement) throws ProcessingException
    {
        int id = RegisterFile.getValue(4);
        GameScreen game = GameScreen.getInstance();
        if (game == null)
        {
            SystemIO.printString(“GameScreen has not been created!”);
            throw new ProcessingException();
        }
        GameObject obj = game.getGameObject(id);
        if (obj == null)
        {
            SystemIO.printString(“GameObject: id=” + id + ” does not exist!”);
            throw new ProcessingException();
        }
        ActiveElementInterface ele = (ActiveElementInterface) obj;
        RegisterFile.updateRegister(2, ele.isHooked()? 1: 0);
    }

}

mars/mips/instructions/BasicInstruction.java
mars/mips/instructions/BasicInstruction.javapackage mars.mips.instructions;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Class to represent a basic instruction in the MIPS instruction set.
 * Basic instruction means it translates directly to a 32-bit binary machine
 * instruction.
 * 
 * @author Pete Sanderson and Ken Vollmar
 * @version August 2003
 */
public class BasicInstruction extends Instruction {

    private String instructionName;
    private BasicInstructionFormat instructionFormat;
    private String operationMask;
    private SimulationCode simulationCode;
    /**
     * BasicInstruction constructor.
     * 
     * @param example An example usage of the instruction, as a String.
     * @param instrFormat The format is R, I, I-branch or J.
     * @param operMask The opcode mask is a 32 character string that contains the opcode in binary in the appropriate bit positions and codes for operand positions (‘f’, ‘s’, ‘t’) in the remainding positions.
     * @param simCode The inline definition of an object and class which anonymously implements the SimulationCode interface.
     * @see SimulationCode
     **/
    /* codes for operand positions are:
     * f == First operand
     * s == Second operand
     * t == Third operand
     * example: “add rd,rs,rt” is R format with fields in this order: opcode, rs, rt, rd, shamt, funct.
     *          Its opcode is 0, shamt is 0, funct is 0x40.  Based on operand order, its mask is
     *          “000000ssssstttttfffff00000100000″, split into
     *          opcode |  rs   |  rt   |  rd   | shamt | funct
     *          000000 | sssss | ttttt | fffff | 00000 | 100000
     * This mask can be used at code generation time to map the assembly component to its
     * correct bit positions in the binary machine instruction.
     * It can also be used at runtime to match a binary machine instruction to the correct
     * instruction simulator — it needs to match all and only the 0’s and 1’s.
     */
    public BasicInstruction(String example, String description, BasicInstructionFormat instrFormat, 
                     String operMask, SimulationCode simCode) {
        this.exampleFormat = example;
        this.mnemonic = this.extractOperator(example);
        this.description = description;
        this.instructionFormat = instrFormat;
        this.operationMask = operMask.replaceAll(” “,””); // squeeze out any/all spaces
          if (operationMask.length() != Instruction.INSTRUCTION_LENGTH_BITS) {
                System.out.println(example+” mask not “+Instruction.INSTRUCTION_LENGTH_BITS+” bits!”);
                 }
        this.simulationCode = simCode;
    }
    
      // Temporary constructor so that instructions without description yet will compile.
    
        public BasicInstruction(String example, BasicInstructionFormat instrFormat, 
                     String operMask, SimulationCode simCode) {
                          this(example,””,instrFormat,operMask,simCode);
        }
        
      /**
       * Gets the 32-character operation mask.  Each mask position represents a 
       * bit position in the 32-bit machine instruction.  Operation codes and
       * unused bits are represented in the mask by 1’s and 0’s.  Operand codes
       * are represented by ‘f’, ‘s’, and ‘t’ for bits occupied by first, secon
       * and third operand, respectively.
       *
       * @return The 32 bit mask, as a String
       */
    public String getOperationMask() {
        return operationMask;
    }
    
      /**
       * Gets the operand format of the instruction.  MIPS defines 3 of these
       * R-format, I-format, and J-format.  R-format is all registers.  I-format
       * is address formed from register base with immediate offset.  J-format
       * is for jump destination addresses.  I have added one more:
       * I-branch-format, for branch destination addresses.  These are a variation
       * of the I-format in that the computed value is address relative to the 
       * Program Counter.  All four formats are represented by static objects.
       *
       * @return The machine instruction format, R, I, J or I-branch.
       */
    public BasicInstructionFormat getInstructionFormat() {
        return instructionFormat;
    }
    
    /**
     * Gets the SimulationCode object.  It is really an object of an anonymous
     * class that implements the SimulationCode interface.  Such an object has but one
     * method: Simulate().
     * 
     * @return the SimulationCode object for this instruction.
     * @see SimulationCode
     **/
     
    public SimulationCode getSimulationCode() {
        return simulationCode;
    }
}

InstructionSet$93

package mars.mips.instructions;
synchronized class InstructionSet$93 implements SimulationCode {
void InstructionSet$93(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$1

package mars.mips.instructions;
synchronized class InstructionSet$1 implements SimulationCode {
void InstructionSet$1(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$137

package mars.mips.instructions;
synchronized class InstructionSet$137 implements SimulationCode {
void InstructionSet$137(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$16

package mars.mips.instructions;
synchronized class InstructionSet$16 implements SimulationCode {
void InstructionSet$16(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

InstructionSet$53

package mars.mips.instructions;
synchronized class InstructionSet$53 implements SimulationCode {
void InstructionSet$53(InstructionSet);
public void simulate(mars.ProgramStatement) throws mars.ProcessingException;
}

mars/mips/hardware/Coprocessor0.java
mars/mips/hardware/Coprocessor0.java   package mars.mips.hardware;
   import mars.Globals;
   import java.util.*;

/*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
  *  Represents Coprocessor 0.  We will use only its interrupt/exception registers.
  *   @author   Pete Sanderson
  *   @version August 2005
  **/

    public class Coprocessor0 {
      /** Coprocessor register names
         */
        public static final int VADDR  = 8;
        public static final int STATUS = 12;
       public static final int CAUSE  = 13;
        public static final int EPC    = 14;
        
        public static final int EXCEPTION_LEVEL = 1;  // bit position in STATUS register
        // bits 8-15 (mask for interrupt levels) all set, bit 4 (user mode) set,
        // bit 1 (exception level) not set, bit 0 (interrupt enable) set.
        public static final int DEFAULT_STATUS_VALUE = 0x0000FF11;
        
      private static Register [] registers = 
          { new Register(“$8 (vaddr)”, 8, 0),  
            new Register(“$12 (status)”, 12, DEFAULT_STATUS_VALUE),
            new Register(“$13 (cause)”, 13, 0),  
            new Register(“$14 (epc)”, 14, 0)
           };
                                                          
     
    /**
      *  Method for displaying the register values for debugging.
      **/    
         
       public static void showRegisters(){
         for (int i=0; i< registers.length; i++){             System.out.println("Name: " + registers[i].getName());             System.out.println("Number: " + registers[i].getNumber());             System.out.println("Value: " + registers[i].getValue());                 System.out.println("");           }       }            /**       *  Sets the value of the register given to the value given.       *   @param n name of register to set the value of ($n, where n is reg number).       *   @param val The desired value for the register.           *   @return old value in register prior to update       **/             public static int updateRegister(String n, int val){            int oldValue = 0;          for (int i=0; i< registers.length; i++){             if(("$"+registers[i].getNumber()).equals(n) || registers[i].getName().equals(n)) {                    oldValue = registers[i].getValue();                registers[i].setValue(val);                break;             }          }             return oldValue;       }            /**       *  This method updates the register value who's number is num.       *   @param num Number of register to set the value of.       *   @param val The desired value for the register.           *   @return old value in register prior to update       **/        public static int updateRegister(int num, int val){          int old = 0;          for (int i=0; i< registers.length; i++){             if(registers[i].getNumber()== num) {                old = (Globals.getSettings().getBackSteppingEnabled())                         ? Globals.program.getBackStepper().addCoprocessor0Restore(num,registers[i].setValue(val))                         : registers[i].setValue(val);                break;             }          }          return old;             }              /**       *  Returns the value of the register who's number is num.       *   @param num The register number.       *   @return The value of the given register.  0 for non-implemented registers       **/             public static int getValue(int num){          for (int i=0; i< registers.length; i++){             if(registers[i].getNumber()== num) {                return registers[i].getValue();             }          }          return 0;       }                      /**           *  For getting the number representation of the register.           *   @param n The string formatted register name to look for.           *   @return The number of the register represented by the string. -1 if no match.           **/                        public static int getNumber(String n){          for (int i=0; i< registers.length; i++){             if(("$"+registers[i].getNumber()).equals(n) || registers[i].getName().equals(n)) {                return registers[i].getNumber();             }          }           return -1;            }            /**       *  For returning the set of registers.       *   @return The set of registers.       **/             public static Register[] getRegisters(){          return registers;       }            /**       *  Coprocessor0 implements only selected registers, so the register number           *  (8, 12, 13, 14) does not correspond to its position in the list of registers           *  (0, 1, 2, 3).             *   @param r A coprocessor0 Register       *   @return the list position of given register, -1 if not found.       **/             public static int getRegisterPosition(Register r){          for (int i=0; i< registers.length; i++){             if(registers[i]==r) {                return i;             }          }           return -1;       }            /**       *  Get register object corresponding to given name.  If no match, return null.       *   @param rname The register name,  in $0 format.       *   @return The register object,or null if not found.       **/             public static Register getRegister(String rname) {          for (int i=0; i< registers.length; i++){             if(("$"+registers[i].getNumber()).equals(rname) || registers[i].getName().equals(rname)) {                return registers[i];             }          }           return null;       }             /**       *  Method to reinitialize the values of the registers.       **/             public static void resetRegisters(){          for(int i=0; i< registers.length; i++){             registers[i].resetValue();          }       }              /**      *  Each individual register is a separate object and Observable.  This handy method      *  will add the given Observer to each one.        */        public static void addRegistersObserver(Observer observer) {          for (int i=0; i= 0 && reg < registers.length) {             registers[reg].setValue(Float.floatToRawIntBits(val));          }       }         /**       *  Sets the value of the FPU register given to the 32-bit       *  pattern given by the int parameter.       *   @param reg Register to set the value of.       *   @param val The desired int bit pattern for the register.       **/             public static void setRegisterToInt(String reg, int val){          setRegisterToInt(getRegisterNumber(reg), val);       }             /**       *  Sets the value of the FPU register given to the 32-bit       *  pattern given by the int parameter.       *   @param reg Register to set the value of.       *   @param val The desired int bit pattern for the register.       **/               public static void setRegisterToInt(int reg, int val){          if(reg >= 0 && reg < registers.length) {             registers[reg].setValue(val);          }       }             /**       *  Sets the value of the FPU register given to the double value given.  The register       *  must be even-numbered, and the low order 32 bits are placed in it.  The high order       *  32 bits are placed in the (odd numbered) register that follows it.       *   @param reg Register to set the value of.       *   @param val The desired double value for the register.       *   @throws InvalidRegisterAccessException if register ID is invalid or odd-numbered.       **/             public static void setRegisterPairToDouble(int reg, double val)                                      throws InvalidRegisterAccessException {          if (reg % 2 != 0) {             throw new InvalidRegisterAccessException();          }           long bits = Double.doubleToRawLongBits(val);           registers[reg+1].setValue(Binary.highOrderLongToInt(bits));  // high order 32 bits          registers[reg].setValue(Binary.lowOrderLongToInt(bits)); // low order 32 bits       }             /**       *  Sets the value of the FPU register given to the double value given.  The register       *  must be even-numbered, and the low order 32 bits are placed in it.  The high order       *  32 bits are placed in the (odd numbered) register that follows it.       *   @param reg Register to set the value of.       *   @param val The desired double value for the register.       *   @throws InvalidRegisterAccessException if register ID is invalid or odd-numbered.       **/           public static void setRegisterPairToDouble(String reg, double val)                                              throws InvalidRegisterAccessException {          setRegisterPairToDouble(getRegisterNumber(reg), val);       }              /**       *  Sets the value of the FPU register pair given to the long value containing 64 bit pattern       *  given.  The register       *  must be even-numbered, and the low order 32 bits from the long are placed in it.  The high order       *  32 bits from the long are placed in the (odd numbered) register that follows it.       *   @param reg Register to set the value of.  Must be even register of even/odd pair.       *   @param val The desired double value for the register.       *   @throws InvalidRegisterAccessException if register ID is invalid or odd-numbered.       **/             public static void setRegisterPairToLong(int reg, long val)                                      throws InvalidRegisterAccessException {          if (reg % 2 != 0) {             throw new InvalidRegisterAccessException();          }           registers[reg+1].setValue(Binary.highOrderLongToInt(val));  // high order 32 bits          registers[reg].setValue(Binary.lowOrderLongToInt(val)); // low order 32 bits       }             /**       *  Sets the value of the FPU register pair given to the long value containing 64 bit pattern       *  given.  The register       *  must be even-numbered, and the low order 32 bits from the long are placed in it.  The high order       *  32 bits from the long are placed in the (odd numbered) register that follows it.       *   @param reg Register to set the value of.  Must be even register of even/odd pair.       *   @param val The desired long value containing the 64 bits for the register pair.       *   @throws InvalidRegisterAccessException if register ID is invalid or odd-numbered.       **/           public static void setRegisterPairToLong(String reg, long val)                                              throws InvalidRegisterAccessException {          setRegisterPairToLong(getRegisterNumber(reg), val);       }                  /**       *  Gets the float value stored in the given FPU register.       *   @param reg Register to get the value of.       *   @return The  float value stored by that register.       **/             public static float getFloatFromRegister(int reg){          float result = 0F;          if(reg >= 0 && reg < registers.length) {             result = Float.intBitsToFloat(registers[reg].getValue());          }          return result;       }               /**       *  Gets the float value stored in the given FPU register.       *   @param reg Register to get the value of.       *   @return The  float value stored by that register.       **/                     public static float getFloatFromRegister(String reg) {          return getFloatFromRegister(getRegisterNumber(reg));       }             /**       *  Gets the 32-bit int bit pattern stored in the given FPU register.       *   @param reg Register to get the value of.       *   @return The int bit pattern stored by that register.       **/             public static int getIntFromRegister(int reg){          int result = 0;          if(reg >= 0 && reg < registers.length) {             result = registers[reg].getValue();          }          return result;       }               /**       *  Gets the 32-bit int bit pattern stored in the given FPU register.       *   @param reg Register to get the value of.       *   @return The int bit pattern stored by that register.       **/                     public static int getIntFromRegister(String reg) {          return getIntFromRegister(getRegisterNumber(reg));       }              /**       *  Gets the double value stored in the given FPU register.  The register       *  must be even-numbered.       *   @param reg Register to get the value of. Must be even number of even/odd pair.       *   @throws InvalidRegisterAccessException if register ID is invalid or odd-numbered.       **/             public static double getDoubleFromRegisterPair(int reg)                                      throws InvalidRegisterAccessException {          double result = 0.0;          if (reg % 2 != 0) {             throw new InvalidRegisterAccessException();          }           long bits = Binary.twoIntsToLong(registers[reg+1].getValue(),registers[reg].getValue());          return Double.longBitsToDouble(bits);       }             /**       *  Gets the double value stored in the given FPU register.  The register       *  must be even-numbered.       *   @param reg Register to get the value of. Must be even number of even/odd pair.       *   @throws InvalidRegisterAccessException if register ID is invalid or odd-numbered.       **/                public static double getDoubleFromRegisterPair(String reg)                                     throws InvalidRegisterAccessException {          return getDoubleFromRegisterPair(getRegisterNumber(reg));       }                   /**       *  Gets a long representing the double value stored in the given double       *  precision FPU register.        *  The register must be even-numbered.       *   @param reg Register to get the value of. Must be even number of even/odd pair.       *   @throws InvalidRegisterAccessException if register ID is invalid or odd-numbered.       **/             public static long getLongFromRegisterPair(int reg)                                      throws InvalidRegisterAccessException {          double result = 0.0;          if (reg % 2 != 0) {             throw new InvalidRegisterAccessException();          }           return Binary.twoIntsToLong(registers[reg+1].getValue(),registers[reg].getValue());       }             /**       *  Gets the double value stored in the given FPU register.  The register       *  must be even-numbered.       *   @param reg Register to get the value of. Must be even number of even/odd pair.       *   @throws InvalidRegisterAccessException if register ID is invalid or odd-numbered.       **/                public static long getLongFromRegisterPair(String reg)                                     throws InvalidRegisterAccessException {          return getLongFromRegisterPair(getRegisterNumber(reg));       }               /**       *  This method updates the FPU register value who's number is num.  Note the       *  registers themselves hold an int value.  There are helper methods available       *  to which you can give a float or double to store.       *   @param num FPU register to set the value of.       *   @param val The desired int value for the register.       **/               public static int updateRegister(int num, int val){          int old = 0;          for (int i=0; i< registers.length; i++){             if(registers[i].getNumber()== num) {                old = (Globals.getSettings().getBackSteppingEnabled())                         ? Globals.program.getBackStepper().addCoprocessor1Restore(num,registers[i].setValue(val))                         : registers[i].setValue(val);                break;             }          }          return old;       }              /**       *  Returns the value of the FPU register who's number is num.  Returns the       *  raw int value actually stored there.  If you need a float, use       *  Float.intBitsToFloat() to get the equivent float.       *   @param num The FPU register number.       *   @return The int value of the given register.       **/             public static int getValue(int num){          return registers[num].getValue();       }                      /**           *  For getting the number representation of the FPU register.           *   @param n The string formatted register name to look for.           *   @return The number of the register represented by the string.           **/                        public static int getRegisterNumber(String n){          int j=-1;          for (int i=0; i< registers.length; i++){             if(registers[i].getName().equals(n)) {                j= registers[i].getNumber();                break;             }          }           return j;            }            /**       *  For returning the set of registers.       *   @return The set of registers.       **/             public static Register[] getRegisters(){          return registers;       }            /**       *  Get register object corresponding to given name.  If no match, return null.       *   @param rName The FPU register name, must be "$f0" through "$f31".       *   @return The register object,or null if not found.       **/             public static Register getRegister(String rName) {          Register reg = null;          if (rName.charAt(0) == '$' && rName.length() > 1 && rName.charAt(1) == ‘f’) {
            try {
                   // check for register number 0-31.
               reg = registers[Binary.stringToInt(rName.substring(2))];    // KENV 1/6/05
            }
                catch (Exception e) {
                   // handles both NumberFormat and ArrayIndexOutOfBounds
                  reg = null; 
               }
         }
         return reg;
      }
   
    
    /**
      *  Method to reinitialize the values of the registers.
      **/
    
       public static void resetRegisters(){
         for(int i=0; i < registers.length; i++)             registers[i].resetValue();          clearConditionFlags();       }                  /**      *  Each individual register is a separate object and Observable.  This handy method      *  will add the given Observer to each one.        */        public static void addRegistersObserver(Observer observer) {          for (int i=0; i= 0 && flag < numConditionFlags) {             old = getConditionFlag(flag);             condition.setValue(Binary.setBit(condition.getValue(),flag));             if (Globals.getSettings().getBackSteppingEnabled())                if (old==0) {                   Globals.program.getBackStepper().addConditionFlagClear(flag);                }                 else {                   Globals.program.getBackStepper().addConditionFlagSet(flag);                }          }          return old;       }         /**      *  Set condition flag to 0 (false).      *      *  @param flag condition flag number (0-7)      *  @return previous flag setting (0 or 1)      */        public static int clearConditionFlag(int flag) {          int old = 0;          if (flag >= 0 && flag < numConditionFlags) {             old = getConditionFlag(flag);             condition.setValue(Binary.clearBit(condition.getValue(),flag));             if (Globals.getSettings().getBackSteppingEnabled())                if (old==0) {                   Globals.program.getBackStepper().addConditionFlagClear(flag);                }                 else {                   Globals.program.getBackStepper().addConditionFlagSet(flag);                }          }          return old;       }              /**      *  Get value of specified condition flag (0-7).      *      *  @param flag condition flag number (0-7)      *  @return 0 if condition is false, 1 if condition is true      */        public static int getConditionFlag(int flag) {          if (flag < 0 || flag >= numConditionFlags) 
            flag = 0;
         return Binary.bitValue(condition.getValue(), flag);
      }     
    
    
    /**
     *  Get array of condition flags (0-7).
     *
     *  @return array of int condition flags
     */
       public static int getConditionFlags() {
         return condition.getValue();
      } 
    
    
    /**
     *  Clear all condition flags (0-7).
     *
     */
       public static void clearConditionFlags() {
         condition.setValue(0);  // sets all 32 bits to 0.
      }     
    
      /**
     *  Set all condition flags (0-7).
     *
     */
       public static void setConditionFlags() {
         condition.setValue(-1);  // sets all 32 bits to 1.
      } 
    
      /**
     *  Get count of condition flags.
     *
     *  @return number of condition flags
     */
       public static int getConditionFlagCount() {
         return numConditionFlags;        
      } 
   }

MemoryAccessNotice

package mars.mips.hardware;
public synchronized class MemoryAccessNotice extends AccessNotice {
private int address;
private int length;
private int value;
void MemoryAccessNotice(int, int, int, int);
void MemoryAccessNotice(int, int, int);
public int getAddress();
public int getLength();
public int getValue();
public String toString();
}

Coprocessor0

package mars.mips.hardware;
public synchronized class Coprocessor0 {
public static final int VADDR = 8;
public static final int STATUS = 12;
public static final int CAUSE = 13;
public static final int EPC = 14;
public static final int EXCEPTION_LEVEL = 1;
public static final int DEFAULT_STATUS_VALUE = 65297;
private static Register[] registers;
static void ();
public void Coprocessor0();
public static void showRegisters();
public static int updateRegister(String, int);
public static int updateRegister(int, int);
public static int getValue(int);
public static int getNumber(String);
public static Register[] getRegisters();
public static int getRegisterPosition(Register);
public static Register getRegister(String);
public static void resetRegisters();
public static void addRegistersObserver(java.util.Observer);
public static void deleteRegistersObserver(java.util.Observer);
}

mars/mips/hardware/AccessNotice.java
mars/mips/hardware/AccessNotice.javapackage mars.mips.hardware;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Object provided to Observers of runtime access to MIPS memory or registers.
 * The access types READ and WRITE defined here; use subclasses defined for
 * MemoryAccessNotice and RegisterAccessNotice.  This is abstract class.
 * 
 * @author Pete Sanderson 
 * @version July 2005
 */

public abstract class AccessNotice {
 /** Indicates the purpose of access was to read. */
   public static final int READ  = 0;
 /** Indicates the purpose of access was to write. */
    public static final int WRITE = 1;
    
    private int accessType;
    private Thread thread;
    
    protected AccessNotice(int type) {
       if (type != READ && type != WRITE) {
           throw new IllegalArgumentException();
        }
        accessType = type;
        thread = Thread.currentThread();
    }
    /** Get the access type: READ or WRITE.  
     * @return Access type, either AccessNotice.READ or AccessNotice.WRITE
     */
    public int getAccessType() {
       return accessType;
    }
    
    /** Get reference to thread that created this notice 
     * @return Return reference to the thread that created this notice.
     */
    public Thread getThread() {
       return thread;
    }

    /** Query whether the access originated from MARS GUI (AWT event queue)
     * @return true if this access originated from MARS GUI, false otherwise
     */
     // ‘A’ is the first character of the main AWT event queue thread name.
     // “AWT-EventQueue-0”
    public boolean accessIsFromGUI() {
       return thread.getName().startsWith(“AWT”);
    }   
    
    /** Query whether the access originated from executing MIPS program
     * @return true if this access originated from executing MIPS program, false otherwise
     */
     // Thread to execute the MIPS program is instantiated in SwingWorker.java.
     // There it is given the name “MIPS” to replace the default “Thread-x”. 
    public boolean accessIsFromMIPS() {
       return thread.getName().startsWith(“MIPS”);
    }   
    
}

RegisterFile

package mars.mips.hardware;
public synchronized class RegisterFile {
public static final int GLOBAL_POINTER_REGISTER = 28;
public static final int STACK_POINTER_REGISTER = 29;
private static Register[] regFile;
private static Register programCounter;
private static Register hi;
private static Register lo;
static void ();
public void RegisterFile();
public static void showRegisters();
public static int updateRegister(int, int);
public static void updateRegister(String, int);
public static int getValue(int);
public static int getNumber(String);
public static Register[] getRegisters();
public static Register getUserRegister(String);
public static void initializeProgramCounter(int);
public static void initializeProgramCounter(boolean);
public static int setProgramCounter(int);
public static int getProgramCounter();
public static Register getProgramCounterRegister();
public static int getInitialProgramCounter();
public static void resetRegisters();
public static void incrementPC();
public static void addRegistersObserver(java.util.Observer);
public static void deleteRegistersObserver(java.util.Observer);
}

Register

package mars.mips.hardware;
public synchronized class Register extends java.util.Observable {
private String name;
private int number;
private int resetValue;
private volatile int value;
public void Register(String, int, int);
public String getName();
public synchronized int getValue();
public synchronized int getValueNoNotify();
public int getResetValue();
public int getNumber();
public synchronized int setValue(int);
public synchronized void resetValue();
public synchronized void changeResetValue(int);
private void notifyAnyObservers(int);
}

MemoryConfigurations

package mars.mips.hardware;
public synchronized class MemoryConfigurations {
private static java.util.ArrayList configurations;
private static MemoryConfiguration defaultConfiguration;
private static MemoryConfiguration currentConfiguration;
private static final String[] configurationItemNames;
private static int[] defaultConfigurationItemValues;
private static int[] dataBasedCompactConfigurationItemValues;
private static int[] textBasedCompactConfigurationItemValues;
static void ();
public void MemoryConfigurations();
public static void buildConfigurationCollection();
public static java.util.Iterator getConfigurationsIterator();
public static MemoryConfiguration getConfigurationByName(String);
public static MemoryConfiguration getDefaultConfiguration();
public static MemoryConfiguration getCurrentConfiguration();
public static boolean setCurrentConfiguration(MemoryConfiguration);
public static int getDefaultTextBaseAddress();
public static int getDefaultDataSegmentBaseAddress();
public static int getDefaultExternBaseAddress();
public static int getDefaultGlobalPointer();
public static int getDefaultDataBaseAddress();
public static int getDefaultHeapBaseAddress();
public static int getDefaultStackPointer();
public static int getDefaultStackBaseAddress();
public static int getDefaultUserHighAddress();
public static int getDefaultKernelBaseAddress();
public static int getDefaultKernelTextBaseAddress();
public static int getDefaultExceptionHandlerAddress();
public static int getDefaultKernelDataBaseAddress();
public static int getDefaultMemoryMapBaseAddress();
public static int getDefaultKernelHighAddress();
public int getDefaultDataSegmentLimitAddress();
public int getDefaultTextLimitAddress();
public int getDefaultKernelDataSegmentLimitAddress();
public int getDefaultKernelTextLimitAddress();
public int getDefaultStackLimitAddress();
public int getMemoryMapLimitAddress();
}

mars/mips/hardware/MemoryConfiguration.java
mars/mips/hardware/MemoryConfiguration.java   package mars.mips.hardware;

/*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Models the memory configuration for the simulated MIPS machine.
 * “configuration” refers to the starting memory addresses for
 * the various memory segments.
 * The default configuration is based on SPIM.  Starting with MARS 3.7,
 * the configuration can be changed.  
 * 
 * @author Pete Sanderson 
 * @version August 2009
 */

    public class MemoryConfiguration {
       // Identifier is used for saving setting; name is used for display
      private String configurationIdentifier, configurationName;
      private String[] configurationItemNames;
      private int[] configurationItemValues;
    
   
       public MemoryConfiguration(String ident, String name, String[] items, int[] values) {
           this.configurationIdentifier = ident;
         this.configurationName = name;
         this.configurationItemNames = items;
         this.configurationItemValues = values;
      }
    
    public String getConfigurationIdentifier() {
           return configurationIdentifier;
       }
        
       public String getConfigurationName() {
         return configurationName;
      }
   
       public int[] getConfigurationItemValues() {
         return configurationItemValues;
      }
    
       public String[] getConfigurationItemNames() {
         return configurationItemNames;
      }
            
       public int getTextBaseAddress() {
         return configurationItemValues[0];
      }
        
       public int getDataSegmentBaseAddress() {
         return configurationItemValues[1];
      }
        
       public int getExternBaseAddress() {
         return configurationItemValues[2];
      }
           
       public int getGlobalPointer() {
         return configurationItemValues[3];
      }
   
       public int getDataBaseAddress() {
         return configurationItemValues[4];
      }
   
       public int getHeapBaseAddress() {
         return configurationItemValues[5];
      }
   
       public int getStackPointer() {
         return configurationItemValues[6];
      }
   
       public int getStackBaseAddress() {
         return configurationItemValues[7];
      }
   
       public int getUserHighAddress() {
         return configurationItemValues[8];
      }
   
       public int getKernelBaseAddress() {
         return configurationItemValues[9];
      }
   
       public int getKernelTextBaseAddress() {
         return configurationItemValues[10];
      }
   
       public int getExceptionHandlerAddress() {
         return configurationItemValues[11];
      }
   
       public int getKernelDataBaseAddress() {
         return configurationItemValues[12];
      }
   
       public int getMemoryMapBaseAddress() {
         return configurationItemValues[13];
      }
   
       public int getKernelHighAddress () {
         return configurationItemValues[14];
      }
      
       public int getDataSegmentLimitAddress() {
         return configurationItemValues[15];
      }
      
       public int getTextLimitAddress() {
         return configurationItemValues[16];
      }
      
       public int getKernelDataSegmentLimitAddress() {
         return configurationItemValues[17];
      }
      
       public int getKernelTextLimitAddress() {
         return configurationItemValues[18];
      }
      
       public int getStackLimitAddress() {
         return configurationItemValues[19];
      }
      
       public int getMemoryMapLimitAddress() {
         return configurationItemValues[20];
      }   
   
   }

mars/mips/hardware/Register.java
mars/mips/hardware/Register.java   package mars.mips.hardware;
   import mars.*;
   import java.util.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

     /**
      *  Abstraction to represent a register of a MIPS Assembler.
      *   @author Jason Bumgarner, Jason Shrewsbury, Ben Sherman
      *   @version June 2003
      **/    
    
    public class Register extends Observable {
      private String name;
      private int number, resetValue;
    // volatile should be enough to allow safe multi-threaded access  
    // w/o the use of synchronized methods.  getValue and setValue
    // are the only methods here used by the register collection
    // (RegisterFile, Coprocessor0, Coprocessor1) methods. 
      private volatile int value;
      
     /**
        *  Creates a new register with specified name, number, and value.
        *   @param n The name of the register.
        *   @param num The number of the register.
        *   @param val The inital (and reset) value of the register.
        */
      
       public Register(String n, int num, int val){
         name= n;
         number=num;
         value= val;
         resetValue = val;
      }
      
    /**
        *  Returns the name of the Register.
        *   @return name The name of the Register.
      */
      
       public String getName(){
         return name;
      }
      
      /**
      *  Returns the value of the Register.  Observers are notified
          *  of the READ operation.
      *   @return value The value of the Register.
      */
      
       public synchronized int getValue(){
         notifyAnyObservers(AccessNotice.READ);
         return value;
      }

      
      /**
      *  Returns the value of the Register.  Observers are not notified.
          *  Added for release 3.8.
      *   @return value The value of the Register.
      */
      
       public synchronized int getValueNoNotify(){
         return value;
      }
        
   
    /**
      *  Returns the reset value of the Register.
      *   @return The reset (initial) value of the Register.
      */
      
       public int getResetValue(){
         return resetValue;
      }     
    /**
      *  Returns the number of the Register.
      *   @return number The number of the Register.
      */
      
       public int getNumber(){
         return number;
      }
      
    /**
      *  Sets the value of the register to the val passed to it.
          *  Observers are notified of the WRITE operation.  
      *   @param val Value to set the Register to.
      *   @return previous value of register
      */
      
       public synchronized int setValue(int val){
         int old = value;
         value = val;
         notifyAnyObservers(AccessNotice.WRITE);
         return old;
      }
    
    /**
      *  Resets the value of the register to the value it was constructed with.
      *  Observers are not notified.  
      */
      
       public synchronized void resetValue(){
         value = resetValue;
      }
    
    /**
     *  Change the register’s reset value; the value to which it will be
     *  set when resetValue() is called.
     */
     
       public synchronized void changeResetValue(int reset) {
         resetValue = reset;
      }
   
   //
   // Method to notify any observers of register operation that has just occurred.
   //
       private void notifyAnyObservers(int type) {
         if (this.countObservers() > 0){// && Globals.program != null) && Globals.program.inSteppedExecution()) {
            this.setChanged();
            this.notifyObservers(new RegisterAccessNotice(type, this.name));
         } 
      } 
      
    
   }

Coprocessor1

package mars.mips.hardware;
public synchronized class Coprocessor1 {
private static Register[] registers;
private static Register condition;
private static int numConditionFlags;
static void ();
public void Coprocessor1();
public static void showRegisters();
public static void setRegisterToFloat(String, float);
public static void setRegisterToFloat(int, float);
public static void setRegisterToInt(String, int);
public static void setRegisterToInt(int, int);
public static void setRegisterPairToDouble(int, double) throws InvalidRegisterAccessException;
public static void setRegisterPairToDouble(String, double) throws InvalidRegisterAccessException;
public static void setRegisterPairToLong(int, long) throws InvalidRegisterAccessException;
public static void setRegisterPairToLong(String, long) throws InvalidRegisterAccessException;
public static float getFloatFromRegister(int);
public static float getFloatFromRegister(String);
public static int getIntFromRegister(int);
public static int getIntFromRegister(String);
public static double getDoubleFromRegisterPair(int) throws InvalidRegisterAccessException;
public static double getDoubleFromRegisterPair(String) throws InvalidRegisterAccessException;
public static long getLongFromRegisterPair(int) throws InvalidRegisterAccessException;
public static long getLongFromRegisterPair(String) throws InvalidRegisterAccessException;
public static int updateRegister(int, int);
public static int getValue(int);
public static int getRegisterNumber(String);
public static Register[] getRegisters();
public static Register getRegister(String);
public static void resetRegisters();
public static void addRegistersObserver(java.util.Observer);
public static void deleteRegistersObserver(java.util.Observer);
public static int setConditionFlag(int);
public static int clearConditionFlag(int);
public static int getConditionFlag(int);
public static int getConditionFlags();
public static void clearConditionFlags();
public static void setConditionFlags();
public static int getConditionFlagCount();
}

mars/mips/hardware/MemoryAccessNotice.java
mars/mips/hardware/MemoryAccessNotice.javapackage mars.mips.hardware;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Object provided to Observers of runtime access to MIPS memory.
 * Observer can get the access type (R/W), address and length in bytes (4,2,1).
 * 
 * @author Pete Sanderson 
 * @version July 2005
 */
 
public class MemoryAccessNotice extends AccessNotice {
   private int address;
    private int length;
    private int value;

  /** Constructor will be called only within this package, so assume
   *  address and length are in valid ranges.
    */
   MemoryAccessNotice(int type, int address, int length, int value) {
     super(type);
      this.address = address;
      this.length = length;
      this.value = value;
  }
  /** Constructor will be called only within this package, so assume
   *  address is in valid range.
    */
   MemoryAccessNotice(int type, int address, int value) {
     super(type);
      this.address = address;
      this.length = Memory.WORD_LENGTH_BYTES;
      this.value = value;
  }
  /** Fetch the memory address that was accessed. */
  public int getAddress() {
     return address;
  }
  /** Fetch the length in bytes of the access operation (4,2,1). */
  public int getLength() {
     return length;
  }
  /** Fetch the value of the access operation (the value read or written). */
  public int getValue() {
     return value;
  }
  /** String representation indicates access type, address and length in bytes */
  public String toString() {
     return ((this.getAccessType()==AccessNotice.READ) ? “R ” : “W “) +
             “Mem ” + address + ” ” + length + “B = “+value;
  }
}

mars/mips/hardware/MemoryConfigurations.java
mars/mips/hardware/MemoryConfigurations.java   package mars.mips.hardware;
   import mars.Globals;
   import java.util.*;

/*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Models the collection of MIPS memory configurations.
 * The default configuration is based on SPIM.  Starting with MARS 3.7,
 * the configuration can be changed.  
 * 
 * @author Pete Sanderson 
 * @version August 2009
 */

    public class MemoryConfigurations {
    
      private static ArrayList configurations = null;
      private static MemoryConfiguration defaultConfiguration;
      private static MemoryConfiguration currentConfiguration;
    
    // Be careful, these arrays are parallel and position-sensitive.
    // The getters in this and in MemoryConfiguration depend on this
    // sequence.  Should be refactored…  The order comes from the
    // original listed order in Memory.java, where most of these were
    // “final” until Mars 3.7 and changeable memory configurations.
      private static final String[] configurationItemNames = {
         “.text base address”,
         “data segment base address”,
         “.extern base address”,
         “global pointer $gp”,
         “.data base address”,
         “heap base address”,
         “stack pointer $sp”,
         “stack base address”,
         “user space high address”,
         “kernel space base address”,
         “.ktext base address”,
         “exception handler address”,
         “.kdata base address”,
         “MMIO base address”,
         “kernel space high address”,
         “data segment limit address”,
         “text limit address”,
         “kernel data segment limit address”,
         “kernel text limit address”,
         “stack limit address”,
         “memory map limit address”
         };
    
      // Default configuration comes from SPIM
      private static int[] defaultConfigurationItemValues = { 
         0x00400000, // .text Base Address
         0x10000000, // Data Segment base address
         0x10000000, // .extern Base Address
         0x10008000, // Global Pointer $gp)
         0x10010000, // .data base Address
         0x10040000, // heap base address
         0x7fffeffc, // stack pointer $sp (from SPIM not MIPS)
         0x7ffffffc, // stack base address
         0x7fffffff, // highest address in user space
         0x80000000, // lowest address in kernel space
         0x80000000, // .ktext base address
         0x80000180, // exception handler address
         0x90000000, // .kdata base address
         0xffff0000, // MMIO base address
         0xffffffff, // highest address in kernel (and memory)
         0x7fffffff, // data segment limit address
         0x0ffffffc, // text limit address
         0xfffeffff, // kernel data segment limit address
         0x8ffffffc, // kernel text limit address
         0x10040000, // stack limit address
         0xffffffff  // memory map limit address
         };
   
      // Compact allows 16 bit addressing, data segment starts at 0
      private static int[] dataBasedCompactConfigurationItemValues = { 
         0x00003000, // .text Base Address
         0x00000000, // Data Segment base address
         0x00001000, // .extern Base Address
         0x00001800, // Global Pointer $gp)
         0x00000000, // .data base Address
         0x00002000, // heap base address
         0x00002ffc, // stack pointer $sp 
         0x00002ffc, // stack base address
         0x00003fff, // highest address in user space
         0x00004000, // lowest address in kernel space
         0x00004000, // .ktext base address
         0x00004180, // exception handler address
         0x00005000, // .kdata base address
         0x00007f00, // MMIO base address
         0x00007fff, // highest address in kernel (and memory)
         0x00002fff, // data segment limit address
         0x00003ffc, // text limit address
         0x00007eff, // kernel data segment limit address
         0x00004ffc, // kernel text limit address
         0x00002000, // stack limit address
         0x00007fff  // memory map limit address
         };
   
      // Compact allows 16 bit addressing, text segment starts at 0
      private static int[] textBasedCompactConfigurationItemValues = { 
         0x00000000, // .text Base Address
         0x00001000, // Data Segment base address
         0x00001000, // .extern Base Address
         0x00001800, // Global Pointer $gp)
         0x00002000, // .data base Address
         0x00003000, // heap base address
         0x00003ffc, // stack pointer $sp 
         0x00003ffc, // stack base address
         0x00003fff, // highest address in user space
         0x00004000, // lowest address in kernel space
         0x00004000, // .ktext base address
         0x00004180, // exception handler address
         0x00005000, // .kdata base address
         0x00007f00, // MMIO base address
         0x00007fff, // highest address in kernel (and memory)
         0x00003fff, // data segment limit address
         0x00000ffc, // text limit address
         0x00007eff, // kernel data segment limit address
         0x00004ffc, // kernel text limit address
         0x00003000, // stack limit address
         0x00007fff  // memory map limit address
         };
         
   
   
       public MemoryConfigurations() {
        
      }
    
   
       public static void buildConfigurationCollection() {
         if (configurations == null) {
            configurations = new ArrayList();
            configurations.add(new MemoryConfiguration(“Default”, “Default”, configurationItemNames, defaultConfigurationItemValues));
            configurations.add(new MemoryConfiguration(“CompactDataAtZero”, “Compact, Data at Address 0”, configurationItemNames, dataBasedCompactConfigurationItemValues));
            configurations.add(new MemoryConfiguration(“CompactTextAtZero”, “Compact, Text at Address 0”, configurationItemNames, textBasedCompactConfigurationItemValues));
            defaultConfiguration = (MemoryConfiguration) configurations.get(0);
            currentConfiguration = defaultConfiguration;
            // Get current config from settings
            //String currentConfigurationIdentifier = Globals.getSettings().getMemoryConfiguration();
            setCurrentConfiguration(getConfigurationByName(Globals.getSettings().getMemoryConfiguration()));
         // Iterator configurationsIterator = getConfigurationsIterator();
         // while (configurationsIterator.hasNext()) {
            //  MemoryConfiguration config = (MemoryConfiguration)configurationsIterator.next();
         //   if (currentConfigurationIdentifier.equals(config.getConfigurationIdentifier())) {
         //      setCurrentConfiguration(config);
         //         }
         //    }
         }
      }
    
       public static Iterator getConfigurationsIterator() {
         if (configurations == null) {
            buildConfigurationCollection();
         }
         return configurations.iterator();
      
      }
    
       public static MemoryConfiguration getConfigurationByName(String name) {
         Iterator configurationsIterator = getConfigurationsIterator();
         while (configurationsIterator.hasNext()) {
            MemoryConfiguration config = (MemoryConfiguration)configurationsIterator.next();
            if (name.equals(config.getConfigurationIdentifier())) {
               return config;
            }
         }       
         return null;
      }
     
     
       public static MemoryConfiguration getDefaultConfiguration() {
         if (defaultConfiguration == null) {
            buildConfigurationCollection();
         }
         return defaultConfiguration;
      }
      
       public static MemoryConfiguration getCurrentConfiguration() {
         if (currentConfiguration == null) {
            buildConfigurationCollection();
         }
         return currentConfiguration;
      }
    
       public static boolean setCurrentConfiguration(MemoryConfiguration config) {
         if (config == null) 
            return false;
         if (config != currentConfiguration) {
            currentConfiguration = config;
            Globals.memory.clear();
            RegisterFile.getUserRegister(“$gp”).changeResetValue(config.getGlobalPointer());
            RegisterFile.getUserRegister(“$sp”).changeResetValue(config.getStackPointer());
            RegisterFile.getProgramCounterRegister().changeResetValue(config.getTextBaseAddress());
            RegisterFile.initializeProgramCounter(config.getTextBaseAddress());
            RegisterFile.resetRegisters();
            return true;
         }
         else {
            return false;
         }
      }
    
   
   ////  Use these to intialize Memory static variables at launch
            
       public static int getDefaultTextBaseAddress() {
         return defaultConfigurationItemValues[0];
      }
    
       public static int getDefaultDataSegmentBaseAddress() {
         return defaultConfigurationItemValues[1];
      }
    
       public static int getDefaultExternBaseAddress() {
         return defaultConfigurationItemValues[2];
      }
   
       public static int getDefaultGlobalPointer() {
         return defaultConfigurationItemValues[3];
      }
   
       public static int getDefaultDataBaseAddress() {
         return defaultConfigurationItemValues[4];
      }
   
       public static int getDefaultHeapBaseAddress() {
         return defaultConfigurationItemValues[5];
      }
   
       public static int getDefaultStackPointer() {
         return defaultConfigurationItemValues[6];
      }
   
       public static int getDefaultStackBaseAddress() {
         return defaultConfigurationItemValues[7];
      }
   
       public static int getDefaultUserHighAddress() {
         return defaultConfigurationItemValues[8];
      }
   
       public static int getDefaultKernelBaseAddress() {
         return defaultConfigurationItemValues[9];
      }
   
       public static int getDefaultKernelTextBaseAddress() {
         return defaultConfigurationItemValues[10];
      }
   
       public static int getDefaultExceptionHandlerAddress() {
         return defaultConfigurationItemValues[11];
      }
   
       public static int getDefaultKernelDataBaseAddress() {
         return defaultConfigurationItemValues[12];
      }
   
       public static int getDefaultMemoryMapBaseAddress() {
         return defaultConfigurationItemValues[13];
      }
   
       public static int getDefaultKernelHighAddress () {
         return defaultConfigurationItemValues[14];
      }   
      
       public int getDefaultDataSegmentLimitAddress() {
         return defaultConfigurationItemValues[15];
      }
      
       public int getDefaultTextLimitAddress() {
         return defaultConfigurationItemValues[16];
      }
      
       public int getDefaultKernelDataSegmentLimitAddress() {
         return defaultConfigurationItemValues[17];
      }
      
       public int getDefaultKernelTextLimitAddress() {
         return defaultConfigurationItemValues[18];
      }
      
       public int getDefaultStackLimitAddress() {
         return defaultConfigurationItemValues[19];
      }
      
       public int getMemoryMapLimitAddress() {
         return defaultConfigurationItemValues[20];
      } 
   
   
   
   }

InvalidRegisterAccessException

package mars.mips.hardware;
public synchronized class InvalidRegisterAccessException extends Exception {
private mars.ErrorList errs;
public void InvalidRegisterAccessException();
}

mars/mips/hardware/AddressErrorException.java
mars/mips/hardware/AddressErrorException.javapackage mars.mips.hardware;
import mars.util.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Represents MIPS AddressErrorException. This is generated by the assembler when the
 * source code references a memory address not valid for the context.
 * 
 * @author Pete Sanderson 
 * @version August 2003
 **/
public class AddressErrorException extends Exception {  
   private int address;
    private int type;  // Exceptions.ADDRESS_EXCEPTION_LOAD,Exceptions.ADDRESS_EXCEPTION_STORE 

   /**
    * Constructor for the AddressErrorException class
    * 
    * @param addr The erroneous memory address.
    **/
    
   public AddressErrorException(String message, int exceptType, int addr) {
       super(message+Binary.intToHexString(addr));
      address = addr;
        type = exceptType;
   }

   /**
    * Get the erroneous memory address.
    * 
    * @return The erroneous memory address.
    **/
   public int getAddress() {
      return address;
   }
    
       /**
    * Get the exception type (load or store).
    * 
    * @return Exception type: Exceptions.ADDRESS_EXCEPTION_LOAD, Exceptions.ADDRESS_EXCEPTION_STORE
    **/
   public int getType() {
      return type;
   }
}

MemoryConfiguration

package mars.mips.hardware;
public synchronized class MemoryConfiguration {
private String configurationIdentifier;
private String configurationName;
private String[] configurationItemNames;
private int[] configurationItemValues;
public void MemoryConfiguration(String, String, String[], int[]);
public String getConfigurationIdentifier();
public String getConfigurationName();
public int[] getConfigurationItemValues();
public String[] getConfigurationItemNames();
public int getTextBaseAddress();
public int getDataSegmentBaseAddress();
public int getExternBaseAddress();
public int getGlobalPointer();
public int getDataBaseAddress();
public int getHeapBaseAddress();
public int getStackPointer();
public int getStackBaseAddress();
public int getUserHighAddress();
public int getKernelBaseAddress();
public int getKernelTextBaseAddress();
public int getExceptionHandlerAddress();
public int getKernelDataBaseAddress();
public int getMemoryMapBaseAddress();
public int getKernelHighAddress();
public int getDataSegmentLimitAddress();
public int getTextLimitAddress();
public int getKernelDataSegmentLimitAddress();
public int getKernelTextLimitAddress();
public int getStackLimitAddress();
public int getMemoryMapLimitAddress();
}

mars/mips/hardware/InvalidRegisterAccessException.java
mars/mips/hardware/InvalidRegisterAccessException.javapackage mars.mips.hardware;
import mars.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Represents attempt to access double precision register using an odd
 * (e.g. $f1, $f23) register name.
 * 
 * @author Pete Sanderson
 * @version July 2005
 **/

public class InvalidRegisterAccessException extends Exception {  
   private ErrorList errs;

   /**
    * Constructor for IllegalRegisterException.
    * 
    **/
   public InvalidRegisterAccessException() {
   }

 }
   

Memory

package mars.mips.hardware;
public synchronized class Memory extends java.util.Observable {
public static int textBaseAddress;
public static int dataSegmentBaseAddress;
public static int externBaseAddress;
public static int globalPointer;
public static int dataBaseAddress;
public static int heapBaseAddress;
public static int stackPointer;
public static int stackBaseAddress;
public static int userHighAddress;
public static int kernelBaseAddress;
public static int kernelTextBaseAddress;
public static int exceptionHandlerAddress;
public static int kernelDataBaseAddress;
public static int memoryMapBaseAddress;
public static int kernelHighAddress;
public static final int WORD_LENGTH_BYTES = 4;
public static final boolean LITTLE_ENDIAN = 1;
public static final boolean BIG_ENDIAN = 0;
private static boolean byteOrder;
public static int heapAddress;
java.util.Collection observables;
private static final int BLOCK_LENGTH_WORDS = 1024;
private static final int BLOCK_TABLE_LENGTH = 1024;
private int[][] dataBlockTable;
private int[][] kernelDataBlockTable;
private int[][] stackBlockTable;
private static final int MMIO_TABLE_LENGTH = 16;
private int[][] memoryMapBlockTable;
private static final int TEXT_BLOCK_LENGTH_WORDS = 1024;
private static final int TEXT_BLOCK_TABLE_LENGTH = 1024;
private mars.ProgramStatement[][] textBlockTable;
private mars.ProgramStatement[][] kernelTextBlockTable;
public static int dataSegmentLimitAddress;
public static int textLimitAddress;
public static int kernelDataSegmentLimitAddress;
public static int kernelTextLimitAddress;
public static int stackLimitAddress;
public static int memoryMapLimitAddress;
private static Memory uniqueMemoryInstance;
private static final boolean STORE = 1;
private static final boolean FETCH = 0;
static void ();
private void Memory();
public static Memory getInstance();
public void clear();
public static void setConfiguration();
public boolean usingCompactMemoryConfiguration();
private void initialize();
public int allocateBytesFromHeap(int) throws IllegalArgumentException;
public void setByteOrder(boolean);
public boolean getByteOrder();
public int set(int, int, int) throws AddressErrorException;
public int setRawWord(int, int) throws AddressErrorException;
public int setWord(int, int) throws AddressErrorException;
public int setHalf(int, int) throws AddressErrorException;
public int setByte(int, int) throws AddressErrorException;
public double setDouble(int, double) throws AddressErrorException;
public void setStatement(int, mars.ProgramStatement) throws AddressErrorException;
public int get(int, int) throws AddressErrorException;
private int get(int, int, boolean) throws AddressErrorException;
public int getRawWord(int) throws AddressErrorException;
public Integer getRawWordOrNull(int) throws AddressErrorException;
public int getAddressOfFirstNull(int, int) throws AddressErrorException;
public int getWord(int) throws AddressErrorException;
public int getWordNoNotify(int) throws AddressErrorException;
public int getHalf(int) throws AddressErrorException;
public int getByte(int) throws AddressErrorException;
public mars.ProgramStatement getStatement(int) throws AddressErrorException;
public mars.ProgramStatement getStatementNoNotify(int) throws AddressErrorException;
public static boolean wordAligned(int);
public static boolean doublewordAligned(int);
public static int alignToWordBoundary(int);
public static boolean inTextSegment(int);
public static boolean inKernelTextSegment(int);
public static boolean inDataSegment(int);
public static boolean inKernelDataSegment(int);
public static boolean inMemoryMapSegment(int);
public void addObserver(java.util.Observer);
public void addObserver(java.util.Observer, int) throws AddressErrorException;
public void addObserver(java.util.Observer, int, int) throws AddressErrorException;
public int countObservers();
public void deleteObserver(java.util.Observer);
public void deleteObservers();
public void notifyObservers();
public void notifyObservers(Object);
private java.util.Collection getNewMemoryObserversCollection();
private void notifyAnyObservers(int, int, int, int);
private int storeBytesInTable(int[][], int, int, int);
private int fetchBytesFromTable(int[][], int, int);
private synchronized int storeOrFetchBytesInTable(int[][], int, int, int, boolean);
private synchronized int storeWordInTable(int[][], int, int);
private synchronized int fetchWordFromTable(int[][], int);
private synchronized Integer fetchWordOrNullFromTable(int[][], int);
private int replaceByte(int, int, int, int);
private int reverseBytes(int);
private void storeProgramStatement(int, mars.ProgramStatement, int, mars.ProgramStatement[][]);
private mars.ProgramStatement readProgramStatement(int, int, mars.ProgramStatement[][], boolean);
}

mars/mips/hardware/Memory.java
mars/mips/hardware/Memory.java   package mars.mips.hardware;
   import mars.*;
   import mars.util.*;
   import mars.simulator.*;
   import mars.mips.instructions.*;
   import java.util.*;
    
    /*
Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Represents MIPS memory.  Different segments are represented by different data structs.
 * 
 * @author Pete Sanderson 
 * @version August 2003
 */

/////////////////////////////////////////////////////////////////////
// NOTE: This implementation is purely big-endian.  MIPS can handle either one.
/////////////////////////////////////////////////////////////////////

    public class Memory extends Observable  {
   
    /** base address for (user) text segment: 0x00400000 **/
      public static int textBaseAddress = MemoryConfigurations.getDefaultTextBaseAddress(); //0x00400000;
    /** base address for (user) data segment: 0x10000000 **/
      public static int dataSegmentBaseAddress = MemoryConfigurations.getDefaultDataSegmentBaseAddress(); //0x10000000;
    /** base address for .extern directive: 0x10000000 **/
      public static int externBaseAddress = MemoryConfigurations.getDefaultExternBaseAddress(); //0x10000000;
    /** base address for storing globals **/
      public static int globalPointer = MemoryConfigurations.getDefaultGlobalPointer(); //0x10008000;
    /** base address for storage of non-global static data in data segment: 0x10010000 (from SPIM) **/      
      public static int dataBaseAddress = MemoryConfigurations.getDefaultDataBaseAddress(); //0x10010000; // from SPIM not MIPS
    /** base address for heap: 0x10040000 (I think from SPIM not MIPS) **/
      public static int heapBaseAddress = MemoryConfigurations.getDefaultHeapBaseAddress(); //0x10040000; // I think from SPIM not MIPS
    /** starting address for stack: 0x7fffeffc (this is from SPIM not MIPS) **/
      public static int stackPointer = MemoryConfigurations.getDefaultStackPointer(); //0x7fffeffc;
    /** base address for stack: 0x7ffffffc (this is mine – start of highest word below kernel space) **/
      public static int stackBaseAddress = MemoryConfigurations.getDefaultStackBaseAddress(); //0x7ffffffc;
    /** highest address accessible in user (not kernel) mode. **/
      public static int userHighAddress = MemoryConfigurations.getDefaultUserHighAddress(); //0x7fffffff;
    /** kernel boundary.  Only OS can access this or higher address **/
      public static int kernelBaseAddress = MemoryConfigurations.getDefaultKernelBaseAddress(); //0x80000000;
    /** base address for kernel text segment: 0x80000000 **/
      public static int kernelTextBaseAddress = MemoryConfigurations.getDefaultKernelTextBaseAddress(); //0x80000000;
    /** starting address for exception handlers: 0x80000180 **/
      public static int exceptionHandlerAddress = MemoryConfigurations.getDefaultExceptionHandlerAddress(); //0x80000180;
    /** base address for kernel data segment: 0x90000000 **/
      public static int kernelDataBaseAddress = MemoryConfigurations.getDefaultKernelDataBaseAddress(); //0x90000000;
    /** starting address for memory mapped I/O: 0xffff0000 (-65536) **/
      public static int memoryMapBaseAddress = MemoryConfigurations.getDefaultMemoryMapBaseAddress(); //0xffff0000;
    /** highest address acessible in kernel mode. **/
      public static int kernelHighAddress = MemoryConfigurations.getDefaultKernelHighAddress(); //0xffffffff;
   
    /** MIPS word length in bytes. **/
    // NOTE:  Much of the code is hardwired for 4 byte words.  Refactoring this is low priority.
      public static final int WORD_LENGTH_BYTES = 4;
    /** Constant representing byte order of each memory word.  Little-endian means lowest 
        numbered byte is right most [3][2][1][0]. */
      public static final boolean LITTLE_ENDIAN = true;
    /** Constant representing byte order of each memory word.  Big-endian means lowest 
        numbered byte is left most [0][1][2][3]. */
      public static final boolean BIG_ENDIAN = false;
    /** Current setting for endian (default LITTLE_ENDIAN) **/
      private static boolean byteOrder = LITTLE_ENDIAN;
    
      public static int heapAddress;
   
    // Memory will maintain a collection of observables.  Each one is associated
    // with a specific memory address or address range, and each will have at least
    // one observer registered with it.  When memory access is made, make sure only
    // observables associated with that address send notices to their observers.
    // This assures that observers are not bombarded with notices from memory
    // addresses they do not care about.
    //
    // Would like a tree-like implementation, but that is complicated by this fact:
    // key for insertion into the tree would be based on Comparable using both low 
    // and high end of address range, but retrieval from the tree has to be based
    // on target address being ANYWHERE IN THE RANGE (not an exact key match).
      
      Collection observables = getNewMemoryObserversCollection();
   
    // The data segment is allocated in blocks of 1024 ints (4096 bytes).  Each block is
    // referenced by a “block table” entry, and the table has 1024 entries.  The capacity
    // is thus 1024 entries * 4096 bytes = 4 MB.  Should be enough to cover most
    // programs!!  Beyond that it would go to an “indirect” block (similar to Unix i-nodes),
    // which is not implemented.
    //
    // Although this scheme is an array of arrays, it is relatively space-efficient since
    // only the table is created initially. A 4096-byte block is not allocated until a value 
    // is written to an address within it.  Thus most small programs will use only 8K bytes 
    // of space (the table plus one block).  The index into both arrays is easily computed 
    // from the address; access time is constant.
    //
    // SPIM stores statically allocated data (following first .data directive) starting
    // at location 0x10010000.  This is the first Data Segment word beyond the reach of $gp
    // used in conjunction with signed 16 bit immediate offset.  $gp has value 0x10008000
    // and with the signed 16 bit offset can reach from 0x10008000 – 0xFFFF = 0x10000000 
    // (Data Segment base) to 0x10008000 + 0x7FFF = 0x1000FFFF (the byte preceding 0x10010000).
    //
    // Using my scheme, 0x10010000 falls at the beginning of the 17’th block — table entry 16.
    // SPIM uses a heap base address of 0x10040000 which is not part of the MIPS specification.
    // (I don’t have a reference for that offhand…)  Using my scheme, 0x10040000 falls at
    // the start of the 65’th block — table entry 64.  That leaves (1024-64) * 4096 = 3,932,160
    // bytes of space available without going indirect.
    
      private static final int BLOCK_LENGTH_WORDS = 1024;  // allocated blocksize 1024 ints == 4K bytes
      private static final int BLOCK_TABLE_LENGTH = 1024; // Each entry of table points to a block.
      private int[][] dataBlockTable;
      private int[][] kernelDataBlockTable;
    
    // The stack is modeled similarly to the data segment.  It cannot share the same
    // data structure because the stack base address is very large.  To store it in the
    // same data structure would require implementation of indirect blocks, which has not
    // been realized.  So the stack gets its own table of blocks using the same dimensions 
    // and allocation scheme used for data segment.
    //
    // The other major difference is the stack grows DOWNWARD from its base address, not
    // upward.  I.e., the stack base is the largest stack address. This turns the whole 
    // scheme for translating memory address to block-offset on its head!  The simplest
    // solution is to calculate relative address (offset from base) by subtracting the 
    // desired address from the stack base address (rather than subtracting base address 
    // from desired address).  Thus as the address gets smaller the offset gets larger.
    // Everything else works the same, so it shares some private helper methods with
    // data segment algorithms.
    
      private int[][] stackBlockTable;
   
    // Memory mapped I/O is simulated with a separate table using the same structure and
    // logic as data segment.  Memory is allocated in 4K byte blocks.  But since MMIO
    // address range is limited to 0xffff0000 to 0xfffffffc, there are only 64K bytes 
    // total.  Thus there will be a maximum of 16 blocks, and I suspect never more than
    // one since only the first few addresses are typically used.  The only exception
    // may be a rogue program generating such addresses in a loop.  Note that the
    // MMIO addresses are interpreted by Java as negative numbers since it does not 
    // have unsigned types.  As long as the absolute address is correctly translated
    // into a table offset, this is of no concern.
   
      private static final int MMIO_TABLE_LENGTH = 16; // Each entry of table points to a 4K block.
      private int[][] memoryMapBlockTable;
        
    // I use a similar scheme for storing instructions.  MIPS text segment ranges from
    // 0x00400000 all the way to data segment (0x10000000) a range of about 250 MB!  So
    // I’ll provide table of blocks with similar capacity.  This differs from data segment
    // somewhat in that the block entries do not contain int’s, but instead contain
    // references to ProgramStatement objects.  
   
      private static final int TEXT_BLOCK_LENGTH_WORDS = 1024;  // allocated blocksize 1024 ints == 4K bytes
      private static final int TEXT_BLOCK_TABLE_LENGTH = 1024; // Each entry of table points to a block.
      private ProgramStatement[][] textBlockTable;
      private ProgramStatement[][] kernelTextBlockTable;
    
    // Set “top” address boundary to go with each “base” address.  This determines permissable
    // address range for user program.  Currently limit is 4MB, or 1024 * 1024 * 4 bytes based
    // on the table structures described above (except memory mapped IO, limited to 64KB by range).
    
      public static int dataSegmentLimitAddress = dataSegmentBaseAddress + 
                                                              BLOCK_LENGTH_WORDS * BLOCK_TABLE_LENGTH * WORD_LENGTH_BYTES;
      public static int textLimitAddress        = textBaseAddress + 
                                                              TEXT_BLOCK_LENGTH_WORDS * TEXT_BLOCK_TABLE_LENGTH * WORD_LENGTH_BYTES;                                                                  
      public static int kernelDataSegmentLimitAddress = kernelDataBaseAddress + 
                                                              BLOCK_LENGTH_WORDS * BLOCK_TABLE_LENGTH * WORD_LENGTH_BYTES;
      public static int kernelTextLimitAddress  = kernelTextBaseAddress + 
                                                              TEXT_BLOCK_LENGTH_WORDS * TEXT_BLOCK_TABLE_LENGTH * WORD_LENGTH_BYTES;                                                                  
      public static int stackLimitAddress       = stackBaseAddress – 
                                                              BLOCK_LENGTH_WORDS * BLOCK_TABLE_LENGTH * WORD_LENGTH_BYTES;
      public static int memoryMapLimitAddress   = memoryMapBaseAddress + 
                                                      BLOCK_LENGTH_WORDS * MMIO_TABLE_LENGTH * WORD_LENGTH_BYTES;  
    // This will be a Singleton class, only one instance is ever created.  Since I know the 
    // Memory object is always needed, I’ll go ahead and create it at the time of class loading.
    // (greedy rather than lazy instantiation).  The constructor is private and getInstance()
    // always returns this instance.
    
      private static Memory uniqueMemoryInstance = new Memory(); 
    
    
    /*
     * Private constructor for Memory.  Separate data structures for text and data segments. 
     **/
       private Memory() {
         initialize();
      }
   
     /**
      * Returns the unique Memory instance, which becomes in essence global.
    */
    
       public static Memory getInstance() {
         return uniqueMemoryInstance;
      }
    
    /**
     * Explicitly clear the contents of memory.  Typically done at start of assembly.
     */
     
       public void clear() {
         setConfiguration();
         initialize();      
      }
   
     /**
     * Sets current memory configuration for simulated MIPS.  Configuration is 
     * collection of memory segment addresses. e.g. text segment starting at 
     * address 0x00400000.  Configuration can be modified starting with MARS 3.7.
     */
   
       public static void setConfiguration() {
         textBaseAddress = MemoryConfigurations.getCurrentConfiguration().getTextBaseAddress(); //0x00400000;
         dataSegmentBaseAddress = MemoryConfigurations.getCurrentConfiguration().getDataSegmentBaseAddress(); //0x10000000;
         externBaseAddress = MemoryConfigurations.getCurrentConfiguration().getExternBaseAddress(); //0x10000000;
         globalPointer = MemoryConfigurations.getCurrentConfiguration().getGlobalPointer(); //0x10008000;
         dataBaseAddress = MemoryConfigurations.getCurrentConfiguration().getDataBaseAddress(); //0x10010000; // from SPIM not MIPS
         heapBaseAddress = MemoryConfigurations.getCurrentConfiguration().getHeapBaseAddress(); //0x10040000; // I think from SPIM not MIPS
         stackPointer = MemoryConfigurations.getCurrentConfiguration().getStackPointer(); //0x7fffeffc;
         stackBaseAddress = MemoryConfigurations.getCurrentConfiguration().getStackBaseAddress(); //0x7ffffffc;
         userHighAddress = MemoryConfigurations.getCurrentConfiguration().getUserHighAddress(); //0x7fffffff;
         kernelBaseAddress = MemoryConfigurations.getCurrentConfiguration().getKernelBaseAddress(); //0x80000000;
         kernelTextBaseAddress = MemoryConfigurations.getCurrentConfiguration().getKernelTextBaseAddress(); //0x80000000;
         exceptionHandlerAddress = MemoryConfigurations.getCurrentConfiguration().getExceptionHandlerAddress(); //0x80000180;
         kernelDataBaseAddress = MemoryConfigurations.getCurrentConfiguration().getKernelDataBaseAddress(); //0x90000000;
         memoryMapBaseAddress = MemoryConfigurations.getCurrentConfiguration().getMemoryMapBaseAddress(); //0xffff0000;
         kernelHighAddress = MemoryConfigurations.getCurrentConfiguration().getKernelHighAddress(); //0xffffffff;       
         dataSegmentLimitAddress = Math.min(MemoryConfigurations.getCurrentConfiguration().getDataSegmentLimitAddress(),
                                      dataSegmentBaseAddress + 
                                              BLOCK_LENGTH_WORDS * BLOCK_TABLE_LENGTH * WORD_LENGTH_BYTES);
         textLimitAddress        = Math.min(MemoryConfigurations.getCurrentConfiguration().getTextLimitAddress(),
                                      textBaseAddress + 
                                              TEXT_BLOCK_LENGTH_WORDS * TEXT_BLOCK_TABLE_LENGTH * WORD_LENGTH_BYTES);                                                                 
         kernelDataSegmentLimitAddress = Math.min(MemoryConfigurations.getCurrentConfiguration().getKernelDataSegmentLimitAddress(),
                                      kernelDataBaseAddress + 
                                              BLOCK_LENGTH_WORDS * BLOCK_TABLE_LENGTH * WORD_LENGTH_BYTES);
         kernelTextLimitAddress  = Math.min(MemoryConfigurations.getCurrentConfiguration().getKernelTextLimitAddress(),
                                      kernelTextBaseAddress + 
                                              TEXT_BLOCK_LENGTH_WORDS * TEXT_BLOCK_TABLE_LENGTH * WORD_LENGTH_BYTES);                                                                 
         stackLimitAddress       = Math.max(MemoryConfigurations.getCurrentConfiguration().getStackLimitAddress(),
                                      stackBaseAddress – 
                                              BLOCK_LENGTH_WORDS * BLOCK_TABLE_LENGTH * WORD_LENGTH_BYTES);
         memoryMapLimitAddress   = Math.min(MemoryConfigurations.getCurrentConfiguration().getMemoryMapLimitAddress(),
                                      memoryMapBaseAddress + 
                                      BLOCK_LENGTH_WORDS * MMIO_TABLE_LENGTH * WORD_LENGTH_BYTES);
      /*    System.out.println(“dataSegmentLimitAddress “+Binary.intToHexString(dataSegmentLimitAddress));
        System.out.println(“textLimitAddress “+Binary.intToHexString(textLimitAddress));
        System.out.println(“kernelDataSegmentLimitAddress “+Binary.intToHexString(kernelDataSegmentLimitAddress));
        System.out.println(“kernelTextLimitAddress “+Binary.intToHexString(kernelTextLimitAddress));
        System.out.println(“stackLimitAddress “+Binary.intToHexString(stackLimitAddress));
        System.out.println(“memoryMapLimitAddress “+Binary.intToHexString(memoryMapLimitAddress));
      */
      }
   
   
    /**
     *  Determine whether the current memory configuration has a maximum address that can be stored
     *  in 16 bits.  
     *  @return true if maximum address can be stored in 16 bits or less, false otherwise
     */ 
       public boolean usingCompactMemoryConfiguration() {
         return (kernelHighAddress & 0x00007fff) == kernelHighAddress;
      }
   
   
   
       private void initialize() {
         heapAddress = heapBaseAddress;
         textBlockTable  = new ProgramStatement[TEXT_BLOCK_TABLE_LENGTH][];
         dataBlockTable  = new int[BLOCK_TABLE_LENGTH][]; // array of null int[] references
         kernelTextBlockTable  = new ProgramStatement[TEXT_BLOCK_TABLE_LENGTH][];
         kernelDataBlockTable  = new int[BLOCK_TABLE_LENGTH][];      
         stackBlockTable = new int[BLOCK_TABLE_LENGTH][];
         memoryMapBlockTable = new int[MMIO_TABLE_LENGTH][];
         System.gc(); // call garbage collector on any Table memory just deallocated.     
      }  
     
    /**
     * Returns the next available word-aligned heap address.  There is no recycling and
     * no heap management!  There is however nearly 4MB of heap space available in Mars.
     *
     * @param numBytes Number of bytes requested.  Should be multiple of 4, otherwise next higher multiple of 4 allocated.
     * @return address of allocated heap storage. 
     * @throws IllegalArgumentException if number of requested bytes is negative or exceeds available heap storage
     */
       public int allocateBytesFromHeap(int numBytes) throws IllegalArgumentException {
         int result = heapAddress;
         if (numBytes < 0) {             throw new IllegalArgumentException("request ("+numBytes+") is negative heap amount");          }          int newHeapAddress = heapAddress + numBytes;          if (newHeapAddress % 4 != 0) {             newHeapAddress = newHeapAddress + (4 - newHeapAddress % 4) ; // next higher multiple of 4          }          if (newHeapAddress >= dataSegmentLimitAddress) {
            throw new IllegalArgumentException(“request (“+numBytes+”) exceeds available heap storage”);
         }
         heapAddress = newHeapAddress;
         return result;
      }
   
   
     /**
      * Set byte order to either LITTLE_ENDIAN or BIG_ENDIAN.  Default is LITTLE_ENDIAN.
    *
    * @param order either LITTLE_ENDIAN or BIG_ENDIAN
    */
       public void setByteOrder(boolean order) {
         byteOrder = order;
      }
    
     /**
      * Retrieve memory byte order.  Default is LITTLE_ENDIAN (like PCs).
    *
    * @return either LITTLE_ENDIAN or BIG_ENDIAN
    */
       public boolean getByteOrder() {
         return byteOrder;
      }
    
    
   /*  *******************************  THE SETTER METHODS  ******************************/
   
   
    ///////////////////////////////////////////////////////////////////////////////////////
    /** 
    * Starting at the given address, write the given value over the given number of bytes.
    * This one does not check for word boundaries, and copies one byte at a time.
    * If length == 1, takes value from low order byte.  If 2, takes from low order half-word.
    * 
    * @param address Starting address of Memory address to be set.
    * @param value Value to be stored starting at that address.
    * @param length Number of bytes to be written.
    * @return old value that was replaced by the set operation
    **/
    
   // Allocates blocks if necessary.
       public int set(int address, int value, int length) throws AddressErrorException {
         int oldValue = 0;
         if (Globals.debug) System.out.println(“memory[“+address+”] set to “+value+”(“+length+” bytes)”);
         int relativeByteAddress;
         if (inDataSegment(address)) {
           // in data segment.  Will write one byte at a time, w/o regard to boundaries.
            relativeByteAddress = address – dataSegmentBaseAddress; // relative to data segment start, in bytes
            oldValue = storeBytesInTable(dataBlockTable, relativeByteAddress, length, value);
         } 
         else if (address > stackLimitAddress && address <= stackBaseAddress) {            // in stack.  Handle similarly to data segment write, except relative byte            // address calculated "backward" because stack addresses grow down from base.             relativeByteAddress = stackBaseAddress - address;              oldValue = storeBytesInTable(stackBlockTable, relativeByteAddress, length, value);          }           else if (inTextSegment(address)) {            // DEVELOPER: PLEASE USE setStatement() TO WRITE TO TEXT SEGMENT...             throw new AddressErrorException(                "DEVELOPER: You must use setStatement() to write to text segment!",                 Exceptions.ADDRESS_EXCEPTION_STORE, address);          }           else if (address >= memoryMapBaseAddress && address < memoryMapLimitAddress) {            // memory mapped I/O.             relativeByteAddress = address - memoryMapBaseAddress;             oldValue = storeBytesInTable(memoryMapBlockTable, relativeByteAddress, length, value);          }          else if (inKernelDataSegment(address)) {            // in kernel data segment.  Will write one byte at a time, w/o regard to boundaries.             relativeByteAddress = address - kernelDataBaseAddress; // relative to data segment start, in bytes             oldValue = storeBytesInTable(kernelDataBlockTable, relativeByteAddress, length, value);          }           else if (inKernelTextSegment(address)) {            // DEVELOPER: PLEASE USE setStatement() TO WRITE TO KERNEL TEXT SEGMENT...             throw new AddressErrorException(                "DEVELOPER: You must use setStatement() to write to kernel text segment!",                 Exceptions.ADDRESS_EXCEPTION_STORE, address);          }           else {            // falls outside Mars addressing range             throw new AddressErrorException("address out of range ",                Exceptions.ADDRESS_EXCEPTION_STORE, address);          }          notifyAnyObservers(AccessNotice.WRITE, address, length, value);          return oldValue;       }          ///////////////////////////////////////////////////////////////////////////////////////     /**       *  Starting at the given word address, write the given value over 4 bytes (a word).        *  It must be written as is, without adjusting for byte order (little vs big endian).      *  Address must be word-aligned.      *       * @param address Starting address of Memory address to be set.      * @param value Value to be stored starting at that address.      * @return old value that was replaced by the set operation.      * @throws AddressErrorException If address is not on word boundary.     **/        public int setRawWord(int address, int value) throws AddressErrorException {          int relative, oldValue=0;          if (address % WORD_LENGTH_BYTES != 0) {             throw new AddressErrorException("store address not aligned on word boundary ",                Exceptions.ADDRESS_EXCEPTION_STORE, address);          }          if (inDataSegment(address)) {            // in data segment             relative = (address - dataSegmentBaseAddress) >> 2; // convert byte address to words
            oldValue = storeWordInTable(dataBlockTable, relative, value);
         } 
         else if (address > stackLimitAddress && address <= stackBaseAddress) {            // in stack.  Handle similarly to data segment write, except relative             // address calculated "backward" because stack addresses grow down from base.             relative = (stackBaseAddress - address) >> 2; // convert byte address to words
            oldValue = storeWordInTable(stackBlockTable, relative, value);
         }
         else if (inTextSegment(address)) {
           // DEVELOPER: PLEASE USE setStatement() TO WRITE TO TEXT SEGMENT…
            throw new AddressErrorException(
                “DEVELOPER: You must use setStatement() to write to text segment!”, 
                Exceptions.ADDRESS_EXCEPTION_STORE, address);
         }  
         else if (address >= memoryMapBaseAddress && address < memoryMapLimitAddress) {            // memory mapped I/O.             relative = (address - memoryMapBaseAddress) >> 2; // convert byte address to word
            oldValue = storeWordInTable(memoryMapBlockTable, relative, value);
         }
         else if (inKernelDataSegment(address)) {
           // in data segment
            relative = (address – kernelDataBaseAddress) >> 2; // convert byte address to words
            oldValue = storeWordInTable(kernelDataBlockTable, relative, value);
         }
         else if (inKernelTextSegment(address)) {
           // DEVELOPER: PLEASE USE setStatement() TO WRITE TO KERNEL TEXT SEGMENT…
            throw new AddressErrorException(
                “DEVELOPER: You must use setStatement() to write to kernel text segment!”, 
                Exceptions.ADDRESS_EXCEPTION_STORE, address);
         } 
         else {
           // falls outside Mars addressing range
            throw new AddressErrorException(“store address out of range “,
               Exceptions.ADDRESS_EXCEPTION_STORE,  address);
         }
         notifyAnyObservers(AccessNotice.WRITE, address, WORD_LENGTH_BYTES, value);
         if (Globals.getSettings().getBackSteppingEnabled()) {
            Globals.program.getBackStepper().addMemoryRestoreRawWord(address,oldValue);
         }
         return oldValue;
      }
    
    ///////////////////////////////////////////////////////////////////////////////////////
    /** 
     *  Starting at the given word address, write the given value over 4 bytes (a word).  
     *  The address must be word-aligned.
     * 
     * @param address Starting address of Memory address to be set.
     * @param value Value to be stored starting at that address.
     * @return old value that was replaced by setWord operation.
     * @throws AddressErrorException If address is not on word boundary.
    **/
       public int setWord(int address, int value) throws AddressErrorException {
         if (address % WORD_LENGTH_BYTES != 0) {
            throw new AddressErrorException(
               “store address not aligned on word boundary “,
               Exceptions.ADDRESS_EXCEPTION_STORE,address);
         }
         return (Globals.getSettings().getBackSteppingEnabled())
            ? Globals.program.getBackStepper().addMemoryRestoreWord(address,set(address, value, WORD_LENGTH_BYTES))
            : set(address, value, WORD_LENGTH_BYTES);
      }
   
   
    ///////////////////////////////////////////////////////////////////////////////////////
    /** 
     *  Starting at the given halfword address, write the lower 16 bits of given value 
     *  into 2 bytes (a halfword).  
     * 
     * @param address Starting address of Memory address to be set.
     * @param value Value to be stored starting at that address.  Only low order 16 bits used.
     * @return old value that was replaced by setHalf operation.
     * @throws AddressErrorException If address is not on halfword boundary.
    **/   
       public int setHalf(int address, int value) throws AddressErrorException {
         if (address % 2 != 0) {
            throw new AddressErrorException(“store address not aligned on halfword boundary “,
               Exceptions.ADDRESS_EXCEPTION_STORE, address);
         }
         return (Globals.getSettings().getBackSteppingEnabled())
            ? Globals.program.getBackStepper().addMemoryRestoreHalf(address,set(address,value,2))
            : set(address, value, 2);
      }
   
    ///////////////////////////////////////////////////////////////////////////////////////
    /** 
     *  Writes low order 8 bits of given value into specified Memory byte.
     * 
     * @param address Address of Memory byte to be set.
     * @param value Value to be stored at that address.  Only low order 8 bits used.
     * @return old value that was replaced by setByte operation.
     **/
     
       public int setByte(int address, int value) throws AddressErrorException {
         return (Globals.getSettings().getBackSteppingEnabled())
            ? Globals.program.getBackStepper().addMemoryRestoreByte(address,set(address,value,1))
            : set(address, value, 1);
      }
   
    ///////////////////////////////////////////////////////////////////////////////////////
    /** 
     *  Writes 64 bit double value starting at specified Memory address.  Note that 
     *  high-order 32 bits are stored in higher (second) memory word regardless
     *  of “endianness”.
     * 
     * @param address Starting address of Memory address to be set.
     * @param value Value to be stored at that address.  
     * @return old value that was replaced by setDouble operation.
     **/    
       public double setDouble(int address, double value) throws AddressErrorException {
         int oldHighOrder, oldLowOrder;
         long longValue = Double.doubleToLongBits(value);
         oldHighOrder = set(address+4, Binary.highOrderLongToInt(longValue),4);
         oldLowOrder  = set(address, Binary.lowOrderLongToInt(longValue),4);
         return Double.longBitsToDouble(Binary.twoIntsToLong(oldHighOrder, oldLowOrder)); 
      }
     
   
   ////////////////////////////////////////////////////////////////////////////////
   /**
    * Stores ProgramStatement in Text Segment.  
    * @param address Starting address of Memory address to be set.  Must be word boundary.
    * @param statement Machine code to be stored starting at that address — for simulation
    * purposes, actually stores reference to ProgramStatement instead of 32-bit machine code.
    * @throws AddressErrorException If address is not on word boundary or is outside Text Segment.
    * @see ProgramStatement
    **/
   
       public void setStatement(int address, ProgramStatement statement) throws AddressErrorException {
         if (address % 4 != 0 || !(inTextSegment(address) || inKernelTextSegment(address))) {
            throw new AddressErrorException(
               “store address to text segment out of range or not aligned to word boundary “,
               Exceptions.ADDRESS_EXCEPTION_STORE, address);
         }
         if (Globals.debug) System.out.println(“memory[“+address+”] set to “+statement.getBinaryStatement());
         if (inTextSegment(address)) {
            storeProgramStatement(address, statement, textBaseAddress, textBlockTable);
         } 
         else {
            storeProgramStatement(address, statement, kernelTextBaseAddress, kernelTextBlockTable);
         }
      }
    
   
   
   /********************************  THE GETTER METHODS  ******************************/
   
   //////////////////////////////////////////////////////////////////////////////////////////
   /**
    * Starting at the given word address, read the given number of bytes (max 4).
    * This one does not check for word boundaries, and copies one byte at a time.
    * If length == 1, puts value in low order byte.  If 2, puts into low order half-word.
    * @param address Starting address of Memory address to be read.
    * @param length Number of bytes to be read.
    * @return  Value stored starting at that address.
    **/
    
       public int get(int address, int length) throws AddressErrorException {
         return get(address, length, true);
      }
    
    // Does the real work, but includes option to NOT notify observers.
       private int get(int address, int length, boolean notify) throws AddressErrorException {
         int value = 0;
         int relativeByteAddress;
         if (inDataSegment(address)) {
           // in data segment.  Will read one byte at a time, w/o regard to boundaries.
            relativeByteAddress = address – dataSegmentBaseAddress; // relative to data segment start, in bytes
            value = fetchBytesFromTable(dataBlockTable, relativeByteAddress, length);
         } 
         else if (address > stackLimitAddress && address <= stackBaseAddress) {            // in stack. Similar to data, except relative address computed "backward"             relativeByteAddress = stackBaseAddress - address;             value = fetchBytesFromTable(stackBlockTable, relativeByteAddress, length);          }                     else if (address >= memoryMapBaseAddress && address < memoryMapLimitAddress) {            // memory mapped I/O.             relativeByteAddress = address - memoryMapBaseAddress;             value = fetchBytesFromTable(memoryMapBlockTable, relativeByteAddress, length);          }          else if (inTextSegment(address)) {            // DEVELOPER: PLEASE USE getStatement() TO READ FROM TEXT SEGMENT...             throw new AddressErrorException(                "DEVELOPER: You must use getStatement() to read from text segment!",                 Exceptions.ADDRESS_EXCEPTION_LOAD, address);          }           else if (inKernelDataSegment(address)) {            // in kernel data segment.  Will read one byte at a time, w/o regard to boundaries.             relativeByteAddress = address - kernelDataBaseAddress; // relative to data segment start, in bytes             value = fetchBytesFromTable(kernelDataBlockTable, relativeByteAddress, length);          }           else if (inKernelTextSegment(address)) {            // DEVELOPER: PLEASE USE getStatement() TO READ FROM KERNEL TEXT SEGMENT...             throw new AddressErrorException(                "DEVELOPER: You must use getStatement() to read from kernel text segment!",                 Exceptions.ADDRESS_EXCEPTION_LOAD, address);          }           else {            // falls outside Mars addressing range             throw new AddressErrorException("address out of range ",                Exceptions.ADDRESS_EXCEPTION_LOAD, address);          }          if (notify) notifyAnyObservers(AccessNotice.READ, address, length, value);          return value;       }            /////////////////////////////////////////////////////////////////////////     /**       *  Starting at the given word address, read a 4 byte word as an int.        *  It transfers the 32 bit value "raw" as stored in memory, and does not adjust       *  for byte order (big or little endian).  Address must be word-aligned.      *       * @param address Starting address of word to be read.      * @return  Word (4-byte value) stored starting at that address.      * @throws AddressErrorException If address is not on word boundary.     **/              // Note: the logic here is repeated in getRawWordOrNull() below.  Logic is     // simplified by having this method just call getRawWordOrNull() then      // return either the int of its return value, or 0 if it returns null.     // Doing so would be detrimental to simulation runtime performance, so     // I decided to keep the duplicate logic.        public int getRawWord(int address) throws AddressErrorException {          int value = 0;          int relative;          if (address % WORD_LENGTH_BYTES != 0) {             throw new AddressErrorException("address for fetch not aligned on word boundary",                Exceptions.ADDRESS_EXCEPTION_LOAD, address);          }          if (inDataSegment(address)) {            // in data segment             relative = (address - dataSegmentBaseAddress) >> 2; // convert byte address to words
            value = fetchWordFromTable(dataBlockTable, relative);
         } 
         else if (address > stackLimitAddress && address <= stackBaseAddress) {            // in stack. Similar to data, except relative address computed "backward"             relative = (stackBaseAddress - address) >> 2; // convert byte address to words
            value = fetchWordFromTable(stackBlockTable, relative);
         }
         else if (address >= memoryMapBaseAddress && address < memoryMapLimitAddress) {            // memory mapped I/O.             relative = (address - memoryMapBaseAddress) >> 2;
            value = fetchWordFromTable(memoryMapBlockTable, relative);
         }
         else if (inTextSegment(address)) {
           // DEVELOPER: PLEASE USE getStatement() TO READ FROM TEXT SEGMENT…
            throw new AddressErrorException(
                    “DEVELOPER: You must use getStatement() to read from text segment!”,
                  Exceptions.ADDRESS_EXCEPTION_LOAD, address);
         }  
         else if (inKernelDataSegment(address)) {
           // in kernel data segment
            relative = (address – kernelDataBaseAddress) >> 2; // convert byte address to words
            value = fetchWordFromTable(kernelDataBlockTable, relative);
         } 
         else if (inKernelTextSegment(address)) {
           // DEVELOPER: PLEASE USE getStatement() TO READ FROM KERNEL TEXT SEGMENT…
            throw new AddressErrorException(
                    “DEVELOPER: You must use getStatement() to read from kernel text segment!”,
                  Exceptions.ADDRESS_EXCEPTION_LOAD, address);
         } 
         else {
           // falls outside Mars addressing range
            throw new AddressErrorException(“address out of range “, 
               Exceptions.ADDRESS_EXCEPTION_LOAD, address);
         }
         notifyAnyObservers(AccessNotice.READ, address, Memory.WORD_LENGTH_BYTES,value);
         return value;
      } 
   
      /////////////////////////////////////////////////////////////////////////
       /** 
        *  Starting at the given word address, read a 4 byte word as an int and return Integer.  
        *  It transfers the 32 bit value “raw” as stored in memory, and does not adjust 
        *  for byte order (big or little endian).  Address must be word-aligned.
      *
      *  Returns null if reading from text segment and there is no instruction at the
      *  requested address. Returns null if reading from data segment and this is the
      *  first reference to the MARS 4K memory allocation block (i.e., an array to
      *  hold the memory has not been allocated).
      *
      *  This method was developed by Greg Giberling of UC Berkeley to support the memory
      *  dump feature that he implemented in Fall 2007.
        * 
        * @param address Starting address of word to be read.
        * @return  Word (4-byte value) stored starting at that address as an Integer.  Conditions
      * that cause return value null are described above.
        * @throws AddressErrorException If address is not on word boundary.
       **/
     
     // See note above, with getRawWord(), concerning duplicated logic.
     
       public Integer getRawWordOrNull(int address) throws AddressErrorException {
         Integer value = null;
         int relative;
         if (address % WORD_LENGTH_BYTES != 0) {
            throw new AddressErrorException(“address for fetch not aligned on word boundary”,
                  Exceptions.ADDRESS_EXCEPTION_LOAD, address);
         }
         if (inDataSegment(address)) {
              // in data segment
            relative = (address – dataSegmentBaseAddress) >> 2; // convert byte address to words
            value = fetchWordOrNullFromTable(dataBlockTable, relative);
         } 
         else if (address > stackLimitAddress && address <= stackBaseAddress) {               // in stack. Similar to data, except relative address computed "backward"             relative = (stackBaseAddress - address) >> 2; // convert byte address to words
            value = fetchWordOrNullFromTable(stackBlockTable, relative);
         }
         else if (inTextSegment(address) || inKernelTextSegment(address)) {
            try { 
               value = (getStatementNoNotify(address) == null) ? null : new Integer(getStatementNoNotify(address).getBinaryStatement());
            } 
                catch (AddressErrorException aee) { 
                  value = null;               }
         }  
         else if (inKernelDataSegment(address)) {
              // in kernel data segment
            relative = (address – kernelDataBaseAddress) >> 2; // convert byte address to words
            value = fetchWordOrNullFromTable(kernelDataBlockTable, relative);
         } 
         else {
              // falls outside Mars addressing range
            throw new AddressErrorException(“address out of range “, Exceptions.ADDRESS_EXCEPTION_LOAD, address);
         }
            // Do not notify observers.  This read operation is initiated by the 
            // dump feature, not the executing MIPS program.
         return value;
      } 
   
     /**
      *  Look for first “null” memory value in an address range.  For text segment (binary code), this
    *  represents a word that does not contain an instruction.  Normally use this to find the end of 
    *  the program.  For data segment, this represents the first block of simulated memory (block length
    *  currently 4K words) that has not been referenced by an assembled/executing program.
    *
    *  @param baseAddress lowest MIPS address to be searched; the starting point
    *  @param limitAddress highest MIPS address to be searched
    *  @return lowest address within specified range that contains “null” value as described above.
    *  @throws AddressErrorException if the base address is not on a word boundary
    */
       public int getAddressOfFirstNull(int baseAddress, int limitAddress) throws AddressErrorException {
         int address = baseAddress;
         for (; address < limitAddress; address += Memory.WORD_LENGTH_BYTES) {             if (getRawWordOrNull(address) == null) {                break;             }          }          return address;       }             ///////////////////////////////////////////////////////////////////////////////////////     /**       *  Starting at the given word address, read a 4 byte word as an int.        *  Does not use "get()"; we can do it faster here knowing we're working only       *  with full words.      *       * @param address Starting address of word to be read.      * @return  Word (4-byte value) stored starting at that address.      * @throws AddressErrorException If address is not on word boundary.     **/        public int getWord(int address) throws AddressErrorException {          if (address % WORD_LENGTH_BYTES != 0) {             throw new AddressErrorException("fetch address not aligned on word boundary ",                Exceptions.ADDRESS_EXCEPTION_LOAD, address);          }          return get(address, WORD_LENGTH_BYTES, true);       }            ///////////////////////////////////////////////////////////////////////////////////////     /**       *  Starting at the given word address, read a 4 byte word as an int.        *  Does not use "get()"; we can do it faster here knowing we're working only       *  with full words.  Observers are NOT notified.      *       * @param address Starting address of word to be read.      * @return  Word (4-byte value) stored starting at that address.      * @throws AddressErrorException If address is not on word boundary.     **/        public int getWordNoNotify(int address) throws AddressErrorException {          if (address % WORD_LENGTH_BYTES != 0) {             throw new AddressErrorException("fetch address not aligned on word boundary ",                Exceptions.ADDRESS_EXCEPTION_LOAD, address);          }          return get(address, WORD_LENGTH_BYTES, false);       }                  ///////////////////////////////////////////////////////////////////////////////////////     /**       *  Starting at the given word address, read a 2 byte word into lower 16 bits of int.        *       * @param address Starting address of word to be read.      * @return  Halfword (2-byte value) stored starting at that address, stored in lower 16 bits.      * @throws AddressErrorException If address is not on halfword boundary.     **/           public int getHalf(int address) throws AddressErrorException {          if (address % 2 != 0) {             throw new AddressErrorException("fetch address not aligned on halfword boundary ",                Exceptions.ADDRESS_EXCEPTION_LOAD, address);          }          return get(address, 2);       }             ///////////////////////////////////////////////////////////////////////////////////////     /**       *  Reads specified Memory byte into low order 8 bits of int.      *       * @param address Address of Memory byte to be read.      * @return Value stored at that address.  Only low order 8 bits used.      **/        public int getByte(int address) throws AddressErrorException {          return get(address, 1);       }        ////////////////////////////////////////////////////////////////////////////////    /**     * Gets ProgramStatement from Text Segment.       * @param address Starting address of Memory address to be read.  Must be word boundary.     * @return reference to ProgramStatement object associated with that address, or null if none.     * @throws AddressErrorException If address is not on word boundary or is outside Text Segment.     * @see ProgramStatement     **/            public ProgramStatement getStatement(int address) throws AddressErrorException {          if (address % 4 != 0 || !(inTextSegment(address) || inKernelTextSegment(address))) {             throw new AddressErrorException(                "fetch address for text segment out of range or not aligned to word boundary ",                Exceptions.ADDRESS_EXCEPTION_LOAD, address);          }          if (inTextSegment(address)) {             return readProgramStatement(address, textBaseAddress, textBlockTable, true);          }           else {             return readProgramStatement(address, kernelTextBaseAddress, kernelTextBlockTable,true);          }       }        ////////////////////////////////////////////////////////////////////////////////    /**     * Gets ProgramStatement from Text Segment without notifying observers.     * @param address Starting address of Memory address to be read.  Must be word boundary.     * @return reference to ProgramStatement object associated with that address, or null if none.     * @throws AddressErrorException If address is not on word boundary or is outside Text Segment.     * @see ProgramStatement     **/            public ProgramStatement getStatementNoNotify(int address) throws AddressErrorException {          if (address % 4 != 0 || !(inTextSegment(address) || inKernelTextSegment(address))) {             throw new AddressErrorException(                "fetch address for text segment out of range or not aligned to word boundary ",                Exceptions.ADDRESS_EXCEPTION_LOAD, address);          }          if (inTextSegment(address)) {             return readProgramStatement(address, textBaseAddress, textBlockTable, false);          }           else {             return readProgramStatement(address, kernelTextBaseAddress, kernelTextBlockTable, false);          }       }                          /*********************************  THE UTILITIES  *************************************/         /**     *  Utility to determine if given address is word-aligned.     *  @param address the address to check     *  @return true if address is word-aligned, false otherwise     */        public static boolean wordAligned(int address) {          return (address % WORD_LENGTH_BYTES == 0);       }        /**     *  Utility to determine if given address is doubleword-aligned.     *  @param address the address to check     *  @return true if address is doubleword-aligned, false otherwise     */        public static boolean doublewordAligned(int address) {          return (address % (WORD_LENGTH_BYTES+WORD_LENGTH_BYTES) == 0);       }        /**     * Utility method to align given address to next full word boundary, if not already     * aligned.        * @param address  a memory address (any int value is potentially valid)     * @return address aligned to next word boundary (divisible by 4)     */        public static int alignToWordBoundary(int address) {          if (!wordAligned(address)) {             if (address > 0)
               address += (4-(address % WORD_LENGTH_BYTES));
            else
               address -= (4-(address % WORD_LENGTH_BYTES));
         }  
         return address;
      }
   
   /**
    * Handy little utility to find out if given address is in MARS text 
    * segment (starts at Memory.textBaseAddress).
    * Note that MARS does not implement the entire MIPS text segment space,
    * but it does implement enough for hundreds of thousands of lines
    * of code.
    * @param address integer memory address
    * @return true if that address is within MARS-defined text segment,
    *  false otherwise.
    */
       public static boolean inTextSegment(int address) {
         return  address >= textBaseAddress && address < textLimitAddress;       }        /**     * Handy little utility to find out if given address is in MARS kernel      * text segment (starts at Memory.kernelTextBaseAddress).     * @param address integer memory address     * @return true if that address is within MARS-defined kernel text segment,     *  false otherwise.     */        public static boolean inKernelTextSegment(int address) {          return  address >= kernelTextBaseAddress && address < kernelTextLimitAddress;       }          /**     * Handy little utility to find out if given address is in MARS data      * segment (starts at Memory.dataSegmentBaseAddress).     * Note that MARS does not implement the entire MIPS data segment space,     * but it does support at least 4MB.     * @param address integer memory address     * @return true if that address is within MARS-defined data segment,     *  false otherwise.     */        public static boolean inDataSegment(int address) {          return  address >= dataSegmentBaseAddress && address < dataSegmentLimitAddress;       }           /**     * Handy little utility to find out if given address is in MARS kernel data     * segment (starts at Memory.kernelDataSegmentBaseAddress).     * @param address integer memory address     * @return true if that address is within MARS-defined kernel data segment,     *  false otherwise.     */        public static boolean inKernelDataSegment(int address) {          return  address >= kernelDataBaseAddress && address < kernelDataSegmentLimitAddress;       }                     /**     * Handy little utility to find out if given address is in the Memory Map area      * starts at Memory.memoryMapBaseAddress, range 0xffff0000 to 0xffffffff.     * @param address integer memory address     * @return true if that address is within MARS-defined memory map (MMIO) area,     *  false otherwise.     */        public static boolean inMemoryMapSegment(int address) {          return  address >= memoryMapBaseAddress && address < kernelHighAddress;       }                        ///////////////////////////////////////////////////////////////////////////    //  ALL THE OBSERVABLE STUFF GOES HERE.  FOR COMPATIBILITY, Memory IS STILL     //  EXTENDING OBSERVABLE, BUT WILL NOT USE INHERITED METHODS.  WILL INSTEAD    //  USE A COLLECTION OF MemoryObserver OBJECTS, EACH OF WHICH IS COMBINATION    //  OF AN OBSERVER WITH AN ADDRESS RANGE.        /**     *  Method to accept registration from observer for any memory address.  Overrides     *  inherited method.  Note to observers: this class delegates Observable operations     *  so notices will come from the delegate, not the memory object.     *  @param obs  the observer     */             public void addObserver(Observer obs) {          try {  // split so start address always >= end address
            this.addObserver(obs, 0, 0x7ffffffc);
            this.addObserver(obs,0x80000000,0xfffffffc);
         } 
             catch (AddressErrorException aee) {
               System.out.println(“Internal Error in Memory.addObserver: “+aee); 
            }
      }
    
   /**
    *  Method to accept registration from observer for specific address.  This includes
    *  the memory word starting at the given address. Note to observers: this class delegates Observable operations
    *  so notices will come from the delegate, not the memory object.
    *
    *  @param obs  the observer
    *  @param addr the memory address which must be on word boundary
    */
   
       public void addObserver(Observer obs, int addr) throws AddressErrorException {
         this.addObserver(obs, addr, addr);
      }
   
   
   /**
    *  Method to accept registration from observer for specific address range.  The 
    *  last byte included in the address range is the last byte of the word specified
    *  by the ending address. Note to observers: this class delegates Observable operations
    *  so notices will come from the delegate, not the memory object.
    *
    *  @param obs  the observer
    *  @param startAddr the low end of memory address range, must be on word boundary
    *  @param endAddr the high end of memory address range, must be on word boundary
    */  
       public void addObserver(Observer obs, int startAddr, int endAddr) throws AddressErrorException {
         if (startAddr % WORD_LENGTH_BYTES != 0) {
            throw new AddressErrorException(“address not aligned on word boundary “,
               Exceptions.ADDRESS_EXCEPTION_LOAD, startAddr);
         }
         if (endAddr!=startAddr && endAddr % WORD_LENGTH_BYTES != 0) {
            throw new AddressErrorException(“address not aligned on word boundary “,
               Exceptions.ADDRESS_EXCEPTION_LOAD, startAddr);
         }
        // upper half of address space (above 0x7fffffff) has sign bit 1 thus is seen as
        // negative.
         if (startAddr>=0 && endAddr<0) {             throw new AddressErrorException("range cannot cross 0x8000000; please split it up",                Exceptions.ADDRESS_EXCEPTION_LOAD, startAddr);          }                       if (endAddr= lowAddress && address <= highAddress-1+WORD_LENGTH_BYTES);          }                    public void notifyObserver(MemoryAccessNotice notice) {             this.setChanged();             this.notifyObservers(notice);          }                   // Useful to have for future refactoring, if it actually becomes worthwhile to sort         // these or put 'em in a tree (rather than sequential search through list).           public int compareTo(Object obj) {             if (!(obj instanceof MemoryObservable)) {                throw new ClassCastException();             }             MemoryObservable mo = (MemoryObservable) obj;             if (this.lowAddress < mo.lowAddress || this.lowAddress==mo.lowAddress && this.highAddress < mo.highAddress) {                return -1;             }             if (this.lowAddress > mo.lowAddress || this.lowAddress==mo.lowAddress && this.highAddress > mo.highAddress) {
               return -1;
            }
            return 0;  // they have to be equal at this point.
         }
      }
      
   
   /*********************************  THE HELPERS  *************************************/
     
   
   ////////////////////////////////////////////////////////////////////////////////
   //
   // Method to notify any observers of memory operation that has just occurred.
   //
   // The “|| Globals.getGui()==null” is a hack added 19 July 2012 DPS.  IF MIPS simulation
    // is from command mode, Globals.program is null but still want ability to observe.
       private void notifyAnyObservers(int type, int address, int length, int value) {
         if ((Globals.program != null || Globals.getGui()==null) && this.observables.size() > 0) {
            Iterator it = this.observables.iterator();
            MemoryObservable mo;
            while (it.hasNext()) {
               mo = (MemoryObservable)it.next();
               if (mo.match(address)) { 
                  mo.notifyObserver(new MemoryAccessNotice(type, address, length, value));
               }
            }
         }      
      }
   
   ////////////////////////////////////////////////////////////////////////////////
   //
   // Helper method to store 1, 2 or 4 byte value in table that represents MIPS
   // memory. Originally used just for data segment, but now also used for stack.
   // Both use different tables but same storage method and same table size
   // and block size.
   // Modified 29 Dec 2005 to return old value of replaced bytes.
   //
      private static final boolean STORE = true;
      private static final boolean FETCH = false;
     
       private int storeBytesInTable(int [][] blockTable, 
                                   int relativeByteAddress, int length, int value) {
         return storeOrFetchBytesInTable(blockTable, relativeByteAddress, length, value, STORE);
      }
    
   ////////////////////////////////////////////////////////////////////////////////
   //
   // Helper method to fetch 1, 2 or 4 byte value from table that represents MIPS
   // memory.  Originally used just for data segment, but now also used for stack.
   // Both use different tables but same storage method and same table size
   // and block size.
   //   
   
       private int fetchBytesFromTable(int[][] blockTable, int relativeByteAddress, int length) {
         return storeOrFetchBytesInTable(blockTable, relativeByteAddress, length, 0, FETCH);
      }
   
   ////////////////////////////////////////////////////////////////////////////////     
   //
   // The helper’s helper.  Works for either storing or fetching, little or big endian. 
   // When storing/fetching bytes, most of the work is calculating the correct array element(s) 
   // and element byte(s).  This method performs either store or fetch, as directed by its 
   // client using STORE or FETCH in last arg.
   // Modified 29 Dec 2005 to return old value of replaced bytes, for STORE.
   //
       private synchronized int storeOrFetchBytesInTable(int [][] blockTable, 
                                   int relativeByteAddress, int length, int value, boolean op) {
         int relativeWordAddress, block, offset, bytePositionInMemory, bytePositionInValue;
         int oldValue = 0; // for STORE, return old values of replaced bytes
         int loopStopper = 3-length;
        // IF added DPS 22-Dec-2008. NOTE: has NOT been tested with Big-Endian.
        // Fix provided by Saul Spatz; comments that follow are his.
        // If address in stack segment is 4k + m, with 0 < m < 4, then the          // relativeByteAddress we want is stackBaseAddress - 4k + m, but the          // address actually passed in is stackBaseAddress - (4k + m), so we          // need to add 2m.  Because of the change in sign, we get the          // expression 4-delta below in place of m.          if (blockTable == stackBlockTable) {             int delta = relativeByteAddress % 4;             if (delta != 0) {                relativeByteAddress += ( 4 - delta ) << 1;             }          }          for (bytePositionInValue = 3; bytePositionInValue > loopStopper; bytePositionInValue–) {
            bytePositionInMemory = relativeByteAddress % 4;
            relativeWordAddress = relativeByteAddress >> 2;
            block = relativeWordAddress / BLOCK_LENGTH_WORDS;  // Block number
            offset = relativeWordAddress % BLOCK_LENGTH_WORDS; // Word within that block
            if (blockTable[block] == null) {
               if (op==STORE) 
                  blockTable[block] = new int[BLOCK_LENGTH_WORDS];
               else 
                  return 0;
            }
            if (byteOrder == LITTLE_ENDIAN) bytePositionInMemory = 3 – bytePositionInMemory;
            if (op == STORE) {
               oldValue = replaceByte(blockTable[block][offset], bytePositionInMemory,
                                                oldValue, bytePositionInValue);
               blockTable[block][offset] = replaceByte(value, bytePositionInValue, 
                                         blockTable[block][offset], bytePositionInMemory);
            } 
            else {// op == FETCH
               value = replaceByte(blockTable[block][offset], bytePositionInMemory, 
                                                          value, bytePositionInValue);
            }
            relativeByteAddress++;
         }
         return (op == STORE)   ? oldValue : value;
      } 
   
   ////////////////////////////////////////////////////////////////////////////////
   //
   // Helper method to store 4 byte value in table that represents MIPS memory.
   // Originally used just for data segment, but now also used for stack.
   // Both use different tables but same storage method and same table size
   // and block size.  Assumes address is word aligned, no endian processing.
   // Modified 29 Dec 2005 to return overwritten value.
         
       private synchronized int storeWordInTable(int[][] blockTable, int relative, int value) {
         int  block, offset, oldValue;
         block = relative / BLOCK_LENGTH_WORDS;
         offset = relative % BLOCK_LENGTH_WORDS; 
         if (blockTable[block] == null) {
               // First time writing to this block, so allocate the space.
            blockTable[block] = new int[BLOCK_LENGTH_WORDS];
         }
         oldValue = blockTable[block][offset];
         blockTable[block][offset] = value;
         return oldValue;
      }
      
   ////////////////////////////////////////////////////////////////////////////////
   //
   // Helper method to fetch 4 byte value from table that represents MIPS memory.
   // Originally used just for data segment, but now also used for stack.
   // Both use different tables but same storage method and same table size
   // and block size.  Assumes word alignment, no endian processing.
   //
   
       private synchronized int fetchWordFromTable(int[][] blockTable, int relative) {
         int value = 0;
         int block, offset;
         block = relative / BLOCK_LENGTH_WORDS;
         offset = relative % BLOCK_LENGTH_WORDS; 
         if (blockTable[block] == null) {
                   // first reference to an address in this block.  Assume initialized to 0.
            value = 0;
         } 
         else {
            value = blockTable[block][offset];
         }
         return value;
      }     
       
       ////////////////////////////////////////////////////////////////////////////////
       //
       // Helper method to fetch 4 byte value from table that represents MIPS memory.
       // Originally used just for data segment, but now also used for stack.
       // Both use different tables but same storage method and same table size
       // and block size.  Assumes word alignment, no endian processing.
     //
     // This differs from “fetchWordFromTable()” in that it returns an Integer and
     // returns null instead of 0 if the 4K table has not been allocated.  Developed
     // by Greg Gibeling of UC Berkeley, fall 2007.
       //
       
       private synchronized Integer fetchWordOrNullFromTable(int[][] blockTable, int relative) {
         int value = 0;
         int block, offset;
         block = relative / BLOCK_LENGTH_WORDS;
         offset = relative % BLOCK_LENGTH_WORDS; 
         if (blockTable[block] == null) {
                       // first reference to an address in this block.  Assume initialized to 0.
            return null;
         } 
         else {
            value = blockTable[block][offset];
         }
         return new Integer(value);
      }
       
   ////////////////////////////////////////////////////////////////////////////////////
   // Returns result of substituting specified byte of source value into specified byte 
   // of destination value. Byte positions are 0-1-2-3, listed from most to least 
   // significant.  No endian issues.  This is a private helper method used by get() & set().
       private int replaceByte(int sourceValue, int bytePosInSource, int destValue, int bytePosInDest) {
         return
            // Set source byte value into destination byte position; set other 24 bits to 0’s…
             ((sourceValue >> (24 – (bytePosInSource << 3)) & 0xFF)                                               << (24 - (bytePosInDest << 3)))             // and bitwise-OR it with...               |             // Set 8 bits in destination byte position to 0's, other 24 bits are unchanged.              (destValue & ~(0xFF << (24 - (bytePosInDest << 3))));       }           ///////////////////////////////////////////////////////////////////////    // Reverses byte sequence of given value.  Can use to convert between big and    // little endian if needed.        private int reverseBytes(int source) {          return  (source >> 24 & 0x000000FF) |
                 (source >> 8  & 0x0000FF00) |
                  (source << 8  & 0x00FF0000) |                   (source << 24);       }        ///////////////////////////////////////////////////////////////////////          // Store a program statement at the given address.  Address has already been verified    // as valid.  It may be either in user or kernel text segment, as specified by arguments.        private void storeProgramStatement(int address, ProgramStatement statement,                                            int baseAddress, ProgramStatement[][] blockTable) {          int relative = (address - baseAddress) >> 2; // convert byte address to words
         int block = relative / BLOCK_LENGTH_WORDS;
         int offset = relative % BLOCK_LENGTH_WORDS; 
         if (block < TEXT_BLOCK_TABLE_LENGTH) {             if (blockTable[block] == null) {                // No instructions are stored in this block, so allocate the block.                blockTable[block] = new ProgramStatement[BLOCK_LENGTH_WORDS];             }             blockTable[block][offset] = statement;          }       }            ///////////////////////////////////////////////////////////////////////          // Read a program statement from the given address.  Address has already been verified    // as valid.  It may be either in user or kernel text segment, as specified by arguments.      // Returns associated ProgramStatement or null if none.     // Last parameter controls whether or not observers will be notified.        private ProgramStatement readProgramStatement(int address, int baseAddress, ProgramStatement[][] blockTable, boolean notify) {          int relative = (address - baseAddress) >> 2; // convert byte address to words
         int block = relative / TEXT_BLOCK_LENGTH_WORDS;
         int offset = relative % TEXT_BLOCK_LENGTH_WORDS; 
         if (block < TEXT_BLOCK_TABLE_LENGTH) {             if (blockTable[block] == null || blockTable[block][offset] == null) {                // No instructions are stored in this block or offset.                if (notify) notifyAnyObservers(AccessNotice.READ, address, Instruction.INSTRUCTION_LENGTH,0);                return null;             }              else {                if (notify) notifyAnyObservers(AccessNotice.READ, address, Instruction.INSTRUCTION_LENGTH, blockTable[block][offset].getBinaryStatement());                return blockTable[block][offset];             }          }          if (notify) notifyAnyObservers(AccessNotice.READ, address, Instruction.INSTRUCTION_LENGTH,0);          return null;       }             } Memory$MemoryObservable package mars.mips.hardware; synchronized class Memory$MemoryObservable extends java.util.Observable implements Comparable { private int lowAddress; private int highAddress; public void Memory$MemoryObservable(Memory, java.util.Observer, int, int); public boolean match(int); public void notifyObserver(MemoryAccessNotice); public int compareTo(Object); } mars/mips/hardware/RegisterAccessNotice.java mars/mips/hardware/RegisterAccessNotice.javapackage mars.mips.hardware; /* Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Object provided to Observers of runtime access to MIPS register.  * Observer can get the access type (R/W) and register number.  *   * @author Pete Sanderson   * @version July 2005  */ public class RegisterAccessNotice extends AccessNotice {    private String registerName;   /** Constructor will be called only within this package, so assume    *  register number is in valid range.     */   RegisterAccessNotice(int type, String registerName) {      super(type);       this.registerName = registerName;   }  /** Fetch the register number of register accessed. */   public String getRegisterName() {      return registerName;   }  /** String representation indicates access type and which register */     public String toString() {      return ((this.getAccessType()==AccessNotice.READ) ? "R " : "W ") +              "Reg " + registerName;   }    } AddressErrorException package mars.mips.hardware; public synchronized class AddressErrorException extends Exception { private int address; private int type; public void AddressErrorException(String, int, int); public int getAddress(); public int getType(); } RegisterAccessNotice package mars.mips.hardware; public synchronized class RegisterAccessNotice extends AccessNotice { private String registerName; void RegisterAccessNotice(int, String); public String getRegisterName(); public String toString(); } mars/mips/hardware/RegisterFile.java mars/mips/hardware/RegisterFile.java   package mars.mips.hardware;    import java.util.Observer;    import mars.Globals;    import mars.assembler.SymbolTable;    import mars.mips.instructions.Instruction;    import mars.util.Binary; /* Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**   *  Represents the collection of MIPS registers.   *   @author Jason Bumgarner, Jason Shrewsbury   *   @version June 2003   **/     public  class RegisterFile {           public static final int GLOBAL_POINTER_REGISTER = 28;       public static final int STACK_POINTER_REGISTER = 29;           private static Register [] regFile =            { new Register("$zero", 0, 0), new Register("$at", 1, 0),             new Register("$v0", 2, 0),new Register("$v1", 3, 0),             new Register("$a0", 4, 0),new Register("$a1", 5, 0),             new Register("$a2", 6, 0),new Register("$a3", 7, 0),             new Register("$t0", 8, 0),new Register("$t1", 9, 0),             new Register("$t2", 10, 0),new Register("$t3", 11, 0),              new Register("$t4", 12, 0),new Register("$t5", 13, 0),             new Register("$t6", 14, 0),new Register("$t7", 15, 0),             new Register("$s0", 16, 0),new Register("$s1", 17, 0),             new Register("$s2", 18, 0),new Register("$s3", 19, 0),             new Register("$s4", 20, 0),new Register("$s5", 21, 0),             new Register("$s6", 22, 0),new Register("$s7", 23, 0),             new Register("$t8", 24, 0),new Register("$t9", 25, 0),             new Register("$k0", 26, 0),new Register("$k1", 27, 0),             new Register("$gp", GLOBAL_POINTER_REGISTER, Memory.globalPointer),             new Register("$sp", STACK_POINTER_REGISTER, Memory.stackPointer),             new Register("$fp", 30, 0),new Register("$ra", 31, 0)            };                                                                  private static Register programCounter= new Register("pc", 32, Memory.textBaseAddress);        private static Register hi= new Register("hi", 33, 0);//this is an internal register with arbitrary number       private static Register lo= new Register("lo", 34, 0);// this is an internal register with arbitrary number                   /**       *  Method for displaying the register values for debugging.       **/                      public static void showRegisters(){          for (int i=0; i< regFile.length; i++){             System.out.println("Name: " + regFile[i].getName());             System.out.println("Number: " + regFile[i].getNumber());             System.out.println("Value: " + regFile[i].getValue());               System.out.println("");           }       }                       /**       *  This method updates the register value who's number is num.  Also handles the lo and hi registers       *   @param num Register to set the value of.       *   @param val The desired value for the register.       **/               public static int updateRegister(int num, int val){          int old = 0;          if(num == 0){             //System.out.println("You can not change the value of the zero register.");          }          else {             for (int i=0; i< regFile.length; i++){                if(regFile[i].getNumber()== num) {                   old = (Globals.getSettings().getBackSteppingEnabled())                         ? Globals.program.getBackStepper().addRegisterFileRestore(num,regFile[i].setValue(val))                         : regFile[i].setValue(val);                   break;                }             }          }          if(num== 33){//updates the hi register             old = (Globals.getSettings().getBackSteppingEnabled())                       ? Globals.program.getBackStepper().addRegisterFileRestore(num,hi.setValue(val))                         : hi.setValue(val);          }          else if(num== 34){// updates the low register             old = (Globals.getSettings().getBackSteppingEnabled())                       ? Globals.program.getBackStepper().addRegisterFileRestore(num,lo.setValue(val))                         : lo.setValue(val);          }          return old;       }          /**       *  Sets the value of the register given to the value given.       *   @param reg Name of register to set the value of.       *   @param val The desired value for the register.       **/             public static void updateRegister(String reg, int val){          if(reg.equals("zero")){             //System.out.println("You can not change the value of the zero register.");          }          else{             for (int i=0; i< regFile.length; i++){                if(regFile[i].getName().equals(reg)) {                   updateRegister(i,val);                   break;                }             }}       }              /**       *  Returns the value of the register who's number is num.       *   @param num The register number.       *   @return The value of the given register.       **/             public static int getValue(int num){          if(num==33){             return hi.getValue();          }          else if(num==34){             return lo.getValue();          }          else               return regFile[num].getValue();                    }                      /**           *  For getting the number representation of the register.           *   @param n The string formatted register name to look for.           *   @return The number of the register represented by the string           *   or -1 if no match.           **/                        public static int getNumber(String n){          int j=-1;          for (int i=0; i< regFile.length; i++){             if(regFile[i].getName().equals(n)) {                j= regFile[i].getNumber();                break;             }          }           return j;            }            /**       *  For returning the set of registers.       *   @return The set of registers.       **/             public static Register[] getRegisters(){          return regFile;       }            /**       *  Get register object corresponding to given name.  If no match, return null.       *   @param Rname The register name, either in $0 or $zero format.       *   @return The register object,or null if not found.       **/             public static Register getUserRegister(String Rname) {          Register reg = null;          if (Rname.charAt(0) == '$') {             try {                    // check for register number 0-31.                reg = regFile[Binary.stringToInt(Rname.substring(1))];    // KENV 1/6/05             }                 catch (Exception e) {                    // handles both NumberFormat and ArrayIndexOutOfBounds                    // check for register mnemonic $zero thru $ra                   reg = null; // just to be sure                    // just do linear search; there aren't that many registers                   for (int i=0; i < regFile.length; i++) {                      if (Rname.equals(regFile[i].getName())) {                         reg = regFile[i];                         break;                      }                   }                }          }          return reg;       }         /**       *  For initializing the Program Counter.  Do not use this to implement jumps and       *  branches, as it will NOT record a backstep entry with the restore value.       *  If you need backstepping capability, use setProgramCounter instead.       *   @param value The value to set the Program Counter to.       **/              public static void initializeProgramCounter(int value){          programCounter.setValue(value);       }          /**      *  Will initialize the Program Counter to either the default reset value, or the address       *  associated with source program global label "main", if it exists as a text segment label      *  and the global setting is set.      *  @param startAtMain  If true, will set program counter to address of statement labeled      *  'main' (or other defined start label) if defined.  If not defined, or if parameter false,      *  will set program counter to default reset value.      **/              public static void initializeProgramCounter(boolean startAtMain) {            int mainAddr = Globals.symbolTable.getAddress(SymbolTable.getStartLabel());          if (startAtMain && mainAddr != SymbolTable.NOT_FOUND && (Memory.inTextSegment(mainAddr) || Memory.inKernelTextSegment(mainAddr))) {             initializeProgramCounter(mainAddr);          }           else {             initializeProgramCounter(programCounter.getResetValue());          }       }          /**       *  For setting the Program Counter.  Note that ordinary PC update should be done using       *  incrementPC() method. Use this only when processing jumps and branches.       *   @param value The value to set the Program Counter to.       *   @return previous PC value       **/              public static int setProgramCounter(int value){          int old = programCounter.getValue();          programCounter.setValue(value);          if (Globals.getSettings().getBackSteppingEnabled()) {             Globals.program.getBackStepper().addPCRestore(old);          }           return old;       }            /**       *  For returning the program counters value.       *  @return The program counters value as an int.       **/              public static int getProgramCounter(){          return programCounter.getValue();       }          /**       *  Returns Register object for program counter.  Use with caution.     *  @return program counter's Register object.     */        public static Register getProgramCounterRegister() {          return programCounter;       }           /**       *  For returning the program counter's initial (reset) value.       *  @return The program counter's initial value       **/              public static int getInitialProgramCounter(){          return programCounter.getResetValue();       }          /**       *  Method to reinitialize the values of the registers.       *  NOTE: Should not be called from command-mode MARS because this
      *  this method uses global settings from the registry.  Command-mode must operate
      *  using only the command switches, not registry settings.  It can be called
      *  from tools running stand-alone, and this is done in 
      *  AbstractMarsToolAndApplication.
      **/
    
       public static void resetRegisters(){
         for(int i=0; i< regFile.length; i++){             regFile[i].resetValue();          }          initializeProgramCounter(Globals .getSettings().getStartAtMain());// replaces "programCounter.resetValue()", DPS 3/3/09          hi.resetValue();          lo.resetValue();       }             /**        *  Method to increment the Program counter in the general case (not a jump or branch).      **/            public static void incrementPC(){          programCounter.setValue(programCounter.getValue() + Instruction.INSTRUCTION_LENGTH);       }           /**      *  Each individual register is a separate object and Observable.  This handy method      *  will add the given Observer to each one.  Currently does not apply to Program      *  Counter.      */        public static void addRegistersObserver(Observer observer) {          for (int i=0; i();
public void DumpFormatLoader();
public java.util.ArrayList loadDumpFormats();
public static DumpFormat findDumpFormatGivenCommandDescriptor(java.util.ArrayList, String);
}

MIFDumpFormat

package mars.mips.dump;
public synchronized class MIFDumpFormat {
public void MIFDumpFormat();
public void dumpMemoryRange(java.io.File, int, int) throws mars.mips.hardware.AddressErrorException, java.io.IOException;
}

IntelHexDumpFormat

package mars.mips.dump;
public synchronized class IntelHexDumpFormat extends AbstractDumpFormat {
public void IntelHexDumpFormat();
public void dumpMemoryRange(java.io.File, int, int) throws mars.mips.hardware.AddressErrorException, java.io.IOException;
}

mars/mips/dump/BinaryDumpFormat.java
mars/mips/dump/BinaryDumpFormat.java   package mars.mips.dump;

   import mars.Globals;
   import mars.mips.hardware.*;
   import java.io.*;
/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Class that represents the “binary” memory dump format.  The output 
 * is a binary file containing the memory words as a byte stream.  Output
 * is produced using PrintStream’s write() method.
 * @author Pete Sanderson 
 * @version December 2007
 */

    public class BinaryDumpFormat extends AbstractDumpFormat {
   
   /**
   *  Constructor.  There is no standard file extension for this format.
   */
       public BinaryDumpFormat() {
         super(“Binary”, “Binary”, “Written as byte stream to binary file”, null);
      }
   
   
   /**
   *  Write MIPS memory contents in pure binary format.  One byte at a time
    *  using PrintStream’s write() method.  Adapted by Pete Sanderson from
    *  code written by Greg Gibeling.
    *
   *  @param  file  File in which to store MIPS memory contents.  
   *  @param firstAddress first (lowest) memory address to dump.  In bytes but
   *  must be on word boundary.
   *  @param lastAddress last (highest) memory address to dump.  In bytes but
   *  must be on word boundary.  Will dump the word that starts at this address.
    *  @throws AddressErrorException if firstAddress is invalid or not on a word boundary.
    *  @throws IOException if error occurs during file output.
   */
       public void dumpMemoryRange(File file, int firstAddress, int lastAddress) 
        throws AddressErrorException, IOException {
         PrintStream out = new PrintStream(new FileOutputStream(file));
         try {
            for (int address = firstAddress; address <= lastAddress; address += Memory.WORD_LENGTH_BYTES) {                Integer temp = Globals.memory.getRawWordOrNull(address);                if (temp == null)                    break;                int word = temp.intValue();                for (int i = 0; i < 4; i++)                    out.write((word >>> (i << 3)) & 0xFF);             }          }           finally {              out.close();           }       }        } mars/mips/dump/HexTextDumpFormat.java mars/mips/dump/HexTextDumpFormat.java   package mars.mips.dump;    import mars.Globals;    import mars.mips.hardware.*;    import java.io.*; /* Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Class that represents the "hexadecimal text" memory dump format.  The output   * is a text file with one word of MIPS memory per line.  The word is formatted  * using hexadecimal characters, e.g. 3F205A39.  * @author Pete Sanderson   * @version December 2007  */     public class HexTextDumpFormat extends AbstractDumpFormat {        /**    *  Constructor.  There is no standard file extension for this format.    */        public HexTextDumpFormat() {          super("Hexadecimal Text", "HexText", "Written as hex characters to text file", null);       }            /**    *  Write MIPS memory contents in hexadecimal text format.  Each line of    *  text contains one memory word written in hexadecimal characters.  Written     *  using PrintStream's println() method.    *  Adapted by Pete Sanderson from code written by Greg Gibeling.    *    *  @param  file  File in which to store MIPS memory contents.      *  @param firstAddress first (lowest) memory address to dump.  In bytes but    *  must be on word boundary.    *  @param lastAddress last (highest) memory address to dump.  In bytes but    *  must be on word boundary.  Will dump the word that starts at this address.    *  @throws AddressErrorException if firstAddress is invalid or not on a word boundary.    *  @throws IOException if error occurs during file output.    */        public void dumpMemoryRange(File file, int firstAddress, int lastAddress)          throws AddressErrorException, IOException {          PrintStream out = new PrintStream(new FileOutputStream(file));          String string = null;          try {             for (int address = firstAddress; address <= lastAddress; address += Memory.WORD_LENGTH_BYTES) {                Integer temp = Globals.memory.getRawWordOrNull(address);                if (temp == null)                    break;                string = Integer.toHexString(temp.intValue());                while (string.length() < 8) {                   string = '0' + string;                }                out.println(string);             }          }           finally {              out.close();           }       }        } mars/mips/dump/IntelHexDumpFormat.java mars/mips/dump/IntelHexDumpFormat.java   package mars.mips.dump;    import mars.Globals;    import mars.mips.hardware.*;    import java.io.*; /**  * Intel's Hex memory initialization format  * @author Leo Alterman  * @version July 2011  */     public class IntelHexDumpFormat extends AbstractDumpFormat {        /**    * Constructor.  File extention is "hex".    */           public IntelHexDumpFormat() {          super("Intel hex format", "HEX", "Written as Intel Hex Memory File", "hex");       }        /**    *  Write MIPS memory contents according to the Memory Initialization File    *  (MIF) specification.     *    *  @param  file  File in which to store MIPS memory contents.      *  @param firstAddress first (lowest) memory address to dump.  In bytes but    *  must be on word boundary.    *  @param lastAddress last (highest) memory address to dump.  In bytes but    *  must be on word boundary.  Will dump the word that starts at this address.    *  @throws AddressErrorException if firstAddress is invalid or not on a word boundary.    *  @throws IOException if error occurs during file output.    */        public void dumpMemoryRange(File file, int firstAddress, int lastAddress)           throws AddressErrorException, IOException {             PrintStream out = new PrintStream(new FileOutputStream(file));             String string = null;             try {                for (int address = firstAddress; address <= lastAddress; address += Memory.WORD_LENGTH_BYTES) {                   Integer temp = Globals.memory.getRawWordOrNull(address);                   if (temp == null)                       break;                   string = Integer.toHexString(temp.intValue());                   while (string.length() < 8) {                      string = '0' + string;                   }                   String addr = Integer.toHexString(address-firstAddress);                   while (addr.length() < 4) {                      addr = '0' + addr;                   }                   String chksum;                   int tmp_chksum = 0;                   tmp_chksum += 4;                   tmp_chksum += 0xFF & (address-firstAddress);                   tmp_chksum += 0xFF & ((address-firstAddress)>>8);
                  tmp_chksum += 0xFF & temp.intValue();
                  tmp_chksum += 0xFF & (temp.intValue()>>8);
                  tmp_chksum += 0xFF & (temp.intValue()>>16);
                  tmp_chksum += 0xFF & (temp.intValue()>>24);
                  tmp_chksum = tmp_chksum % 256;
                  tmp_chksum = ~tmp_chksum + 1;
                  chksum = Integer.toHexString(0xFF & tmp_chksum);
                  if(chksum.length()==1) chksum = ‘0’ + chksum;
                  String finalstr = “:04″+addr+”00″+string+chksum;
                  out.println(finalstr.toUpperCase());
               }
               out.println(“:00000001FF”);
            } 
            finally { 
               out.close(); 
            }
            
      }
   }

Globals

package mars;
public synchronized class Globals {
private static String configPropertiesFile;
private static String syscallPropertiesFile;
public static mips.instructions.InstructionSet instructionSet;
public static MIPSprogram program;
public static assembler.SymbolTable symbolTable;
public static mips.hardware.Memory memory;
public static Object memoryAndRegistersLock;
public static boolean debug;
static Settings settings;
public static String userInputAlert;
public static final String imagesPath = /images/;
public static final String helpPath = /help/;
private static boolean initialized;
static venus.VenusUI gui;
public static final String version = 4.3;
public static final java.util.ArrayList fileExtensions;
public static final int maximumMessageCharacters;
public static final int maximumErrorMessages;
public static final int maximumBacksteps;
public static final String copyrightYears;
public static final String copyrightHolders;
public static final String ASCII_NON_PRINT;
public static final String[] ASCII_TABLE;
public static int exitCode;
public static boolean runSpeedPanelExists;
static void ();
public void Globals();
private static String getCopyrightYears();
private static String getCopyrightHolders();
public static void setGui(venus.VenusUI);
public static venus.VenusUI getGui();
public static Settings getSettings();
public static void initialize(boolean);
private static int getMessageLimit();
private static int getErrorLimit();
private static int getBackstepLimit();
public static String getAsciiNonPrint();
public static String[] getAsciiStrings();
private static int getIntegerProperty(String, String, int);
private static java.util.ArrayList getFileExtensions();
public static java.util.ArrayList getExternalTools();
public static String getPropertyEntry(String, String);
public java.util.ArrayList getSyscallOverrides();
}

MarsSplashScreen$ImageBackgroundPanel

package mars;
synchronized class MarsSplashScreen$ImageBackgroundPanel extends javax.swing.JPanel {
java.awt.Image image;
public void MarsSplashScreen$ImageBackgroundPanel(MarsSplashScreen);
protected void paintComponent(java.awt.Graphics);
}

MIPSprogram

package mars;
public synchronized class MIPSprogram {
private boolean steppedExecution;
private String filename;
private java.util.ArrayList sourceList;
private java.util.ArrayList tokenList;
private java.util.ArrayList parsedList;
private java.util.ArrayList machineList;
private simulator.BackStepper backStepper;
private assembler.SymbolTable localSymbolTable;
private assembler.MacroPool macroPool;
private java.util.ArrayList sourceLineList;
private assembler.Tokenizer tokenizer;
public void MIPSprogram();
public java.util.ArrayList getSourceList();
public void setSourceLineList(java.util.ArrayList);
public java.util.ArrayList getSourceLineList();
public String getFilename();
public java.util.ArrayList getTokenList();
public assembler.Tokenizer getTokenizer();
public java.util.ArrayList createParsedList();
public java.util.ArrayList getParsedList();
public java.util.ArrayList getMachineList();
public simulator.BackStepper getBackStepper();
public assembler.SymbolTable getLocalSymbolTable();
public boolean backSteppingEnabled();
public String getSourceLine(int);
public void readSource(String) throws ProcessingException;
public void tokenize() throws ProcessingException;
public java.util.ArrayList prepareFilesForAssembly(java.util.ArrayList, String, String) throws ProcessingException;
public ErrorList assemble(java.util.ArrayList, boolean) throws ProcessingException;
public ErrorList assemble(java.util.ArrayList, boolean, boolean) throws ProcessingException;
public boolean simulate(int[]) throws ProcessingException;
public boolean simulate(int) throws ProcessingException;
public boolean simulateFromPC(int[], int, javax.swing.AbstractAction) throws ProcessingException;
public boolean simulateStepAtPC(javax.swing.AbstractAction) throws ProcessingException;
public boolean inSteppedExecution();
public assembler.MacroPool createMacroPool();
public assembler.MacroPool getLocalMacroPool();
public void setLocalMacroPool(assembler.MacroPool);
}

mars/ErrorMessage.java
mars/ErrorMessage.java   package mars;
    
   import java.util.regex.Pattern;
   import java.util.regex.Matcher;
   import java.util.ArrayList;
/*
Copyright (c) 2003-2012,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Represents occurrance of an error detected during tokenizing, assembly or simulation.
 * @author Pete Sanderson
 * @version August 2003
 **/

    public class ErrorMessage {
      private boolean isWarning; // allow for warnings too (added Nov 2006)
      private String filename; // name of source file  (added Oct 2006)
      private int line;     // line in source code where error detected
      private int position; // position in source line where error detected
      private String message;
      private String macroExpansionHistory;
   
   /**
    *  Constant to indicate this message is warning not error
    */
      public static final boolean WARNING = true;
   
   /**
    *  Constant to indicate this message is error not warning
    */
      public static final boolean ERROR = false;
   
   /**
    * Constructor for ErrorMessage.
    * @param filename String containing name of source file in which this error appears.
    * @param line Line number in source program being processed when error occurred.
    * @param position Position within line being processed when error occurred.  Normally is starting
    * position of source token.
    * @param message String containing appropriate error message.
    * @deprecated  Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.
    **/
    // Added filename October 2006 
       @Deprecated
       public ErrorMessage(String filename, int line, int position, String message) {
         this(ERROR, filename, line, position, message, “”);
      }  
     
   /**
    * Constructor for ErrorMessage.
    * @param filename String containing name of source file in which this error appears.
    * @param line Line number in source program being processed when error occurred.
    * @param position Position within line being processed when error occurred.  Normally is starting
    * position of source token.
    * @param message String containing appropriate error message.
    * @param macroExpansionHistory
    * @deprecated  Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.
    **/
    // Added macroExpansionHistory Dec 2012
    
       @Deprecated   
       public ErrorMessage(String filename, int line, int position, String message, String macroExpansionHistory) {
         this(ERROR, filename, line, position, message, macroExpansionHistory);
      }
   
   /**
    * Constructor for ErrorMessage.
    * @param isWarning set to WARNING if message is a warning not error, else set to ERROR or omit.
    * @param filename String containing name of source file in which this error appears.
    * @param line Line number in source program being processed when error occurred.
    * @param position Position within line being processed when error occurred.  Normally is starting
    * position of source token.
    * @param message String containing appropriate error message.
    * @param macroExpansionHistory provided so message for macro can include both definition and usage line numbers
    * @deprecated  Newer constructors replace the String filename parameter with a MIPSprogram parameter to provide more information.
    **/
       @Deprecated
       public ErrorMessage(boolean isWarning, String filename, int line, int position, String message, String macroExpansionHistory) {
         this.isWarning = isWarning;
         this.filename = filename;
         this.line = line;
         this.position = position;
         this.message = message;
         this.macroExpansionHistory=macroExpansionHistory;
      }
   
   
   /**
    * Constructor for ErrorMessage.  Assumes line number is calculated after any .include files expanded, and
    * if there were, it will adjust filename and line number so message reflects original file and line number.
    * @param sourceMIPSprogram MIPSprogram object of source file in which this error appears.
    * @param line Line number in source program being processed when error occurred.
    * @param position Position within line being processed when error occurred.  Normally is starting
    * position of source token.
    * @param message String containing appropriate error message.
    **/
    
       public ErrorMessage(MIPSprogram sourceMIPSprogram, int line, int position, String message) {
         this(ERROR, sourceMIPSprogram, line, position, message);
      }
   
   
   /**
    * Constructor for ErrorMessage.  Assumes line number is calculated after any .include files expanded, and
    * if there were, it will adjust filename and line number so message reflects original file and line number.
    * @param isWarning set to WARNING if message is a warning not error, else set to ERROR or omit.
    * @param sourceMIPSprogram MIPSprogram object of source file in which this error appears.
    * @param line Line number in source program being processed when error occurred.
    * @param position Position within line being processed when error occurred.  Normally is starting
    * position of source token.
    * @param message String containing appropriate error message.
    **/
    
       public ErrorMessage(boolean isWarning, MIPSprogram sourceMIPSprogram, int line, int position, String message) {
         this.isWarning = isWarning;
         if (sourceMIPSprogram == null) {
            this.filename = “”;
            this.line = line;
         } 
         else {
            if (sourceMIPSprogram.getSourceLineList() == null) {
               this.filename = sourceMIPSprogram.getFilename();
               this.line = line;
            } 
            else {
               mars.assembler.SourceLine sourceLine = sourceMIPSprogram.getSourceLineList().get(line-1);
               this.filename = sourceLine.getFilename();
               this.line = sourceLine.getLineNumber();
            }
         }
         this.position = position;
         this.message = message;
         this.macroExpansionHistory = getExpansionHistory(sourceMIPSprogram);
      }
    
   /**
    * Constructor for ErrorMessage, to be used for runtime exceptions.  
    * @param statement The ProgramStatement object for the instruction causing the runtime error
    * @param message String containing appropriate error message.
    **/
   // Added January 2013
   
       public ErrorMessage(ProgramStatement statement, String message) {
         this.isWarning = ERROR;
         this.filename = statement.getSourceMIPSprogram().getFilename();
         this.position = 0;
         this.message = message;
        // Somewhere along the way we lose the macro history, but can
        // normally recreate it here.  The line number for macro use (in the
        // expansion) comes with the ProgramStatement.getSourceLine().  
        // The line number for the macro definition comes embedded in
        // the source code from ProgramStatement.getSource(), which is
        // displayed in the Text Segment display.  It would previously
        // have had the macro definition line prepended in brackets,
        // e.g. “<13>  syscall  # finished”.  So I’ll extract that
        // bracketed number here and include it in the error message.
        // Looks bass-ackwards, but to get the line numbers to display correctly
        // for runtime error occurring in macro expansion (expansion->definition), need 
        // to assign to the opposite variables.
         ArrayList defineLine = parseMacroHistory(statement.getSource());
         if (defineLine.size() == 0) {
            this.line = statement.getSourceLine();
            this.macroExpansionHistory = “”;
         } 
         else {
            this.line = defineLine.get(0);
            this.macroExpansionHistory = “”+statement.getSourceLine();
         }
      }
        
       private ArrayList parseMacroHistory(String string) {        
         Pattern pattern = Pattern.compile(“<\\d+>“);
         Matcher matcher = pattern.matcher(string);
         String verify = new String(string).trim();
         ArrayList macroHistory = new ArrayList();
         while (matcher.find()) {
            String match = matcher.group();
            if (verify.indexOf(match)==0) {
               try {
                  int line = Integer.parseInt(match.substring(1,match.length()-1));
                  macroHistory.add(line);
               } 
                   catch (NumberFormatException e) {
                     break;
                  }
               verify = verify.substring(match.length()).trim();
            } 
            else {
               break;
            }
         } 
         return macroHistory;
      }  
   
   /**
    * Produce name of file containing error.
    * @return Returns String containing name of source file containing the error.
    */
   // Added October 2006
   
       public String getFilename() {
         return filename;
      }
   
   /**
    * Produce line number of error.
    * @return Returns line number in source program where error occurred.
    */
   
       public int getLine() {
         return line;
      }
   
   /**
    * Produce position within erroneous line.
    * @return Returns position within line of source program where error occurred.
    */
   
       public int getPosition() {
         return position;
      }
   
   /**
    * Produce error message.
    * @return Returns String containing textual error message.
    */
   
       public String getMessage() {
         return message;
      }
   
   /**
    * Determine whether this message represents error or warning.
    * @return Returns true if this message reflects warning, false if error.
    */
    // Method added 28 Nov 2006
       public boolean isWarning() {
         return this.isWarning;
      }
    
   /**
    * Returns string describing macro expansion.  Empty string if none.
    * @return string describing macro expansion
    */
    // Method added by Mohammad Sekavat Dec 2012
   
       public String getMacroExpansionHistory() {
         if (macroExpansionHistory==null || macroExpansionHistory.length()==0)
            return “”;
         return macroExpansionHistory+”->”;
      }
    
     // Added by Mohammad Sekavat Dec 2012
       private static String getExpansionHistory(MIPSprogram sourceMIPSprogram) {
         if (sourceMIPSprogram==null || sourceMIPSprogram.getLocalMacroPool()==null)
            return “”;
         return sourceMIPSprogram.getLocalMacroPool().getExpansionHistory();
      }
    
   }  // ErrorMessage

BackStepper

package mars.simulator;
public synchronized class BackStepper {
private static final int MEMORY_RESTORE_RAW_WORD = 0;
private static final int MEMORY_RESTORE_WORD = 1;
private static final int MEMORY_RESTORE_HALF = 2;
private static final int MEMORY_RESTORE_BYTE = 3;
private static final int REGISTER_RESTORE = 4;
private static final int PC_RESTORE = 5;
private static final int COPROC0_REGISTER_RESTORE = 6;
private static final int COPROC1_REGISTER_RESTORE = 7;
private static final int COPROC1_CONDITION_CLEAR = 8;
private static final int COPROC1_CONDITION_SET = 9;
private static final int DO_NOTHING = 10;
private static final int NOT_PC_VALUE = -1;
private boolean engaged;
private BackStepper$BackstepStack backSteps;
public void BackStepper();
public boolean enabled();
public void setEnabled(boolean);
public boolean empty();
public boolean inDelaySlot();
public void backStep();
private int pc();
public int addMemoryRestoreRawWord(int, int);
public int addMemoryRestoreWord(int, int);
public int addMemoryRestoreHalf(int, int);
public int addMemoryRestoreByte(int, int);
public int addRegisterFileRestore(int, int);
public int addPCRestore(int);
public int addCoprocessor0Restore(int, int);
public int addCoprocessor1Restore(int, int);
public int addConditionFlagSet(int);
public int addConditionFlagClear(int);
public int addDoNothing(int);
}

Simulator

package mars.simulator;
public synchronized class Simulator extends java.util.Observable {
private Simulator$SimThread simulatorThread;
private static Simulator simulator;
private static Runnable interactiveGUIUpdater;
public static final int NO_DEVICE = 0;
public static volatile int externalInterruptingDevice;
public static final int BREAKPOINT = 1;
public static final int EXCEPTION = 2;
public static final int MAX_STEPS = 3;
public static final int NORMAL_TERMINATION = 4;
public static final int CLIFF_TERMINATION = 5;
public static final int PAUSE_OR_STOP = 6;
private java.util.ArrayList stopListeners;
static void ();
public static Simulator getInstance();
private void Simulator();
public static boolean inDelaySlot();
public boolean simulate(mars.MIPSprogram, int, int, int[], javax.swing.AbstractAction) throws mars.ProcessingException;
public void stopExecution(javax.swing.AbstractAction);
public void addStopListener(Simulator$StopListener);
public void removeStopListener(Simulator$StopListener);
private void notifyObserversOfExecutionStart(int, int);
private void notifyObserversOfExecutionStop(int, int);
}

mars/simulator/BackStepper.java
mars/simulator/BackStepper.java   package mars.simulator;
   import mars.*;
   import mars.venus.*;
   import mars.mips.hardware.*;
   import mars.mips.instructions.*;
   import java.util.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Used to “step backward” through execution, undoing each instruction.
 * @author Pete Sanderson
 * @version February 2006
 */
 
    public class BackStepper {
      // The types of “undo” actions.  Under 1.5, these would be enumerated type.
    // These fit better in the BackStep class below but inner classes cannot have static members.
      private static final int MEMORY_RESTORE_RAW_WORD = 0;
      private static final int MEMORY_RESTORE_WORD = 1;
      private static final int MEMORY_RESTORE_HALF = 2;
      private static final int MEMORY_RESTORE_BYTE = 3;
      private static final int REGISTER_RESTORE = 4;
      private static final int PC_RESTORE = 5;
      private static final int COPROC0_REGISTER_RESTORE = 6;
      private static final int COPROC1_REGISTER_RESTORE = 7;
      private static final int COPROC1_CONDITION_CLEAR = 8;
      private static final int COPROC1_CONDITION_SET = 9;
      private static final int DO_NOTHING = 10;  // instruction does not write anything.
   
      // Flag to mark BackStep object as prepresenting specific situation: user manipulates
    // memory/register value via GUI after assembling program but before running it.
      private static final int NOT_PC_VALUE = -1;
    
      private boolean engaged;
      private BackstepStack backSteps;
    
    // One can argue using java.util.Stack, given its clumsy implementation.
    // A homegrown linked implementation will be more streamlined, but
    // I anticipate that backstepping will only be used during timed
    // (currently max 30 instructions/second) or stepped execution, where
    // performance is not an issue.  Its Vector implementation may result
    // in quicker garbage collection than a pure linked list implementation.
   
       /**
      * Create a fresh BackStepper.  It is enabled, which means all
      * subsequent instruction executions will have their “undo” action
      * recorded here.
      */
       public BackStepper() {
         engaged = true;
         backSteps = new BackstepStack(Globals.maximumBacksteps);
      }
   
       /**
      * Determine whether execution “undo” steps are currently being recorded.
      * @return true if undo steps being recorded, false if not.
      */
       public boolean enabled() {
         return engaged;
      }
   
       /**
      * Set enable status.
      * @param state If true, will begin (or continue) recoding “undo” steps.  If false, will stop.
      */
       public void setEnabled(boolean state) {
         engaged = state;
      }
   
      /**
     * Test whether there are steps that can be undone.
     * @return true if there are no steps to be undone, false otherwise.
     */
       public boolean empty() {
         return backSteps.empty();
      }
    
    /**
     * Determine whether the next back-step action occurred as the result of
     * an instruction that executed in the “delay slot” of a delayed branch.
     * @return true if next backstep is instruction that executed in delay slot,
     * false otherwise.
     */
    // Added 25 June 2007
       public boolean inDelaySlot() {
         return !empty() && backSteps.peek().inDelaySlot;
      }
    
      /**
     *  Carry out a “back step”, which will undo the latest execution step.
     *  Does nothing if backstepping not enabled or if there are no steps to undo.
     */
     
     // Note that there may be more than one “step” in an instruction execution; for
     // instance the multiply, divide, and double-precision floating point operations 
     // all store their result in register pairs which results in two store operations.  
     // Both must be undone transparently, so we need to detect that multiple steps happen
     // together and carry out all of them here.  
     // Use a do-while loop based on the backstep’s program statement reference.
     
       public void backStep() {
         if (engaged && !backSteps.empty()) {
            ProgramStatement statement = ((BackStep)backSteps.peek()).ps;
            engaged = false; // GOTTA DO THIS SO METHOD CALL IN SWITCH WILL NOT RESULT IN NEW ACTION ON STACK!
            do {
               BackStep step = (BackStep) backSteps.pop();
            /*
                System.out.println(“backstep POP: action “+step.action+” pc “+mars.util.Binary.intToHexString(step.pc)+
                                   ” source “+((step.ps==null)? “none”:step.ps.getSource())+
                                         ” parm1 “+step.param1+” parm2 “+step.param2);
            */
               if (step.pc != NOT_PC_VALUE) {
                  RegisterFile.setProgramCounter(step.pc);
               }
               try {
                  switch (step.action) {
                     case MEMORY_RESTORE_RAW_WORD : 
                        Globals.memory.setRawWord(step.param1, step.param2);
                        break;
                     case MEMORY_RESTORE_WORD : 
                        Globals.memory.setWord(step.param1, step.param2);
                        break;
                     case MEMORY_RESTORE_HALF :
                        Globals.memory.setHalf(step.param1, step.param2);
                        break;
                     case MEMORY_RESTORE_BYTE :
                        Globals.memory.setByte(step.param1, step.param2);
                        break;
                     case REGISTER_RESTORE :
                        RegisterFile.updateRegister(step.param1, step.param2);
                        break;
                     case PC_RESTORE : 
                        RegisterFile.setProgramCounter(step.param1);
                        break;
                     case COPROC0_REGISTER_RESTORE :
                        Coprocessor0.updateRegister(step.param1, step.param2);
                        break;
                     case COPROC1_REGISTER_RESTORE :
                        Coprocessor1.updateRegister(step.param1, step.param2);
                        break;
                     case COPROC1_CONDITION_CLEAR :
                        Coprocessor1.clearConditionFlag(step.param1);
                        break;
                     case COPROC1_CONDITION_SET :
                        Coprocessor1.setConditionFlag(step.param1);
                        break;
                     case DO_NOTHING :
                        break;
                  }
               } 
                   catch (Exception e) { 
                  // if the original action did not cause an exception this will not either.
                     System.out.println(“Internal MARS error: address exception while back-stepping.”);
                     System.exit(0);
                  }
            } while (!backSteps.empty() && statement == ((BackStep)backSteps.peek()).ps);
            engaged = true;  // RESET IT (was disabled at top of loop — see comment)
         }
      }
  
     
      /* Convenience method called below to get program counter value.  If it needs to be
     * be modified (e.g. to subtract 4) that can be done here in one place.
     */
     
       private int pc() {
       // PC incremented prior to instruction simulation, so need to adjust for that.
         return RegisterFile.getProgramCounter()-Instruction.INSTRUCTION_LENGTH;
      }
   
       /**
      * Add a new “back step” (the undo action) to the stack. The action here
      * is to restore a raw memory word value (setRawWord).
      * @param address The affected memory address.
      * @param value The “restore” value to be stored there.
      * @return the argument value
      */
       public int addMemoryRestoreRawWord(int address, int value) {
         backSteps.push(MEMORY_RESTORE_RAW_WORD, pc(), address, value);
         return value;
      }   
    
       /**
      * Add a new “back step” (the undo action) to the stack. The action here
      * is to restore a memory word value.
      * @param address The affected memory address.
      * @param value The “restore” value to be stored there.
      * @return the argument value
      */
       public int addMemoryRestoreWord(int address, int value) {
         backSteps.push(MEMORY_RESTORE_WORD, pc(), address, value);
         return value;
      }   
   
       /**
      * Add a new “back step” (the undo action) to the stack.  The action here
      * is to restore a memory half-word value.
      * @param address The affected memory address.
      * @param value The “restore” value to be stored there, in low order half.
      * @return the argument value
      */
       public int addMemoryRestoreHalf(int address, int value) {
         backSteps.push(MEMORY_RESTORE_HALF, pc(), address, value);
         return value;
      }
   
       /**
      * Add a new “back step” (the undo action) to the stack.  The action here
      * is to restore a memory byte value.
      * @param address The affected memory address.
      * @param value The “restore” value to be stored there, in low order byte.
      * @return the argument value
      */
       public int addMemoryRestoreByte(int address, int value) {
         backSteps.push(MEMORY_RESTORE_BYTE, pc(), address, value);
         return value;
      }   
   
       /**
      * Add a new “back step” (the undo action) to the stack.  The action here
      * is to restore a register file register value.
      * @param register The affected register number.
      * @param value The “restore” value to be stored there.
      * @return the argument value
      */
       public int addRegisterFileRestore(int register, int value) {
         backSteps.push(REGISTER_RESTORE, pc(), register, value);
         return value;
      } 
   
       /**
      * Add a new “back step” (the undo action) to the stack.  The action here
      * is to restore the program counter.  
      * @param value The “restore” value to be stored there.
      * @return the argument value
      */
       public int addPCRestore(int value) {
         // adjust for value reflecting incremented PC.  
         value -= Instruction.INSTRUCTION_LENGTH; 
         // Use “value” insead of “pc()” for second arg because RegisterFile.getProgramCounter() 
         // returns branch target address at this point.
         backSteps.push(PC_RESTORE, value, value); 
         return value;
      }     
   
       /**
      * Add a new “back step” (the undo action) to the stack.  The action here
      * is to restore a coprocessor 0 register value.
      * @param register The affected register number.
      * @param value The “restore” value to be stored there.
      * @return the argument value
      */
       public int addCoprocessor0Restore(int register, int value) {
         backSteps.push(COPROC0_REGISTER_RESTORE, pc(), register, value);
         return value;
      }     
   
       /**
      * Add a new “back step” (the undo action) to the stack.  The action here
      * is to restore a coprocessor 1 register value.
      * @param register The affected register number.
      * @param value The “restore” value to be stored there.
      * @return the argument value
      */
       public int addCoprocessor1Restore(int register, int value) {
         backSteps.push(COPROC1_REGISTER_RESTORE, pc(), register, value);
         return value;
      }     
   
       /**
      * Add a new “back step” (the undo action) to the stack.  The action here
      * is to set the given coprocessor 1 condition flag (to 1).  
      * @param flag The condition flag number.
      * @return the argument value
      */
       public int addConditionFlagSet(int flag) {
         backSteps.push(COPROC1_CONDITION_SET, pc(), flag);
         return flag;
      } 
   
       /**
      * Add a new “back step” (the undo action) to the stack.  The action here
      * is to clear the given coprocessor 1 condition flag (to 0).  
      * @param flag The condition flag number.
      * @return the argument value
      */
       public int addConditionFlagClear(int flag) {
         backSteps.push(COPROC1_CONDITION_CLEAR, pc(), flag);
         return flag;
      } 
        
       /**
      * Add a new “back step” (the undo action) to the stack.  The action here
      * is to do nothing!  This is just a place holder so when user is backstepping
      * through the program no instructions will be skipped.  Cosmetic. If the top of the
      * stack has the same PC counter, the do-nothing action will not be added.  
      * @return 0
      */
       public int addDoNothing(int pc) {
         if (backSteps.empty() || backSteps.peek().pc != pc) { 
            backSteps.push(DO_NOTHING, pc);
         }
         return 0;
      }
    
                
    // Represents a “back step” (undo action) on the stack.
       private class BackStep {
         private int action;  // what do do MEMORY_RESTORE_WORD, etc
         private int pc;      // program counter value when original step occurred
         private ProgramStatement ps;   // statement whose action is being “undone” here
         private int param1;  // first parameter required by that action
         private int param2;  // optional second parameter required by that action
         private boolean inDelaySlot; // true if instruction executed in “delay slot” (delayed branching enabled)
      
         // it is critical that BackStep object get its values by calling this method
        // rather than assigning to individual members, because of the technique used
        // to set its ps member (and possibly pc).
          private void assign(int act, int programCounter, int parm1, int parm2) {
            action = act;
            pc     = programCounter;
            try {
            // Client does not have direct access to program statement, and rather than making all
            // of them go through the methods below to obtain it, we will do it here.  
            // Want the program statement but do not want observers notified.
               ps = Globals.memory.getStatementNoNotify(programCounter);
            } 
                catch (Exception e) {
                // The only situation causing this so far: user modifies memory or register
                // contents through direct manipulation on the GUI, after assembling the program but
                // before starting to run it (or after backstepping all the way to the start).
                // The action will not be associated with any instruction, but will be carried out
                // when popped.
                  ps = null;
                  pc = NOT_PC_VALUE; // Backstep method above will see this as flag to not set PC
               } 
            param1 = parm1;
            param2 = parm2;
            inDelaySlot = Simulator.inDelaySlot(); // ADDED 25 June 2007
         /*             
            System.out.println(“backstep PUSH: action “+action+” pc “+mars.util.Binary.intToHexString(pc)+
                                   ” source “+((ps==null)? “none”:ps.getSource())+
                                         ” parm1 “+param1+” parm2 “+param2);
         */
         }
      }
    
    // *****************************************************************************
    // special purpose stack class for backstepping.  You’ve heard of circular queues
    // implemented with an array, right?  This is a circular stack!  When full, the
    // newly-pushed item overwrites the oldest item, with circular top!  All operations 
    // are constant time.  It’s synchronized too, to be safe (is used by both the 
    // simulation thread and the GUI thread for the back-step button).
    // Upon construction, it is filled with newly-created empty BackStep objects which
    // will exist for the life of the stack.  Push does not create a BackStep object 
    // but instead overwrites the contents of the existing one.  Thus during MIPS
    // program (simulated) execution, BackStep objects are never created or junked
    // regardless of how many steps are executed.  This will speed things up a bit
    // and make life easier for the garbage collector.
    
       private class BackstepStack {
         private int capacity;
         private int size;
         private int top;
         private BackStep[] stack;
      
          // Stack is created upon successful assembly or reset.  The one-time overhead of
         // creating all the BackStep objects will not be noticed by the user, and enhances
         // runtime performance by not having to create or recycle them during MIPS
         // program execution.
          private BackstepStack(int capacity) {
            this.capacity = capacity;
            this.size = 0;
            this.top = -1;
            this.stack = new BackStep[capacity];
            for (int i=0; i();
public void DelayedBranch();
public static void register(int);
static void trigger();
static void clear();
static boolean isRegistered();
static boolean isTriggered();
static int getBranchTargetAddress();
}

BackStepper$BackstepStack

package mars.simulator;
synchronized class BackStepper$BackstepStack {
private int capacity;
private int size;
private int top;
private BackStepper$BackStep[] stack;
private void BackStepper$BackstepStack(BackStepper, int);
private synchronized boolean empty();
private synchronized void push(int, int, int, int);
private synchronized void push(int, int, int);
private synchronized void push(int, int);
private synchronized BackStepper$BackStep pop();
private synchronized BackStepper$BackStep peek();
}

SwingWorker$ThreadVar

package mars.simulator;
synchronized class SwingWorker$ThreadVar {
private Thread thread;
void SwingWorker$ThreadVar(Thread);
synchronized Thread get();
synchronized void clear();
}

mars/simulator/Simulator.java
mars/simulator/Simulator.java   package mars.simulator;
   import mars.*;
   import mars.venus.*;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.mips.instructions.*;
   import java.util.*;
   import javax.swing.*;
   import java.awt.event.*;
    
    /*
Copyright (c) 2003-2010,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
/**
 * Used to simulate the execution of an assembled MIPS program.
 * @author Pete Sanderson
 * @version August 2005
 **/

   public class Simulator extends Observable {
      private SimThread simulatorThread;
      private static Simulator simulator = null;  // Singleton object
      private static Runnable interactiveGUIUpdater = null;
      // Others can set this true to indicate external interrupt.  Initially used
    // to simulate keyboard and display interrupts.  The device is identified
    // by the address of its MMIO control register.  keyboard 0xFFFF0000 and
    // display 0xFFFF0008.  DPS 23 July 2008.
      public static final int NO_DEVICE = 0;
      public static volatile int externalInterruptingDevice = NO_DEVICE;
    /** various reasons for simulate to end… */
      public static final int BREAKPOINT = 1;
      public static final int EXCEPTION  = 2;
      public static final int MAX_STEPS  = 3;  // includes step mode (where maxSteps is 1)
      public static final int NORMAL_TERMINATION = 4;
      public static final int CLIFF_TERMINATION = 5; // run off bottom of program
      public static final int PAUSE_OR_STOP = 6;
   
      /**
     * Returns the Simulator object
     *
     * @return the Simulator object in use
     */
      public static Simulator getInstance() {
         // Do NOT change this to create the Simulator at load time (in declaration above)!
        // Its constructor looks for the GUI, which at load time is not created yet,
        // and incorrectly leaves interactiveGUIUpdater null!  This causes runtime
        // exceptions while running in timed mode.
         if (simulator==null) {
            simulator = new Simulator();
         }
         return simulator;
      }
   
      private Simulator() {
         simulatorThread = null;
         if (Globals.getGui() != null) {
            interactiveGUIUpdater = new UpdateGUI();
         } 
      }
   
   
   
   /**
    *  Determine whether or not the next instruction to be executed is in a
    *  “delay slot”.  This means delayed branching is enabled, the branch
    *  condition has evaluated true, and the next instruction executed will
    *  be the one following the branch.  It is said to occupy the “delay slot.”
    *  Normally programmers put a nop instruction here but it can be anything.  
    *
    *  @return true if next instruction is in delay slot, false otherwise.
    */
   
      public static boolean inDelaySlot() {
         return DelayedBranch.isTriggered();
      } 
   
   
   /**
    * Simulate execution of given MIPS program.  It must have already been assembled.
    * @param p The MIPSprogram to be simulated.
    * @param pc address of first instruction to simulate; this goes into program counter
    * @param maxSteps maximum number of steps to perform before returning false (0 or less means no max)
    * @param breakPoints array of breakpoint program counter values, use null if none
    * @param actor the GUI component responsible for this call, usually GO or STEP.  null if none.
    * @return true if execution completed, false otherwise
    * @throws ProcessingException Throws exception if run-time exception occurs.
    **/
    
      public boolean simulate(MIPSprogram p, int pc, int maxSteps, int[] breakPoints, AbstractAction actor) throws ProcessingException {
         simulatorThread = new SimThread(p,pc,maxSteps,breakPoints,actor);
         simulatorThread.start();
        
        // Condition should only be true if run from command-line instead of GUI.
        // If so, just stick around until execution thread is finished.
         if (actor == null) {
            Object dun = simulatorThread.get(); // this should emulate join()
            ProcessingException pe = simulatorThread.pe;
            boolean done = simulatorThread.done;
            if (done) SystemIO.resetFiles(); // close any files opened in MIPS progra
            this.simulatorThread = null;
            if (pe != null) {
               throw pe;
            }
            return done;
         }
         return true;
      }
        
   
       /**
      *  Set the volatile stop boolean variable checked by the execution
      *  thread at the end of each MIPS instruction execution.  If variable
      *  is found to be true, the execution thread will depart
      *  gracefully so the main thread handling the GUI can take over.
      *  This is used by both STOP and PAUSE features.
      */            
      public void stopExecution(AbstractAction actor) {
      
         if (simulatorThread != null) {
            simulatorThread.setStop(actor);
            for (StopListener l : stopListeners) {
               l.stopped(this);
            }
            simulatorThread = null;
         }
      }
   
      /* This interface is required by the Asker class in MassagesPane
       * to be notified about the fact that the user has requested to
       * stop the execution. When that happens, it must unblock the
       * simulator thread. */
      public interface StopListener {
         void stopped(Simulator s);
      }
   
      private ArrayList stopListeners = new ArrayList(1);
      public void addStopListener(StopListener l) {
         stopListeners.add(l);
      }
   
      public void removeStopListener(StopListener l) {
         stopListeners.remove(l);
      }
   
     // The Simthread object will call this method when it enters and returns from
     // its construct() method.  These signal start and stop, respectively, of
     // simulation execution.  The observer can then adjust its own state depending
     // on the execution state.  Note that “stop” and “done” are not the same thing.
     // “stop” just means it is leaving execution state; this could be triggered
     // by Stop button, by Pause button, by Step button, by runtime exception, by
     // instruction count limit, by breakpoint, or by end of simulation (truly done).
      private void notifyObserversOfExecutionStart(int maxSteps, int programCounter) {
         this.setChanged();
         this.notifyObservers(new SimulatorNotice(SimulatorNotice.SIMULATOR_START,
            maxSteps, RunSpeedPanel.getInstance().getRunSpeed(), programCounter) );
      }
   
      private void notifyObserversOfExecutionStop(int maxSteps, int programCounter) {
         this.setChanged();
         this.notifyObservers(new SimulatorNotice(SimulatorNotice.SIMULATOR_STOP,
            maxSteps, RunSpeedPanel.getInstance().getRunSpeed(), programCounter) );
      }
     
     
    /**
     * SwingWorker subclass to perform the simulated execution in background thread.
     * It is “interrupted” when main thread sets the “stop” variable to true.
     * The variable is tested before the next MIPS instruction is simulated.  Thus
     * interruption occurs in a tightly controlled fashion.
     *
     * See SwingWorker.java for more details on its functionality and usage.  It is
     * provided by Sun Microsystems for download and is not part of the Swing library.
     */     
        
      class SimThread extends SwingWorker {
         private MIPSprogram p;
         private int pc, maxSteps;
         private int[] breakPoints;
         private boolean done;
         private ProcessingException pe;
         private volatile boolean stop = false;
         private volatile AbstractAction stopper;
         private AbstractAction starter;
         private int constructReturnReason;
      
      
         /**
         *  SimThread constructor.  Receives all the information it needs to simulate execution.
         *
         *  @param p  the MIPSprogram to be simulated
         *  @param pc address in text segment of first instruction to simulate
         *  @param maxSteps  maximum number of instruction steps to simulate.  Default of -1 means no maximum
         *  @param breakPoints  array of breakpoints (instruction addresses) specified by user
         *  @param starter the GUI component responsible for this call, usually GO or STEP.  null if none.
         */
         SimThread(MIPSprogram p, int pc, int maxSteps, int[] breakPoints, AbstractAction starter) {
            super(Globals.getGui()!=null);  
            this.p = p;
            this.pc = pc;
            this.maxSteps = maxSteps;
            this.breakPoints = breakPoints;
            this.done = false;
            this.pe = null;
            this.starter = starter;
            this.stopper = null;
         }
        
        /**
         * Sets to “true” the volatile boolean variable that is tested after each
         * MIPS instruction is executed.  After calling this method, the next test
         * will yield “true” and “construct” will return.
         *
         * @param actor the Swing component responsible for this call.  
         */
         public void setStop(AbstractAction actor) {
            stop = true;
            stopper = actor;
         }
        
      
        /**
         *  This is comparable to the Runnable “run” method (it is called by
         *  SwingWorker’s “run” method).  It simulates the program
         *  execution in the backgorund.
         *
         *  @return  boolean value true if execution done, false otherwise
         */
        
         public Object construct() {
            // The next two statements are necessary for GUI to be consistently updated
            // before the simulation gets underway.  Without them, this happens only intermittently,
            // with a consequence that some simulations are interruptable using PAUSE/STOP and others
            // are not (because one or the other or both is not yet enabled).
            Thread.currentThread().setPriority(Thread.NORM_PRIORITY-1);
            Thread.yield();  // let the main thread run a bit to finish updating the GUI
            
            if (breakPoints == null || breakPoints.length == 0) {
               breakPoints = null;
            } 
            else {
               Arrays.sort(breakPoints);  // must be pre-sorted for binary search
            }
            
            Simulator.getInstance().notifyObserversOfExecutionStart(maxSteps, pc);
            
            RegisterFile.initializeProgramCounter(pc);
            ProgramStatement statement = null;
            try {
               statement = Globals.memory.getStatement(RegisterFile.getProgramCounter());
            } 
               catch (AddressErrorException e) {
                  ErrorList el = new ErrorList();
                  el.add(new ErrorMessage((MIPSprogram)null,0,0,”invalid program counter value: “+RegisterFile.getProgramCounter()));
                  this.pe = new ProcessingException(el);
                  this.constructReturnReason = EXCEPTION;
                  this.done = true;
                  SystemIO.resetFiles(); // close any files opened in MIPS program
                  Simulator.getInstance().notifyObserversOfExecutionStop(maxSteps, pc);
                  return new Boolean(done);
               }
            int steps = 0;
            
            // *******************  PS addition 26 July 2006  **********************
            // A couple statements below were added for the purpose of assuring that when
            // “back stepping” is enabled, every instruction will have at least one entry
            // on the back-stepping stack.  Most instructions will because they write either
            // to a register or memory.  But “nop” and branches not taken do not.  When the
            // user is stepping backward through the program, the stack is popped and if
            // an instruction has no entry it will be skipped over in the process.  This has
            // no effect on the correctness of the mechanism but the visual jerkiness when
            // instruction highlighting skips such instrutions is disruptive.  Current solution
            // is to add a “do nothing” stack entry for instructions that do no write anything.
            // To keep this invisible to the “simulate()” method writer, we
            // will push such an entry onto the stack here if there is none for this instruction
            // by the time it has completed simulating.  This is done by the IF statement
            // just after the call to the simulate method itself.  The BackStepper method does
            // the aforementioned check and decides whether to push or not.  The result
            // is a a smoother interaction experience.  But it comes at the cost of slowing
            // simulation speed for flat-out runs, for every MIPS instruction executed even
            // though very few will require the “do nothing” stack entry.  For stepped or
            // timed execution the slower execution speed is not noticeable.
            //
            // To avoid this cost I tried a different technique: back-fill with “do nothings”
            // during the backstepping itself when this situation is recognized.  Problem
            // was in recognizing all possible situations in which the stack contained such
            // a “gap”.  It became a morass of special cases and it seemed every weird test
            // case revealed another one.  In addition, when a program
            // begins with one or more such instructions (“nop” and branches not taken),
            // the backstep button is not enabled until a “real” instruction is executed.
            // This is noticeable in stepped mode.
            // *********************************************************************
            
            int pc = 0;  // added: 7/26/06 (explanation above)
         
            while (statement != null) {
               pc = RegisterFile.getProgramCounter(); // added: 7/26/06 (explanation above)
               RegisterFile.incrementPC();              
                // Perform the MIPS instruction in synchronized block.  If external threads agree
                // to access MIPS memory and registers only through synchronized blocks on same 
                // lock variable, then full (albeit heavy-handed) protection of MIPS memory and 
                // registers is assured.  Not as critical for reading from those resources.
               synchronized (Globals.memoryAndRegistersLock) {
                  try {                      
                     if (Simulator.externalInterruptingDevice != NO_DEVICE) {
                        int deviceInterruptCode = externalInterruptingDevice;
                        Simulator.externalInterruptingDevice = NO_DEVICE;
                        throw new ProcessingException(statement, “External Interrupt”, deviceInterruptCode);
                     }
                     // THIS IS WHERE THE INSTRUCTION EXECUTION IS ACTUALLY SIMULATED!
                     ((BasicInstruction)statement.getInstruction()).getSimulationCode().simulate(statement);
                    // IF statement added 7/26/06 (explanation above)
                     if (Globals.getSettings().getBackSteppingEnabled()) {
                        Globals.program.getBackStepper().addDoNothing(pc);
                     }
                  } 
                     catch (ProcessingException pe) {
                        if (pe.errors() == null) {
                           this.constructReturnReason = NORMAL_TERMINATION;
                           this.done = true;
                           SystemIO.resetFiles(); // close any files opened in MIPS program
                           Simulator.getInstance().notifyObserversOfExecutionStop(maxSteps, pc);
                           return new Boolean(done); // execution completed without error.
                        } 
                        else {
                           // See if an exception handler is present.  Assume this is the case
                            // if and only if memory location Memory.exceptionHandlerAddress
                            // (e.g. 0x80000180) contains an instruction.  If so, then set the
                            // program counter there and continue.  Otherwise terminate the
                            // MIPS program with appropriate error message.
                           ProgramStatement exceptionHandler = null;
                           try {
                              exceptionHandler = Globals.memory.getStatement(Memory.exceptionHandlerAddress);
                           } 
                              catch (AddressErrorException aee) { } // will not occur with this well-known addres
                           if (exceptionHandler != null) {
                              RegisterFile.setProgramCounter(Memory.exceptionHandlerAddress);
                           } 
                           else {
                              this.constructReturnReason = EXCEPTION;
                              this.pe = pe;
                              this.done = true;
                              SystemIO.resetFiles(); // close any files opened in MIPS program
                              Simulator.getInstance().notifyObserversOfExecutionStop(maxSteps, pc);
                              return new Boolean(done);
                           }
                        }
                     }
               }// end synchronized block
                
                ///////// DPS 15 June 2007.  Handle delayed branching if it occurs./////
               if (DelayedBranch.isTriggered()) {
                  RegisterFile.setProgramCounter(DelayedBranch.getBranchTargetAddress());
                  DelayedBranch.clear();
               } 
               else if (DelayedBranch.isRegistered()) {
                  DelayedBranch.trigger();
               }//////////////////////////////////////////////////////////////////////
                
                // Volatile variable initialized false but can be set true by the main thread.
                // Used to stop or pause a running MIPS program.  See stopSimulation() above.
               if (stop == true) { 
                  this.constructReturnReason = PAUSE_OR_STOP;
                  this.done = false;
                  Simulator.getInstance().notifyObserversOfExecutionStop(maxSteps, pc);
                  return new Boolean(done);
               }
                //  Return if we’ve reached a breakpoint.                   
               if((breakPoints != null) && 
               (Arrays.binarySearch(breakPoints,RegisterFile.getProgramCounter()) >= 0)) {
                  this.constructReturnReason = BREAKPOINT;
                  this.done = false;
                  Simulator.getInstance().notifyObserversOfExecutionStop(maxSteps, pc);
                  return new Boolean(done); // false;
               }
                // Check number of MIPS instructions executed.  Return if at limit (-1 is no limit).
               if (maxSteps > 0) {
                  steps++;
                  if (steps >= maxSteps) {
                     this.constructReturnReason = MAX_STEPS;
                     this.done = false;
                     Simulator.getInstance().notifyObserversOfExecutionStop(maxSteps, pc);
                     return new Boolean(done);// false;
                  }
               }
                
                // schedule GUI update only if: there is in fact a GUI! AND
                //                              using Run,  not Step (maxSteps > 1) AND
                //                              running slowly enough for GUI to keep up
               //if (Globals.getGui() != null && maxSteps != 1 &&             
               if (interactiveGUIUpdater != null && maxSteps != 1 && 
                          RunSpeedPanel.getInstance().getRunSpeed() < RunSpeedPanel.UNLIMITED_SPEED) {                   SwingUtilities.invokeLater(interactiveGUIUpdater);                }                if (Globals.getGui() != null || Globals.runSpeedPanelExists) { // OR added by DPS 24 July 2008 to enable speed control by stand-alone tool                   if (maxSteps != 1 &&                            RunSpeedPanel.getInstance().getRunSpeed() < RunSpeedPanel.UNLIMITED_SPEED) {                      try { Thread.sleep((int)(1000/RunSpeedPanel.getInstance().getRunSpeed())); // make sure it's never zero!                      }                          catch (InterruptedException e) {}                   }                }                                             // Get next instruction in preparation for next iteration.                             try {                   statement = Globals.memory.getStatement(RegisterFile.getProgramCounter());                }                    catch (AddressErrorException e) {                      ErrorList el = new ErrorList();                      el.add(new ErrorMessage((MIPSprogram)null,0,0,"invalid program counter value: "+RegisterFile.getProgramCounter()));                      this.pe = new ProcessingException(el);                      this.constructReturnReason = EXCEPTION;                      this.done = true;                      SystemIO.resetFiles(); // close any files opened in MIPS program                      Simulator.getInstance().notifyObserversOfExecutionStop(maxSteps, pc);                      return  new Boolean(done);                   }             }             // DPS July 2007.  This "if" statement is needed for correct program             // termination if delayed branching on and last statement in             // program is a branch/jump.  Program will terminate rather than branch,             // because that's what MARS does when execution drops off the bottom.             if (DelayedBranch.isTriggered() || DelayedBranch.isRegistered()) {                DelayedBranch.clear();             }             // If we got here it was due to null statement, which means program             // counter "fell off the end" of the program.  NOTE: Assumes the              // "while" loop contains no "break;" statements.             this.constructReturnReason = CLIFF_TERMINATION;             this.done = true;             SystemIO.resetFiles(); // close any files opened in MIPS program             Simulator.getInstance().notifyObserversOfExecutionStop(maxSteps, pc);             return new Boolean(done); // true;  // execution completed          }                            /**          *   This method is invoked by the SwingWorker when the "construct" method returns.            *   It will update the GUI appropriately.  According to Sun's documentation, it           *   is run in the main thread so should work OK with Swing components (which are           *   not thread-safe).          *          *   Its action depends on what caused the return from construct() and what          *   action led to the call of construct() in the first place.          */                    public void finished() {            // If running from the command-line, then there is no GUI to update.             if (Globals.getGui() == null) {                return;             }             String starterName = (String) starter.getValue(AbstractAction.NAME);             if (starterName.equals("Step")) {                ((RunStepAction)starter).stepped(done,constructReturnReason,pe);             }                if (starterName.equals("Go")) {                if (done) {                   ((RunGoAction)starter).stopped(pe,constructReturnReason);                }                 else if (constructReturnReason == BREAKPOINT) {                   ((RunGoAction)starter).paused(done,constructReturnReason,pe);                }                 else {                   String stopperName = (String) stopper.getValue(AbstractAction.NAME);                   if ("Pause".equals(stopperName)) {                      ((RunGoAction)starter).paused(done,constructReturnReason,pe);                   }                   else if ("Stop".equals(stopperName)) {                      ((RunGoAction)starter).stopped(pe,constructReturnReason);                   }                }             }             return;          }                 }            private class UpdateGUI implements Runnable {          public void run() {             if (Globals.getGui().getRegistersPane().getSelectedComponent() ==                                                       Globals.getGui().getMainPane().getExecutePane().getRegistersWindow()) {                Globals.getGui().getMainPane().getExecutePane().getRegistersWindow().updateRegisters();             }              else {                Globals.getGui().getMainPane().getExecutePane().getCoprocessor1Window().updateRegisters();             }             Globals.getGui().getMainPane().getExecutePane().getDataSegmentWindow().updateValues();             Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().setCodeHighlighting(true);             Globals.getGui().getMainPane().getExecutePane().getTextSegmentWindow().highlightStepAtPC();             }       }        } mars/simulator/SimulatorNotice.java mars/simulator/SimulatorNotice.javapackage mars.simulator; /* Copyright (c) 2003-2009,  Pete Sanderson and Kenneth Vollmar Developed by Pete Sanderson ( ) and Kenneth Vollmar ( ) Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the  "Software"), to deal in the Software without restriction, including  without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject  to the following conditions: The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR  ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (MIT license, http://www.opensource.org/licenses/mit-license.html)  */ /**  * Object provided to Observers of the Simulator.  * They are notified at important phases of the runtime simulator,  * such as start and stop of simulation.  *   * @author Pete Sanderson   * @version January 2009  */   public class SimulatorNotice {    private int action;     private int maxSteps;     private double runSpeed;     private int programCounter;     public static final int SIMULATOR_START = 0;     public static final int SIMULATOR_STOP  = 1;   /** Constructor will be called only within this package, so assume    *  address and length are in valid ranges.     */    public SimulatorNotice(int action, int maxSteps, double runSpeed, int programCounter) {       this.action = action;       this.maxSteps = maxSteps;       this.runSpeed = runSpeed;       this.programCounter = programCounter;   }   /** Fetch the memory address that was accessed. */   public int getAction() {      return this.action;   }   /** Fetch the length in bytes of the access operation (4,2,1). */   public int getMaxSteps() {      return this.maxSteps;   }   /** Fetch the value of the access operation (the value read or written). */   public double getRunSpeed() {      return this.runSpeed;   }      /** Fetch the value of the access operation (the value read or written). */   public int getProgramCounter() {      return this.programCounter;   }   /** String representation indicates access type, address and length in bytes */   public String toString() {      return ((this.getAction()==SIMULATOR_START) ? "START " : "STOP  ") +              "Max Steps " + this.maxSteps + " " +                  "Speed "+ ((this.runSpeed==mars.venus.RunSpeedPanel.UNLIMITED_SPEED)? "unlimited " : ""+this.runSpeed+" inst/sec") +                 "Prog Ctr "+this.programCounter;   } } mars/simulator/SwingWorker.java mars/simulator/SwingWorker.javapackage mars.simulator; import javax.swing.SwingUtilities; /*-----------------------------------------------------  * This file downloaded from the Sun Microsystems URL given below.  *  * I will subclass it to create worker thread for running   * MIPS simulated execution.  */ /**  * This is the 3rd version of SwingWorker (also known as  * SwingWorker 3), an abstract class that you subclass to  * perform GUI-related work in a dedicated thread.  For  * instructions on and examples of using this class, see:  *   * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html  *  * Note that the API changed slightly in the 3rd version:  * You must now invoke start() on the SwingWorker after  * creating it.  */ public abstract class SwingWorker {     private Object value;  // see getValue(), setValue()     /**       * Class to maintain reference to current worker thread      * under separate synchronization control.      */     private static class ThreadVar {         private Thread thread;         ThreadVar(Thread t) { thread = t; }         synchronized Thread get() { return thread; }         synchronized void clear() { thread = null; }     }     private ThreadVar threadVar;     /**       * Get the value produced by the worker thread, or null if it       * hasn't been constructed yet.      */     protected synchronized Object getValue() {          return value;      }     /**       * Set the value produced by worker thread       */     private synchronized void setValue(Object x) {          value = x;      }     /**       * Compute the value to be returned by the get method. 
     */
    public abstract Object construct();

    /**
     * Called on the event dispatching thread (not on the worker thread)
     * after the construct method has returned.
     */
    public void finished() { 
    }

    /**
     * A new method that interrupts the worker thread.  Call this method
     * to force the worker to stop what it’s doing.
     */
    public void interrupt() {
        Thread t = threadVar.get();
        if (t != null) {
            t.interrupt();
        }
        threadVar.clear();
    }

    /**
     * Return the value created by the construct method.  
     * Returns null if either the constructing thread or the current
     * thread was interrupted before a value was produced.
     * 
     * @return the value created by the construct method
     */
    public Object get() {
        while (true) {  
            Thread t = threadVar.get();
            if (t == null) {
                return getValue();
            }
            try {
                t.join();
            }
            catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // propagate
                return null;
            }
        }
    }

    /**
     * Start a thread that will call the construct method
     * and then exit.
      * @param useSwing Set true if MARS is running from GUI, false otherwise.
     */
    public SwingWorker(final boolean useSwing) {
        final Runnable doFinished = new Runnable() {
           public void run() { finished(); }
        };

        Runnable doConstruct = new Runnable() { 
            public void run() {
                try {
                    setValue(construct());
                }
                finally {
                    threadVar.clear();
                }

                if (useSwing) SwingUtilities.invokeLater(doFinished);
                else doFinished.run();
            }
        };

         // Thread that represents executing MIPS program…
        Thread t = new Thread(doConstruct, “MIPS”);
          
          //t.setPriority(Thread.NORM_PRIORITY-1);//******************
          
        threadVar = new ThreadVar(t);
    }

    /**
     * Start the worker thread.
     */
    public void start() {
        Thread t = threadVar.get();
        if (t != null) {
            t.start();
        }
    }
}

mars/simulator/ProgramArgumentList.java
mars/simulator/ProgramArgumentList.java   package mars.simulator;
   import mars.*;
   import mars.venus.*;
   import mars.util.*;
   import mars.mips.hardware.*;
   import mars.mips.instructions.*;
   import java.util.*;
   import javax.swing.*;
   import java.awt.event.*;
    
    /*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */
    
/**
 * Models Program Arguments, one or more strings provided to the MIPS
 * program at runtime. Equivalent to C’s main(int argc, char **argv) or
 * Java’s main(String[] args).
 * @author Pete Sanderson
 * @version July 2008
 **/

    public class ProgramArgumentList {
   
      ArrayList programArgumentList;
   
    /**
     *  Constructor that parses string to produce list.  Delimiters
     *  are the default Java StringTokenizer delimiters (space, tab, 
     *  newline, return, formfeed)
     *
     *  @param args  String containing delimiter-separated arguments
     */
       public ProgramArgumentList(String args) {
         StringTokenizer st = new StringTokenizer(args);
         programArgumentList = new ArrayList(st.countTokens());
         while (st.hasMoreTokens()) {
            programArgumentList.add(st.nextToken());
         }
      }
   
    /**
     *  Constructor that gets list from String array, one argument per element.
     *
     *  @param list  Array of String, each element containing one argument
     */  
       public ProgramArgumentList(String[] list) {
         this(list, 0);
      }
    
    /**
     *  Constructor that gets list from section of String array, one
     *  argument per element.
     *
     *  @param args  Array of String, each element containing one argument
     *  @param startPosition Index of array element containing the first argument; all remaining
     *   elements are assumed to contain an argument.
     */  
       public ProgramArgumentList(String[] list, int startPosition) {
         programArgumentList = new ArrayList(list.length-startPosition);
         for (int i=startPosition; i= 0; j–) {
                  Globals.memory.set(highAddress, programArgument.charAt(j), 1);
                  highAddress–;                  
               }
               argStartAddress[i] = highAddress+1;
            }
            // now place a null word, the arg starting addresses, and arg count onto stack.
            int stackAddress = Memory.stackPointer;  // base address for runtime stack.
            if (highAddress < Memory.stackPointer) {                // Based on current values for stackBaseAddress and stackPointer, this will                // only happen if the combined lengths of program arguments is greater than                // 0x7ffffffc - 0x7fffeffc = 0x00001000 = 4096 bytes.  In this case, set                // stackAddress to next lower word boundary minus 4 for clearance (since every                // byte from highAddress+1 is filled).                stackAddress = highAddress - (highAddress % Memory.WORD_LENGTH_BYTES) - Memory.WORD_LENGTH_BYTES;              }             Globals.memory.set(stackAddress, 0, Memory.WORD_LENGTH_BYTES);  // null word for end of argv array             stackAddress -= Memory.WORD_LENGTH_BYTES;             for (int i=argStartAddress.length-1; i >= 0; i–) {
               Globals.memory.set(stackAddress, argStartAddress[i], Memory.WORD_LENGTH_BYTES);
               stackAddress -= Memory.WORD_LENGTH_BYTES;
            }
            Globals.memory.set(stackAddress, argStartAddress.length, Memory.WORD_LENGTH_BYTES); // argc
            stackAddress -= Memory.WORD_LENGTH_BYTES;
            
            // Need to set $sp register to stack address, $a0 to argc, $a1 to argv
            // Need to by-pass the backstepping mechanism so go directly to Register instead of RegisterFile
            Register[] registers = RegisterFile.getRegisters();
            RegisterFile.getUserRegister(“$sp”).setValue(stackAddress+Memory.WORD_LENGTH_BYTES);  
            RegisterFile.getUserRegister(“$a0”).setValue(argStartAddress.length); // argc
            RegisterFile.getUserRegister(“$a1”).setValue(stackAddress+Memory.WORD_LENGTH_BYTES+Memory.WORD_LENGTH_BYTES); // argv
            //RegisterFile.updateRegister(“$sp”,stackAddress+Memory.WORD_LENGTH_BYTES);
            //RegisterFile.updateRegister(“$a0”,argStartAddress.length); // argc
            //RegisterFile.updateRegister(“$a1”,stackAddress+Memory.WORD_LENGTH_BYTES+Memory.WORD_LENGTH_BYTES); // argv
         } 
             catch (AddressErrorException aee) {
               System.out.println(“Internal Error: Memory write error occurred while storing program arguments! “+aee);
               System.exit(0);
            }
         return;
      }
   
   
   
   }

mars/simulator/DelayedBranch.java
mars/simulator/DelayedBranch.javapackage mars.simulator;

/*
Copyright (c) 2003-2007,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Represents a (potential) delayed branch.  Note it is necessary only when
 * delayed branching is enabled.  Here’s the protocol for using it:
 *
 * (1) When a runtime decision to branch is made (by either a branch or jump
 * instruction’s simulate() method in InstructionSet), then if delayed branching
 * is enabled, the register() method is called with the branch target address but
 * the program counter is NOT set to the branch target address.
 *
 * (2) At the end of that instruction cycle, the simulate() method in Simulator
 * will detect the registered branch, and set its trigger.  Don’t do anything yet
 * because the next instruction cycle is the delay slot and needs to complete.
 *
 * (3) At the end of the next (delay slot) instruction cycle, the simulate()
 * method in Simulator will detect the triggered branch, set the program
 * counter to its target value and clear the delayed branch.
 *
 * The only interesting situation is when the delay slot itself contains a
 * successful branch!  I tried this with SPIM (e.g. beq followed by b) 
 * and it treats it as if nothing was there and continues the delay slot 
 * into the next cycle.  The eventual branch taken is the original one (as one
 * would hope) but in the meantime the first statement following the sequence
 * of successful branches will constitute the delay slot and will be executed!
 *
 * Since only one pending delayed branch can be taken at a time, everything
 * here is done with statics.  The class itself represents the potential branch.
 * 
 * @author Pete Sanderson
 * @version June 2007
 **/

public class DelayedBranch {
   // Class states.
   private static final int CLEARED    = 0;
    private static final int REGISTERED = 1;
    private static final int TRIGGERED  = 2;

   // Initially nothing is happening.
    
    private static int state = CLEARED;
    private static int branchTargetAddress = 0;
    
    /**
    *  Register the fact that a successful branch is to occur.  This is called in
     *  the instruction’s simulated execution (its simulate() method in InstructionSet).
     *  If a branch is registered but not triggered, this registration will be ignored 
     *  (cannot happen if class usage protocol is followed).  If a branch is currently 
     *  registered and triggered, reset the state back to registered (but not triggered)
     *  in order to carry over the delay slot for another execution cycle.  This is the
     *  only public member of the class.
     *
     *  @param targetAddress The address to branch to after executing the next instruction
     */
    public static void register(int targetAddress) {
      // About as clean as a switch statement can be!
      switch (state) {
        case CLEARED    :  branchTargetAddress = targetAddress;
         case REGISTERED :
         case TRIGGERED  :  state = REGISTERED;
      }          
    }

    /**
    *  Trigger a registered branch.  This is called at the end of the MIPS simulator
     *  instruction execution cycle (simulate method in Simulator), so a registered 
     *  branch will be triggered right away.  The next execution cycle will be the
     *  delay slot and at the end of THAT cycle, the trigger will be detected and the
     *  branch carried out.  This method has package visibility.
     *
     *  Precondition: DelayedBranch.isRegistered()
     *
     *  Postcondition: DelayedBranch.isTriggered() && !DelayedBranch.isRegistered()
     *
     */
     static void trigger() {
      // About as clean as a switch statement can be!
      switch (state) {
         case REGISTERED :
         case TRIGGERED  :  state = TRIGGERED;
         case CLEARED    :
      }          
    }

    /**
    *  Clear the delayed branch. This must be done immediately after setting the
     *  program counter to the target address.  This method has package visibility.
     */
     static void clear() {
      state = CLEARED;
      branchTargetAddress = 0; 
    }

   /**
     *  Return registration status.  Is false initially, true after register() is called
     *  but becomes false after trigger() or clear() are called.  This method has package
     *  visibility.
     *
     *  @return true if branch is registered but not triggered, false otherwise.
     */

    static boolean isRegistered() {
       return state == REGISTERED;
    }
    
   /**
     *  Return trigger status.  Is false initially, true after trigger() is called
     *  but becomes false after clear() is called.  This method has package visibility.
    *
    *  @return true if branch is registered but not triggered, false otherwise.
     */

   static boolean isTriggered() {
       return state == TRIGGERED;
    }   

  /**
   *  Return branch target address.  This should be retrieved only to set the program
    *  counter at the end of the delay slot.  This method has package visibility.
    *
    *  Precondition: DelayedBranch.isTriggered()
    *
    *  @return Target address of the delayed branch.
    */
     static int getBranchTargetAddress() {
        return branchTargetAddress;
    }
    
}  // DelayedBranch

SwingWorker$1

package mars.simulator;
synchronized class SwingWorker$1 implements Runnable {
void SwingWorker$1(SwingWorker);
public void run();
}

BackStepper$BackStep

package mars.simulator;
synchronized class BackStepper$BackStep {
private int action;
private int pc;
private mars.ProgramStatement ps;
private int param1;
private int param2;
private boolean inDelaySlot;
private void BackStepper$BackStep(BackStepper);
private void assign(int, int, int, int);
}

ProgramArgumentList

package mars.simulator;
public synchronized class ProgramArgumentList {
java.util.ArrayList programArgumentList;
public void ProgramArgumentList(String);
public void ProgramArgumentList(String[]);
public void ProgramArgumentList(String[], int);
public void ProgramArgumentList(java.util.ArrayList);
public void ProgramArgumentList(java.util.ArrayList, int);
public void storeProgramArguments();
}

SwingWorker

package mars.simulator;
public abstract synchronized class SwingWorker {
private Object value;
private SwingWorker$ThreadVar threadVar;
protected synchronized Object getValue();
private synchronized void setValue(Object);
public abstract Object construct();
public void finished();
public void interrupt();
public Object get();
public void SwingWorker(boolean);
public void start();
}

Simulator$UpdateGUI

package mars.simulator;
synchronized class Simulator$UpdateGUI implements Runnable {
private void Simulator$UpdateGUI(Simulator);
public void run();
}

SimulatorNotice

package mars.simulator;
public synchronized class SimulatorNotice {
private int action;
private int maxSteps;
private double runSpeed;
private int programCounter;
public static final int SIMULATOR_START = 0;
public static final int SIMULATOR_STOP = 1;
public void SimulatorNotice(int, int, double, int);
public int getAction();
public int getMaxSteps();
public double getRunSpeed();
public int getProgramCounter();
public String toString();
}

ErrorMessage

package mars;
public synchronized class ErrorMessage {
private boolean isWarning;
private String filename;
private int line;
private int position;
private String message;
private String macroExpansionHistory;
public static final boolean WARNING = 1;
public static final boolean ERROR = 0;
public void ErrorMessage(String, int, int, String);
public void ErrorMessage(String, int, int, String, String);
public void ErrorMessage(boolean, String, int, int, String, String);
public void ErrorMessage(MIPSprogram, int, int, String);
public void ErrorMessage(boolean, MIPSprogram, int, int, String);
public void ErrorMessage(ProgramStatement, String);
private java.util.ArrayList parseMacroHistory(String);
public String getFilename();
public int getLine();
public int getPosition();
public String getMessage();
public boolean isWarning();
public String getMacroExpansionHistory();
private static String getExpansionHistory(MIPSprogram);
}

mars/ProgramStatement.java
mars/ProgramStatement.java   package mars;
   import mars.assembler.*;
   import mars.mips.instructions.*;
   import mars.mips.hardware.*;
   import mars.util.*;
   import java.util.*;

/*
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Represents one assembly/machine statement.  This represents the “bare machine” level.
 * Pseudo-instructions have already been processed at this point and each assembly 
 * statement generated by them is one of these.
 * 
 * @author Pete Sanderson and Jason Bumgarner 
 * @version August 2003
 */

    public class ProgramStatement {
      private MIPSprogram sourceMIPSprogram;
      private String source, basicAssemblyStatement, machineStatement;
      private TokenList originalTokenList, strippedTokenList;
      private BasicStatementList basicStatementList;
      private int[] operands;
      private int numOperands;
      private Instruction instruction;
      private int textAddress;
      private int sourceLine;
      private int binaryStatement;
      private boolean altered;
    
    //////////////////////////////////////////////////////////////////////////////////
    /**
     * Constructor for ProgramStatement when there are links back to all source and token 
     * information.  These can be used by a debugger later on.
     * @param sourceMIPSprogram The MIPSprogram object that contains this statement
     * @param source The corresponding MIPS source statement.
     * @param origTokenList Complete list of Token objects (includes labels, comments, parentheses, etc)
     * @param strippedTokenList List of Token objects with all but operators and operands removed.
     * @param inst The Instruction object for this statement’s operator.
     * @param textAddress The Text Segment address in memory where the binary machine code for this statement
     * is stored.
     **/
       public ProgramStatement(MIPSprogram sourceMIPSprogram, String source, TokenList origTokenList, TokenList strippedTokenList,
                            Instruction inst, int textAddress, int sourceLine) {
         this.sourceMIPSprogram = sourceMIPSprogram;
         this.source = source;
         this.originalTokenList = origTokenList;
         this.strippedTokenList = strippedTokenList;
         this.operands = new int[4];
         this.numOperands = 0;
         this.instruction = inst;
         this.textAddress = textAddress;
         this.sourceLine = sourceLine;
         this.basicAssemblyStatement = null;
         this.basicStatementList = new BasicStatementList();
         this.machineStatement = null;
         this.binaryStatement = 0;  // nop, or sll $0, $0, 0  (32 bits of 0’s)
         this.altered = false;
      }
   
//  public MIPSprogram getOriginalProgram() {
//    return (originalTokenList != null && originalTokenList.size() > 0) ? originalTokenList.get(0).getOriginalProgram() : null;
//    }
//  public int getOriginalSourceLine() {
//    return (originalTokenList != null && originalTokenList.size() > 0) ? originalTokenList.get(0).getOriginalSourceLine() : 0;
//    }   
    //////////////////////////////////////////////////////////////////////////////////
    /**
     * Constructor for ProgramStatement used only for writing a binary machine 
     * instruction with no source code to refer back to.  It could be extended to support
     * self-modifying code but currently supports only NOP which is all zeroes.
     * @param binaryStatement The 32-bit machine code.
     * @param textAddress The Text Segment address in memory where the binary machine code for this statement
     * is stored.
     **/
    //////////////////////////////////////////////////////////////////////////////////
   
       public ProgramStatement(int binaryStatement, int textAddress) {
         this.sourceMIPSprogram = null;
         this.binaryStatement = binaryStatement;
         this.textAddress = textAddress;
         this.originalTokenList = this.strippedTokenList = null;
         this.source = “”;
         this.machineStatement = this.basicAssemblyStatement = null;
         this.operands = null;
         this.numOperands = 0;
         this.instruction = (binaryStatement==0) // this is a “nop” statement
                            ? (Instruction) Globals.instructionSet.matchOperator(“nop”).get(0)
                                 : null;
         this.altered = false;
      }
   
   
    /////////////////////////////////////////////////////////////////////////////
    /**
     * Given specification of BasicInstruction for this operator, build the
     * corresponding assembly statement in basic assembly format (e.g. substituting
     * register numbers for register names, replacing labels by values).
     * @param errors The list of assembly errors encountered so far.  May add to it here.
     **/
       public void buildBasicStatementFromBasicInstruction(ErrorList errors) {
         Token token = strippedTokenList.get(0);
            String basicStatementElement = token.getValue()+” “;;
            String basic = basicStatementElement;
         basicStatementList.addString(basicStatementElement); // the operator
         TokenTypes tokenType, nextTokenType;
         String tokenValue;
         int registerNumber;
         this.numOperands = 0;
         for (int i=1; i> 2;
                     address = (address – (this.textAddress+Instruction.INSTRUCTION_LENGTH)) >> 2;
                     absoluteAddress = false;
                  }
               }
                 //////////////////////////////////////////////////////////////////////
                    basic += address;
               if (absoluteAddress) { // record as address if absolute, value if relative
                  basicStatementList.addAddress(address);
               } 
               else {
                  basicStatementList.addValue(address);
               }
               this.operands[this.numOperands++] = address;
            } 
            else if (tokenType == TokenTypes.INTEGER_5 || tokenType == TokenTypes.INTEGER_16 ||
                     tokenType == TokenTypes.INTEGER_16U || tokenType == TokenTypes.INTEGER_32) {
            
               int tempNumeric = Binary.stringToInt(tokenValue);
                
            /***************************************************************************
            *  MODIFICATION AND COMMENT, DPS 3-July-2008
            *
            * The modifications of January 2005 documented below are being rescinded.
            * All hexadecimal immediate values are considered 32 bits in length and
            * their classification as INTEGER_5, INTEGER_16, INTEGER_16U (new)
            * or INTEGER_32 depends on their 32 bit value.  So 0xFFFF will be
            * equivalent to 0x0000FFFF instead of 0xFFFFFFFF.  This change, along with
            * the introduction of INTEGER_16U (adopted from Greg Gibeling of Berkeley),
            * required extensive changes to instruction templates especially for
            * pseudo-instructions.
            *
            * This modification also appears inbuildBasicStatementFromBasicInstruction()
            * in mars.ProgramStatement. 
            *                
            *  ///// Begin modification 1/4/05 KENV   ///////////////////////////////////////////
            *  // We have decided to interpret non-signed (no + or -) 16-bit hexadecimal immediate  
            *  // operands as signed values in the range -32768 to 32767. So 0xffff will represent
            *  // -1, not 65535 (bit 15 as sign bit), 0x8000 will represent -32768 not 32768.
            *  // NOTE: 32-bit hexadecimal immediate operands whose values fall into this range
            *  // will be likewise affected, but they are used only in pseudo-instructions.  The
            *  // code in ExtendedInstruction.java to split this number into upper 16 bits for “lui” 
            *  // and lower 16 bits for “ori” works with the original source code token, so it is 
            *  // not affected by this tweak.  32-bit immediates in data segment directives
            *  // are also processed elsewhere so are not affected either.
            *  ////////////////////////////////////////////////////////////////////////////////
            *  
            *        if (tokenType != TokenTypes.INTEGER_16U) { // part of the Berkeley mod…         
            *           if ( Binary.isHex(tokenValue) &&
            *             (tempNumeric >= 32768) &&
            *             (tempNumeric <= 65535) )  // Range 0x8000 ... 0xffff             *           {             *              // Subtract the 0xffff bias, because strings in the             *              // range "0x8000" ... "0xffff" are used to represent             *              // 16-bit negative numbers, not positive numbers.             *              tempNumeric = tempNumeric - 65536;             *              // Note: no action needed for range 0xffff8000 ... 0xffffffff             *           }             *        }             **************************  END DPS 3-July-2008 COMMENTS *******************************/                                  basic += tempNumeric;                basicStatementList.addValue(tempNumeric);                  this.operands[this.numOperands++] = tempNumeric;                 ///// End modification 1/7/05 KENV   ///////////////////////////////////////////             }              else {                    basicStatementElement = tokenValue;                     basic += basicStatementElement;                basicStatementList.addString(basicStatementElement);             }             // add separator if not at end of token list AND neither current nor              // next token is a parenthesis             if ((i < strippedTokenList.size()-1)) {                nextTokenType = strippedTokenList.get(i+1).getType();                if (tokenType != TokenTypes.LEFT_PAREN  &&  tokenType != TokenTypes.RIGHT_PAREN  &&                    nextTokenType != TokenTypes.LEFT_PAREN && nextTokenType != TokenTypes.RIGHT_PAREN)                          {                            basicStatementElement = ",";                             basic += basicStatementElement;                      basicStatementList.addString(basicStatementElement);                         }             }          }          this.basicAssemblyStatement = basic;       } //buildBasicStatementFromBasicInstruction()                   /////////////////////////////////////////////////////////////////////////////     /**      * Given the current statement in Basic Assembly format (see above), build the      * 32-bit binary machine code statement.      * @param errors The list of assembly errors encountered so far.  May add to it here.      **/        public void buildMachineStatementFromBasicStatement(ErrorList errors) {                 try {                //mask indicates bit positions for 'f'irst, 's'econd, 't'hird operand             this.machineStatement = ((BasicInstruction)instruction).getOperationMask();          }   // This means the pseudo-instruction expansion generated another              // pseudo-instruction (expansion must be to all basic instructions).              // This is an error on the part of the pseudo-instruction author.              catch (ClassCastException cce) {                errors.add(new ErrorMessage(this.sourceMIPSprogram,this.sourceLine,0,                           "INTERNAL ERROR: pseudo-instruction expansion contained a pseudo-instruction"));                return;                         }                  BasicInstructionFormat format = ((BasicInstruction)instruction).getInstructionFormat();                 if (format == BasicInstructionFormat.J_FORMAT) {             if ((this.textAddress & 0xF0000000) != (this.operands[0] & 0xF0000000)) {                // attempt to jump beyond 28-bit byte (26-bit word) address range.                  // SPIM flags as warning, I'll flag as error b/c MARS text segment not long enough for it to be OK.                errors.add(new ErrorMessage(this.sourceMIPSprogram, this.sourceLine, 0,                           "Jump target word address beyond 26-bit range"));                return;             }             // Note the  bit shift to make this a word address.             this.operands[0] = this.operands[0] >>> 2;
            this.insertBinaryCode(this.operands[0], Instruction.operandMask[0], errors);          
         } 
         else if (format == BasicInstructionFormat.I_BRANCH_FORMAT) { 
            for (int i=0; i= numOperands, it returns -1.
     **/   
       public int getOperand(int i) {
         if (i >= 0 && i < this.numOperands) {             return operands[i];          }           else {             return -1;          }       }                //////////////////////////////////////////////////////////      //      //  Little class to represent basic statement as list      //  of elements.  Each element is either a string, an      //  address or a value.  The toString() method will      //  return a string representation of the basic statement          //  in which any addresses or values are rendered in the           //  current number format (e.g. decimal or hex).      //          //  NOTE: Address operands on Branch instructions are          //  considered values instead of addresses because they          //  are relative to the PC.          //      //  DPS 29-July-2010              private class BasicStatementList {                 private ArrayList list;                  BasicStatementList() {             list = new ArrayList();          }                  void addString(String string) {             list.add(new ListElement(0, string, 0));          }                  void addAddress(int address) {             list.add(new ListElement(1, null, address));          }                  void addValue(int value) {             list.add(new ListElement(2, null, value));          }                  public String toString() {             int addressBase =  (Globals.getSettings().getBooleanSetting(Settings.DISPLAY_ADDRESSES_IN_HEX)) ? mars.venus.NumberDisplayBaseChooser.HEXADECIMAL : mars.venus.NumberDisplayBaseChooser.DECIMAL;             int valueBase =  (Globals.getSettings().getBooleanSetting(Settings.DISPLAY_VALUES_IN_HEX)) ? mars.venus.NumberDisplayBaseChooser.HEXADECIMAL : mars.venus.NumberDisplayBaseChooser.DECIMAL;                          StringBuffer result = new StringBuffer();             for (int i=0; i();
public void Settings();
public void Settings(boolean);
public boolean getBackSteppingEnabled();
public void reset(boolean);
public void setEditorSyntaxStyleByPosition(int, venus.editors.jeditsyntax.SyntaxStyle);
public venus.editors.jeditsyntax.SyntaxStyle getEditorSyntaxStyleByPosition(int);
public venus.editors.jeditsyntax.SyntaxStyle getDefaultEditorSyntaxStyleByPosition(int);
private void saveEditorSyntaxStyle(int);
private void initializeEditorSyntaxStyles();
private void getEditorSyntaxStyleSettingsFromPreferences();
public boolean getBooleanSetting(int);
public boolean getBareMachineEnabled();
public boolean getExtendedAssemblerEnabled();
public boolean getAssembleOnOpenEnabled();
public boolean getDisplayAddressesInHex();
public boolean getDisplayValuesInHex();
public boolean getAssembleAllEnabled();
public boolean getExceptionHandlerEnabled();
public boolean getDelayedBranchingEnabled();
public boolean getLabelWindowVisibility();
public boolean getEditorLineNumbersDisplayed();
public boolean getWarningsAreErrors();
public boolean getProgramArguments();
public boolean getDataSegmentHighlighting();
public boolean getRegistersHighlighting();
public boolean getStartAtMain();
public String getExceptionHandler();
public String getMemoryConfiguration();
public java.awt.Font getEditorFont();
public java.awt.Font getFontByPosition(int);
public java.awt.Font getDefaultFontByPosition(int);
public int[] getTextColumnOrder();
public int getCaretBlinkRate();
public int getEditorTabSize();
public int getEditorPopupPrefixLength();
public int getDefaultEditorTabSize();
public String getLabelSortState();
public java.awt.Color getColorSettingByKey(String);
public java.awt.Color getDefaultColorSettingByKey(String);
public java.awt.Color getColorSettingByPosition(int);
public java.awt.Color getDefaultColorSettingByPosition(int);
public void setBooleanSetting(int, boolean);
public void setExtendedAssemblerEnabled(boolean);
public void setAssembleOnOpenEnabled(boolean);
public void setAssembleAllEnabled(boolean);
public void setDisplayAddressesInHex(boolean);
public void setDisplayValuesInHex(boolean);
public void setLabelWindowVisibility(boolean);
public void setExceptionHandlerEnabled(boolean);
public void setDelayedBranchingEnabled(boolean);
public void setEditorLineNumbersDisplayed(boolean);
public void setWarningsAreErrors(boolean);
public void setProgramArguments(boolean);
public void setDataSegmentHighlighting(boolean);
public void setRegistersHighlighting(boolean);
public void setStartAtMain(boolean);
public void setDelayedBranchingEnabledNonPersistent(boolean);
public void setExceptionHandler(String);
public void setMemoryConfiguration(String);
public void setCaretBlinkRate(int);
public void setEditorTabSize(int);
public void setEditorPopupPrefixLength(int);
public void setEditorFont(java.awt.Font);
public void setFontByPosition(int, java.awt.Font);
public void setTextColumnOrder(int[]);
public void setLabelSortState(String);
public void setColorSettingByKey(String, java.awt.Color);
public void setColorSettingByPosition(int, java.awt.Color);
private void initialize();
private void applyDefaultSettings();
private void internalSetBooleanSetting(int, boolean);
private void setStringSetting(int, String);
private void setColorSetting(int, java.awt.Color);
private java.awt.Color getColorValueByKey(String, String[]);
private java.awt.Color getColorValueByPosition(int, String[]);
private int getIndexOfKey(String, String[]);
private boolean readSettingsFromPropertiesFile(String);
private void getSettingsFromPreferences();
private void saveBooleanSetting(int);
private void saveStringSetting(int);
private void saveFontSetting(int, String[], String[]);
private void saveColorSetting(int);
private int[] getTextSegmentColumnOrder(String);
}

MarsLaunch$2

package mars;
synchronized class MarsLaunch$2 implements java.util.Observer {
private int lastAddress;
void MarsLaunch$2(MarsLaunch);
public void update(java.util.Observable, Object);
}

mars/MarsLaunch.java
mars/MarsLaunch.java   package mars;
   import mars.venus.*;
   import mars.util.*;
   import mars.mips.dump.*;
   import mars.mips.hardware.*;
   import mars.simulator.*;
   import java.io.*;
   import java.util.*;
   import java.awt.*;
   import javax.swing.*;
   import javax.swing.JOptionPane;   // KENV 9/8/2004

/*
Copyright (c) 2003-2012,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Launch the Mars application
 * 
 * @author Pete Sanderson
 * @version December 2009
 **/

   public class MarsLaunch {
   
   /**
    * Main takes a number of command line arguments.
      Usage:  Mars  [options] filename
      Valid options (not case sensitive, separate by spaces) are:
            a  — assemble only, do not simulate
           ad  — both a and d
      ae  — terminate MARS with integer exit code  if an assemble error occurs.
      ascii  — display memory or register contents interpreted as ASCII
           b  — brief – do not display register/memory address along with contents
           d  — print debugging statements
           da  — both a and d
           db  — MIPS delayed branching is enabled.
          dec  — display memory or register contents in decimal.
         dump  — dump memory contents to file.  Option has 3 arguments, e.g. 
                  dump <segment> <format> <file>.  Also supports
                  an address range (see m-n below).  Current supported 
                  segments are .text and .data.  Current supported dump formats 
                  are BinaryHexTextBinaryText.
            h  — display help.  Use by itself and with no filename

          hex  — display memory or register contents in hexadecimal (default)
           ic  — display count of MIPS basic instructions ‘executed'”);
           mc  — set memory configuration.  Option has 1 argument, e.g.
                  mc <config$gt;, where <config$gt; is Default
                  for the MARS default 32-bit address space, CompactDataAtZero for
                  a 32KB address space with data segment at address 0, or CompactTextAtZero
                  for a 32KB address space with text segment at address 0.
           me  — display MARS messages to standard err instead of standard out. Can separate via redirection.

           nc  — do not display copyright notice (for cleaner redirected/piped output).

          np  — No Pseudo-instructions allowed (“ne” will work also).
           p  — Project mode – assemble all files in the same directory as given file.
      se  — terminate MARS with integer exit code  if a simulation (run) error occurs.
           sm  — Start execution at Main – Execution will start at program statement globally labeled main.
           we  — assembler Warnings will be considered Errors
            — where  is an integer maximum count of steps to simulate.
                  If 0, negative or not specified, there is no maximum.
       $  — where  is number or name (e.g. 5, t3, f10) of register whose 
                  content to display at end of run.  Option may be repeated.
     — where  is name (e.g. t3, f10) of register whose 
                  content to display at end of run.  Option may be repeated. $ not required.
        — memory address range from  to  whose contents to
                  display at end of run.  and  may be hex or decimal,
                   <= , both must be on word boundary.  Option may be repeated.
           pa  — Program Arguments follow in a space-separated list.  This
                  option must be placed AFTER ALL FILE NAMES, because everything
                  that follows it is interpreted as a program argument to be
                  made available to the MIPS program at runtime.
    **/
    
   
   
      private boolean simulate;
      private int displayFormat;
      private boolean verbose;  // display register name or address along with contents
      private boolean assembleProject; // assemble only the given file or all files in its directory
      private boolean pseudo;  // pseudo instructions allowed in source code or not.
      private boolean delayedBranching;  // MIPS delayed branching is enabled.
      private boolean warningsAreErrors; // Whether assembler warnings should be considered errors.
      private boolean startAtMain; // Whether to start execution at statement labeled ‘main’ 
      private boolean countInstructions; // Whether to count and report number of instructions executed 
      private static final String rangeSeparator = “-“;
      private static final int splashDuration = 2000; // time in MS to show splash screen
      private static final int memoryWordsPerLine = 4; // display 4 memory words, tab separated, per line
      private static final int DECIMAL = 0; // memory and register display format
      private static final int HEXADECIMAL = 1;// memory and register display format
      private static final int ASCII = 2;// memory and register display format
      private ArrayList registerDisplayList;
      private ArrayList memoryDisplayList;
      private ArrayList filenameList;
      private MIPSprogram code;
      private int maxSteps;
      private int instructionCount;
      private PrintStream out; // stream for display of command line output
      private ArrayList dumpTriples = null; // each element holds 3 arguments for dump option
      private ArrayList programArgumentList; // optional program args for MIPS program (becomes argc, argv)
      private int assembleErrorExitCode;  // MARS command exit code to return if assemble error occurs
      private int simulateErrorExitCode;// MARS command exit code to return if simulation error occurs
        
      public MarsLaunch(String[] args) {
         boolean gui = (args.length == 0);
         Globals.initialize(gui);  
         if (gui) {
            launchIDE();  
         } 
         else { // running from command line.
            // assure command mode works in headless environment (generates exception if not)
            System.setProperty(“java.awt.headless”, “true”); 
            simulate = true;
            displayFormat = HEXADECIMAL;
            verbose = true;  
            assembleProject = false;
            pseudo = true;
            delayedBranching = false;
            warningsAreErrors = false;
            startAtMain = false;
            countInstructions = false;
            instructionCount = 0;
            assembleErrorExitCode = 0;
            simulateErrorExitCode = 0;
            registerDisplayList = new ArrayList();
            memoryDisplayList = new ArrayList();
            filenameList = new ArrayList();
            MemoryConfigurations.setCurrentConfiguration(MemoryConfigurations.getDefaultConfiguration());
            // do NOT use Globals.program for command line MARS — it triggers ‘backstep’ log.
            code = new MIPSprogram();  
            maxSteps = -1;
            out = System.out;  
            if (parseCommandArgs(args)) {
               if (runCommand()) {
                  displayMiscellaneousPostMortem();
                  displayRegistersPostMortem();
                  displayMemoryPostMortem();
               }
               dumpSegments();
            }
            System.exit(Globals.exitCode);
         }
      }         
    
      /////////////////////////////////////////////////////////////
    // Perform any specified dump operations.  See “dump” option.
    //
   
      private void dumpSegments() {
       
         if (dumpTriples == null) 
            return;
         
         for (int i=0; i 1) {
                  // Using “p” project option PLUS listing more than one filename on command line.
                  // Add the additional files, avoiding duplicates.
                  filenameList.remove(0); // first one has already been processed
                  ArrayList moreFilesToAssemble = FilenameFinder.getFilenameList(filenameList, FilenameFinder.MATCH_ALL_EXTENSIONS);
                  // Remove any duplicates then merge the two lists.
                  for (int index2 = 0; index2 0 && 
                   arg.indexOf(rangeSeparator) < arg.length()-1) {             // assume correct format, two numbers separated by -, no embedded spaces.             // If that doesn't work it is invalid.             memoryRange = new String[2];             memoryRange[0] = arg.substring(0,arg.indexOf(rangeSeparator));             memoryRange[1] = arg.substring(arg.indexOf(rangeSeparator)+1);             // NOTE: I will use homegrown decoder, because Integer.decode will throw             // exception on address higher than 0x7FFFFFFF (e.g. sign bit is 1).             if (Binary.stringToInt(memoryRange[0]) > Binary.stringToInt(memoryRange[1]) ||
                         !Memory.wordAligned(Binary.stringToInt(memoryRange[0])) ||
                         !Memory.wordAligned(Binary.stringToInt(memoryRange[1]))) {
               throw new NumberFormatException();
            }
         }
         return memoryRange;
      }
   
      /////////////////////////////////////////////////////////////////
    // Required for counting instructions executed, if that option is specified.
    // DPS 19 July 2012
      private void establishObserver() { 
         if (countInstructions) {
            Observer instructionCounter = 
               new Observer() {
                  private int lastAddress = 0;
                  public void update(Observable o, Object obj) { 
                     if (obj instanceof AccessNotice) {
                        AccessNotice notice = (AccessNotice) obj;
                        if (!notice.accessIsFromMIPS()) 
                           return;
                        if (notice.getAccessType() != AccessNotice.READ) 
                           return;
                        MemoryAccessNotice m = (MemoryAccessNotice) notice;
                        int a = m.getAddress();
                        if (a == lastAddress) 
                           return;
                        lastAddress = a;
                        instructionCount++;               
                     }
                  }
               };
            try {
               Globals.memory.addObserver(instructionCounter, Memory.textBaseAddress, Memory.textLimitAddress);
            } 
               catch (AddressErrorException aee) {
                  out.println(“Internal error: MarsLaunch uses incorrect text segment address for instruction observer”);
               }
         }      
      }
                    
    //////////////////////////////////////////////////////////////////////
    // Displays any specified runtime properties. Initially just instruction count 
    // DPS 19 July 2012     
      private void displayMiscellaneousPostMortem() {
         if (countInstructions) {
            out.println(“\n”+instructionCount);
         }
      }
   
                    
    //////////////////////////////////////////////////////////////////////
    // Displays requested register or registers             
                
      private void displayRegistersPostMortem() {
         int value;  // handy local to use throughout the next couple loops
         String strValue;
         // Display requested register contents
         out.println();
         Iterator regIter = registerDisplayList.iterator();
         while (regIter.hasNext()) {
            String reg = regIter.next().toString();
            if (RegisterFile.getUserRegister(reg)!=null) {
                     // integer register
               if (verbose) 
                  out.print(reg+”\t”);
               value = RegisterFile.getUserRegister(reg).getValue();
               out.println( formatIntForDisplay(value) );
            } 
            else {
                     // floating point register
               float fvalue = Coprocessor1.getFloatFromRegister(reg);
               int ivalue = Coprocessor1.getIntFromRegister(reg);
               double dvalue = Double.NaN;
               long lvalue = 0;
               boolean hasDouble = false;
               try {
                  dvalue = Coprocessor1.getDoubleFromRegisterPair(reg);
                  lvalue = Coprocessor1.getLongFromRegisterPair(reg);
                  hasDouble = true;
               } 
                  catch (InvalidRegisterAccessException irae) { }
               if (verbose) {
                  out.print(reg+”\t”);
               }
               if (displayFormat == HEXADECIMAL) {
                  // display float (and double, if applicable) in hex
                  out.print(
                           Binary.binaryStringToHexString(
                                          Binary.intToBinaryString(ivalue)));                           
                  if (hasDouble) {
                     out.println(“\t”+
                              Binary.binaryStringToHexString(
                                          Binary.longToBinaryString(lvalue)));
                  } 
                  else {
                     out.println(“”);
                  }
               } 
               else if (displayFormat == DECIMAL) {
                  // display float (and double, if applicable) in decimal
                  out.print(fvalue);
                  if (hasDouble) {
                     out.println(“\t”+dvalue);
                  } 
                  else {
                     out.println(“”);
                  }
               } 
               else { // displayFormat == ASCII
                  out.print(Binary.intToAscii(ivalue));
                  if (hasDouble) {
                     out.println(“\t”+ 
                            Binary.intToAscii(Binary.highOrderLongToInt(lvalue))+
                            Binary.intToAscii(Binary.lowOrderLongToInt(lvalue)));
                  } 
                  else {
                     out.println(“”);
                  }
               }
            }
         }
      }
   
    //////////////////////////////////////////////////////////////////////
    // Formats int value for display: decimal, hex, ascii    
      private String formatIntForDisplay(int value) {
         String strValue; 
         switch (displayFormat) {
            case DECIMAL : 
               strValue = “”+value;
               break;
            case HEXADECIMAL :
               strValue = Binary.intToHexString(value);
               break;
            case ASCII :
               strValue = Binary.intToAscii(value);
               break;
            default :
               strValue = Binary.intToHexString(value);
         }   
         return strValue;
      }
    
    //////////////////////////////////////////////////////////////////////
    // Displays requested memory range or ranges
    
      private void displayMemoryPostMortem() {  
         int value;  
         // Display requested memory range contents
         Iterator memIter = memoryDisplayList.iterator();
         int addressStart=0, addressEnd=0;
         while (memIter.hasNext()) {
            try { // This will succeed; error would have been caught during command arg parse
               addressStart = Binary.stringToInt(memIter.next().toString());
               addressEnd = Binary.stringToInt(memIter.next().toString());
            } 
               catch (NumberFormatException nfe) {
               }
            int valuesDisplayed = 0;
            for (int addr=addressStart; addr<=addressEnd; addr+=Memory.WORD_LENGTH_BYTES) {                if (addr < 0 && addressEnd > 0) 
                  break;  // happens only if addressEnd is 0x7ffffffc
               if (valuesDisplayed % memoryWordsPerLine == 0) {
                  out.print( (valuesDisplayed > 0) ? “\n” : “”);
                  if (verbose) {
                     out.print(“Mem[“+Binary.intToHexString(addr)+”]\t”);
                  }
               }
               try {
                  // Allow display of binary text segment (machine code) DPS 14-July-2008
                  if (Memory.inTextSegment(addr) || Memory.inKernelTextSegment(addr)) {
                     Integer iValue = Globals.memory.getRawWordOrNull(addr);
                     value = (iValue==null) ? 0 : iValue.intValue();
                  } 
                  else {
                     value = Globals.memory.getWord(addr);
                  }
                  out.print( formatIntForDisplay(value)+”\t”);
               }
                  catch (AddressErrorException aee) {
                     out.print(“Invalid address: “+addr+”\t”);
                  }
               valuesDisplayed++;
            }
            out.println();
         }                  
      }
   
      ///////////////////////////////////////////////////////////////////////
    //  If option to display MARS messages to standard err (System.err) is
    //  present, it must be processed before all others.  Since messages may
    //  be output as early as during the command parse.  
      private void processDisplayMessagesToErrSwitch(String[] args, String displayMessagesToErrSwitch) {
         for (int i=0; i  — terminate MARS with integer exit code  if an assemble error occurs.”);
         out.println(”  ascii  — display memory or register contents interpreted as ASCII codes.”);
         out.println(”      b  — brief – do not display register/memory address along with contents”);
         out.println(”      d  — display MARS debugging statements”);
         out.println(”     db  — MIPS delayed branching is enabled”);
         out.println(”    dec  — display memory or register contents in decimal.”);
         out.println(”   dump    — memory dump of specified memory segment”);
         out.println(”            in specified format to specified file.  Option may be repeated.”); 
         out.println(”            Dump occurs at the end of simulation unless ‘a’ option is used.”);
         out.println(”            Segment and format are case-sensitive and possible values are:”);
         out.println(”             = “+segments);
         out.println(”             = “+formats);
         out.println(”      h  — display this help.  Use by itself with no filename.”);
         out.println(”    hex  — display memory or register contents in hexadecimal (default)”);
         out.println(”     ic  — display count of MIPS basic instructions ‘executed'”);
         out.println(”     mc   — set memory configuration.  Argument  is”);
         out.println(”            case-sensitive and possible values are: Default for the default”);
         out.println(”            32-bit address space, CompactDataAtZero for a 32KB memory with”);
         out.println(”            data segment at address 0, or CompactTextAtZero for a 32KB”);
         out.println(”            memory with text segment at address 0.”);
         out.println(”     me  — display MARS messages to standard err instead of standard out. “);
         out.println(”            Can separate messages from program output using redirection”);
         out.println(”     nc  — do not display copyright notice (for cleaner redirected/piped output).”);
         out.println(”     np  — use of pseudo instructions and formats not permitted”);
         out.println(”      p  — Project mode – assemble all files in the same directory as given file.”);
         out.println(”  se  — terminate MARS with integer exit code  if a simulation (run) error occurs.”);
         out.println(”     sm  — start execution at statement with global label main, if defined”);
         out.println(”      — where  is an integer maximum count of steps to simulate.”);
         out.println(”            If 0, negative or not specified, there is no maximum.”);
         out.println(” $  — where  is number or name (e.g. 5, t3, f10) of register whose “);
         out.println(”            content to display at end of run.  Option may be repeated.”);
         out.println(“  — where  is name (e.g. t3, f10) of register whose”);
         out.println(”            content to display at end of run.  Option may be repeated. “);
         out.println(”            The $ is not required.”);
         out.println(“  — memory address range from  to  whose contents to”);
         out.println(”            display at end of run.  and  may be hex or decimal,”);
         out.println(”            must be on word boundary,  <= .  Option may be repeated.”);
         out.println(”     pa  — Program Arguments follow in a space-separated list.  This”);
         out.println(”            option must be placed AFTER ALL FILE NAMES, because everything”);
         out.println(”            that follows it is interpreted as a program argument to be”);
         out.println(”            made available to the MIPS program at runtime.”);
         out.println(“If more than one filename is listed, the first is assumed to be the main”);
         out.println(“unless the global statement label ‘main’ is defined in one of the files.”);
         out.println(“Exception handler not automatically assembled.  Add it to the file list.”);
         out.println(“Options used here do not affect MARS Settings menu values and vice versa.”);
      }
   
   }
    
    

ProgramStatement

package mars;
public synchronized class ProgramStatement {
private MIPSprogram sourceMIPSprogram;
private String source;
private String basicAssemblyStatement;
private String machineStatement;
private assembler.TokenList originalTokenList;
private assembler.TokenList strippedTokenList;
private ProgramStatement$BasicStatementList basicStatementList;
private int[] operands;
private int numOperands;
private mips.instructions.Instruction instruction;
private int textAddress;
private int sourceLine;
private int binaryStatement;
private boolean altered;
public void ProgramStatement(MIPSprogram, String, assembler.TokenList, assembler.TokenList, mips.instructions.Instruction, int, int);
public void ProgramStatement(int, int);
public void buildBasicStatementFromBasicInstruction(ErrorList);
public void buildMachineStatementFromBasicStatement(ErrorList);
private void insertBinaryCode(int, char, ErrorList);
public String toString();
public void setBasicAssemblyStatement(String);
public void setMachineStatement(String);
public void setBinaryStatement(int);
public void setSource(String);
public MIPSprogram getSourceMIPSprogram();
public String getSourceFile();
public String getSource();
public int getSourceLine();
public String getBasicAssemblyStatement();
public String getPrintableBasicAssemblyStatement();
public String getMachineStatement();
public int getBinaryStatement();
public assembler.TokenList getOriginalTokenList();
public assembler.TokenList getStrippedTokenList();
public mips.instructions.Instruction getInstruction();
public int getAddress();
public int[] getOperands();
public int getOperand(int);
}

mars/MIPSprogram.java
mars/MIPSprogram.java   package mars;
    
   import mars.venus.*;
   import mars.assembler.*;
   import mars.simulator.*;
   import mars.mips.hardware.*;
    
   import java.util.*;
   import java.io.*;
   import java.awt.event.*;
   import javax.swing.*;

/*
Copyright (c) 2003-2006,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Internal representations of MIPS program.  Connects source, tokens and machine code.  Having
 * all these structures available facilitates construction of good messages,
 * debugging, and easy simulation.
 * 
 * @author Pete Sanderson
 * @version August 2003
 **/

    public class MIPSprogram {
   
   // See explanation of method inSteppedExecution() below.
      private boolean steppedExecution = false;
   
      private String filename;
      private ArrayList sourceList;
      private ArrayList tokenList;
      private ArrayList parsedList;
      private ArrayList machineList;
      private BackStepper backStepper;
      private SymbolTable localSymbolTable;
      private MacroPool macroPool;
      private ArrayList sourceLineList;
        private Tokenizer tokenizer;
   
   /**
    * Produces list of source statements that comprise the program.
    * @return ArrayList of String.  Each String is one line of MIPS source code.
    **/
    
       public ArrayList getSourceList() {
         return sourceList;
      }
   
   /**
    * Set list of source statements that comprise the program.
    * @param sourceLineList ArrayList of SourceLine.  
     * Each SourceLine represents one line of MIPS source code.
    **/
    
       public void setSourceLineList(ArrayList sourceLineList) { 
         this.sourceLineList = sourceLineList; 
         sourceList = new ArrayList();
         for (SourceLine sl : sourceLineList) {
            sourceList.add(sl.getSource());
         } 
      }
   
   /**
    * Retrieve list of source statements that comprise the program.
    * @return ArrayList of SourceLine.  
     * Each SourceLine represents one line of MIPS source cod
    **/
    
       public ArrayList getSourceLineList() {
         return this.sourceLineList;
      }
   
   /**
    * Produces name of associated source code file.
    * @return File name as String. 
    **/
    
       public String getFilename() {
         return filename;
      }
   
   /**
    * Produces list of tokens that comprise the program.
    * @return ArrayList of TokenList.  Each TokenList is list of tokens generated by
    * corresponding line of MIPS source code.
    * @see TokenList
    **/
    
       public ArrayList getTokenList() {
         return tokenList;
      }
   
   /**
    * Retrieves Tokenizer for this program
    * @return Tokenizer
    **/   
    
       public Tokenizer getTokenizer() {
         return tokenizer;
      } 
        
   /**
    * Produces new empty list to hold parsed source code statements.
    * @return ArrayList of ProgramStatement.  Each ProgramStatement represents a parsed
    * MIPS statement.
    * @see ProgramStatement
    **/
    
       public ArrayList createParsedList() {
         parsedList = new ArrayList();
         return parsedList;
      }
   
   /**
    * Produces existing list of parsed source code statements.
    * @return ArrayList of ProgramStatement.  Each ProgramStatement represents a parsed
    * MIPS statement.
    * @see ProgramStatement
    **/
    
       public ArrayList getParsedList() {
         return parsedList;
      }
   
   /**
    * Produces list of machine statements that are assembled from the program.
    * @return ArrayList of ProgramStatement.  Each ProgramStatement represents an assembled
    * basic MIPS instruction.
    * @see ProgramStatement
    **/
    
       public ArrayList getMachineList() {
         return machineList;
      }
   
   
   /**
    * Returns BackStepper associated with this program.  It is created upon successful assembly.
    * @return BackStepper object, null if there is none.
    **/
    
       public BackStepper getBackStepper() {
         return backStepper;
      }
   
   /**
    * Returns SymbolTable associated with this program.  It is created at assembly time,
    * and stores local labels (those not declared using .globl directive).
    **/
    
       public SymbolTable getLocalSymbolTable() {
         return localSymbolTable;
      }
   
   /**
    * Returns status of BackStepper associated with this program.  
    * @return true if enabled, false if disabled or non-existant.
    **/
    
       public boolean backSteppingEnabled() {
         return (backStepper!=null && backStepper.enabled());
      }
   
   /**
    * Produces specified line of MIPS source program.
    * @param i Line number of MIPS source program to get.  Line 1 is first line.
    * @return Returns specified line of MIPS source.  If outside the line range,
    * it returns null.  Line 1 is first line.
    **/
    
       public String getSourceLine(int i) {
         if ( (i >= 1) && (i <= sourceList.size()) )             return (String) sourceList.get(i-1);          else             return null;       }            /**     * Reads MIPS source code from file into structure.  Will always read from file.     * It is GUI responsibility to assure that source edits are written to file     * when user selects compile or run/step options.     *      * @param file String containing name of MIPS source code file.     * @throws ProcessingException Will throw exception if there is any problem reading the file.     **/            public void readSource(String file) throws ProcessingException {          this.filename = file;          this.sourceList = new ArrayList();          ErrorList errors = null;          BufferedReader inputFile;          String line;          int lengthSoFar = 0;          try {             inputFile = new BufferedReader(new FileReader(file));             line = inputFile.readLine();             while (line != null) {                sourceList.add(line);                line = inputFile.readLine();             }          }               catch (Exception e) {                errors = new ErrorList();                errors.add(new ErrorMessage((MIPSprogram)null,0,0,e.toString()));                throw new ProcessingException(errors);             }          return;       }        /**     * Tokenizes the MIPS source program. Program must have already been read from file.     * @throws ProcessingException Will throw exception if errors occured while tokenizing.     **/            public void tokenize() throws ProcessingException {          this.tokenizer = new Tokenizer();          this.tokenList = tokenizer.tokenize(this);          this.localSymbolTable = new SymbolTable(this.filename); // prepare for assembly          return;       }        /**     * Prepares the given list of files for assembly.  This involves     * reading and tokenizing all the source files.  There may be only one.     * @param filenames  ArrayList containing the source file name(s) in no particular order     * @param leadFilename String containing name of source file that needs to go first and      * will be represented by "this" MIPSprogram object.     * @param exceptionHandler String containing name of source file containing exception     * handler.  This will be assembled first, even ahead of leadFilename, to allow it to     * include "startup" instructions loaded beginning at 0x00400000.  Specify null or     * empty String to indicate there is no such designated exception handler.     * @return ArrayList containing one MIPSprogram object for each file to assemble.     * objects for any additional files (send ArrayList to assembler)     * @throws ProcessingException Will throw exception if errors occured while reading or tokenizing.     **/            public ArrayList prepareFilesForAssembly(ArrayList filenames, String leadFilename, String exceptionHandler) throws ProcessingException {          ArrayList MIPSprogramsToAssemble = new ArrayList();          int leadFilePosition = 0;          if (exceptionHandler != null && exceptionHandler.length() > 0) {
            filenames.add(0, exceptionHandler);
            leadFilePosition = 1;
         }
         for (int i=0; i0) {
               MIPSprogramsToAssemble.add(leadFilePosition,preparee);
            } 
            else {
               MIPSprogramsToAssemble.add(preparee);
            }
         }
         return MIPSprogramsToAssemble;
      }
   
   /**
    * Assembles the MIPS source program. All files comprising the program must have 
    * already been tokenized.  Assembler warnings are not considered errors.
    * @param MIPSprogramsToAssemble ArrayList of MIPSprogram objects, each representing a tokenized source file.
    * @param extendedAssemblerEnabled A boolean value – true means extended (pseudo) instructions
    * are permitted in source code and false means they are to be flagged as errors.
    * @throws ProcessingException Will throw exception if errors occured while assembling.
    * @return ErrorList containing nothing or only warnings (otherwise would have thrown exception).
    **/
   
       public ErrorList assemble(ArrayList MIPSprogramsToAssemble, boolean extendedAssemblerEnabled)
              throws ProcessingException {   
         return assemble(MIPSprogramsToAssemble, extendedAssemblerEnabled, false);
      }
      
   /**
    * Assembles the MIPS source program. All files comprising the program must have 
    * already been tokenized.
    * @param MIPSprogramsToAssemble ArrayList of MIPSprogram objects, each representing a tokenized source file.
    * @param extendedAssemblerEnabled A boolean value – true means extended (pseudo) instructions
    * are permitted in source code and false means they are to be flagged as errors
    * @param warningsAreErrors A boolean value – true means assembler warnings will be considered errors and terminate
      the assemble; false means the assembler will produce warning message but otherwise ignore warnings.
    * @throws ProcessingException Will throw exception if errors occured while assembling.
    * @return ErrorList containing nothing or only warnings (otherwise would have thrown exception).
    **/
    
       public ErrorList assemble(ArrayList MIPSprogramsToAssemble, boolean extendedAssemblerEnabled,
              boolean warningsAreErrors) throws ProcessingException {
         this.backStepper = null;
         Assembler asm = new Assembler();
         this.machineList = asm.assemble(MIPSprogramsToAssemble, extendedAssemblerEnabled, warningsAreErrors);
         this.backStepper = new BackStepper();
         return asm.getErrorList();
      }
   
   
   /**
    * Simulates execution of the MIPS program. Program must have already been assembled.
    * Begins simulation at beginning of text segment and continues to completion.
    * @param breakPoints int array of breakpoints (PC addresses).  Can be null.
    * @return true if execution completed and false otherwise
    * @throws ProcessingException Will throw exception if errors occured while simulating.
    **/
    
       public boolean simulate(int[] breakPoints) throws ProcessingException {
         return this.simulateFromPC(breakPoints, -1, null);
      }
   
   
   /**
    * Simulates execution of the MIPS program. Program must have already been assembled.
    * Begins simulation at beginning of text segment and continues to completion or
    * until the specified maximum number of steps are simulated.
    * @param maxSteps  maximum number of steps to simulate.
    * @return true if execution completed and false otherwise
    * @throws ProcessingException Will throw exception if errors occured while simulating.
    **/
    
       public boolean simulate(int maxSteps) throws ProcessingException {
         return this.simulateFromPC(null, maxSteps, null);
      } 
   
   /**
    * Simulates execution of the MIPS program. Program must have already been assembled.
    * Begins simulation at current program counter address and continues until stopped,
    * paused, maximum steps exceeded, or exception occurs.
    * @param breakPoints int array of breakpoints (PC addresses).  Can be null.
    * @param maxSteps maximum number of instruction executions.  Default -1 means no maximum.
    * @param a the GUI component responsible for this call (GO normally).  set to null if none.
    * @return true if execution completed and false otherwise
    * @throws ProcessingException Will throw exception if errors occured while simulating.
    **/ 
       public boolean simulateFromPC(int[] breakPoints, int maxSteps, AbstractAction a) throws ProcessingException {
         steppedExecution = false;
         Simulator sim = Simulator.getInstance();
         return sim.simulate(this, RegisterFile.getProgramCounter(), maxSteps, breakPoints, a);
      }
   
   
   
   /**
    * Simulates execution of the MIPS program. Program must have already been assembled.
    * Begins simulation at current program counter address and executes one step.
    * @param a the GUI component responsible for this call (STEP normally). Set to null if none.
    * @return true if execution completed and false otherwise
    * @throws ProcessingException Will throw exception if errors occured while simulating.
    **/
       public boolean simulateStepAtPC(AbstractAction a) throws ProcessingException {
         steppedExecution = true;
         Simulator sim = Simulator.getInstance();
         boolean done = sim.simulate(this, RegisterFile.getProgramCounter(), 1, null,a);
         return done;
      }
   
   /** Will be true only while in process of simulating a program statement
   * in step mode (e.g. returning to GUI after each step).  This is used to
   * prevent spurious AccessNotices from being sent from Memory and Register
   * to observers at other times (e.g. while updating the data and register
   * displays, while assembling program’s data segment, etc).
   */
       public boolean inSteppedExecution() {
         return steppedExecution;
      }
   
   /**
    * Instantiates a new {@link MacroPool} and sends reference of this
    * {@link MIPSprogram} to it
    * 
    * @return instatiated MacroPool
    * @author M.H.Sekhavat < >
    */
       public MacroPool createMacroPool() {
         macroPool = new MacroPool(this);
         return macroPool;
      }
   
   /**
    * Gets local macro pool {@link MacroPool} for this program
    * @return MacroPool
    * @author M.H.Sekhavat < >
    */  
       public MacroPool getLocalMacroPool() {
         return macroPool;
      }
   
   /**
    * Sets local macro pool {@link MacroPool} for this program
    * @param macroPool reference to MacroPool
    * @author M.H.Sekhavat < >
    */   
       public void setLocalMacroPool(MacroPool macroPool) {
         this.macroPool = macroPool;
      }
    
   }  // MIPSprogram

mars/Settings.java
mars/Settings.java   package mars;
   import mars.*;
   import mars.util.*;
   import mars.venus.editors.jeditsyntax.*;
   import java.io.*;
   import java.util.*;
   import java.util.prefs.*;
   import java.awt.Color;
   import java.awt.Font;

/*
Copyright (c) 2003-2011,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson ( )
and Kenneth Vollmar ( )

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
“Software”), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

   /**
      *  Contains various IDE settings.  Persistent settings are maintained for the
      *  current user and on the current machine using
      *  Java’s Preference objects.  Failing that, default setting values come from
      *  Settings.properties file.  If both of those fail, default values come from
      *  static arrays defined in this class.  The latter can can be modified prior to 
      *  instantiating Settings object.
      *
      *  NOTE: If the Preference objects fail due to security exceptions, changes to
      *  settings will not carry over from one MARS session to the next.
      *
      *  Actual implementation of the Preference objects is platform-dependent.  
      *  For Windows, they are stored in Registry.  To see, run regedit and browse to:
     *  HKEY_CURRENT_USER\Software\JavaSoft\Prefs\mars
      *   @author Pete Sanderson
      **/
      
    public class Settings extends Observable {
    /* Properties file used to hold default settings. */
      private static String settingsFile = “Settings”;  
    /////////////////////////////  PROPERTY ARRAY INDEXES /////////////////////////////
    // Because MARS is programmed to Java 1.4, we cannot use an enumerated type.
    
    // BOOLEAN SETTINGS…  
    /** Flag to determine whether or not program being assembled is limited to 
       basic MIPS instructions and formats. */
      public static final int EXTENDED_ASSEMBLER_ENABLED = 0;
    /** Flag to determine whether or not program being assembled is limited to 
       using register numbers instead of names. NOTE: Its default value is
         false and the IDE provides no means to change it! */
      public static final int BARE_MACHINE_ENABLED = 1;
    /** Flag to determine whether or not a file is immediately and automatically assembled 
       upon opening. Handy when using externa editor like mipster. */
      public static final int ASSEMBLE_ON_OPEN_ENABLED = 2;
    /** Flag to determine whether only the current editor source file (enabled false) or 
       all files in its directory (enabled true) will be assembled when assembly is selected. */
      public static final int ASSEMBLE_ALL_ENABLED = 3;
    /** Default visibilty of label window (symbol table).  Default only, dynamic status 
       maintained by ExecutePane */
      public static final int LABEL_WINDOW_VISIBILITY = 4;
    /** Default setting for displaying addresses and values in hexidecimal in the Execute 
       pane.*/
      public static final int DISPLAY_ADDRESSES_IN_HEX = 5;
      public static final int DISPLAY_VALUES_IN_HEX = 6;
    /** Flag to determine whether the currently selected exception handler source file will
       be included in each assembly operation. */
      public static final int EXCEPTION_HANDLER_ENABLED = 7;    
    /** Flag to determine whether or not delayed branching is in effect at MIPS execution.
       This means we simulate the pipeline and statement FOLLOWING a successful branch
     is executed before branch is taken. DPS 14 June 2007.*/
      public static final int DELAYED_BRANCHING_ENABLED = 8;
    /** Flag to determine whether or not the editor will display line numbers. */
      public static final int EDITOR_LINE_NUMBERS_DISPLAYED = 9;
    /** Flag to determine whether or not assembler warnings are considered errors. */
      public static final int WARNINGS_ARE_ERRORS = 10;
    /** Flag to determine whether or not to display and use program arguments */
      public static final int PROGRAM_ARGUMENTS = 11;
    /** Flag to control whether or not highlighting is applied to data segment window */
      public static final int DATA_SEGMENT_HIGHLIGHTING = 12;
    /** Flag to control whether or not highlighting is applied to register windows */
      public static final int REGISTERS_HIGHLIGHTING = 13;
    /** Flag to control whether or not assembler automatically initializes program counter to ‘main’s address */
      public static final int START_AT_MAIN = 14;
    /** Flag to control whether or not editor will highlight the line currently being edited */
      public static final int EDITOR_CURRENT_LINE_HIGHLIGHTING = 15;
    /** Flag to control whether or not editor will provide popup instruction guidance while typing */
      public static final int POPUP_INSTRUCTION_GUIDANCE = 16;
    /** Flag to control whether or not simulator will use popup dialog for input syscalls */
      public static final int POPUP_SYSCALL_INPUT = 17;
    /** Flag to control whether or not to use generic text editor instead of language-aware styled editor */
      public static final int GENERIC_TEXT_EDITOR = 18;
    /** Flag to control whether or not language-aware editor will use auto-indent feature */
      public static final int AUTO_INDENT = 19;
   
      // NOTE: key sequence must match up with labels above which are used for array indexes!
      private static String[] booleanSettingsKeys = {“ExtendedAssembler”, “BareMachine”, “AssembleOnOpen”, “AssembleAll”,
                                             “LabelWindowVisibility”, “DisplayAddressesInHex”, “DisplayValuesInHex”,
                                                        “LoadExceptionHandler”, “DelayedBranching”, “EditorLineNumbersDisplayed”,
                                                        “WarningsAreErrors”, “ProgramArguments”, “DataSegmentHighlighting”,
                                                        “RegistersHighlighting”, “StartAtMain”, “EditorCurrentLineHighlighting”,
                                                        “PopupInstructionGuidance”, “PopupSyscallInput”, “GenericTextEditor”, 
                                                            “AutoIndent” };
   
      /** Last resort default values for boolean settings; will use only  if neither
     *  the Preferences nor the properties file work. If you wish to change them, 
     *  do so before instantiating the Settings object.
     *  Values are matched to keys by list position.
     */
      public static boolean[] defaultBooleanSettingsValues = { // match the above list by position
                                              true, false, false, false, false, true, true, false, false, 
                                                             true, false, false, true, true, false, true, true, false, false, true };
   
      // STRING SETTINGS.  Each array position has associated name.
    /** Current specified exception handler file (a MIPS assembly source file) */
      public static final int EXCEPTION_HANDLER = 0;
    /** Order of text segment table columns */
      public static final int TEXT_COLUMN_ORDER = 1;
    /** State for sorting label window display */
      public static final int LABEL_SORT_STATE = 2;
    /** Identifier of current memory configuration */
      public static final int MEMORY_CONFIGURATION = 3;
    /** Caret blink rate in milliseconds, 0 means don’t blink. */
      public static final int CARET_BLINK_RATE = 4;
    /** Editor tab size in characters. */
      public static final int EDITOR_TAB_SIZE = 5;
    /** Number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled) */
      public static final int EDITOR_POPUP_PREFIX_LENGTH = 6;
    // Match the above by position.
      private static final String[] stringSettingsKeys = { “ExceptionHandler”, “TextColumnOrder”, “LabelSortState”, “MemoryConfiguration”, “CaretBlinkRate”, “EditorTabSize”, “EditorPopupPrefixLength” };
   
      /** Last resort default values for String settings; 
     *  will use only if neither the Preferences nor the properties file work.
     *  If you wish to change, do so before instantiating the Settings object.
     *  Must match key by list position.
     */
      private static String[] defaultStringSettingsValues = { “”, “0 1 2 3 4”, “0”, “”, “500”, “8”, “2” }; 
   
   
      // FONT SETTINGS.  Each array position has associated name.
    /** Font for the text editor */
      public static final int EDITOR_FONT = 0;
    /** Font for table even row background (text, data, register displays) */
      public static final int EVEN_ROW_FONT = 1;
    /** Font for table odd row background (text, data, register displays) */
      public static final int ODD_ROW_FONT = 2;
    /** Font for table odd row foreground (text, data, register displays) */
      public static final int TEXTSEGMENT_HIGHLIGHT_FONT = 3;
    /** Font for text segment delay slot highlighted background */
      public static final int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FONT = 4;
    /** Font for text segment highlighted background */
      public static final int DATASEGMENT_HIGHLIGHT_FONT = 5;
    /** Font for register highlighted background */
      public static final int REGISTER_HIGHLIGHT_FONT = 6;
   
      private static final String[] fontFamilySettingsKeys = { “EditorFontFamily”, “EvenRowFontFamily”,
         “OddRowFontFamily”, ” TextSegmentHighlightFontFamily”, “TextSegmentDelayslotHighightFontFamily”,
         “DataSegmentHighlightFontFamily”, “RegisterHighlightFontFamily”
         };
      private static final String[] fontStyleSettingsKeys = { “EditorFontStyle”, “EvenRowFontStyle”,
         “OddRowFontStyle”, ” TextSegmentHighlightFontStyle”, “TextSegmentDelayslotHighightFontStyle”,
         “DataSegmentHighlightFontStyle”, “RegisterHighlightFontStyle”
         };     
      private static final String[] fontSizeSettingsKeys = { “EditorFontSize”, “EvenRowFontSize”,
         “OddRowFontSize”, ” TextSegmentHighlightFontSize”, “TextSegmentDelayslotHighightFontSize”,
         “DataSegmentHighlightFontSize”, “RegisterHighlightFontSize”
         };         
   
   
      /** Last resort default values for Font settings; 
     *  will use only if neither the Preferences nor the properties file work.
     *  If you wish to change, do so before instantiating the Settings object.
     *  Must match key by list position shown above.
     */
   
      // DPS 3-Oct-2012
      // Changed default font family from “Courier New” to “Monospaced” after receiving reports that Mac were not
        // correctly rendering the left parenthesis character in the editor or text segment display.
        // See http://www.mirthcorp.com/community/issues/browse/MIRTH-1921?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
      private static final String[] defaultFontFamilySettingsValues = { “Monospaced”,”Monospaced”,”Monospaced”,
         “Monospaced”,”Monospaced”,”Monospaced”,”Monospaced”
         };
      private static final String[] defaultFontStyleSettingsValues = {“Plain”, “Plain”, “Plain”, “Plain”, 
         “Plain”, “Plain”, “Plain”
         };     
      private static final String[] defaultFontSizeSettingsValues = {“12”, “12”, “12”, “12”, “12”, “12”, “12”, 
            };  
   
   
   
      // COLOR SETTINGS.  Each array position has associated name.
    /** RGB color for table even row background (text, data, register displays) */
      public static final int EVEN_ROW_BACKGROUND = 0;
    /** RGB color for table even row foreground (text, data, register displays) */
      public static final int EVEN_ROW_FOREGROUND = 1;
    /** RGB color for table odd row background (text, data, register displays) */
      public static final int ODD_ROW_BACKGROUND = 2;
    /** RGB color for table odd row foreground (text, data, register displays) */
      public static final int ODD_ROW_FOREGROUND = 3;
    /** RGB color for text segment highlighted background */
      public static final int TEXTSEGMENT_HIGHLIGHT_BACKGROUND = 4;
    /** RGB color for text segment highlighted foreground */
      public static final int TEXTSEGMENT_HIGHLIGHT_FOREGROUND = 5; 
    /** RGB color for text segment delay slot highlighted background */
      public static final int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_BACKGROUND = 6;
    /** RGB color for text segment delay slot highlighted foreground */
      public static final int TEXTSEGMENT_DELAYSLOT_HIGHLIGHT_FOREGROUND = 7;
    /** RGB color for text segment highlighted background */
      public static final int DATASEGMENT_HIGHLIGHT_BACKGROUND = 8;
    /** RGB color for text segment highlighted foreground */
      public static final int DATASEGMENT_HIGHLIGHT_FOREGROUND = 9; 
    /** RGB color for register highlighted background */
      public static final int REGISTER_HIGHLIGHT_BACKGROUND = 10;
    /** RGB color for register highlighted foreground */
      public static final int REGISTER_HIGHLIGHT_FOREGROUND = 11;
    // Match the above by position.
      private static final String[] colorSettingsKeys = { 
                                                        “EvenRowBackground”,”EvenRowForeground”, “OddRowBackground”, “OddRowForeground”,
                                                        “TextSegmentHighlightBackground”, “TextSegmentHighlightForeground”,
                                                        “TextSegmentDelaySlotHighlightBackground”,”TextSegmentDelaySlotHighlightForeground”,
                                                        “DataSegmentHighlightBackground”, “DataSegmentHighlightForeground”,
                                                        “RegisterHighlightBackground”, “RegisterHighlightForeground”   };
      /** Last resort default values for color settings; 
     *  will use only if neither the Preferences nor the properties file work.
     *  If you wish to change, do so before instantiating the Settings object.
     *  Must match key by list position.
     */
      private static String[] defaultColorSettingsValues = { 
                 “0x00e0e0e0”, “0”, “0x00ffffff”, “0”, “0x00ffff99”, “0”, “0x0033ff00”, “0”, “0x0099ccff”, “0”, “0x0099cc55″,”0” };
      
   
      
      private boolean[] booleanSettingsValues;
      private String[] stringSettingsValues;
      private String[] fontFamilySettingsValues;    
      private String[] fontStyleSettingsValues; 
      private String[] fontSizeSettingsValues;  
      private String[] colorSettingsValues;
   
      private Preferences preferences;
    
   /**
     * Create Settings object and set to saved values.  If saved values not found, will set
     * based on defaults stored in Settings.properties file.  If file problems, will set based
     * on defaults stored in this class.   
     */
       public Settings() {
         this(true);
      }
   
   /**
     * Create Settings object and set to saved values.  If saved values not found, will set
     * based on defaults stored in Settings.properties file.  If file problems, will set based
     * on defaults stored in this class.
     * @param gui true if running the graphical IDE, false if running from command line.
     * Ignored as of release 3.6 but retained for compatability.
     */
     
       public Settings(boolean gui) {
         booleanSettingsValues = new boolean[booleanSettingsKeys.length];
         stringSettingsValues = new String[stringSettingsKeys.length];
         fontFamilySettingsValues = new String[fontFamilySettingsKeys.length];
         fontStyleSettingsValues = new String[fontStyleSettingsKeys.length];
         fontSizeSettingsValues = new String[fontSizeSettingsKeys.length];
         colorSettingsValues = new String[colorSettingsKeys.length];
        // This determines where the values are actually stored.  Actual implementation
        // is platform-dependent.  For Windows, they are stored in Registry.  To see,
        // run regedit and browse to: HKEY_CURRENT_USER\Software\JavaSoft\Prefs\mars
         preferences = Preferences.userNodeForPackage(this.getClass());
        // The gui parameter, formerly passed to initialize(), is no longer needed
        // because I removed (1/21/09) the call to generate the Font object for the text editor.
        // Font objects are now generated only on demand so the “if (gui)” guard
        // is no longer necessary.  Originally added by Berkeley b/c they were running it on a 
        // headless server and running in command mode.  The Font constructor resulted in Swing 
        // initialization which caused problems.  Now this will only occur on demand from
        // Venus, which happens only when running as GUI.
         initialize();
      }
   
   
   /**
     * Return whether backstepping is permitted at this time.  Backstepping is ability to undo execution
     * steps one at a time.  Available only in the IDE.  This is not a persistent setting and is not under
     * MARS user control.
     * @return true if backstepping is permitted, false otherwise.
     */
       public boolean getBackSteppingEnabled() {
         return (Globals.program!=null && Globals.program.getBackStepper()!=null && Globals.program.getBackStepper().enabled());
      }
   
   
    /**
      * Reset settings to default values, as described in the constructor comments.
    * @param gui true if running from GUI IDE and false if running from command mode. 
    * Ignored as of release 3.6 but retained for compatibility.
    */
       public void reset(boolean gui) {
         initialize();
      }
   
   
   /* **************************************************************************
    This section contains all code related to syntax highlighting styles settings.
    A style includes 3 components: color, bold (t/f), italic (t/f)
   
   The fallback defaults will come not from an array here, but from the
   existing static method SyntaxUtilities.getDefaultSyntaxStyles()
   in the mars.venus.editors.jeditsyntax package.  It returns an array
   of SyntaxStyle objects.
   
   */
      private String[] syntaxStyleColorSettingsValues;
      private boolean[] syntaxStyleBoldSettingsValues;
      private boolean[] syntaxStyleItalicSettingsValues;
    
      private static final String SYNTAX_STYLE_COLOR_PREFIX = “SyntaxStyleColor_”;
      private static final String SYNTAX_STYLE_BOLD_PREFIX = “SyntaxStyleBold_”;
      private static final String SYNTAX_STYLE_ITALIC_PREFIX = “SyntaxStyleItalic_”;
    
      private static String[] syntaxStyleColorSettingsKeys, syntaxStyleBoldSettingsKeys, syntaxStyleItalicSettingsKeys; 
      private static String[] defaultSyntaxStyleColorSettingsValues;
      private static boolean[] defaultSyntaxStyleBoldSettingsValues;
      private static boolean[] defaultSyntaxStyleItalicSettingsValues;
   
   
       public void setEditorSyntaxStyleByPosition( int index, SyntaxStyle syntaxStyle ) {
         syntaxStyleColorSettingsValues[index] = syntaxStyle.getColorAsHexString();
         syntaxStyleItalicSettingsValues[index] = syntaxStyle.isItalic();        
         syntaxStyleBoldSettingsValues[index] = syntaxStyle.isBold();
         saveEditorSyntaxStyle(index);
      }
    
       public SyntaxStyle getEditorSyntaxStyleByPosition( int index ) {
         return new SyntaxStyle(getColorValueByPosition(index, syntaxStyleColorSettingsValues),
                                syntaxStyleItalicSettingsValues[index],
                                syntaxStyleBoldSettingsValues[index]);
      }
   
       public SyntaxStyle getDefaultEditorSyntaxStyleByPosition( int index ) {
         return new SyntaxStyle(getColorValueByPosition(index, defaultSyntaxStyleColorSettingsValues),
                                defaultSyntaxStyleItalicSettingsValues[index],
                                defaultSyntaxStyleBoldSettingsValues[index]);
      }     
   
       private void saveEditorSyntaxStyle(int index) {
         try {
            preferences.put(syntaxStyleColorSettingsKeys[index], syntaxStyleColorSettingsValues[index]);
            preferences.putBoolean(syntaxStyleBoldSettingsKeys[index], syntaxStyleBoldSettingsValues[index]);
            preferences.putBoolean(syntaxStyleItalicSettingsKeys[index], syntaxStyleItalicSettingsValues[index]);
            preferences.flush();
         } 
             catch (SecurityException se) {
            // cannot write to persistent storage for security reasons
            } 
             catch (BackingStoreException bse) {
            // unable to communicate with persistent storage (strange days)
            } 
      }
    
        // For syntax styles, need to initialize from SyntaxUtilities defaults.
        // Taking care not to explicitly create a Color object, since it may trigger
        // Swing initialization (that caused problems for UC Berkeley when we
        // created Font objects here).  It shouldn’t, but then again Font shouldn’t
        // either but they said it did.  (see HeadlessException)   
        // On othe other hand, the first statement of this method causes Color objects
        // to be created!  It is possible but a real pain in the rear to avoid using 
        // Color objects totally.  Requires new methods for the SyntaxUtilities class.
       private void initializeEditorSyntaxStyles() {
         SyntaxStyle syntaxStyle[] = SyntaxUtilities.getDefaultSyntaxStyles();
         int tokens = syntaxStyle.length;
         syntaxStyleColorSettingsKeys = new String[tokens]; 
         syntaxStyleBoldSettingsKeys = new String[tokens]; 
         syntaxStyleItalicSettingsKeys = new String[tokens]; 
         defaultSyntaxStyleColorSettingsValues = new String[tokens];
         defaultSyntaxStyleBoldSettingsValues = new boolean[tokens];
         defaultSyntaxStyleItalicSettingsValues = new boolean[tokens];
         syntaxStyleColorSettingsValues = new String[tokens];
         syntaxStyleBoldSettingsValues = new boolean[tokens];
         syntaxStyleItalicSettingsValues = new boolean[tokens];     
         for (int i=0; i=0 && id < booleanSettingsValues.length) {             return booleanSettingsValues[id];          }           else {             throw new IllegalArgumentException("Invalid boolean setting ID");          }       }          /**      *  Setting for whether user programs limited to "bare machine" formatted basic instructions.      *  This was added 8 Aug 2006 but is fixed at false for now, due to uncertainty as to what      *  exactly constitutes "bare machine".      *  @return true if only bare machine instructions allowed, false otherwise.      *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
     *  (e.g. Settings.BARE_MACHINE_ENABLED)
     */
       public boolean getBareMachineEnabled() {
         return booleanSettingsValues[BARE_MACHINE_ENABLED];
      }
      /**
       * Setting for whether user programs can use pseudo-instructions or extended addressing modes
        * or alternative instruction formats (all are implemented as pseudo-instructions).
        * @return true if pseudo-instructions and formats permitted, false otherwise.
       *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
       *  (e.g. Settings.EXTENDED_ASSEMBLER_ENABLED)
        */
       public boolean getExtendedAssemblerEnabled() {
         return booleanSettingsValues[EXTENDED_ASSEMBLER_ENABLED];
      }
   
      /**
       * Setting for whether selected program will be automatically assembled upon opening. This
        * can be useful if user employs an external editor such as MIPSter.
        * @return true if file is to be automatically assembled upon opening and false otherwise.
       *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
       *  (e.g. Settings.ASSEMBLE_ON_OPEN_ENABLED)
        */
       public boolean getAssembleOnOpenEnabled() {
         return booleanSettingsValues[ASSEMBLE_ON_OPEN_ENABLED];
      }
   
      /**
       * Setting for whether Addresses in the Execute pane will be displayed in hexadecimal.
        * @return true if addresses are displayed in hexadecimal and false otherwise (decimal).
       *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
       *  (e.g. Settings.DISPLAY_ADDRESSES_IN_HEX)
        */
       public boolean getDisplayAddressesInHex() {
         return booleanSettingsValues[DISPLAY_ADDRESSES_IN_HEX];
      }
   
      /**
       * Setting for whether values in the Execute pane will be displayed in hexadecimal.
        * @return true if values are displayed in hexadecimal and false otherwise (decimal).
       *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
       *  (e.g. Settings.DISPLAY_VALUES_IN_HEX)
        */
       public boolean getDisplayValuesInHex() {
         return booleanSettingsValues[DISPLAY_VALUES_IN_HEX];
      }
   
      /**
       * Setting for whether the assemble operation applies only to the file currently open in
        * the editor or whether it applies to all files in that file’s directory (primitive project
        * capability).  If the “assemble on open” setting is set, this “assemble all” setting will
        * be applied as soon as the file is opened.
        * @return true if all files are to be assembled, false if only the file open in editor.
       *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
       *  (e.g. Settings.ASSEMBLE_ALL_ENABLED)
        */
       public boolean getAssembleAllEnabled() {
         return booleanSettingsValues[ASSEMBLE_ALL_ENABLED];
      }         
   
              
     /**
       * Setting for whether the currently selected exception handler
        * (a MIPS source file) will be automatically included in each
        * assemble operation.
        @return true if exception handler is to be included in assemble, false otherwise.
       *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
       *  (e.g. Settings.EXCEPTION_HANDLER_ENABLED)
        */
       public boolean getExceptionHandlerEnabled() {
         return booleanSettingsValues[EXCEPTION_HANDLER_ENABLED];
      } 
   
     /**
       * Setting for whether delayed branching will be applied during MIPS
        * program execution.  If enabled, the statement following a successful
        * branch will be executed and then the branch is taken!  This simulates
        * pipelining and all MIPS processors do it.  However it is confusing to
        * assembly language students so is disabled by default.  SPIM does same thing.
        @return true if delayed branching is enabled, false otherwise.
       *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
       *  (e.g. Settings.DELAYED_BRANCHING_ENABLED)
        */
       public boolean getDelayedBranchingEnabled() {
         return booleanSettingsValues[DELAYED_BRANCHING_ENABLED];
      } 
        
    /**
     * Setting concerning whether or not to display the Labels Window — symbol table.
     * @return true if label window is to be displayed, false otherwise.
     *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
     *  (e.g. Settings.LABEL_WINDOW_VISIBILITY)
     */
       public boolean getLabelWindowVisibility() {
         return booleanSettingsValues[LABEL_WINDOW_VISIBILITY];
      }
   
        
    /**
     * Setting concerning whether or not the editor will display line numbers.
     * @return true if line numbers are to be displayed, false otherwise.
     *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
     *  (e.g. Settings.EDITOR_LINE_NUMBERS_DISPLAYED)
     */
       public boolean getEditorLineNumbersDisplayed() {
         return booleanSettingsValues[EDITOR_LINE_NUMBERS_DISPLAYED];
      }
   
        
    /**
     * Setting concerning whether or not assembler will consider warnings to be errors.
     * @return true if warnings are considered errors, false otherwise.
     *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
     *  (e.g. Settings.WARNINGS_ARE_ERRORS)
     */
       public boolean getWarningsAreErrors() {
         return booleanSettingsValues[WARNINGS_ARE_ERRORS];
      }
   
        
    /**
     * Setting concerning whether or not program arguments can be entered and used.
     * @return true if program arguments can be entered/used, false otherwise.
     *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
     *  (e.g. Settings.PROGRAM_ARGUMENTS)
     */
       public boolean getProgramArguments() {
         return booleanSettingsValues[PROGRAM_ARGUMENTS];
      }
          
        
    /**
     * Setting concerning whether or not highlighting is applied to Data Segment window.
     * @return true if highlighting is to be applied, false otherwise.
     *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
     *  (e.g. Settings.DATA_SEGMENT_HIGHLIGHTING)
     */
       public boolean getDataSegmentHighlighting() {
         return booleanSettingsValues[DATA_SEGMENT_HIGHLIGHTING];
      }
          
        
    /**
     * Setting concerning whether or not highlighting is applied to Registers,
     * Coprocessor0, and Coprocessor1 windows.
     * @return true if highlighting is to be applied, false otherwise.
     *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
     *  (e.g. Settings.REGISTERS_HIGHLIGHTING)
     */
       public boolean getRegistersHighlighting() {
         return booleanSettingsValues[REGISTERS_HIGHLIGHTING];
      }   
                                      
        
    /**
     * Setting concerning whether or not assembler will automatically initialize
     * the program counter to address of statement labeled ‘main’ if defined.
     * @return true if it initializes to ‘main’, false otherwise.
     *  @deprecated Use getBooleanSetting(int id) with the appropriate boolean setting ID
     *  (e.g. Settings.START_AT_MAIN)
     */
       public boolean getStartAtMain() {
         return booleanSettingsValues[START_AT_MAIN];
      }   
        
    /**
     * Name of currently selected exception handler file.
     * @return String pathname of current exception handler file, empty if none.
     */
       public String getExceptionHandler() {
         return stringSettingsValues[EXCEPTION_HANDLER];
      }
                        
    /**
     * Returns identifier of current built-in memory configuration.
     * @return String identifier of current built-in memory configuration, empty if none.
     */
       public String getMemoryConfiguration() {
         return stringSettingsValues[MEMORY_CONFIGURATION];
      }
        
    /**
     * Current editor font.  Retained for compatibility but replaced  
     * by: getFontByPosition(Settings.EDITOR_FONT)
     * @return Font object for current editor font.
     */
       public Font getEditorFont() {
         return getFontByPosition(EDITOR_FONT);
      }
    
    /**
     *  Retrieve a Font setting
     *  @param fontSettingPosition  constant that identifies which item
     *  @return Font object for given item
     */
       public Font getFontByPosition(int fontSettingPosition) {
         if (fontSettingPosition >=0 && fontSettingPosition < fontFamilySettingsValues.length) {             return EditorFont.createFontFromStringValues(fontFamilySettingsValues[fontSettingPosition],                                fontStyleSettingsValues[fontSettingPosition],                                   fontSizeSettingsValues[fontSettingPosition]);          }           else {             return null;          }       }              /**      *  Retrieve a default Font setting      *  @param fontSettingPosition  constant that identifies which item      *  @return Font object for given item      */        public Font getDefaultFontByPosition(int fontSettingPosition) {          if (fontSettingPosition >=0 && fontSettingPosition < defaultFontFamilySettingsValues.length) {             return EditorFont.createFontFromStringValues(defaultFontFamilySettingsValues[fontSettingPosition],                                defaultFontStyleSettingsValues[fontSettingPosition],                                   defaultFontSizeSettingsValues[fontSettingPosition]);          }           else {             return null;          }       }              /**      * Order of text segment display columns (there are 5, numbered 0 to 4).      * @return Array of int indicating the order.  Original order is 0 1 2 3 4.      */        public int[] getTextColumnOrder() {          return getTextSegmentColumnOrder(stringSettingsValues[TEXT_COLUMN_ORDER]);       }          /**      * Retrieve the caret blink rate in milliseconds.  Blink rate of 0 means       * do not blink.      * @return int blink rate in milliseconds      */              public int getCaretBlinkRate() {          int rate = 500;          try {             rate = Integer.parseInt(stringSettingsValues[CARET_BLINK_RATE]);          }              catch (NumberFormatException nfe) {                rate = Integer.parseInt(defaultStringSettingsValues[CARET_BLINK_RATE]);             }          return rate;       }                /**      * Get the tab size in characters.      * @return tab size in characters.      */             public int getEditorTabSize() {          int size = 8;          try {             size = Integer.parseInt(stringSettingsValues[EDITOR_TAB_SIZE]);          }              catch (NumberFormatException nfe) {                size = getDefaultEditorTabSize();             }          return size;       }             /**      * Get number of letters to be matched by editor's instruction guide before popup generated (if popup enabled).      * Should be 1 or 2.  If 1, the popup will be generated after first letter typed, based on all matches; if 2,       * the popup will be generated after second letter typed.      * @return number of letters (should be 1 or 2).      */             public int getEditorPopupPrefixLength() {          int length = 2;          try {             length = Integer.parseInt(stringSettingsValues[EDITOR_POPUP_PREFIX_LENGTH]);          }              catch (NumberFormatException nfe) {                             }          return length;       }              /**      * Get the text editor default tab size in characters      * @return tab size in characters      */        public int getDefaultEditorTabSize() {          return Integer.parseInt(defaultStringSettingsValues[EDITOR_TAB_SIZE]);       }          /**      * Get the saved state of the Labels Window sorting  (can sort by either      * label or address and either ascending or descending order).      * Default state is 0, by ascending addresses.      * @return State value 0-7, as a String.      */        public String getLabelSortState() {          return stringSettingsValues[LABEL_SORT_STATE];       }            /**       * Get Color object for specified settings key.       * Returns null if key is not found or its value is not a valid color encoding.       * @param key the Setting key       * @return corresponding Color, or null if key not found or value not valid color       */        public Color getColorSettingByKey(String key) {          return getColorValueByKey(key, colorSettingsValues);       }           /**       * Get default Color value for specified settings key.       * Returns null if key is not found or its value is not a valid color encoding.       * @param key the Setting key       * @return corresponding default Color, or null if key not found or value not valid color       */            public Color getDefaultColorSettingByKey(String key) {          return getColorValueByKey(key, defaultColorSettingsValues);       }               /**       * Get Color object for specified settings name (a static constant).       * Returns null if argument invalid or its value is not a valid color encoding.       * @param position the Setting name (see list of static constants)       * @return corresponding Color, or null if argument invalid or value not valid color       */        public Color getColorSettingByPosition(int position) {          return getColorValueByPosition(position, colorSettingsValues);       }           /**       * Get default Color object for specified settings name (a static constant).       * Returns null if argument invalid or its value is not a valid color encoding.       * @param position the Setting name (see list of static constants)       * @return corresponding default Color, or null if argument invalid or value not valid color       */            public Color getDefaultColorSettingByPosition(int position) {          return getColorValueByPosition(position, defaultColorSettingsValues);       }                       ////////////////////////////////////////////////////////////////////////     //  Setting Setters     ////////////////////////////////////////////////////////////////////////               /**      *  Set value of a boolean setting given its id and the value.      *  @param id int containing the setting's identifier (constants listed above)      *  @param value boolean value to store      *  @throws IllegalArgumentException if identifier is not valid.      */        public void setBooleanSetting(int id, boolean value) {          if (id >=0 && id < booleanSettingsValues.length) {             internalSetBooleanSetting(id, value);          }           else {             throw new IllegalArgumentException("Invalid boolean setting ID");          }       }              /**      * Establish setting for whether or not pseudo-instructions and formats are permitted      * in user programs.  User can change this setting via the IDE.  If setting changes,      * new setting will be written to properties file.      * @param value True to permit, false otherwise.      *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
     *  (e.g. Settings.EXTENDED_ASSEMBLER_ENABLED)
     */
       public void setExtendedAssemblerEnabled(boolean value) {
         internalSetBooleanSetting(EXTENDED_ASSEMBLER_ENABLED, value);
      }
    
     /**
       * Establish setting for whether a file will be automatically assembled as soon as it
        * is opened.  This is handy for those using an external text editor such as Mipster.
        * If setting changes, new setting will be written to properties file.   
       * @param value True to automatically assemble, false otherwise.
       *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
       *  (e.g. Settings.ASSEMBLE_ON_OPEN_ENABLED)
        */
       public void setAssembleOnOpenEnabled(boolean value) {
         internalSetBooleanSetting(ASSEMBLE_ON_OPEN_ENABLED, value);
      }
              
     /**
       * Establish setting for whether a file will be assembled by itself (false) or along
        * with all other files in its directory (true).  This permits multi-file programs
        * and a primitive “project” capability.  If setting changes,
       * new setting will be written to properties file.
        * @param value True to assemble all, false otherwise.
       *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
       *  (e.g. Settings.ASSEMBLE_ALL_ENABLED)
        */
       public void setAssembleAllEnabled(boolean value) {
         internalSetBooleanSetting(ASSEMBLE_ALL_ENABLED, value);
      }
   
     /**
       * Establish setting for whether addresses in the Execute pane will be displayed
        * in hexadecimal format.
        * @param value True to display addresses in hexadecimal, false for decimal.
       *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
       *  (e.g. Settings.DISPLAY_ADDRESSES_IN_HEX)
        */
       public void setDisplayAddressesInHex(boolean value) {
         internalSetBooleanSetting(DISPLAY_ADDRESSES_IN_HEX, value);
      }
   
     /**
       * Establish setting for whether values in the Execute pane will be displayed
        * in hexadecimal format.
        * @param value True to display values in hexadecimal, false for decimal.
       *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
       *  (e.g. Settings.DISPLAY_VALUES_IN_HEX)
        */
       public void setDisplayValuesInHex(boolean value) {
         internalSetBooleanSetting(DISPLAY_VALUES_IN_HEX, value);
      }
   
     /**
       * Establish setting for whether the labels window (i.e. symbol table) will
        * be displayed as part of the Text Segment display.  If setting changes,
       * new setting will be written to properties file.
        * @param value True to dispay labels window, false otherwise.
       *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
       *  (e.g. Settings.LABEL_WINDOW_VISIBILITY)
        */
       public void setLabelWindowVisibility(boolean value) {
         internalSetBooleanSetting(LABEL_WINDOW_VISIBILITY, value);
      }
                          
     /**
       * Establish setting for whether the currently selected exception handler
        * (a MIPS source file) will be automatically included in each
        * assemble operation. If setting changes, new setting will be written 
        * to properties file.
        * @param value True to assemble exception handler, false otherwise.
       *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
       *  (e.g. Settings.EXCEPTION_HANDLER_ENABLED)
        */
       public void setExceptionHandlerEnabled(boolean value) {
         internalSetBooleanSetting(EXCEPTION_HANDLER_ENABLED, value);
      }                   
   
     /**
       * Establish setting for whether delayed branching will be applied during 
        * MIPS program execution.  If enabled, the statement following a successful
        * branch will be executed and then the branch is taken!  This simulates
        * pipelining and all MIPS processors do it.  However it is confusing to
        * assembly language students so is disabled by default.  SPIM does same thing.
        * @param value True to enable delayed branching, false otherwise.
       *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
       *  (e.g. Settings.DELAYED_BRANCHING_ENABLED)
        */
        
       public void setDelayedBranchingEnabled(boolean value) {
         internalSetBooleanSetting(DELAYED_BRANCHING_ENABLED, value);
      }   
    
    /**
     * Establish setting for whether line numbers will be displayed by the
     * text editor.
     * @param value True to display line numbers, false otherwise.
     *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
     *  (e.g. Settings.EDITOR_LINE_NUMBERS_DISPLAYED)
     */
       public void setEditorLineNumbersDisplayed(boolean value) {
         internalSetBooleanSetting(EDITOR_LINE_NUMBERS_DISPLAYED, value);
      }
    
    /**
     * Establish setting for whether assembler warnings will be considered errors.
     * @param value True to consider warnings to be errors, false otherwise.
     *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
     *  (e.g. Settings.WARNINGS_ARE_ERRORS)
     */
       public void setWarningsAreErrors(boolean value) {
         internalSetBooleanSetting(WARNINGS_ARE_ERRORS, value);
      }
   
   
    /**
     * Establish setting for whether program arguments can be ented/used.
     * @param value True if program arguments can be entered/used, false otherwise.
     *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
     *  (e.g. Settings.PROGRAM_ARGUMENTS)
     */
       public void setProgramArguments(boolean value) {
         internalSetBooleanSetting(PROGRAM_ARGUMENTS, value);
      }
   
    /**
     * Establish setting for whether highlighting is to be applied to
     * Data Segment window.
     * @param value True if highlighting is to be applied, false otherwise.
     *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
     *  (e.g. Settings.DATA_SEGMENT_HIGHLIGHTING)
     */
       public void setDataSegmentHighlighting(boolean value) {
         internalSetBooleanSetting(DATA_SEGMENT_HIGHLIGHTING, value);
      }     
        
   
    /**
     * Establish setting for whether highlighting is to be applied to
     * Registers, Coprocessor0 and Coprocessor1 windows.
     * @param value True if highlighting is to be applied, false otherwise.
     *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
     *  (e.g. Settings.REGISTERS_HIGHLIGHTING)
     */
       public void setRegistersHighlighting(boolean value) {
         internalSetBooleanSetting(REGISTERS_HIGHLIGHTING, value);
      }     
            
   
    /**
     * Establish setting for whether assembler will automatically initialize
     * program counter to address of statement labeled ‘main’ if defined.
     * @param value True if PC set to address of ‘main’, false otherwise.
     *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
     *  (e.g. Settings.START_AT_MAIN)
     */
       public void setStartAtMain(boolean value) {
         internalSetBooleanSetting(START_AT_MAIN, value);
      }           
   
    
      /**
     * Establish setting for whether delayed branching will be applied during
     * MIPS program execution.  This setting will NOT be written to persisent
     * store!  This method should be called only to temporarily set this 
     * setting — currently this is needed only when running MARS from the
     * command line (MarsLaunch.java).
     * @param value True to enabled delayed branching, false otherwise.
     *  @deprecated Use setBooleanSetting(int id, boolean value) with the appropriate boolean setting ID
     *  (e.g. Settings.DELAYED_BRANCHING_ENABLED)
     */
       public void setDelayedBranchingEnabledNonPersistent(boolean value) {
         // Note: Doing assignment to array results in non-persistent 
        // setting (lost when MARS terminates).  For persistent, use
        // the internalSetBooleanSetting() method instead.
         booleanSettingsValues[DELAYED_BRANCHING_ENABLED] = value;
      }
    
     /**
       * Set name of exception handler file and write it to persistent storage.
        * @param newFilename name of exception handler file
        */
       public void setExceptionHandler(String newFilename) {
         setStringSetting(EXCEPTION_HANDLER, newFilename);
      }
     
     /**
      * Store the identifier of the memory configuration. 
      * @param config A string that identifies the current built-in memory configuration
      */
      
       public void setMemoryConfiguration(String config) {
         setStringSetting(MEMORY_CONFIGURATION, config);
      }
      
    /**
     * Set the caret blinking rate in milliseconds.  Rate of 0 means no blinking.
     * @param rate blink rate in milliseconds
     */
       public void setCaretBlinkRate(int rate) {
         setStringSetting(CARET_BLINK_RATE, “”+rate);
      }
      
    /**
     * Set the tab size in characters.
     * @param size tab size in characters.
     */     
       public void setEditorTabSize(int size) {
         setStringSetting(EDITOR_TAB_SIZE, “”+size);
      }
   
    /**
     * Set number of letters to be matched by editor’s instruction guide before popup generated (if popup enabled).
     * Should be 1 or 2.  If 1, the popup will be generated after first letter typed, based on all matches; if 2, 
     * the popup will be generated after second letter typed.
     * @param number of letters (should be 1 or 2).
     */     
       public void setEditorPopupPrefixLength(int length) {
         setStringSetting(EDITOR_POPUP_PREFIX_LENGTH, “”+length);
      }
   
    /**
     * Set editor font to the specified Font object and write it to persistent storage.
     * This method retained for compatibility but replaced by: 
     * setFontByPosition(Settings.EDITOR_FONT, font)
     * @param font Font object to be used by text editor.
     */
       public void setEditorFont(Font font) {
         setFontByPosition(EDITOR_FONT, font);
      }
   
    /**
     *  Store a Font setting
     *  @param fontSettingPosition Constant that identifies the item the font goes with
     *  @font The font to set that item to
     */
       public void setFontByPosition(int fontSettingPosition, Font font) {
         if (fontSettingPosition >=0 && fontSettingPosition < fontFamilySettingsValues.length) {             fontFamilySettingsValues[fontSettingPosition] = font.getFamily();             fontStyleSettingsValues[fontSettingPosition] = EditorFont.styleIntToStyleString(font.getStyle());             fontSizeSettingsValues[fontSettingPosition] = EditorFont.sizeIntToSizeString(font.getSize());             saveFontSetting(fontSettingPosition, fontFamilySettingsKeys, fontFamilySettingsValues);             saveFontSetting(fontSettingPosition, fontStyleSettingsKeys, fontStyleSettingsValues);             saveFontSetting(fontSettingPosition, fontSizeSettingsKeys, fontSizeSettingsValues);          }           if (fontSettingPosition == EDITOR_FONT) {             setChanged();             notifyObservers();          }       }                      /**      * Store the current order of Text Segment window table columns, so the ordering      * can be preserved and restored.      * @param columnOrder An array of int indicating column order.      */              public void setTextColumnOrder(int[] columnOrder) {          String stringifiedOrder = new String();          for (int i=0; i= 0 && position < colorSettingsKeys.length) {             setColorSetting(position, color);          }       }        /////////////////////////////////////////////////////////////////////////    //    //     PRIVATE HELPER METHODS TO DO THE REAL WORK    //    /////////////////////////////////////////////////////////////////////////          // Initialize settings to default values.      // Strategy: First set from properties file.        //           If that fails, set from array.      //           In either case, use these values as defaults in call to Preferences.             private void initialize() {          applyDefaultSettings();          if (!readSettingsFromPropertiesFile(settingsFile)) {             System.out.println("MARS System error: unable to read Settings.properties defaults. Using built-in defaults.");          }          getSettingsFromPreferences();         }          // Default values.  Will be replaced if available from property file or Preferences object.        private void applyDefaultSettings() {          for (int i=0; i= 0 && position < colorSettingsKeys.length) {             try {                color = Color.decode(values[position]);             }                  catch (NumberFormatException nfe) {                   color = null;                }          }          return color;       }               // Maybe someday I'll convert the whole shebang to use Maps.  In the meantime, we use     // linear search of array.  Not a huge deal as settings are little-used.     // Returns index or -1 if not found.        private int getIndexOfKey(String key, String[] array) {          int index = -1;          for (int i=0; i maxLength) maxLength = lets[i].length();
            }
            String padding = ”        “;
            maxLength++;
            for (int i = 0; i < lets.length; i++) {              lets[i] = padding.substring(0,maxLength-lets[i].length()) + lets[i];             }             return lets;       }                       // Read and return integer property value for given file and property name.     // Default value is returned if property file or name not found.        private static int getIntegerProperty(String propertiesFile, String propertyName, int defaultValue) {          int limit = defaultValue;  // just in case no entry is found          Properties properties = PropertiesFile.loadPropertiesFromFile(propertiesFile);          try {             limit = Integer.parseInt(properties.getProperty(propertyName, Integer.toString(defaultValue)));          }               catch (NumberFormatException nfe) { } // do nothing, I already have a default          return limit;       }             // Read assembly language file extensions from properties file.  Resulting     // string is tokenized into array list (assume StringTokenizer default delimiters).        private static ArrayList getFileExtensions() {          ArrayList extensionsList = new ArrayList();          String extensions = getPropertyEntry(configPropertiesFile,"Extensions");          if (extensions != null) {             StringTokenizer st = new StringTokenizer(extensions);              while (st.hasMoreTokens()) {                 extensionsList.add(st.nextToken());              }           }          return extensionsList;       }           /**      * Get list of MarsTools that reside outside the MARS distribution.       * Currently this is done by adding the tool's path name to the list      * of values for the external_tools property. Use ";" as delimiter!      * @return ArrayList.  Each item is file path to .class file      * of a class that implements MarsTool.  If none, returns empty list.      */        public static ArrayList getExternalTools() {          ArrayList toolsList = new ArrayList();          String delimiter = ";";          String tools = getPropertyEntry(configPropertiesFile,"ExternalTools");          if (tools != null) {             StringTokenizer st = new StringTokenizer(tools, delimiter);              while (st.hasMoreTokens()) {                 toolsList.add(st.nextToken());              }           }          return toolsList;       }          /**      * Read and return property file value (if any) for requested property.      * @param propertiesFile  name of properties file (do NOT include filename extension,      * which is assumed to be ".properties")      * @param propertyName String containing desired property name      * @return String containing associated value; null if property not found      */        public static String getPropertyEntry(String propertiesFile, String propertyName) {          return PropertiesFile.loadPropertiesFromFile(propertiesFile).getProperty(propertyName);       }             /**      * Read any syscall number assignment overrides from config file.      * @return ArrayList of SyscallNumberOverride objects      */        public ArrayList getSyscallOverrides() {          ArrayList overrides = new ArrayList();          Properties properties = PropertiesFile.loadPropertiesFromFile(syscallPropertiesFile);          Enumeration keys = properties.keys();          while (keys.hasMoreElements()) {             String key = (String) keys.nextElement();             overrides.add(new SyscallNumberOverride(key,properties.getProperty(key)));          }          return overrides;       }        } MarsLaunch package mars; public synchronized class MarsLaunch { private boolean simulate; private int displayFormat; private boolean verbose; private boolean assembleProject; private boolean pseudo; private boolean delayedBranching; private boolean warningsAreErrors; private boolean startAtMain; private boolean countInstructions; private static final String rangeSeparator = -; private static final int splashDuration = 2000; private static final int memoryWordsPerLine = 4; private static final int DECIMAL = 0; private static final int HEXADECIMAL = 1; private static final int ASCII = 2; private java.util.ArrayList registerDisplayList; private java.util.ArrayList memoryDisplayList; private java.util.ArrayList filenameList; private MIPSprogram code; private int maxSteps; private int instructionCount; private java.io.PrintStream out; private java.util.ArrayList dumpTriples; private java.util.ArrayList programArgumentList; private int assembleErrorExitCode; private int simulateErrorExitCode; public void MarsLaunch(String[]); private void dumpSegments(); private void launchIDE(); private boolean parseCommandArgs(String[]); private boolean runCommand(); private String[] checkMemoryAddressRange(String) throws NumberFormatException; private void establishObserver(); private void displayMiscellaneousPostMortem(); private void displayRegistersPostMortem(); private String formatIntForDisplay(int); private void displayMemoryPostMortem(); private void processDisplayMessagesToErrSwitch(String[], String); private void displayCopyright(String[], String); private void displayHelp(); } MarsLaunch$1 package mars; synchronized class MarsLaunch$1 implements Runnable { void MarsLaunch$1(MarsLaunch); public void run(); } XMI2MID.EXE by Markus Hein ( -berlin.de)