From 84fd2f7c76cbf1564701223c3b70149ad8af8bd6 Mon Sep 17 00:00:00 2001 From: Dan Adler <2274667+dadler64@users.noreply.github.co> Date: Fri, 9 Apr 2021 16:20:42 -0400 Subject: [PATCH] Massive clean up and overhaul of the build system to push project to 2.8.0 --- .editorconfig | 19 + .gitignore | 1 + README.md | 55 ++- build.gradle | 190 +++++----- dist/linux/Logisim.png | Bin 0 -> 963 bytes dist/linux/logisim.desktop | 9 + dist/linux/resources/logisim.desktop | 9 - dist/macos/{resources => }/Info.plist | 14 +- dist/macos/LogisimApp.icns | Bin 0 -> 24007 bytes dist/macos/LogisimDoc.icns | Bin 0 -> 38638 bytes dist/macos/resources/logisim.icns | Bin 20153 -> 0 bytes .../universalJavaApplicationStub.sh | 165 +++++++-- .../windows/Logisim.ico | Bin gradle/wrapper/gradle-wrapper.jar | Bin 55190 -> 0 bytes gradle/wrapper/gradle-wrapper.properties | 6 - gradlew | 172 --------- gradlew.bat | 84 ----- .../com/cburch/draw/actions/ModelAction.java | 8 +- .../cburch/draw/actions/ModelAddAction.java | 4 +- .../actions/ModelChangeAttributeAction.java | 8 +- .../draw/actions/ModelDeleteHandleAction.java | 2 +- .../draw/actions/ModelEditTextAction.java | 6 +- .../draw/actions/ModelInsertHandleAction.java | 2 +- .../draw/actions/ModelMoveHandleAction.java | 2 +- .../draw/actions/ModelRemoveAction.java | 2 +- .../draw/actions/ModelReorderAction.java | 6 +- .../draw/actions/ModelTranslateAction.java | 8 +- .../java/com/cburch/draw/actions/Strings.java | 2 +- .../java/com/cburch/draw/canvas/Canvas.java | 3 +- .../cburch/draw/canvas/CanvasListener.java | 2 +- .../com/cburch/draw/canvas/Selection.java | 10 +- .../cburch/draw/canvas/SelectionEvent.java | 4 +- .../cburch/draw/gui/AttrTableDrawManager.java | 11 +- .../draw/gui/AttrTableSelectionModel.java | 2 +- .../cburch/draw/gui/AttrTableToolModel.java | 2 +- src/main/java/com/cburch/draw/gui/Main.java | 3 + .../cburch/draw/gui/SelectionAttributes.java | 5 +- .../java/com/cburch/draw/gui/Strings.java | 2 +- .../java/com/cburch/draw/gui/Toolbar.java | 22 +- .../draw/model/AbstractCanvasObject.java | 2 +- .../cburch/draw/model/AttributeMapKey.java | 4 +- .../cburch/draw/model/CanvasModelEvent.java | 19 +- .../java/com/cburch/draw/model/Drawing.java | 8 +- .../cburch/draw/model/DrawingOverlaps.java | 4 +- .../java/com/cburch/draw/model/Handle.java | 6 +- .../com/cburch/draw/model/HandleGesture.java | 10 +- .../com/cburch/draw/model/ReorderRequest.java | 10 +- .../java/com/cburch/draw/shapes/Curve.java | 10 +- .../com/cburch/draw/shapes/CurveUtil.java | 28 +- .../java/com/cburch/draw/shapes/DrawAttr.java | 62 ++-- .../draw/shapes/FillableCanvasObject.java | 3 +- .../java/com/cburch/draw/shapes/Line.java | 23 +- .../java/com/cburch/draw/shapes/Poly.java | 6 +- .../com/cburch/draw/shapes/Rectangular.java | 14 +- .../java/com/cburch/draw/shapes/Strings.java | 2 +- .../com/cburch/draw/shapes/SvgCreator.java | 5 +- .../com/cburch/draw/shapes/SvgReader.java | 4 +- .../java/com/cburch/draw/shapes/Text.java | 4 +- .../draw/toolbar/AbstractToolbarModel.java | 2 +- .../java/com/cburch/draw/toolbar/Toolbar.java | 4 +- .../cburch/draw/toolbar/ToolbarButton.java | 4 +- .../cburch/draw/toolbar/ToolbarSeparator.java | 2 +- .../com/cburch/draw/tools/AbstractTool.java | 16 +- .../java/com/cburch/draw/tools/CurveTool.java | 4 +- .../draw/tools/DrawingAttributeSet.java | 37 +- .../java/com/cburch/draw/tools/LineTool.java | 2 +- .../java/com/cburch/draw/tools/OvalTool.java | 2 +- .../java/com/cburch/draw/tools/PolyTool.java | 6 +- .../com/cburch/draw/tools/RectangleTool.java | 2 +- .../cburch/draw/tools/RectangularTool.java | 2 +- .../cburch/draw/tools/RoundRectangleTool.java | 2 +- .../com/cburch/draw/tools/SelectTool.java | 4 +- .../java/com/cburch/draw/tools/TextTool.java | 6 +- .../cburch/draw/tools/ToolbarToolItem.java | 4 +- .../com/cburch/draw/undo/ActionUnion.java | 4 +- .../java/com/cburch/draw/undo/UndoLog.java | 6 +- .../cburch/draw/undo/UndoLogDispatcher.java | 2 +- .../com/cburch/draw/undo/UndoLogEvent.java | 4 +- .../com/cburch/draw/util/EditableLabel.java | 18 +- .../cburch/draw/util/EditableLabelField.java | 9 +- .../com/cburch/draw/util/MatchingSet.java | 4 +- .../java/com/cburch/draw/util/ZOrder.java | 16 +- src/main/java/com/cburch/gray/Components.java | 4 +- .../java/com/cburch/gray/CounterPoker.java | 2 +- .../java/com/cburch/gray/GrayCounter.java | 26 +- .../java/com/cburch/gray/GrayIncrementer.java | 13 +- .../com/cburch/gray/SimpleGrayCounter.java | 10 +- src/main/java/com/cburch/hex/Caret.java | 6 +- src/main/java/com/cburch/hex/HexEditor.java | 10 +- src/main/java/com/cburch/hex/Highlighter.java | 8 +- src/main/java/com/cburch/hex/Measures.java | 4 +- src/main/java/com/cburch/hex/Test.java | 4 +- .../com/cburch/logisim/LogisimVersion.java | 10 +- src/main/java/com/cburch/logisim/Main.java | 5 +- .../cburch/logisim/analyze/gui/Analyzer.java | 51 +-- .../logisim/analyze/gui/AnalyzerManager.java | 2 +- .../analyze/gui/BuildCircuitButton.java | 59 ++-- .../logisim/analyze/gui/DefaultRegistry.java | 4 +- .../logisim/analyze/gui/ExpressionTab.java | 179 +++++----- .../logisim/analyze/gui/ExpressionView.java | 166 +++++---- .../logisim/analyze/gui/KarnaughMapPanel.java | 49 +-- .../logisim/analyze/gui/MinimizedTab.java | 70 ++-- .../logisim/analyze/gui/OutputSelector.java | 11 +- .../logisim/analyze/gui/TableTabCaret.java | 29 +- .../logisim/analyze/gui/VariableTab.java | 35 +- .../logisim/analyze/model/AnalyzerModel.java | 8 +- .../logisim/analyze/model/Assignments.java | 2 +- .../cburch/logisim/analyze/model/Entry.java | 4 +- .../logisim/analyze/model/Expressions.java | 8 +- .../logisim/analyze/model/Implicant.java | 15 +- .../analyze/model/OutputExpressions.java | 13 +- .../analyze/model/OutputExpressionsEvent.java | 8 +- .../cburch/logisim/analyze/model/Parser.java | 10 +- .../analyze/model/ParserException.java | 8 +- .../cburch/logisim/analyze/model/Strings.java | 3 +- .../logisim/analyze/model/TruthTable.java | 14 +- .../analyze/model/TruthTableEvent.java | 2 +- .../logisim/analyze/model/VariableList.java | 12 +- .../analyze/model/VariableListEvent.java | 8 +- .../com/cburch/logisim/circuit/Analyze.java | 28 +- .../com/cburch/logisim/circuit/Circuit.java | 26 +- .../cburch/logisim/circuit/CircuitAction.java | 4 +- .../logisim/circuit/CircuitAttributes.java | 26 +- .../cburch/logisim/circuit/CircuitChange.java | 40 +-- .../cburch/logisim/circuit/CircuitEvent.java | 6 +- .../cburch/logisim/circuit/CircuitLocker.java | 18 +- .../logisim/circuit/CircuitMutation.java | 14 +- .../logisim/circuit/CircuitMutatorImpl.java | 10 +- .../cburch/logisim/circuit/CircuitPoints.java | 48 ++- .../cburch/logisim/circuit/CircuitState.java | 62 ++-- .../circuit/CircuitTransactionResult.java | 2 +- .../cburch/logisim/circuit/CircuitWires.java | 14 +- .../logisim/circuit/PropagationPoints.java | 8 +- .../cburch/logisim/circuit/Propagator.java | 42 +-- .../cburch/logisim/circuit/RadixOption.java | 8 +- .../logisim/circuit/ReplacementMap.java | 13 +- .../com/cburch/logisim/circuit/Simulator.java | 16 +- .../logisim/circuit/SimulatorEvent.java | 2 +- .../logisim/circuit/SimulatorTicker.java | 6 +- .../com/cburch/logisim/circuit/Splitter.java | 22 +- .../logisim/circuit/SplitterAttributes.java | 6 +- .../circuit/SplitterDistributeItem.java | 19 +- .../logisim/circuit/SplitterFactory.java | 16 +- .../logisim/circuit/SplitterPainter.java | 12 +- .../logisim/circuit/SplitterParameters.java | 38 +- .../com/cburch/logisim/circuit/Strings.java | 3 +- .../logisim/circuit/SubcircuitFactory.java | 10 +- .../logisim/circuit/SubcircuitPoker.java | 4 +- .../circuit/WidthIncompatibilityData.java | 4 +- .../java/com/cburch/logisim/circuit/Wire.java | 24 +- .../cburch/logisim/circuit/WireFactory.java | 2 +- .../cburch/logisim/circuit/WireIterator.java | 4 +- .../cburch/logisim/circuit/WireRepair.java | 4 +- .../com/cburch/logisim/circuit/WireSet.java | 4 +- .../cburch/logisim/circuit/WireThread.java | 3 +- .../com/cburch/logisim/circuit/WireUtil.java | 16 +- .../circuit/appear/AppearanceAnchor.java | 11 +- .../circuit/appear/AppearanceElement.java | 2 +- .../circuit/appear/AppearancePort.java | 8 +- .../circuit/appear/AppearanceSvgReader.java | 30 +- .../circuit/appear/CircuitAppearance.java | 6 +- .../appear/CircuitAppearanceEvent.java | 4 +- .../logisim/circuit/appear/CircuitPins.java | 10 +- .../circuit/appear/DefaultAppearance.java | 12 +- .../logisim/circuit/appear/PortManager.java | 20 +- .../logisim/circuit/appear/Strings.java | 3 +- .../logisim/comp/ComponentDrawContext.java | 52 +-- .../cburch/logisim/comp/ComponentEvent.java | 6 +- .../logisim/comp/ComponentUserEvent.java | 2 +- .../java/com/cburch/logisim/comp/EndData.java | 18 +- .../cburch/logisim/comp/ManagedComponent.java | 15 +- .../com/cburch/logisim/comp/TextField.java | 21 +- .../cburch/logisim/comp/TextFieldCaret.java | 98 +++--- .../cburch/logisim/comp/TextFieldEvent.java | 14 +- .../com/cburch/logisim/data/Attribute.java | 10 +- .../cburch/logisim/data/AttributeEvent.java | 8 +- .../cburch/logisim/data/AttributeOption.java | 16 +- .../cburch/logisim/data/AttributeSetImpl.java | 20 +- .../com/cburch/logisim/data/Attributes.java | 58 +-- .../com/cburch/logisim/data/BitWidth.java | 7 +- .../java/com/cburch/logisim/data/Bounds.java | 6 +- .../com/cburch/logisim/data/Direction.java | 16 +- .../com/cburch/logisim/data/Location.java | 6 +- .../java/com/cburch/logisim/data/Strings.java | 2 +- .../java/com/cburch/logisim/data/Value.java | 54 +-- .../cburch/logisim/file/FileStatistics.java | 17 +- .../com/cburch/logisim/file/LibraryEvent.java | 6 +- .../cburch/logisim/file/LibraryManager.java | 28 +- .../logisim/file/LoadFailedException.java | 4 +- .../cburch/logisim/file/LoadedLibrary.java | 19 +- .../java/com/cburch/logisim/file/Loader.java | 57 +-- .../cburch/logisim/file/LoaderException.java | 4 +- .../com/cburch/logisim/file/LogisimFile.java | 28 +- .../logisim/file/LogisimFileActions.java | 24 +- .../cburch/logisim/file/MouseMappings.java | 10 +- .../java/com/cburch/logisim/file/Options.java | 22 +- .../cburch/logisim/file/ProjectsDirty.java | 4 +- .../logisim/file/ReaderInputStream.java | 4 +- .../java/com/cburch/logisim/file/Strings.java | 3 +- .../com/cburch/logisim/file/ToolbarData.java | 33 +- .../cburch/logisim/file/XmlCircuitReader.java | 34 +- .../com/cburch/logisim/file/XmlIterator.java | 2 +- .../com/cburch/logisim/file/XmlReader.java | 40 +-- .../logisim/file/XmlReaderException.java | 2 +- .../com/cburch/logisim/file/XmlWriter.java | 22 +- .../logisim/gui/appear/AppearanceCanvas.java | 20 +- .../gui/appear/AppearanceEditHandler.java | 28 +- .../gui/appear/AppearanceEditPopup.java | 8 +- .../gui/appear/AppearanceToolbarModel.java | 26 +- .../logisim/gui/appear/AppearanceView.java | 14 +- .../gui/appear/CanvasActionAdapter.java | 6 +- .../cburch/logisim/gui/appear/Clipboard.java | 3 +- .../logisim/gui/appear/ClipboardActions.java | 10 +- .../logisim/gui/appear/ClipboardContents.java | 11 +- .../gui/appear/LayoutPopupManager.java | 4 +- .../logisim/gui/appear/LayoutThumbnail.java | 4 +- .../gui/appear/RevertAppearanceAction.java | 2 +- .../logisim/gui/appear/SelectionAction.java | 28 +- .../cburch/logisim/gui/appear/Strings.java | 3 +- .../cburch/logisim/gui/generic/AttrTable.java | 28 +- .../gui/generic/AttrTableModelEvent.java | 4 +- .../gui/generic/AttributeSetTableModel.java | 11 +- .../logisim/gui/generic/BasicZoomModel.java | 12 +- .../logisim/gui/generic/CanvasPane.java | 10 +- .../cburch/logisim/gui/generic/CardPanel.java | 2 +- .../logisim/gui/generic/GridPainter.java | 6 +- .../logisim/gui/generic/ProjectExplorer.java | 156 ++++----- .../gui/generic/ProjectExplorerEvent.java | 2 +- .../generic/ProjectExplorerLibraryNode.java | 5 +- .../gui/generic/ProjectExplorerToolNode.java | 3 +- .../cburch/logisim/gui/generic/Strings.java | 3 +- .../logisim/gui/generic/ZoomControl.java | 8 +- .../java/com/cburch/logisim/gui/hex/Clip.java | 48 ++- .../com/cburch/logisim/gui/hex/HexFile.java | 7 +- .../com/cburch/logisim/gui/hex/HexFrame.java | 30 +- .../com/cburch/logisim/gui/hex/Strings.java | 3 +- .../cburch/logisim/gui/log/ComponentIcon.java | 4 +- .../logisim/gui/log/ComponentSelector.java | 95 +++-- .../com/cburch/logisim/gui/log/FilePanel.java | 38 +- .../com/cburch/logisim/gui/log/LogFrame.java | 39 +-- .../com/cburch/logisim/gui/log/LogPanel.java | 2 +- .../com/cburch/logisim/gui/log/LogThread.java | 20 +- .../com/cburch/logisim/gui/log/Model.java | 26 +- .../cburch/logisim/gui/log/ScrollPanel.java | 6 +- .../com/cburch/logisim/gui/log/Selection.java | 6 +- .../cburch/logisim/gui/log/SelectionItem.java | 57 ++- .../cburch/logisim/gui/log/SelectionList.java | 40 +-- .../logisim/gui/log/SelectionPanel.java | 33 +- .../com/cburch/logisim/gui/log/Strings.java | 3 +- .../cburch/logisim/gui/log/TablePanel.java | 32 +- .../com/cburch/logisim/gui/log/ValueLog.java | 4 +- .../gui/main/AttrTableCircuitModel.java | 22 +- .../gui/main/AttrTableComponentModel.java | 36 +- .../gui/main/AttrTableSelectionModel.java | 18 +- .../logisim/gui/main/AttrTableToolModel.java | 8 +- .../com/cburch/logisim/gui/main/Canvas.java | 73 ++-- .../logisim/gui/main/CanvasPaintThread.java | 5 +- .../logisim/gui/main/CanvasPainter.java | 20 +- .../cburch/logisim/gui/main/CircuitJList.java | 30 +- .../cburch/logisim/gui/main/Clipboard.java | 11 +- .../gui/main/ExplorerToolbarModel.java | 33 +- .../cburch/logisim/gui/main/ExportImage.java | 62 ++-- .../com/cburch/logisim/gui/main/Frame.java | 57 ++- .../gui/main/KeyboardToolSelection.java | 10 +- .../logisim/gui/main/LayoutEditHandler.java | 7 +- .../logisim/gui/main/LayoutToolbarModel.java | 18 +- .../logisim/gui/main/LogisimToolbarItem.java | 6 +- .../cburch/logisim/gui/main/MenuListener.java | 24 +- .../com/cburch/logisim/gui/main/Print.java | 99 +++--- .../logisim/gui/main/ProjectToolbarModel.java | 44 +-- .../cburch/logisim/gui/main/Selection.java | 16 +- .../logisim/gui/main/SelectionActions.java | 60 ++-- .../logisim/gui/main/SelectionAttributes.java | 10 +- .../logisim/gui/main/SelectionBase.java | 20 +- .../logisim/gui/main/SelectionSave.java | 13 +- .../logisim/gui/main/SimulationExplorer.java | 23 +- .../gui/main/SimulationToolbarModel.java | 34 +- .../gui/main/SimulationTreeCircuitNode.java | 46 +-- .../logisim/gui/main/SimulationTreeModel.java | 6 +- .../gui/main/SimulationTreeRenderer.java | 13 +- .../logisim/gui/main/StatisticsDialog.java | 10 +- .../com/cburch/logisim/gui/main/Strings.java | 3 +- .../cburch/logisim/gui/main/TickCounter.java | 6 +- .../logisim/gui/main/ToolAttributeAction.java | 2 +- .../com/cburch/logisim/gui/main/Toolbox.java | 2 +- .../cburch/logisim/gui/main/ToolboxManip.java | 52 +-- .../logisim/gui/main/ToolboxToolbarModel.java | 28 +- .../cburch/logisim/gui/menu/EditPopup.java | 4 +- .../logisim/gui/menu/LogisimMenuBar.java | 90 +++-- .../logisim/gui/menu/LogisimMenuItem.java | 2 +- .../com/cburch/logisim/gui/menu/MenuEdit.java | 88 ++--- .../com/cburch/logisim/gui/menu/MenuFile.java | 42 +-- .../com/cburch/logisim/gui/menu/MenuHelp.java | 10 +- .../logisim/gui/menu/MenuItemCheckImpl.java | 2 +- .../logisim/gui/menu/MenuItemHelper.java | 12 +- .../cburch/logisim/gui/menu/MenuItemImpl.java | 2 +- .../cburch/logisim/gui/menu/MenuProject.java | 72 ++-- .../cburch/logisim/gui/menu/MenuSimulate.java | 92 ++--- .../cburch/logisim/gui/menu/MenuTheme.java | 296 ++++++++-------- .../cburch/logisim/gui/menu/OpenRecent.java | 8 +- .../com/cburch/logisim/gui/menu/Popups.java | 40 +-- .../gui/menu/ProjectCircuitActions.java | 39 +-- .../gui/menu/ProjectLibraryActions.java | 38 +- .../com/cburch/logisim/gui/menu/Strings.java | 3 +- .../logisim/gui/menu/WindowManagers.java | 9 +- .../cburch/logisim/gui/opts/ComboOption.java | 6 +- .../cburch/logisim/gui/opts/MouseOptions.java | 30 +- .../logisim/gui/opts/OptionsActions.java | 22 +- .../cburch/logisim/gui/opts/OptionsFrame.java | 32 +- .../cburch/logisim/gui/opts/OptionsPanel.java | 2 +- .../logisim/gui/opts/SimulateOptions.java | 44 +-- .../com/cburch/logisim/gui/opts/Strings.java | 3 +- .../logisim/gui/opts/ToolbarActions.java | 8 +- .../cburch/logisim/gui/opts/ToolbarList.java | 20 +- .../logisim/gui/opts/ToolbarOptions.java | 28 +- .../gui/prefs/ExperimentalOptions.java | 14 +- .../cburch/logisim/gui/prefs/IntlOptions.java | 24 +- .../logisim/gui/prefs/LayoutOptions.java | 40 +-- .../logisim/gui/prefs/OptionsPanel.java | 2 +- .../cburch/logisim/gui/prefs/PrefBoolean.java | 7 +- .../cburch/logisim/gui/prefs/PrefOption.java | 6 +- .../logisim/gui/prefs/PrefOptionList.java | 18 +- .../logisim/gui/prefs/PreferencesFrame.java | 24 +- .../com/cburch/logisim/gui/prefs/Strings.java | 3 +- .../logisim/gui/prefs/TemplateOptions.java | 18 +- .../logisim/gui/prefs/WindowOptions.java | 40 +-- .../com/cburch/logisim/gui/start/About.java | 8 +- .../logisim/gui/start/AboutCredits.java | 52 +-- .../logisim/gui/start/SplashScreen.java | 33 +- .../com/cburch/logisim/gui/start/Startup.java | 23 +- .../com/cburch/logisim/gui/start/Strings.java | 3 +- .../logisim/gui/start/TtyInterface.java | 56 ++- .../com/cburch/logisim/instance/Instance.java | 43 ++- .../logisim/instance/InstanceComponent.java | 39 +-- .../logisim/instance/InstanceFactory.java | 4 +- .../instance/InstanceLoggerAdapter.java | 2 +- .../logisim/instance/InstancePainter.java | 94 +++-- .../instance/InstancePokerAdapter.java | 33 +- .../logisim/instance/InstanceStateImpl.java | 13 +- .../logisim/instance/InstanceTextField.java | 6 +- .../com/cburch/logisim/instance/Port.java | 14 +- .../com/cburch/logisim/instance/StdAttr.java | 4 +- .../com/cburch/logisim/instance/Strings.java | 3 +- .../logisim/prefs/AbstractPrefMonitor.java | 2 +- .../cburch/logisim/prefs/AppPreferences.java | 67 ++-- .../logisim/prefs/PrefMonitorBoolean.java | 2 +- .../logisim/prefs/PrefMonitorDouble.java | 20 +- .../cburch/logisim/prefs/PrefMonitorInt.java | 20 +- .../logisim/prefs/PrefMonitorString.java | 16 +- .../logisim/prefs/PrefMonitorStringOpts.java | 27 +- .../cburch/logisim/prefs/RecentProjects.java | 20 +- .../com/cburch/logisim/prefs/Strings.java | 2 +- .../com/cburch/logisim/prefs/Template.java | 12 +- .../com/cburch/logisim/proj/Dependencies.java | 62 ++-- .../java/com/cburch/logisim/proj/Project.java | 26 +- .../cburch/logisim/proj/ProjectActions.java | 57 +-- .../com/cburch/logisim/proj/ProjectEvent.java | 6 +- .../com/cburch/logisim/proj/Projects.java | 62 ++-- .../java/com/cburch/logisim/proj/Strings.java | 3 +- .../java/com/cburch/logisim/std/Builtin.java | 14 +- .../java/com/cburch/logisim/std/Strings.java | 3 +- .../com/cburch/logisim/std/arith/Adder.java | 13 +- .../cburch/logisim/std/arith/Arithmetic.java | 41 +-- .../cburch/logisim/std/arith/BitAdder.java | 10 +- .../cburch/logisim/std/arith/BitFinder.java | 16 +- .../cburch/logisim/std/arith/Comparator.java | 11 +- .../com/cburch/logisim/std/arith/Divider.java | 9 +- .../cburch/logisim/std/arith/Multiplier.java | 63 ++-- .../com/cburch/logisim/std/arith/Negator.java | 3 +- .../com/cburch/logisim/std/arith/Shifter.java | 20 +- .../com/cburch/logisim/std/arith/Strings.java | 3 +- .../cburch/logisim/std/arith/Subtractor.java | 17 +- .../com/cburch/logisim/std/base/Base.java | 14 +- .../com/cburch/logisim/std/base/Strings.java | 3 +- .../com/cburch/logisim/std/base/Text.java | 44 +-- .../logisim/std/base/TextAttributes.java | 22 +- .../logisim/std/gates/AbstractGate.java | 87 +++-- .../com/cburch/logisim/std/gates/AndGate.java | 2 +- .../com/cburch/logisim/std/gates/Buffer.java | 35 +- .../logisim/std/gates/CircuitBuilder.java | 90 +++-- .../std/gates/CircuitDetermination.java | 48 ++- .../logisim/std/gates/ControlledBuffer.java | 65 ++-- .../logisim/std/gates/EvenParityGate.java | 9 +- .../logisim/std/gates/GateAttributeList.java | 8 +- .../logisim/std/gates/GateAttributes.java | 14 +- .../logisim/std/gates/GateFunctions.java | 6 +- .../com/cburch/logisim/std/gates/Gates.java | 24 +- .../cburch/logisim/std/gates/NandGate.java | 12 +- .../logisim/std/gates/NegateAttribute.java | 9 +- .../com/cburch/logisim/std/gates/NorGate.java | 12 +- .../com/cburch/logisim/std/gates/NotGate.java | 33 +- .../logisim/std/gates/OddParityGate.java | 12 +- .../com/cburch/logisim/std/gates/OrGate.java | 15 +- .../cburch/logisim/std/gates/PainterDin.java | 17 +- .../logisim/std/gates/PainterShaped.java | 20 +- .../com/cburch/logisim/std/gates/Strings.java | 3 +- .../cburch/logisim/std/gates/XnorGate.java | 3 +- .../com/cburch/logisim/std/io/Button.java | 22 +- .../com/cburch/logisim/std/io/DotMatrix.java | 45 ++- .../com/cburch/logisim/std/io/HexDigit.java | 76 ++-- .../java/com/cburch/logisim/std/io/Io.java | 52 +-- .../com/cburch/logisim/std/io/Joystick.java | 29 +- .../com/cburch/logisim/std/io/Keyboard.java | 104 +++--- .../cburch/logisim/std/io/KeyboardData.java | 86 +++-- .../java/com/cburch/logisim/std/io/Led.java | 34 +- .../cburch/logisim/std/io/SevenSegment.java | 47 ++- .../com/cburch/logisim/std/io/Strings.java | 3 +- .../java/com/cburch/logisim/std/io/Tty.java | 83 ++--- .../com/cburch/logisim/std/io/TtyState.java | 5 +- .../logisim/std/memory/AbstractFlipFlop.java | 93 ++--- .../cburch/logisim/std/memory/Counter.java | 122 +++---- .../logisim/std/memory/CounterAttributes.java | 59 ++-- .../cburch/logisim/std/memory/DFlipFlop.java | 3 +- .../cburch/logisim/std/memory/JKFlipFlop.java | 9 +- .../com/cburch/logisim/std/memory/Mem.java | 69 ++-- .../logisim/std/memory/MemContents.java | 158 ++++----- .../logisim/std/memory/MemContentsSub.java | 64 ++-- .../cburch/logisim/std/memory/MemMenu.java | 102 +++--- .../cburch/logisim/std/memory/MemPoker.java | 49 ++- .../cburch/logisim/std/memory/MemState.java | 201 ++++++----- .../com/cburch/logisim/std/memory/Memory.java | 42 +-- .../com/cburch/logisim/std/memory/Ram.java | 132 ++++--- .../com/cburch/logisim/std/memory/Random.java | 100 +++--- .../cburch/logisim/std/memory/Register.java | 80 ++--- .../logisim/std/memory/RegisterLogger.java | 4 +- .../logisim/std/memory/RegisterPoker.java | 28 +- .../com/cburch/logisim/std/memory/Rom.java | 89 +++-- .../logisim/std/memory/RomAttributes.java | 53 ++- .../std/memory/RomContentsListener.java | 49 ++- .../cburch/logisim/std/memory/SRFlipFlop.java | 7 +- .../logisim/std/memory/ShiftRegister.java | 142 ++++---- .../logisim/std/memory/ShiftRegisterData.java | 88 ++--- .../std/memory/ShiftRegisterLogger.java | 11 +- .../std/memory/ShiftRegisterPoker.java | 97 +++--- .../cburch/logisim/std/memory/Strings.java | 3 +- .../cburch/logisim/std/memory/TFlipFlop.java | 13 +- .../logisim/std/plexers/BitSelector.java | 29 +- .../cburch/logisim/std/plexers/Decoder.java | 84 +++-- .../logisim/std/plexers/Demultiplexer.java | 53 +-- .../logisim/std/plexers/Multiplexer.java | 134 +++---- .../cburch/logisim/std/plexers/Plexers.java | 46 +-- .../logisim/std/plexers/PriorityEncoder.java | 100 +++--- .../cburch/logisim/std/plexers/Strings.java | 3 +- .../logisim/std/wiring/BitExtender.java | 90 +++-- .../com/cburch/logisim/std/wiring/Clock.java | 110 +++--- .../cburch/logisim/std/wiring/Constant.java | 97 +++--- .../std/wiring/ConstantConfigurator.java | 6 +- .../logisim/std/wiring/DurationAttribute.java | 9 +- .../com/cburch/logisim/std/wiring/Ground.java | 17 +- .../com/cburch/logisim/std/wiring/Pin.java | 207 ++++++----- .../logisim/std/wiring/PinAttributes.java | 4 +- .../com/cburch/logisim/std/wiring/Power.java | 17 +- .../com/cburch/logisim/std/wiring/Probe.java | 231 ++++++------ .../logisim/std/wiring/ProbeAttributes.java | 15 +- .../logisim/std/wiring/PullResistor.java | 48 +-- .../cburch/logisim/std/wiring/Strings.java | 3 +- .../cburch/logisim/std/wiring/Transistor.java | 68 ++-- .../logisim/std/wiring/TransmissionGate.java | 30 +- .../com/cburch/logisim/std/wiring/Tunnel.java | 76 ++-- .../logisim/std/wiring/TunnelAttributes.java | 31 +- .../com/cburch/logisim/std/wiring/Wiring.java | 44 +-- .../cburch/logisim/tools/AbstractCaret.java | 10 +- .../com/cburch/logisim/tools/AddTool.java | 64 ++-- .../com/cburch/logisim/tools/CaretEvent.java | 16 +- .../com/cburch/logisim/tools/EditTool.java | 171 +++++---- .../logisim/tools/FactoryAttributes.java | 51 ++- .../logisim/tools/FactoryDescription.java | 15 +- .../com/cburch/logisim/tools/Library.java | 6 +- .../com/cburch/logisim/tools/MenuTool.java | 153 ++++---- .../com/cburch/logisim/tools/PokeTool.java | 91 +++-- .../com/cburch/logisim/tools/SelectTool.java | 329 +++++++++--------- .../logisim/tools/SetAttributeAction.java | 54 +-- .../com/cburch/logisim/tools/Strings.java | 3 +- .../com/cburch/logisim/tools/TextTool.java | 81 +++-- .../cburch/logisim/tools/WireRepairData.java | 4 +- .../com/cburch/logisim/tools/WiringTool.java | 213 ++++++------ .../tools/key/DirectionConfigurator.java | 4 +- .../tools/key/IntegerConfigurator.java | 3 +- .../logisim/tools/key/JoinedConfigurator.java | 16 +- .../tools/key/KeyConfigurationEvent.java | 8 +- .../tools/key/KeyConfigurationResult.java | 10 +- .../tools/key/NumericConfigurator.java | 12 +- .../tools/key/ParallelConfigurator.java | 16 +- .../com/cburch/logisim/tools/key/Strings.java | 3 +- .../logisim/tools/move/AvoidanceMap.java | 115 +++--- .../logisim/tools/move/ConnectionData.java | 29 +- .../cburch/logisim/tools/move/Connector.java | 248 +++++++------ .../logisim/tools/move/ConnectorThread.java | 35 +- .../logisim/tools/move/MoveGesture.java | 109 +++--- .../logisim/tools/move/MoveRequest.java | 10 +- .../cburch/logisim/tools/move/MoveResult.java | 47 ++- .../cburch/logisim/tools/move/SearchNode.java | 144 ++++---- .../com/cburch/logisim/util/ArraySet.java | 38 +- .../java/com/cburch/logisim/util/Cache.java | 4 +- .../cburch/logisim/util/CollectionUtil.java | 12 +- .../logisim/util/ConcurrentHashQueue.java | 6 +- .../java/com/cburch/logisim/util/Dag.java | 55 ++- .../logisim/util/EventSourceWeakSupport.java | 4 +- .../com/cburch/logisim/util/GifEncoder.java | 188 +++++----- .../com/cburch/logisim/util/GraphicsUtil.java | 75 ++-- .../logisim/util/HorizontalSplitPane.java | 83 +++-- .../cburch/logisim/util/InputEventUtil.java | 31 +- .../com/cburch/logisim/util/IteratorUtil.java | 24 +- .../com/cburch/logisim/util/JDialogOk.java | 10 +- .../cburch/logisim/util/JFileChoosers.java | 14 +- .../logisim/util/JTreeDragController.java | 6 +- .../com/cburch/logisim/util/JTreeUtil.java | 151 ++++---- .../com/cburch/logisim/util/ListUtil.java | 6 +- .../cburch/logisim/util/LocaleManager.java | 103 +++--- .../cburch/logisim/util/LocaleSelector.java | 37 +- .../cburch/logisim/util/MacCompatibility.java | 12 +- .../util/PropertyChangeWeakSupport.java | 69 ++-- .../com/cburch/logisim/util/SmallSet.java | 94 +++-- .../com/cburch/logisim/util/StringUtil.java | 71 ++-- .../java/com/cburch/logisim/util/Strings.java | 3 +- .../cburch/logisim/util/TableConstraints.java | 4 +- .../com/cburch/logisim/util/TableLayout.java | 101 +++--- .../com/cburch/logisim/util/TableSorter.java | 87 ++--- .../com/cburch/logisim/util/UnionFind.java | 10 +- .../cburch/logisim/util/UnmodifiableList.java | 2 +- .../logisim/util/VerticalSplitPane.java | 44 ++- .../com/cburch/logisim/util/WindowMenu.java | 52 +-- .../cburch/logisim/util/WindowMenuItem.java | 2 +- .../logisim/util/WindowMenuItemManager.java | 7 +- .../logisim/util/WindowMenuManager.java | 5 +- .../cburch/logisim/util/ZipClassLoader.java | 67 ++-- src/main/resources/logisim/default.templ | 2 +- 527 files changed, 7764 insertions(+), 8111 deletions(-) create mode 100644 .editorconfig create mode 100644 dist/linux/Logisim.png create mode 100644 dist/linux/logisim.desktop delete mode 100644 dist/linux/resources/logisim.desktop rename dist/macos/{resources => }/Info.plist (92%) create mode 100644 dist/macos/LogisimApp.icns create mode 100644 dist/macos/LogisimDoc.icns delete mode 100644 dist/macos/resources/logisim.icns rename dist/macos/{resources => }/universalJavaApplicationStub.sh (84%) rename src/main/resources/logisim/img/logisim-icon.ico => dist/windows/Logisim.ico (100%) delete mode 100644 gradle/wrapper/gradle-wrapper.jar delete mode 100644 gradle/wrapper/gradle-wrapper.properties delete mode 100644 gradlew delete mode 100644 gradlew.bat diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..0622625 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,19 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 + +# 4 space indentation +[*.{gradle, java, xml}] +indent_style = space +indent_size = 4 + +# Tab indentation (no size specified) +[Makefile] +indent_style = tab \ No newline at end of file diff --git a/.gitignore b/.gitignore index b633ac7..8adf5c3 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ /.idea /target /src/test +/build # Build Files dependency-reduced-pom.xml diff --git a/README.md b/README.md index 76ca9b8..9d176ab 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@
-

A backup of the original Logisim circuit simulator.

+

A continuation of the original Logisim circuit simulator by Carl Burch.

@@ -53,33 +53,50 @@ ## About -This is a backup of the original Logisim source code which can be found on the original [Logisim website](http://www.cburch.com/logisim/). +This is a backup of the original Logisim source code which can be found on the +original [Logisim website](http://www.cburch.com/logisim/). -Logisim is an educational tool for designing and simulating digital logic circuits. With its simple toolbar interface and simulation of circuits as you build them, it is simple enough to facilitate learning the most basic concepts related to logic circuits. With the capacity to build larger circuits from smaller subcircuits, and to draw bundles of wires with a single mouse drag, Logisim can be used (and is used) to design and simulate entire CPUs for educational purposes. +Logisim is an educational tool originally created by Carl Burch and is used for designing and simulating digital logic circuits. +With its simple toolbar interface and simulation of circuits as you build them, it is simple enough to facilitate learning the +most basic concepts related to logic circuits. With the capacity to build larger circuits from smaller subcircuits, and to draw +bundles of wires with a single mouse drag, Logisim can be used (and is used) to design and simulate entire CPUs for educational +purposes. -Logisim is used by students at colleges and universities around the world in many types of classes, ranging from a brief unit on logic in general-education computer science surveys, to computer organization courses, to full-semester courses on computer architecture. +Logisim is used by students at colleges and universities around the world in many types of classes, ranging from a brief unit on +logic in general-education computer science surveys, to computer organization courses, to full-semester courses on computer +architecture. This is a continuation of the original project since original development was ceased in October of 2014. ## Features - * It runs on any machine supporting Java 8 or later; special versions are to be released later for MacOS X, Linux, and Windows. The cross-platform nature is important for students who have a variety of home/dorm computer systems. - * The drawing interface is based on an intuitive toolbar. Color-coded wires aid in simulating and debugging a circuit. - * The wiring tool draws horizontal and vertical wires, automatically connecting to components and to other wires. It's very easy to draw circuits! - * Completed circuits can be saved into a file, exported to a GIF file, or printed on a printer. - * Circuit layouts can be used as "subcircuits" of other circuits, allowing for hierarchical circuit design. - * Included circuit components include inputs and outputs, gates, multiplexers, arithmetic circuits, flip-flops, and RAM memory. - * The included "combinational analysis" module allows for conversion between circuits, truth tables, and Boolean expressions. - - See the [Features Status page]() on the project Wiki for information about the status of the above features as well as any additional plans for features +* It is designed to run on any machine supporting Java 10 or later; and each release is packaged for MacOS, Linux, and Windows. + The cross-platform nature is important for students who have a variety of home/school/dorm computer systems. +* The drawing interface is based on an intuitive toolbar. Color-coded wires aid in simulating and debugging a circuit. +* The wiring tool draws horizontal and vertical wires, automatically connecting to components and to other wires. It's very easy + to draw circuits! +* Completed circuits can be saved into a file, exported to a GIF file, or printed on a printer. +* Circuit layouts can be used as "subcircuits" of other circuits, allowing for hierarchical circuit design. +* Included circuit components include inputs and outputs, gates, multiplexers, arithmetic circuits, flip-flops, and RAM memory. +* The included "combinational analysis" module allows for conversion between circuits, truth tables, and Boolean expressions. + +See the [Features Status page]() on the project Wiki for information about the status of the above features as well as any +additional plans for features ## How To Use - This project is a WIP and although it is currently building correctly there are still [issues](https://github.com/dadler64/Logisim/issues) that keep coming up. At this tie, if you are looking for a fully wokring program I recommend going to the original [Logisim website](http://www.cburch.com/logisim/) and downloading the stable builds from there until the builds here are more stable. - - The initial release on the releases page is the one from the original Logisim website. I will periodically post ALPHA and BETA releases so that you can see what is being changed as this project progresses. - - If you want to try your hand at running or building what is here, import the project into an IDE such as IntelliJ IDEA and build it in there using the build system provided. + +This project is a WIP and although it is currently building correctly there are +still [issues](https://github.com/dadler64/Logisim/issues) that keep coming up. At this tie, if you are looking for a fully +working program I recommend going to the original [Logisim website](http://www.cburch.com/logisim/) and downloading the stable +builds from there until the builds here are more stable. + +The initial release on the releases page is the one from the original Logisim website. I will periodically post ALPHA and BETA +releases so that you can see what is being changed as this project progresses. + +If you want to try your hand at running or building what is here, import the project into an IDE such as IntelliJ IDEA and build +it in there using the build system provided. ## Contributing - For now if you would like to contribute check out any open [issues](https://github.com/dadler64/Logisim/issues) which could be resolved. +For now if you would like to contribute check out any open [issues](https://github.com/dadler64/Logisim/issues) which could be +resolved. diff --git a/build.gradle b/build.gradle index 851cfc5..acab7bc 100644 --- a/build.gradle +++ b/build.gradle @@ -4,28 +4,36 @@ buildscript { } dependencies { - classpath fileTree(dir: 'libs', include: '*.jar') - classpath 'com.yuvimasory:orange-extensions:1.3.0' // OSX support - classpath 'com.netflix.nebula:gradle-ospackage-plugin:8.1.0' // https://plugins.gradle.org/plugin/nebula.ospackage - classpath 'edu.sc.seis.gradle:launch4j:2.4.6' // https://plugins.gradle.org/plugin/edu.sc.seis.launch4j + classpath 'com.yuvimasory:orange-extensions:1.3.0' // OSX support } } +plugins { + id "nebula.ospackage" version "8.5.6" + id "edu.sc.seis.launch4j" version "2.4.9" +} + apply plugin: 'java' apply plugin: 'distribution' -apply plugin: 'edu.sc.seis.launch4j' -apply plugin: 'nebula.ospackage' // Common Configuration // -rootProject.version='2.8.0' -targetCompatibility='1.8' +project.version = '2.8.0' + +project.ext.author = 'Dan Adler' +project.ext.email = '<2274667+dadler64@users.noreply.github.com>' +project.ext.copyright = '(C) 2021' +project.ext.description = 'Logisim Circuit Simulator' +project.ext.url = 'https://github.com/dadler64/Logisim' +project.ext.bundleId = 'com.cburch.logisim' +project.ext.mainClass = "${project.ext.bundleId}.Main" +project.ext.resPath = '/src/main/resources' allprojects { apply plugin: 'eclipse' apply plugin: 'idea' tasks.withType(JavaCompile) { - sourceCompatibility = targetCompatibility = '1.8' + sourceCompatibility = targetCompatibility = '1.10' options.compilerArgs << '-Xlint:deprecation' options.compilerArgs << '-Xlint:unchecked' options.encoding = 'UTF-8' @@ -48,32 +56,22 @@ cleanIdea.doFirst { followSymLinks = true } -subprojects.each { subproject -> - evaluationDependsOn(subproject.path) -} - // All in one JAR file // jar { - def deps = [] - - subprojects.each { subproject -> - from subproject.sourceSets.main.output.classesDirs - from subproject.sourceSets.main.output.resourcesDir - deps += subproject.configurations.runtime - subproject.configurations.provided - } - subprojects.each { subproject -> - deps -= subproject.jar.archivePath - } - deps = deps.unique().collect {it.isDirectory() ? it : zipTree(it)} - from deps - manifest { - attributes 'Main-Class': 'com.cburch.logisim.Main', - 'SplashScreen-Image': 'src/main/resources/logisim/img/logisim-icon-128.png', - 'Logisim-Version': project.version + attributes 'Main-Class': project.ext.mainClass, 'JD-FX-Version': project.version } duplicatesStrategy DuplicatesStrategy.EXCLUDE + + // This line of code recursively collects and copies all of a project's files + // and adds them to the JAR itself. One can extend this task, to skip certain + // files or particular types at will + from { + configurations.compileClasspath.collect { + it.isDirectory() ? it : zipTree(it) + } + } } // Java executable wrapper for Windows // @@ -81,77 +79,83 @@ launch4j { createExe.dependsOn 'jar' version = textVersion = project.version - fileDescription = productName = 'Logisim' - errTitle 'Logisim Windows Wrapper' - copyright 'Dan Adler (C) 2019,2020' - fileDescription = 'Continuation on the Logisim circuit simulator' - icon projectDir.path + '/src/main/resources/logisim/img/logisim-icon.ico' + fileDescription = productName = rootProject.name + errTitle = "${rootProject.name} Wrapper" + copyright = "${project.ext.author} ${project.ext.copyright}" + fileDescription = project.ext.description + icon = "${projectDir.path}/dist/windows/${project.name}.ico" bundledJrePath = '%JAVA_HOME%' } -// Packages for Linux // -//ospackage { -// buildDeb.dependsOn 'proguard' -// buildRpm.dependsOn 'proguard' -// buildDeb.dependsOn 'jar' -// buildRpm.dependsOn 'jar' -// -// license = file('LICENSE') -// maintainer 'Dan Adler ' -// os LINUX -// packageDescription 'Continuation on the Logisim circuit simulator' -// packageGroup 'java' -// packageName 'logisim' -// release '0' -// summary 'Software Simulator' -// url 'https://github.com/dadler64/logisim' -// -// logger.debug('/opt/' + project.name) -// into '/opt/' + project.name -// from (jar) { -// fileMode 0755 -// } -// from ('dist/linux/resources/') { -// fileMode 0755 -// } -// from 'LICENSE', 'README.md' -// -// postInstall 'cd /opt/' + project.name + '; ln -s ./' + file(jar).name + ' ./pennsim.jar; ' + -// 'xdg-icon-resource install --size 128 --novendor ./PenSimIcon.png pennsim; xdg-desktop-menu install ./*.desktop' -// preUninstall 'cd /opt/' + project.name + '; rm -f ./jd-gui.jar; rm -fr ./ext; xdg-desktop-menu uninstall ./*.desktop' -//} - // Distributions for MacOS and Windows // distributions { osx.contents { - into('Logisim.app/Contents') { - into('Logisim.app/Contents/Resources') { - from('dist/macos/resources') { - include 'logisim.icns' + // info.plist file + into("${rootProject.name}.app/Contents") { + if (file("./dist/macos/Info.plist").exists()) { + from('./dist/macos') { + include 'Info.plist' + expand VERSION: project.version, + JAR: project.name, + COPYRIGHT: project.ext.copyright, + AUTHOR: project.ext.author, + BUNDLE_ID: project.ext.bundleId, + MAIN_CLASS: project.ext.mainClass + } + } else { + println("WARNING: Unable to locate the \'Info.plist\' file!\nMacOS bundled app may not work!") + } + } + // universalJavaApplicationStub.sh + into("${rootProject.name}.app/Contents/MacOS") { + if (file("./dist/macos/universalJavaApplicationStub.sh").exists()) { + from('./dist/macos') { + include 'universalJavaApplicationStub.sh' + fileMode 0755 } + } else { + println("WARNING: Unable to locate the \'universalJavaApplicationStub.sh\' file!\nMacOS bundled app may not work!") } - from('dist/macos/resources') { - include 'Info.plist' - expand VERSION: project.version, -// JAR: file(proguard.outJarFiles[0]).name - JAR: jar.baseName + } + // App *.icns file + into("${rootProject.name}.app/Contents/Resources") { + String iconFileName = "${rootProject.name}App" + if (file("./dist/macos/${iconFileName}.icns").exists()) { + from('./dist/macos') { + // Make sure this matches the name of the .icns file in the 'dist/macos/resources/' folder + include "${iconFileName}.icns" + } + } else { + println("WARNING: Unable to locate icon for MacOS app at: <./dist/macos/resources/${rootProject.name}.icns>!") } } - into('Logisim.app/Contents/MacOS') { - from('dist/macos/resources') { - include 'universalJavaApplicationStub.sh' - fileMode 0755 + // Document *.icns file + into("${rootProject.name}.app/Contents/Resources") { + String iconFileName = "${rootProject.name}Doc" + if (file("./dist/macos/${iconFileName}.icns").exists()) { + from('./dist/macos') { + // Make sure this matches the name of the .icns file in the 'dist/macos/resources/' folder + include "${iconFileName}.icns" + } + } else { + println("WARNING: Unable to locate icon for MacOS app at: <./dist/macos/resources/${rootProject.name}.icns>!") } } - into('Logisim.app/Contents/Resources/Java') { + // project *.jar file + into("${rootProject.name}.app/Contents/Resources/Java") { from jar } from 'LICENSE', 'README.md' } windows.contents { - from 'build/launch4j/Logisim.exe' + from "build/launch4j/${project.name}.exe" + from 'LICENSE', 'README.md' + } + + crossplatform.contents { + from "build/libs/${project.name}-${project.version}.jar" from 'LICENSE', 'README.md' } @@ -162,25 +166,13 @@ distributions { installOsxDist.dependsOn 'jar' osxDistTar.dependsOn 'jar' osxDistZip.dependsOn 'jar' -} - -//build.finalizedBy buildDeb -//build.finalizedBy buildRpm - -//==================== -// Local Dependencies -//==================== -repositories { - flatDir { - dirs 'libs' - } + // Use this cross platform build until linux building resumes + installCrossplatformDist.dependsOn 'jar' + crossplatformDistTar.dependsOn 'jar' + crossplatformDistZip.dependsOn 'jar' } dependencies { - compile name: 'ColorPicker' - compile name: 'FontChooser' - compile name: 'JavaHelp' - compile name: 'Logger-1.0.0' - compile name: 'MRJAdapter' -} \ No newline at end of file + implementation fileTree(dir: 'libs', include: ('*.jar')) +} diff --git a/dist/linux/Logisim.png b/dist/linux/Logisim.png new file mode 100644 index 0000000000000000000000000000000000000000..fc794f858fec9240ad4c5e513bedf25f4182f9c2 GIT binary patch literal 963 zcmV;!13dhRP)C00001b5ch_0Itp) z=>Px#V^B;~Mf-RE000073I!1p5C9+m8XFk^GXNweBr!5DK0rPIS^!2!MF3;~Pf<@< zTUcUaVQg+|0Ga@NetU(7gp7`h0nz}MnUK)2 z@Bjb*pH`b}00001bW%=J06^y0W&i*H32;bRa{vG&=>PyE=>bqA=lB2s0_;gdK~#9! z?V4+ssvs1G6UR}UhKC8BDe628 zR$^dd6WrAm3BxmN$NHQ!!QB#B2xfQz_!55^@;B;^F%n@rX@Z)+Rd)zr2-`^$?D&$Z z1cdMku>J5nHY^hG{*M`qcw)(AR2o7ML&j17e8`z8f=-Tr_j?mY5Ci61R&9bO@D@VB zNOcHD5W_VJ1j8OpAV%AB6;(bKL5$@q0q{PC6SQgs{K$|5VyHq9fS-|j(UZvsFMDx^ zBT#fi1Ir-B=`{#yA4Tx4E_&+?5r{yHlIZ~4f|7yqTwXb5E6PeNnic?TLSBsKKdtMAydt?_PoBSKq(DRt#b-te#pGnv`m|gSAYzbbtso)J ze*s7=+MisM(kpXXS^n#P)T+23#2O?C$or>{}6}cz2^KG=z2hN z5B4$ahNRU>KLPBHNNW!k40lHr=`KI&mM+s=e%L)_X>Iv6_h7-W^Q&GJV;@b#PzSZ- z7sB5wR5DSQg5QihrFw8UFavK^@=jOiv0#-PUU1Vd9EQh&v6w!04wZI!>Y^O^7GyLL2|$1D!)H8fi7>9pO{y0PEa lyK!=Ia&mHVa&r1_^aIzN{@Fabfc*df002ovPDHLkV1l|CtD67- literal 0 HcmV?d00001 diff --git a/dist/linux/logisim.desktop b/dist/linux/logisim.desktop new file mode 100644 index 0000000..79597e4 --- /dev/null +++ b/dist/linux/logisim.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Comment=COMMENT +Terminal=TERMINAL +Name=NAME +Exec=java -jar /opt/logisim/JAR_FILE +Type=Application +Icon=NAME.png +MimeType=application/java;application/java-vm;application/java-archive +StartupWMClass=MAIN_CLASS diff --git a/dist/linux/resources/logisim.desktop b/dist/linux/resources/logisim.desktop deleted file mode 100644 index 4d715ca..0000000 --- a/dist/linux/resources/logisim.desktop +++ /dev/null @@ -1,9 +0,0 @@ -[Desktop Entry] -Comment=Logisim Circuit Simulator -Terminal=false -Name=Logisim -Exec=java -jar /opt/logisim/logisim.jar -Type=Application -Icon=logisim -MimeType=application/java;application/java-vm;application/java-archive -StartupWMClass=com-cburch-logisim-Main \ No newline at end of file diff --git a/dist/macos/resources/Info.plist b/dist/macos/Info.plist similarity index 92% rename from dist/macos/resources/Info.plist rename to dist/macos/Info.plist index 6054f50..12637fa 100644 --- a/dist/macos/resources/Info.plist +++ b/dist/macos/Info.plist @@ -5,16 +5,16 @@ CFBundleDevelopmentRegion English CFBundleExecutable universalJavaApplicationStub.sh CFBundleName ${JAR} - CFBundleGetInfoString ${JAR} version ${VERSION}, 2019-2020 Dan Adler - CFBundleIconFile logisim.icns - CFBundleIdentifier com.cburch.logisim + CFBundleGetInfoString ${JAR} version ${VERSION}, ${COPYRIGHT} ${AUTHOR} + CFBundleIconFile ${JAR}App.icns + CFBundleIdentifier ${BUNDLE_ID} CFBundleInfoDictionaryVersion 6.0 CFBundlePackageType APPL - CFBundleLongVersionString ${VERSION}, 2019-2020 Dan Adler + CFBundleLongVersionString ${VERSION}, ${COPYRIGHT} ${AUTHOR} CFBundleShortVersionString ${VERSION} CSResourcesFileMapped LSRequiresCarbon - NSHumanReadableCopyright 2019-2020 Dan Adler + NSHumanReadableCopyright ${COPYRIGHT} ${AUTHOR} NSAppleEventsUsageDescription There was an error while launching the application. Please click OK to display a dialog with more information or cancel and view the syslog for details. NSPrincipalClass NSApplication @@ -147,7 +147,7 @@ JavaX - MainClass com.cburch.logisim.Main + MainClass ${MAIN_CLASS} JVMVersion 1.8+ ClassPath \$JAVAROOT/${JAR}-${VERSION}.jar WorkingDirectory \$JAVAROOT @@ -159,4 +159,4 @@ VMOptions -Xms512m - \ No newline at end of file + diff --git a/dist/macos/LogisimApp.icns b/dist/macos/LogisimApp.icns new file mode 100644 index 0000000000000000000000000000000000000000..aef209632300ca71e97089e39a2bc4f6e30f7a1d GIT binary patch literal 24007 zcmeHP33wDm7Jk(;lapKoVo*^)BD)_TV#o$Qktn!+upsd55*J|?kV}H=%C{QbUHCr3 z5p#gxs^MM}NCG4X2y$jUf(F8!5Rpq(g5i=Q2b+*c=Y4@da7Q% zdhgZ$UUhd>S4f!l*H;1lT%0g%)aHUE3^QORxqYYSoP-qCD6w7!` z0*X{FT&n?elozsJjR1u59q@`B99JroEmsjAC9yB|vR@mlnk`m%i-m$+yC)W}-lS+8 zMX`}sJ?9y1LIN1SG<*_fML!1M)5OOii>5;sM&6+FG3Yq55Fq;BGzgK88ZkUBwr}@{ zkU*a#AYt*VQ7G(*lXok>FE81%@}6AM?B|Hhz zvC8$jXilew+NAriOB!7QB)xGlH8f@Z8ttU=_2|mCss6JVtY)AiK}9C47WP8v_j$iE z8kbVC_JJgLkFWiueks+PQ^Ubh9aFcA>YHZ-0KCh$#?`z-x$;+E&bjNlsU_Krjq(E>}iwh1F(x_j_X!SgLbWc2?QQG>a;uJ{Es z3en4{0dFV$zBVOMUsH2KUHRtc!}wq&L16TW+Pd01mk(`89@l+7#&i`jeTTe0d%~DO z4~Hy*HR$9AG)0)td-*i_QRPuujLsj#nUpfxXUy1V0-~I7JcC7(8_u zP%At;_)G2i{5eCrhUnaO>Aduoy#p4i4<`)>)4T1luu9y4(kt)Bgt!|?hgA-jEIljc z_V9PpqtmtqXA6{mIjxJEVe~j+a_!KR^{@+6;UaqRuB$wy1%v#ZhMj4r57usW9Rc6H zY*diA!$A@4Ki=HZ04;w`+#y&*0e#EOQXR$yh%JcAo23lU^KrgnAyGM@UP3?O+D|6d zvDK3DbW@~Asi+uvQEC8`HcyuxLg0xOA+s1f`ACOAo_s{gv53!MX@_W0eol6F_Qn@n zH&>i0Eh#A}`=_&fz+oAGuEhE4d2&g=@NZf$&f&Yr3}1|B5nOY_-dJg5P~5KtI87D*=p>Chiu=xWx&0XH z@*a~_PW+}j-5kt~wM7%fxbO~(DCqAu9b+{&)ty~ADn!)WqWFwMn$n6*lOB-u+tRh; zi7KPXWURhax^eC^5gvrG3m4w4cb`6ey5A#r=V;-P#*joH;Wd5-An;{=PlYo7yA52x zjHL^={Z&@BCD?(2I%*?0c*n`J` z1mD2Yt=QuLOEyzd8FLKCqb4j>|MnQbHy=`BnsXFj%@!=Yas*(+HVUsC2GZfiR!Z&+ zJ`AvX8ww9T1n~Mt$Qe`&@Z5GvzKT2u5V3=jeTD;Q_tFju*~mGH9P{)8xXbY|B~{Ty z0P}ZJQX2Fnz*D;@WLSQQY2+8k*iFfmko{QLLm_KFknSer+#QUZ<~@|0^DDF!KDW0a z%PKAEz6*U96k09VP1>EXxK(6z^d0oi=DK4r!tfr(;aLV;3?$+XVjv8iM`a{pVTb89 z0@pa_hz-l%AcPipk6IDG8jJ7>LFkBxTjPR35MnhOVlC<#Q$Sx~ogY>F{1_AJe-(5AGZMBWZG{E%6Lb@z zqB^qAJqjC{=P8As)lAKU%<(V;ccHBFbt7br0o+`(Wyc1-9*ymmxtohsGCBy`ty4G$ z)@_G-vHizAkrx2;TsAe&K4sD2SC`RzVJ;ia`2jrnt#kF*GU_UwXPxG#D{fglU$fsU zeguDn}PP& z#`gj3vHeqeY`-RKIzEYaaE&wsGz2sRGz2sRGz2sRGz5YZR}>T!+;Hq0n+gi{BqmPk zk7sFq2ztO_*|}76Wkbq@`+eKmhi=YRU2B)}X7|Q3I&DXrTrIY&U;S`mSX(*pgv7U( zmLAah-EVYj8yCh^N|=*kHSHYZ-xe;!$b7q$@Zs8uN7}%Hjz=X-$*{}?Ppdy8!gtG9 zlVqQstok~tH3*OeoIgC+829W6KKsp`NK$uklTa}uSaPpIj^dI<|2SjL4aKAY|-^I%P?`FL0LAQ;&4 zyS|i3XI}km^&CicR?Sv3Z^Fac>QJZuvYB*|I@DVo^8iy^G&5GOKdzDkeg_yWx`-Jk zGdWQ1k!oBNvsRl@@Nlq4V%6r2To%Lgz#F~Heb#xt6*24bN^o5VPXU<2KpVWWEp+;b zAq1XWgwR$$2OSRQcn*O_`;hO@*XmM^3a>@uT5VO-VFSxFbdP~A`+7iR*j7w*ubicI zk4=|1zvd|{Cfv%*@W!sa&#hRu${8B(bvaOHSIt(qrFgA;naz-#REg3_utiQYBR_)y zWOpKeW3(eD)->FmcF%3&uj5~ODWHc~?a0b~tmsJ)B-)LWHQ~NN*=^{8d*uwR zw-qf8mD{Jg6vQ7sVi=(Z5z|-&4y^E?oTa&9)W{aZ>XI7vrF_)vvmx+vz`w#zbYkCH zWE(xS`}|Yk{yP$cf3@@aQ_=d{{Gv=wv9p!!Kd{@8lWgbxm$ux0+QmSnQZJ5d zyc|!fE;cpZN_pM@^;R=eKhNfc|15+_mlr}T`_F4UQlS@?`7Uhx?{ZVl&i6axo&83( z?+TTe^mSaYRGN< z@at6k{+!Ty^GESdXw{;AGJnx8@6}BezdS={(cgK?n-sTXsx|9)1Y3Ll#I#@4^Czu7 zf1}!@6Vj)h&mV=i=Jb)VOzrbmQLQ?E7N^#Pv*~Hg`MYHG&)>~tJ%3oUbyypmKV&_B zxnq1M8(`}GW{B@8(&ekGhbvvv%KO|++NPCjKC`@y&)>?PKfYPE;k60MJ|xMH+R+l6 rnCyK1`bI%PPGaK7{+<>y4i#ESLqJ17LqJ17LqJ17LqJ1727&(rsiy3v literal 0 HcmV?d00001 diff --git a/dist/macos/LogisimDoc.icns b/dist/macos/LogisimDoc.icns new file mode 100644 index 0000000000000000000000000000000000000000..df44f2e5798955f13d1e11ccf8aee1df4df5da89 GIT binary patch literal 38638 zcmeHw33MFQmG$+wbx zo5{D6e0$0F5cy_(ziI5n{;&K-ICHK^#(hWIhwIbZ+h^6A%O68%_O~Rg0Hys~+RvDm z5)A}a)k29e>j?lK0UJnphYHJ4m&Z@Y;v*OczvbmQ`0hOhQX)$@D;*Iz!kuBos5BZP8@vq7qv zuU4x_>20mejaA3jHF$O9e?};qyDlTwyStPf?QN|$s!wgKWgWT;e}SyoI4H!V)o8UE z4XvH8(Qw7IwbY&Yw4P-L4HaU9GI1$6CaDfvU<0T|Tf_P7Uu@mF<4}1?20|Ic!YtF@ zt<&HDyn`o*ua-+$}(|M}tC?SC1zurNId`X0SrtA^@yt5mdF&{2JS+d4W|n7{V( zf;W(YoeNFU-`m@x*Xb=5v(aei(W=$7CRy8Da;T{2;KBWScOTk}ker_F%b;yCS$K&*LUT6duew5P;=%Jf4AFY&}pIVpy^r~8uwts zBrtTCEEc1o&wB1VH^l55&sUG6-LUlN)KGaaY&(RO6SIv@iw=fTUER&!{9MY$Sl@l1 z*bLo3D~0X1x{hHZ5ulsfb?i~*3F-&mpIs+olXu>;vq!0fMpSmFPhpc}F!5MT8g+Mf zS6Ar0K>vDNK zPMdYWbr`ZtJoud^XFu2*?G>XI?tYcJ8`@F(+Yi&(q>{fm=^Ys8@3)v7mDnT(7s8%i z{zK+T{`XU$!32f(9v-yORuR>lJA`%{OH2eft3jz(>S5f;aFJYh zIPBb2k~2*%$GTl^H~722TVQ9$l8_D}FEgm{#(TV8kH_WUE|GQ}8XWX)7!xhn6d#btSEhnf1~-aZOBhbxlpv2?V!)0sM#3 zwj$o_-WLL@dv5{8x2oO=2Gx#=cbV1H zAKpo=m9Z3tYFZhCCqxdaG0b|bW|&)O4d1kigX+D0pxO!`Ychrb)x$XYqn=*9UN;e{ zaVf)4{SRANyWOY@4Ao%Zu$y{{oi_`?}J*JkMH(Oh8RzFZ35USlSj8Jy=W$hoXBUoA2j;^e~dotw8`m4YGm9;C9mG!dXL6|`T zudI^`?>#bPhY|y=tY^W>x@-tmxz+(FD8R}(o~*0~VbyF4xVBClSzFujqM5#JbsZ*P zPhxQ$7_oyau4xZ))1Hw9Hpcv53+y|D+7T_V-~7Sbzegx8mPZbLV(OBm_l!H1E?E?Z zxT}7?e{R&@c4$vLE8zRFg;Q~FW8&(zW8h!>+w+tDaGNbTVSa`0&x4=xNB{P$#jitP zd$#`-KLLW+`;8FHp0)h*ZFLB0?h{7^^`T_N7ZAv|lQWsQj|1eSlk-I~{GGpv}WZ+b7ySzAZ4d z@sRw1Z(08S|KbuKeB&j)*4ow{PoTr53zw)ptblT``D7Z6X`DN_nMl<*O^i*DU&YXdjBWf693YHB2IwKdh1 zmoJu`J5zk@aM8ZQW@#Bxbn=y*owSnfK<)G`e%sBPOzR>p7A&Qohvzc?BKp#yGtHBkC-lAXBXYcfFn;CBw$TVWyPhk zv!_oSKCriNPw9$tND7{vV$P50pxY^2JGxak(kOFr?P{)7UAa_xrub;l-dzPpN>`jk z*&#e|8(uhn`oy7qI|~ZVoLzAS<$woLipPbxLE4>!sD|b%J6n8s|IUIf`>vc_QG#;2 znJ(1HDA9-u)0&F2x`Ergp`otkTE)e()5nYUZ2#i3^2#$SPNTeu9yGM~m`iv3(4zt+>^}~V9=dhmaAg`BYOh@`D?Ye$%ew5d2F~X=S|7v*23%bYb(8?5NKn;=}8{Jy2qE^Yw<>%JPyUyFSm&Wqf=NqR$}Cunzoq?6JLD*T^J3ZU+#pm1>YS zU&E+*Diuw-7D2pO*bg8G>U5>__}5>qOPBh%?MD(IoyFSRiEb(221Dq2Lv_XZll!)< z&ye|e?L#sksAO6`Y${~vdNzoIX_eS+4X?@4dC^H*dW0>))<=``y)R_f>%V9<&j5cVjdf9I+cBj{3r` z_RZ#c*o{B3>x;FDPd<3>owt7XyWhX{&VRl4{zsokzC3$o#cqW3n{=@n*d4YtHsP(CXyS`YTBbP8A|C#1bZaBQRaO>tx%m#WRy&-Pnr<*o?{`rUf!$y2D3ENY3lg_)-?k0^*qG}2lkUs(Sf3(efz%NyL->BUAuSgEEW|ax>wpm!JY?)d3jk`IeeJ%q_Xqp&z?CAeuobg9V#hAvOZC74@d)aT1G>id2(5*1jXI8?76f* zZM&pWtK~qp#^b%Q?yk1x#+qwPC9kTIsYctR$r~Se4+I0sgs3> zXD~?mgj^bAST{V3&;wd2EA*&N<-N2}jQC66tE6>EE7iqnK?Bi^g$1&fWIU%`Z>+0@ zSr%3hrwb8dWDKG{t|YNmsQf8H4_QHx(Io$Sibj0FKcAp=e2`N}bOIQ~ol5%Fyqj(C zA=3(!)ld&r0OomeaAd=Q}ndF+F2ufcwP+=nVXC`U*KKwY#t4Ja)@&jPT4 z*HoGKHR6 z&nBK^2g{R2YOr+~kmIm#H)36Omu68F;e z1c=JV)y!1lsaS}s*>)4g2-xvq>yj}j`Y714r#G>p-ARbr*xi)_b^_9?IO2e$KgMDP zIf}v9#~9N4`1hhmKV^j%z;;7-27nmTB_dsT>lV}pt2g>B7L$oKDh$-`5Y_Q1D>yAc zaR=piIiQN`#_)^VyWQ8CG0F|p5rn?{j1}w>poJBg>NpjKYGMj$*lZGOEGZhNLL1W! zlr|3iZZj*$MCg0UEKLl|3B(%ujwnQM8fNIl3?u&$v|=+G@BI}*Z@_&IP{9B+0`v&M z1$_z=2!;u! z8*T$fwmlAW@}x2*#z^faE(wEAB7WZPUAuPf{OT*Zkk$)17wCTni9=k>CNXh1vW4X} zia_55cMaURP&V|xg947;A-0QbR@=aU#UwEbOa~AevE}uGF@=o_Q6?x`D66gCEHQ%W z2#g?U0nT7Ia}8aks{|DlaF@|~KA1z!_G|~=ZXKXaJR>9^FmbgMLM>mnSQs;cnhRhb zAA9h0;E?0s*#~Gd&t#I0v||jkktp)hu}-Vk1x}$ z%m9N6h8qg13dIgcT^tSx2@Y+OTO|WDSU^H1qY(`Hr7l^abVp1@qi`Q!y9~G7CD48sp`&?h{PouW_2Xp&u;rg+MK&2!l@EqsXUuX-U4nj?sqySs z3bUi=)mA6ifgufsVq8;fm+Pio!u}VAXX4KE??6!AKVF0pDYwgQQZPisF5fLQL1~X! z6|BHpEniM1{#P$3z)S|^F$2&R22ZYA*zw5dD&uIzOLJkBaX-_-II&?mKqU=^$iR3q z-8|Qmc!?vmJOC%^}$%8Mxo^|w=Q|ihj#mH=8E4Imo%re1GPST~xxxC?XIGoJJ z1zYRMac8*{U?;OnZHU;d2Rj8RFCA2Q*p6@TdhyweVM}J%TkM5xJ8wRefv==Pj(nR9 zx1K=(XLF(FGRRr3MKj?X&+W;E!WB*#1Vp6ca=dFiS>&7?FpvxmV?LN>gF7yi89sN_ zD*-Tb;Bjh_4PNjPAQ}B7bCR2ZTtO}=`NcO44N1U~=YnC4@cm>G57BUffe}n@c#~}C zf>#W;CHZB>za%cc(}}@={F1rGuE76eR3YaPjJB~~v|H?B$G91vUlKRpjik&@p$GrMCb4^AkcpE(1DEg)y)9%cm}rA#oVZ%rHq82HOU@bYLlH2&(Y)4#~K!!%rU(lWyyEvdI!|n{;vTp#4`xxJgxW)T&U7 zTXv6pBI71i3Dodl31nLQOw(@nY1H@wv|D+^v|F~C(TKt)-DH|M@Sp~K4iIlumoH3~ zcuUu$kXMLsS<}J2$!n8pY9nFa1dCqVqXzDchY2`wnB-f`2nR@Og#O64DonnKb@5vA zInIWne$1JZxa0yC;>mj!zX*|y!lOy8ZS}`3%h_vb8 z-nMP~@=Io`Vhgq6cJ58lkpRn4jxHM`-|}Cke!>gIzpeQNb+TL#$+ z7GX{k7Q#T21tj3sj}maW5vM}H5xOo20Y}+@CSt5H91~>%CTctb*Ezz#0mV7Oz+px$ z3K3rCg>(|n;RI02#HB#|+20x4$Tq+7wCiAkGv(c1c6ia5CV)IMZpT;YO&rF&Zvol$sl%;W%3bTOIQuB~7MO|SSh@dAJX{vgZX6HCH?u6q z%uNds7pdqiT}i>B6dr$>_V~6ovLT9DIQlvtG)r{D98k&;$y@0}$s1nVL_)(MP`m*P z7pdfp?vg|qxF`b$`W=57xv1W4`t)v6HHh9K6}-W7`)9sX7$(wYQtg)Q8!RO6HVLKM z6iGMWQ6{Bw!!n-@Q`ET;ZNt=cZdfok4LY|JC`KJZ>6Qc1wee!NbP!$AAp~y-^f?nG zZwipSsljo{t;Wa|Z*my;YH1|wTe@a8&}LI5-xR7#iAnQ%Cow{(4K#GG5g2PEIfg>4}jfEw78)n^za85T- z^ERwms}8MsV|rqGIob_2O~Vzvabk<7TIe335Ain4i;alhgq-LNlyXzhyy?|g$mgGT zG8)CfG;i%QsCgTv z+yblK{BdrWdkLR&i$wKCIJaq5y}b$wpdhRpSD7)^ji}!8@3`u1&y1?xx}XQcSG|3M zlp7Jf874~D#zb$9F$yhA(c74V59d}g05YdYWN$k_LNq2}3rqI4U1swmdn2TqukLMI zx-Eq6ZM)nSSoc;iUiW4TpnI$I(Y@7V*m%}3q;INBAmhi0-^Q_SLM(C?$+JP1g=KW1 z)Neq$WdU0iLjQ(|w`^h-ME%wRf6JM}p6jc9`{qbDtbGfEbo++2Z&>Fh2b~+wN|bhM zi6Bl+7`E}^H!PeR5x;?+)Vt2F_$?CF4NL0eP^xrP^_GXlaJLKJ@_@=4FMN{_+KuOM zGXDoyx9L*9ttNl_#*g4{4;z2*_ySQ}LQ--{%B=8@l$4a@q{R4GkpTV*gz@D?_>0FE z#wN|VYeDMbB}>CTmMmGkcv0%N=Fd)wkAc7cBf^lr<~*JtHhI3kw~a%dbL;m1c){GH zI1x341bCDvY5qMSV+Al6Ed9Z^W+hA|0iGak&frjh_pm~hv9kB1Q` zkcnsY;<-~ufG0{?@Zi&d3J>SJBW(%^@c5$S)Q6uBCr&^cNMO=k0P#~6Ke{qt*Vb}#uK&tM7pDY6fSHc})5q>?{1=ulxuf-e@y^Ge6%%9znCbq1 zarx5!)A3)r!}X8Gzq8{n+Wyh@zmxbI9e>gB7af0r9{^^0{S&?aqW53){)^s!ck1~+ zia$~OiQ-Qbf1>!~zXhV}Kdk?n2K`e2ZB%sriOxUK`6oL6_(xxaqWBxd-{|}koqq!? zAEtady8ei+Kcef8==vkN{_x)d-1=+E@BakE>G1R)cQpPqynhw2`YhHT1;?Lhc>gSL zcs8{DYwGXc1qshS|8Oek-vZ+g{6jWVeg806c=qWB7X;P+A@2RlmA_iG`lF9Op{MWo z$M3r;|21vp4 z!iz7yG+oDwFTSwy`KKR$=$`pW!CwpH-alS^--8c7x_o+%M<0IhzQyyCL4X}(_~9qe zNxXj@#*5lZ7N;(_Yfe&Z2mv}yU=r`2hkjEXzo4EFCko^3aQKIt1wxTX6f?aClqd}E U?Rfa7qj^03^dF?$+vdIh0W!uWE&u=k literal 0 HcmV?d00001 diff --git a/dist/macos/resources/logisim.icns b/dist/macos/resources/logisim.icns deleted file mode 100644 index 79223ca0833865de48e04e0f1ed6f0565cfd9962..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 20153 zcmeI3PfT3b6~^xvkEdc$fmi{XED&qJo30QW5UV0~U{-)P5tL0M&BB&tFnH{OFp3ip zX%!Hu`)3GM?Bba)w!>ih2Z~jMk);$$7a+Q5WDT0_EM9--^6W4$@4fqGu)Ue_BJaEB z-0wT@+;cy_NXf^&1HV-2=Sv@da=AgNpZ-ztvohX)US|SIWioeFIy0gEm-$@%H*-^k zs^arg{cZK3akURr^S7)^2P?DJJL}6w)qiBA{#Vw;qxGqt`n&4iI%6ChA8D(KsDEWj zLL}U`N_MAOLbuglGoQlnxm9u$@2|P7o@eeUNvN5&F6@pqj;LhjzEbgDgRWN%tM4d7 z!ku4Qf%%qU^^|BJbTngKIJjPQOZ`*CX6LNHEZ~KJ#;>dkMBQD{#pW&Xb zvWI(xvEORBbv)@+UlD1%r8Zq5LOG|a0`1c;aaMy_Ga2(vd4 zkc-#DyfDX4h6=1rRvNIj^u}~=1J3pA+Rdd~Oc#LO>HfmyVR;bAt9b@WWnwPC$fF z*luMM1k^GziCTP4z$zf!%ftxiWwI73m@EMm_}pQW4YnD^@lt$FBGZiN1_aLqbTPo` zE(TaYE!HM!8XN)=75JP)7PtV14O{>L1Kg8zFZV=10~aWQ&xP^1(lkCd4Z%~1tm1PE zfF}YXT*g({5}JT(x?RmR70|^6KCI;e3uxkMr_qTEXyDSPTLs{4)%aW&1|ZL+cpJ}; zB`M7_Ig9eVhqI)c@Hqh+c#cp#5|F^>4r_V1{7~Q=PPbRh!__-4AIQQuUbkJ!!xs^I z0k>-he`Mo1{4RpMmA*+x;CIt{!KT>2?-p#iL$njn=|ZS5umM=KOAl<*2Mu^9%CL)X z!0!a;w`%3pB`qe!bni?Ml#9-L7dGDJ|BG+@QsCfP~h;@22rP+24TQMeIZA z<+uj$J6WIR91m%iKF4iNcmw%my&E9ssE@k=zZ<~sWXk~KB2%R&WKIT&Evpid5tA(% z)Z%wcr5?8%Or^}Lp2`j8b*~-2lP%TwUHS$Sucvo_Az!GrhkTXs-)_b4bRK@U(1hO! z=*92!4O$9Myi{MXlECp2?WH&#D7~{tyX!DLox$s+V#95fn4VPf+>7%5`w1^N#b)+z!L$(T*4%52~EKD+^pn!3h3bC?#uU_0QsIvp%WKS$7N47 z3&7hd@wpBzzB~uGUQoah?z%X&9J&P^Y09lq9wuSr%P;~`U|Ct^khhb^mm zKO-euG?4E&rcjU9HKtJJQxD!6^SLA6ak8ZnUrSwM!u7QFG1SpYd#IC)`(`t~rt|Q% zsC>r>=*HLdjajlj;~ep{SX&TJlgn0yq3w*yH=KRhy19$VKKX`|@TT0=Xh#`lX5ZCj z%#7PDxA~QYnI*aHJ2QQCLCj3VcA(gSVh4&HD0ZOOfno=W9r)lKu=tMqkiV0k zkRPOulLgq%@3oE``g-ZT72#BXtiP8c+zNOfHF)U1`x3khc(*5EqJNHEFqF%cb}sXn zi`aPW94au@%AHtn1-WT`tQJ^-4<)D60xLMX-ATxC{VYX6D~>vjfr8}DZg$jh4xA+^ zV8vO+IZ}Y!nXS$$Zjm!I`7gN1ILGqWJH69c!##4ECtvKY;u6hQ@bo?x3HQ)xqCBy? zh-)-Y#q4da3Le31ru>kHgnKwY$?RS33LepHs=Sbgf=4(n$*fHt0$$-Pu6%%(fM+}( z(UW^T1-ueYlI8L2MeiNYL-fQJZ+_2=6Kwt;J=qNs{Hy-B!+_p9`@w+RB*nMxn++!9COL2T{QlE~+bGAcu$^zjZIqN>0Y=njNqH4uMs1dr zPXT7k{_D*t#SRoZ MQ0zdl1I8WrKgw^W{Qv*} diff --git a/dist/macos/resources/universalJavaApplicationStub.sh b/dist/macos/universalJavaApplicationStub.sh similarity index 84% rename from dist/macos/resources/universalJavaApplicationStub.sh rename to dist/macos/universalJavaApplicationStub.sh index 2707ca9..c2dc186 100644 --- a/dist/macos/resources/universalJavaApplicationStub.sh +++ b/dist/macos/universalJavaApplicationStub.sh @@ -11,14 +11,14 @@ # # # @author Tobias Fischer # # @url https://github.com/tofi86/universalJavaApplicationStub # -# @date 2020-03-19 # -# @version 3.0.6 # +# @date 2021-02-21 # +# @version 3.2.0 # # # ################################################################################## # # # The MIT License (MIT) # # # -# Copyright (c) 2014-2020 Tobias Fischer # +# Copyright (c) 2014-2021 Tobias Fischer # # # # Permission is hereby granted, free of charge, to any person obtaining a copy # # of this software and associated documentation files (the "Software"), to deal # @@ -166,6 +166,8 @@ if [ $exitcode -eq 0 ]; then JavaFolder="${AppleJavaFolder}" ResourcesFolder="${AppleResourcesFolder}" + # set expandable variables + APP_ROOT="${AppPackageFolder}" APP_PACKAGE="${AppPackageFolder}" JAVAROOT="${AppleJavaFolder}" USER_HOME="$HOME" @@ -180,7 +182,7 @@ if [ $exitcode -eq 0 ]; then # AppPackageRoot is the standard WorkingDirectory when the script is started WorkingDirectory="${AppPackageRoot}" fi - # expand variables $APP_PACKAGE, $JAVAROOT, $USER_HOME + # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME WorkingDirectory=$(eval echo "${WorkingDirectory}") @@ -203,7 +205,7 @@ if [ $exitcode -eq 0 ]; then else JVMClassPath=${JVMClassPath_RAW} fi - # expand variables $APP_PACKAGE, $JAVAROOT, $USER_HOME + # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME JVMClassPath=$(eval echo "${JVMClassPath}") # read the JVM Options in either Array or String style @@ -213,6 +215,8 @@ if [ $exitcode -eq 0 ]; then else JVMDefaultOptions=${JVMDefaultOptions_RAW} fi + # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME (#84) + JVMDefaultOptions=$(eval echo "${JVMDefaultOptions}") # read StartOnMainThread and add as -XstartOnFirstThread JVMStartOnMainThread=$(plist_get_java ':StartOnMainThread') @@ -245,7 +249,11 @@ else ResourcesFolder="${OracleResourcesFolder}" WorkingDirectory="${OracleJavaFolder}" + # set expandable variables APP_ROOT="${AppPackageFolder}" + APP_PACKAGE="${AppPackageFolder}" + JAVAROOT="${OracleJavaFolder}" + USER_HOME="$HOME" # read the MainClass name JVMMainClass="$(plist_get ':JVMMainClassName')" @@ -263,12 +271,12 @@ else JVMClassPath_RAW=$(plist_get ':JVMClassPath') if [[ $JVMClassPath_RAW == *Array* ]] ; then JVMClassPath=.$(plist_get ':JVMClassPath' | grep " " | sed 's/^ */:/g' | tr -d '\n' | xargs) - # expand variables $APP_PACKAGE, $JAVAROOT, $USER_HOME + # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME JVMClassPath=$(eval echo "${JVMClassPath}") elif [[ ! -z ${JVMClassPath_RAW} ]] ; then JVMClassPath=${JVMClassPath_RAW} - # expand variables $APP_PACKAGE, $JAVAROOT, $USER_HOME + # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME JVMClassPath=$(eval echo "${JVMClassPath}") else @@ -277,8 +285,11 @@ else # Do NOT expand the default 'AppName.app/Contents/Java/*' classpath (#42) fi - # read the JVM Default Options + # read the JVM Default Options by parsing the :JVMDefaultOptions + # and pulling all values starting with a dash (-) JVMDefaultOptions=$(plist_get ':JVMDefaultOptions' | grep -o " \-.*" | tr -d '\n' | xargs) + # expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME (#99) + JVMDefaultOptions=$(eval echo "${JVMDefaultOptions}") # read the Main Arguments from JVMArguments key as an array and retain spaces (see #46 for naming details) IFS=$'\t\n' @@ -314,14 +325,14 @@ fi stub_logger "[JavaRequirement] JVM minimum version: ${JVMVersion}" stub_logger "[JavaRequirement] JVM maximum version: ${JVMMaxVersion}" -# MainArgs: replace occurences of $APP_ROOT with its content +# MainArgs: expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME MainArgsArr=() for i in "${MainArgs[@]}" do MainArgsArr+=("$(eval echo "$i")") done -# JVMOptions: replace occurences of $APP_ROOT with its content +# JVMOptions: expand variables $APP_PACKAGE, $APP_ROOT, $JAVAROOT, $USER_HOME JVMOptionsArr=() for i in "${JVMOptions[@]}" do @@ -332,11 +343,34 @@ done # internationalized messages ############################################ -LANG=$(defaults read -g AppleLocale) -stub_logger "[Language] $LANG" +# supported languages / available translations +stubLanguages="^(fr|de|zh|es|en)-" + +# read user preferred languages as defined in macOS System Preferences (#101) +stub_logger '[LanguageSearch] Checking preferred languages in macOS System Preferences...' +appleLanguages=($(defaults read -g AppleLanguages | grep '\s"' | tr -d ',' | xargs)) +stub_logger "[LanguageSearch] ... found [${appleLanguages[*]}]" + +language="" +for i in "${appleLanguages[@]}" +do + langValue="${i%-*}" + if [[ "$i" =~ $stubLanguages ]]; then + stub_logger "[LanguageSearch] ... selected '$i' ('$langValue') as the default language for the launcher stub" + language=${langValue} + break + fi +done +if [ -z "${language}" ]; then + language="en" + stub_logger "[LanguageSearch] ... selected fallback 'en' as the default language for the launcher stub" +fi +stub_logger "[Language] $language" + -# French localization -if [[ $LANG == fr* ]] ; then +case "${language}" in +# French +fr) MSG_ERROR_LAUNCHING="ERREUR au lancement de '${CFBundleName}'." MSG_MISSING_MAINCLASS="'MainClass' n'est pas spécifié.\nL'application Java ne peut pas être lancée." MSG_JVMVERSION_REQ_INVALID="La syntaxe de la version de Java demandée est invalide: %s\nVeuillez contacter le développeur de l'application." @@ -349,9 +383,10 @@ if [[ $LANG == fr* ]] ; then MSG_LATER="Plus tard" MSG_VISIT_JAVA_DOT_COM="Java by Oracle" MSG_VISIT_ADOPTOPENJDK="Java by AdoptOpenJDK" + ;; -# German localization -elif [[ $LANG == de* ]] ; then +# German +de) MSG_ERROR_LAUNCHING="FEHLER beim Starten von '${CFBundleName}'." MSG_MISSING_MAINCLASS="Die 'MainClass' ist nicht spezifiziert!\nDie Java-Anwendung kann nicht gestartet werden!" MSG_JVMVERSION_REQ_INVALID="Die Syntax der angeforderten Java-Version ist ungültig: %s\nBitte kontaktieren Sie den Entwickler der App." @@ -364,9 +399,10 @@ elif [[ $LANG == de* ]] ; then MSG_LATER="Später" MSG_VISIT_JAVA_DOT_COM="Java von Oracle" MSG_VISIT_ADOPTOPENJDK="Java von AdoptOpenJDK" + ;; -# Simplifyed Chinese localization -elif [[ $LANG == zh* ]] ; then +# Simplified Chinese +zh) MSG_ERROR_LAUNCHING="无法启动 '${CFBundleName}'." MSG_MISSING_MAINCLASS="没有指定 'MainClass'!\nJava程序无法启动!" MSG_JVMVERSION_REQ_INVALID="Java版本参数语法错误: %s\n请联系该应用的开发者。" @@ -379,9 +415,26 @@ elif [[ $LANG == zh* ]] ; then MSG_LATER="稍后" MSG_VISIT_JAVA_DOT_COM="Java by Oracle" MSG_VISIT_ADOPTOPENJDK="Java by AdoptOpenJDK" - -# English default localization -else + ;; + +# Spanish +es) + MSG_ERROR_LAUNCHING="ERROR iniciando '${CFBundleName}'." + MSG_MISSING_MAINCLASS="¡'MainClass' no especificada!\n¡La aplicación Java no puede iniciarse!" + MSG_JVMVERSION_REQ_INVALID="La sintaxis de la versión Java requerida no es válida: %s\nPor favor, contacte con el desarrollador de la aplicación." + MSG_NO_SUITABLE_JAVA="¡No se encontró una versión de Java adecuada en su sistema!\nEste programa requiere Java %s" + MSG_JAVA_VERSION_OR_LATER="o posterior" + MSG_JAVA_VERSION_LATEST="(ultima actualización)" + MSG_JAVA_VERSION_MAX="superior a %s" + MSG_NO_SUITABLE_JAVA_CHECK="Asegúrese de instalar la versión Java requerida." + MSG_INSTALL_JAVA="¡Necesita tener JAVA instalado en su Mac!\nVisite java.com para consultar las instrucciones para su instalación..." + MSG_LATER="Más tarde" + MSG_VISIT_JAVA_DOT_COM="Java de Oracle" + MSG_VISIT_ADOPTOPENJDK="Java de AdoptOpenJDK" + ;; + +# English | default +en|*) MSG_ERROR_LAUNCHING="ERROR launching '${CFBundleName}'." MSG_MISSING_MAINCLASS="'MainClass' isn't specified!\nJava application cannot be started!" MSG_JVMVERSION_REQ_INVALID="The syntax of the required Java version is invalid: %s\nPlease contact the App developer." @@ -394,7 +447,8 @@ else MSG_LATER="Later" MSG_VISIT_JAVA_DOT_COM="Java by Oracle" MSG_VISIT_ADOPTOPENJDK="Java by AdoptOpenJDK" -fi + ;; +esac @@ -510,20 +564,28 @@ if [ -n "$JAVA_HOME" ] ; then if [[ $JAVA_HOME == /* ]] ; then # if "$JAVA_HOME" starts with a Slash it's an absolute path JAVACMD="$JAVA_HOME/bin/java" + stub_logger "[JavaSearch] ... parsing JAVA_HOME as absolute path to the executable '$JAVACMD'" else # otherwise it's a relative path to "$AppPackageFolder" JAVACMD="$AppPackageFolder/$JAVA_HOME/bin/java" + stub_logger "[JavaSearch] ... parsing JAVA_HOME as relative path inside the App bundle to the executable '$JAVACMD'" fi JAVACMD_version=$(get_comparable_java_version $(get_java_version_from_cmd "${JAVACMD}")) else - stub_logger "[JavaSearch] ... didn't found JAVA_HOME" + stub_logger "[JavaSearch] ... haven't found JAVA_HOME" fi # check for any other or a specific Java version # also if $JAVA_HOME exists but isn't executable if [ -z "${JAVACMD}" ] || [ ! -x "${JAVACMD}" ] ; then - stub_logger "[JavaSearch] Checking for JavaVirtualMachines on the system ..." + + # add a warning in the syslog if JAVA_HOME is not executable or not found (#100) + if [ -n "$JAVA_HOME" ] ; then + stub_logger "[JavaSearch] ... but no 'java' executable was found at the JAVA_HOME location!" + fi + + stub_logger "[JavaSearch] Searching for JavaVirtualMachines on the system ..." # reset variables JAVACMD="" JAVACMD_version="" @@ -552,15 +614,41 @@ if [ -z "${JAVACMD}" ] || [ ! -x "${JAVACMD}" ] ; then # find installed JavaVirtualMachines (JDK + JRE) allJVMs=() - # read JDK's from '/usr/libexec/java_home -V' command - while read -r line; do - version=$(echo $line | awk -F $',' '{print $1;}') - path=$(echo $line | awk -F $'" ' '{print $2;}') - path+="/bin/java" - allJVMs+=("$version:$path") - done < <(/usr/libexec/java_home -V 2>&1 | grep '^[[:space:]]') - # unset while loop variables - unset version path + + # read JDK's from '/usr/libexec/java_home --xml' command with PlistBuddy and a custom Dict iterator + # idea: https://stackoverflow.com/a/14085460/1128689 and https://scriptingosx.com/2018/07/parsing-dscl-output-in-scripts/ + javaXml=$(/usr/libexec/java_home --xml) + javaCounter=$(/usr/libexec/PlistBuddy -c "Print" /dev/stdin <<< $javaXml | grep "Dict" | wc -l | tr -d ' ') + + # iterate over all Dict entries + # but only if there are any JVMs at all (#93) + if [ "$javaCounter" -gt "0" ] ; then + for idx in $(seq 0 $((javaCounter - 1))) + do + version=$(/usr/libexec/PlistBuddy -c "print :$idx:JVMVersion" /dev/stdin <<< $javaXml) + path=$(/usr/libexec/PlistBuddy -c "print :$idx:JVMHomePath" /dev/stdin <<< $javaXml) + path+="/bin/java" + allJVMs+=("$version:$path") + done + # unset for loop variables + unset version path + fi + + # add SDKMAN! java versions (#95) + if [ -d ~/.sdkman/candidates/java/ ] ; then + for sdkjdk in ~/.sdkman/candidates/java/*/ + do + if [[ ${sdkjdk} =~ /current/$ ]] ; then + continue + fi + + sdkjdkcmd="${sdkjdk}bin/java" + version=$(get_java_version_from_cmd "${sdkjdkcmd}") + allJVMs+=("$version:$sdkjdkcmd") + done + # unset for loop variables + unset version + fi # add Apple JRE if available if [ -x "${apple_jre_plugin}" ] ; then @@ -580,6 +668,9 @@ if [ -z "${JAVACMD}" ] || [ ! -x "${JAVACMD}" ] ; then # determine JVMs matching the min/max version requirement + + stub_logger "[JavaSearch] Filtering the result list for JVMs matching the min/max version requirement ..." + minC=$(get_comparable_java_version ${JVMVersion}) maxC=$(get_comparable_java_version ${JVMMaxVersion}) matchingJVMs=() @@ -664,7 +755,7 @@ if [ -z "${JAVACMD}" ] || [ ! -x "${JAVACMD}" ] ; then # debug output for i in "${matchingJVMs[@]}" do - stub_logger "[JavaSearch] ... ... matches all requirements: $i" + stub_logger "[JavaSearch] ... matches all requirements: $i" done @@ -784,14 +875,14 @@ stub_logger "[WorkingDirectory] ${WorkingDirectory}" # - main class # - main class arguments # - passthrough arguments from Terminal or Drag'n'Drop to Finder icon -stub_logger "[Exec] \"$JAVACMD\" -cp \"${JVMClassPath}\" -splash:\"${ResourcesFolder}/${JVMSplashFile}\" -Xdock:icon=\"${ResourcesFolder}/${CFBundleIconFile}\" -Xdock:name=\"${CFBundleName}\" ${JVMOptionsArr:+$(printf "'%s' " "${JVMOptionsArr[@]}") }${JVMDefaultOptions:+$JVMDefaultOptions }${JVMMainClass}${MainArgsArr:+ $(printf "'%s' " "${MainArgsArr[@]}")}${ArgsPassthru:+ $(printf "'%s' " "${ArgsPassthru[@]}")}" +stub_logger "[Exec] \"$JAVACMD\" -cp \"${JVMClassPath}\" ${JVMSplashFile:+ -splash:\"${ResourcesFolder}/${JVMSplashFile}\"} -Xdock:icon=\"${ResourcesFolder}/${CFBundleIconFile}\" -Xdock:name=\"${CFBundleName}\" ${JVMOptionsArr:+$(printf "'%s' " "${JVMOptionsArr[@]}") }${JVMDefaultOptions:+$JVMDefaultOptions }${JVMMainClass}${MainArgsArr:+ $(printf "'%s' " "${MainArgsArr[@]}")}${ArgsPassthru:+ $(printf "'%s' " "${ArgsPassthru[@]}")}" exec "${JAVACMD}" \ -cp "${JVMClassPath}" \ - -splash:"${ResourcesFolder}/${JVMSplashFile}" \ + ${JVMSplashFile:+ -splash:"${ResourcesFolder}/${JVMSplashFile}"} \ -Xdock:icon="${ResourcesFolder}/${CFBundleIconFile}" \ -Xdock:name="${CFBundleName}" \ ${JVMOptionsArr:+"${JVMOptionsArr[@]}" }\ ${JVMDefaultOptions:+$JVMDefaultOptions }\ "${JVMMainClass}"\ ${MainArgsArr:+ "${MainArgsArr[@]}"}\ - ${ArgsPassthru:+ "${ArgsPassthru[@]}"} \ No newline at end of file + ${ArgsPassthru:+ "${ArgsPassthru[@]}"} diff --git a/src/main/resources/logisim/img/logisim-icon.ico b/dist/windows/Logisim.ico similarity index 100% rename from src/main/resources/logisim/img/logisim-icon.ico rename to dist/windows/Logisim.ico diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 87b738cbd051603d91cc39de6cb000dd98fe6b02..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 55190 zcmafaW0WS*vSoFbZQHhO+s0S6%`V%vZQJa!ZQHKus_B{g-pt%P_q|ywBQt-*Stldc z$+IJ3?^KWm27v+sf`9-50uuadKtMnL*BJ;1^6ynvR7H?hQcjE>7)art9Bu0Pcm@7C z@c%WG|JzYkP)<@zR9S^iR_sA`azaL$mTnGKnwDyMa;8yL_0^>Ba^)phg0L5rOPTbm7g*YIRLg-2^{qe^`rb!2KqS zk~5wEJtTdD?)3+}=eby3x6%i)sb+m??NHC^u=tcG8p$TzB<;FL(WrZGV&cDQb?O0GMe6PBV=V z?tTO*5_HTW$xea!nkc~Cnx#cL_rrUGWPRa6l+A{aiMY=<0@8y5OC#UcGeE#I>nWh}`#M#kIn-$A;q@u-p71b#hcSItS!IPw?>8 zvzb|?@Ahb22L(O4#2Sre&l9H(@TGT>#Py)D&eW-LNb!=S;I`ZQ{w;MaHW z#to!~TVLgho_Pm%zq@o{K3Xq?I|MVuVSl^QHnT~sHlrVxgsqD-+YD?Nz9@HA<;x2AQjxP)r6Femg+LJ-*)k%EZ}TTRw->5xOY z9#zKJqjZgC47@AFdk1$W+KhTQJKn7e>A&?@-YOy!v_(}GyV@9G#I?bsuto4JEp;5|N{orxi_?vTI4UF0HYcA( zKyGZ4<7Fk?&LZMQb6k10N%E*$gr#T&HsY4SPQ?yerqRz5c?5P$@6dlD6UQwZJ*Je9 z7n-@7!(OVdU-mg@5$D+R%gt82Lt%&n6Yr4=|q>XT%&^z_D*f*ug8N6w$`woqeS-+#RAOfSY&Rz z?1qYa5xi(7eTCrzCFJfCxc%j{J}6#)3^*VRKF;w+`|1n;Xaojr2DI{!<3CaP`#tXs z*`pBQ5k@JLKuCmovFDqh_`Q;+^@t_;SDm29 zCNSdWXbV?9;D4VcoV`FZ9Ggrr$i<&#Dx3W=8>bSQIU_%vf)#(M2Kd3=rN@^d=QAtC zI-iQ;;GMk|&A++W5#hK28W(YqN%?!yuW8(|Cf`@FOW5QbX|`97fxmV;uXvPCqxBD zJ9iI37iV)5TW1R+fV16y;6}2tt~|0J3U4E=wQh@sx{c_eu)t=4Yoz|%Vp<#)Qlh1V z0@C2ZtlT>5gdB6W)_bhXtcZS)`9A!uIOa`K04$5>3&8An+i9BD&GvZZ=7#^r=BN=k za+=Go;qr(M)B~KYAz|<^O3LJON}$Q6Yuqn8qu~+UkUKK~&iM%pB!BO49L+?AL7N7o z(OpM(C-EY753=G=WwJHE`h*lNLMNP^c^bBk@5MyP5{v7x>GNWH>QSgTe5 z!*GPkQ(lcbEs~)4ovCu!Zt&$${9$u(<4@9%@{U<-ksAqB?6F`bQ;o-mvjr)Jn7F&j$@`il1Mf+-HdBs<-`1FahTxmPMMI)@OtI&^mtijW6zGZ67O$UOv1Jj z;a3gmw~t|LjPkW3!EZ=)lLUhFzvO;Yvj9g`8hm%6u`;cuek_b-c$wS_0M4-N<@3l|88 z@V{Sd|M;4+H6guqMm4|v=C6B7mlpP(+It%0E;W`dxMOf9!jYwWj3*MRk`KpS_jx4c z=hrKBkFK;gq@;wUV2eqE3R$M+iUc+UD0iEl#-rECK+XmH9hLKrC={j@uF=f3UiceB zU5l$FF7#RKjx+6!JHMG5-!@zI-eG=a-!Bs^AFKqN_M26%cIIcSs61R$yuq@5a3c3& z4%zLs!g}+C5%`ja?F`?5-og0lv-;(^e<`r~p$x%&*89_Aye1N)9LNVk?9BwY$Y$$F^!JQAjBJvywXAesj7lTZ)rXuxv(FFNZVknJha99lN=^h`J2> zl5=~(tKwvHHvh|9-41@OV`c;Ws--PE%{7d2sLNbDp;A6_Ka6epzOSFdqb zBa0m3j~bT*q1lslHsHqaHIP%DF&-XMpCRL(v;MV#*>mB^&)a=HfLI7efblG z(@hzN`|n+oH9;qBklb=d^S0joHCsArnR1-h{*dIUThik>ot^!6YCNjg;J_i3h6Rl0ji)* zo(tQ~>xB!rUJ(nZjCA^%X;)H{@>uhR5|xBDA=d21p@iJ!cH?+%U|VSh2S4@gv`^)^ zNKD6YlVo$%b4W^}Rw>P1YJ|fTb$_(7C;hH+ z1XAMPb6*p^h8)e5nNPKfeAO}Ik+ZN_`NrADeeJOq4Ak;sD~ zTe77no{Ztdox56Xi4UE6S7wRVxJzWxKj;B%v7|FZ3cV9MdfFp7lWCi+W{}UqekdpH zdO#eoOuB3Fu!DU`ErfeoZWJbWtRXUeBzi zBTF-AI7yMC^ntG+8%mn(I6Dw}3xK8v#Ly{3w3_E?J4(Q5JBq~I>u3!CNp~Ekk&YH` z#383VO4O42NNtcGkr*K<+wYZ>@|sP?`AQcs5oqX@-EIqgK@Pmp5~p6O6qy4ml~N{D z{=jQ7k(9!CM3N3Vt|u@%ssTw~r~Z(}QvlROAkQQ?r8OQ3F0D$aGLh zny+uGnH5muJ<67Z=8uilKvGuANrg@s3Vu_lU2ajb?rIhuOd^E@l!Kl0hYIxOP1B~Q zggUmXbh$bKL~YQ#!4fos9UUVG#}HN$lIkM<1OkU@r>$7DYYe37cXYwfK@vrHwm;pg zbh(hEU|8{*d$q7LUm+x&`S@VbW*&p-sWrplWnRM|I{P;I;%U`WmYUCeJhYc|>5?&& zj}@n}w~Oo=l}iwvi7K6)osqa;M8>fRe}>^;bLBrgA;r^ZGgY@IC^ioRmnE&H4)UV5 zO{7egQ7sBAdoqGsso5q4R(4$4Tjm&&C|7Huz&5B0wXoJzZzNc5Bt)=SOI|H}+fbit z-PiF5(NHSy>4HPMrNc@SuEMDuKYMQ--G+qeUPqO_9mOsg%1EHpqoX^yNd~~kbo`cH zlV0iAkBFTn;rVb>EK^V6?T~t~3vm;csx+lUh_%ROFPy0(omy7+_wYjN!VRDtwDu^h4n|xpAMsLepm% zggvs;v8+isCW`>BckRz1MQ=l>K6k^DdT`~sDXTWQ<~+JtY;I~I>8XsAq3yXgxe>`O zZdF*{9@Z|YtS$QrVaB!8&`&^W->_O&-JXn1n&~}o3Z7FL1QE5R*W2W@=u|w~7%EeC1aRfGtJWxImfY-D3t!!nBkWM> zafu>^Lz-ONgT6ExjV4WhN!v~u{lt2-QBN&UxwnvdH|I%LS|J-D;o>@@sA62@&yew0 z)58~JSZP!(lX;da!3`d)D1+;K9!lyNlkF|n(UduR-%g>#{`pvrD^ClddhJyfL7C-(x+J+9&7EsC~^O`&}V%)Ut8^O_7YAXPDpzv8ir4 zl`d)(;imc6r16k_d^)PJZ+QPxxVJS5e^4wX9D=V2zH&wW0-p&OJe=}rX`*->XT=;_qI&)=WHkYnZx6bLoUh_)n-A}SF_ z9z7agNTM5W6}}ui=&Qs@pO5$zHsOWIbd_&%j^Ok5PJ3yUWQw*i4*iKO)_er2CDUME ztt+{Egod~W-fn^aLe)aBz)MOc_?i-stTj}~iFk7u^-gGSbU;Iem06SDP=AEw9SzuF zeZ|hKCG3MV(z_PJg0(JbqTRf4T{NUt%kz&}4S`)0I%}ZrG!jgW2GwP=WTtkWS?DOs znI9LY!dK+1_H0h+i-_~URb^M;4&AMrEO_UlDV8o?E>^3x%ZJyh$JuDMrtYL8|G3If zPf2_Qb_W+V?$#O; zydKFv*%O;Y@o_T_UAYuaqx1isMKZ^32JtgeceA$0Z@Ck0;lHbS%N5)zzAW9iz; z8tTKeK7&qw!8XVz-+pz>z-BeIzr*#r0nB^cntjQ9@Y-N0=e&ZK72vlzX>f3RT@i7@ z=z`m7jNk!9%^xD0ug%ptZnM>F;Qu$rlwo}vRGBIymPL)L|x}nan3uFUw(&N z24gdkcb7!Q56{0<+zu zEtc5WzG2xf%1<@vo$ZsuOK{v9gx^0`gw>@h>ZMLy*h+6ueoie{D#}}` zK2@6Xxq(uZaLFC%M!2}FX}ab%GQ8A0QJ?&!vaI8Gv=vMhd);6kGguDmtuOElru()) zuRk&Z{?Vp!G~F<1#s&6io1`poBqpRHyM^p;7!+L??_DzJ8s9mYFMQ0^%_3ft7g{PD zZd}8E4EV}D!>F?bzcX=2hHR_P`Xy6?FOK)mCj)Ym4s2hh z0OlOdQa@I;^-3bhB6mpw*X5=0kJv8?#XP~9){G-+0ST@1Roz1qi8PhIXp1D$XNqVG zMl>WxwT+K`SdO1RCt4FWTNy3!i?N>*-lbnn#OxFJrswgD7HjuKpWh*o@QvgF&j+CT z{55~ZsUeR1aB}lv#s_7~+9dCix!5(KR#c?K?e2B%P$fvrsZxy@GP#R#jwL{y#Ld$} z7sF>QT6m|}?V;msb?Nlohj7a5W_D$y+4O6eI;Zt$jVGymlzLKscqer9#+p2$0It&u zWY!dCeM6^B^Z;ddEmhi?8`scl=Lhi7W%2|pT6X6^%-=q90DS(hQ-%c+E*ywPvmoF(KqDoW4!*gmQIklm zk#!GLqv|cs(JRF3G?=AYY19{w@~`G3pa z@xR9S-Hquh*&5Yas*VI};(%9%PADn`kzm zeWMJVW=>>wap*9|R7n#!&&J>gq04>DTCMtj{P^d12|2wXTEKvSf?$AvnE!peqV7i4 zE>0G%CSn%WCW1yre?yi9*aFP{GvZ|R4JT}M%x_%Hztz2qw?&28l&qW<6?c6ym{f$d z5YCF+k#yEbjCN|AGi~-NcCG8MCF1!MXBFL{#7q z)HO+WW173?kuI}^Xat;Q^gb4Hi0RGyB}%|~j8>`6X4CPo+|okMbKy9PHkr58V4bX6<&ERU)QlF8%%huUz&f+dwTN|tk+C&&o@Q1RtG`}6&6;ncQuAcfHoxd5AgD7`s zXynq41Y`zRSiOY@*;&1%1z>oNcWTV|)sjLg1X8ijg1Y zbIGL0X*Sd}EXSQ2BXCKbJmlckY(@EWn~Ut2lYeuw1wg?hhj@K?XB@V_ZP`fyL~Yd3n3SyHU-RwMBr6t-QWE5TinN9VD4XVPU; zonIIR!&pGqrLQK)=#kj40Im%V@ij0&Dh0*s!lnTw+D`Dt-xmk-jmpJv$1-E-vfYL4 zqKr#}Gm}~GPE+&$PI@4ag@=M}NYi7Y&HW82Q`@Y=W&PE31D110@yy(1vddLt`P%N^ z>Yz195A%tnt~tvsSR2{m!~7HUc@x<&`lGX1nYeQUE(%sphTi>JsVqSw8xql*Ys@9B z>RIOH*rFi*C`ohwXjyeRBDt8p)-u{O+KWP;$4gg||%*u{$~yEj+Al zE(hAQRQ1k7MkCq9s4^N3ep*$h^L%2Vq?f?{+cicpS8lo)$Cb69b98au+m2J_e7nYwID0@`M9XIo1H~|eZFc8Hl!qly612ADCVpU zY8^*RTMX(CgehD{9v|^9vZ6Rab`VeZ2m*gOR)Mw~73QEBiktViBhR!_&3l$|be|d6 zupC`{g89Y|V3uxl2!6CM(RNpdtynaiJ~*DqSTq9Mh`ohZnb%^3G{k;6%n18$4nAqR zjPOrP#-^Y9;iw{J@XH9=g5J+yEVh|e=4UeY<^65`%gWtdQ=-aqSgtywM(1nKXh`R4 zzPP&7r)kv_uC7X9n=h=!Zrf<>X=B5f<9~Q>h#jYRD#CT7D~@6@RGNyO-#0iq0uHV1 zPJr2O4d_xLmg2^TmG7|dpfJ?GGa`0|YE+`2Rata9!?$j#e9KfGYuLL(*^z z!SxFA`$qm)q-YKh)WRJZ@S+-sD_1E$V?;(?^+F3tVcK6 z2fE=8hV*2mgiAbefU^uvcM?&+Y&E}vG=Iz!%jBF7iv){lyC`)*yyS~D8k+Mx|N3bm zI~L~Z$=W9&`x)JnO;8c>3LSDw!fzN#X3qi|0`sXY4?cz{*#xz!kvZ9bO=K3XbN z5KrgN=&(JbXH{Wsu9EdmQ-W`i!JWEmfI;yVTT^a-8Ch#D8xf2dtyi?7p z%#)W3n*a#ndFpd{qN|+9Jz++AJQO#-Y7Z6%*%oyEP5zs}d&kKIr`FVEY z;S}@d?UU=tCdw~EJ{b}=9x}S2iv!!8<$?d7VKDA8h{oeD#S-$DV)-vPdGY@x08n)@ zag?yLF_E#evvRTj4^CcrLvBL=fft&@HOhZ6Ng4`8ijt&h2y}fOTC~7GfJi4vpomA5 zOcOM)o_I9BKz}I`q)fu+Qnfy*W`|mY%LO>eF^a z;$)?T4F-(X#Q-m}!-k8L_rNPf`Mr<9IWu)f&dvt=EL+ESYmCvErd@8B9hd)afc(ZL94S z?rp#h&{7Ah5IJftK4VjATklo7@hm?8BX*~oBiz)jyc9FuRw!-V;Uo>p!CWpLaIQyt zAs5WN)1CCeux-qiGdmbIk8LR`gM+Qg=&Ve}w?zA6+sTL)abU=-cvU`3E?p5$Hpkxw znu0N659qR=IKnde*AEz_7z2pdi_Bh-sb3b=PdGO1Pdf_q2;+*Cx9YN7p_>rl``knY zRn%aVkcv1(W;`Mtp_DNOIECtgq%ufk-mu_<+Fu3Q17Tq4Rr(oeq)Yqk_CHA7LR@7@ zIZIDxxhS&=F2IQfusQ+Nsr%*zFK7S4g!U0y@3H^Yln|i;0a5+?RPG;ZSp6Tul>ezM z`40+516&719qT)mW|ArDSENle5hE2e8qY+zfeZoy12u&xoMgcP)4=&P-1Ib*-bAy` zlT?>w&B|ei-rCXO;sxo7*G;!)_p#%PAM-?m$JP(R%x1Hfas@KeaG%LO?R=lmkXc_MKZW}3f%KZ*rAN?HYvbu2L$ zRt_uv7~-IejlD1x;_AhwGXjB94Q=%+PbxuYzta*jw?S&%|qb=(JfJ?&6P=R7X zV%HP_!@-zO*zS}46g=J}#AMJ}rtWBr21e6hOn&tEmaM%hALH7nlm2@LP4rZ>2 zebe5aH@k!e?ij4Zwak#30|}>;`bquDQK*xmR=zc6vj0yuyC6+U=LusGnO3ZKFRpen z#pwzh!<+WBVp-!$MAc<0i~I%fW=8IO6K}bJ<-Scq>e+)951R~HKB?Mx2H}pxPHE@} zvqpq5j81_jtb_WneAvp<5kgdPKm|u2BdQx9%EzcCN&U{l+kbkhmV<1}yCTDv%&K^> zg;KCjwh*R1f_`6`si$h6`jyIKT7rTv5#k~x$mUyIw)_>Vr)D4fwIs@}{FSX|5GB1l z4vv;@oS@>Bu7~{KgUa_8eg#Lk6IDT2IY$41$*06{>>V;Bwa(-@N;ex4;D`(QK*b}{ z{#4$Hmt)FLqERgKz=3zXiV<{YX6V)lvYBr3V>N6ajeI~~hGR5Oe>W9r@sg)Na(a4- zxm%|1OKPN6^%JaD^^O~HbLSu=f`1px>RawOxLr+1b2^28U*2#h*W^=lSpSY4(@*^l z{!@9RSLG8Me&RJYLi|?$c!B0fP=4xAM4rerxX{xy{&i6=AqXueQAIBqO+pmuxy8Ib z4X^}r!NN3-upC6B#lt7&x0J;)nb9O~xjJMemm$_fHuP{DgtlU3xiW0UesTzS30L+U zQzDI3p&3dpONhd5I8-fGk^}@unluzu%nJ$9pzoO~Kk!>dLxw@M)M9?pNH1CQhvA`z zV;uacUtnBTdvT`M$1cm9`JrT3BMW!MNVBy%?@ZX%;(%(vqQAz<7I!hlDe|J3cn9=} zF7B;V4xE{Ss76s$W~%*$JviK?w8^vqCp#_G^jN0j>~Xq#Zru26e#l3H^{GCLEXI#n z?n~F-Lv#hU(bZS`EI9(xGV*jT=8R?CaK)t8oHc9XJ;UPY0Hz$XWt#QyLBaaz5+}xM zXk(!L_*PTt7gwWH*HLWC$h3Ho!SQ-(I||nn_iEC{WT3S{3V{8IN6tZ1C+DiFM{xlI zeMMk{o5;I6UvaC)@WKp9D+o?2Vd@4)Ue-nYci()hCCsKR`VD;hr9=vA!cgGL%3k^b(jADGyPi2TKr(JNh8mzlIR>n(F_hgiV(3@Ds(tjbNM7GoZ;T|3 zWzs8S`5PrA!9){jBJuX4y`f<4;>9*&NY=2Sq2Bp`M2(fox7ZhIDe!BaQUb@P(ub9D zlP8!p(AN&CwW!V&>H?yPFMJ)d5x#HKfwx;nS{Rr@oHqpktOg)%F+%1#tsPtq7zI$r zBo-Kflhq-=7_eW9B2OQv=@?|y0CKN77)N;z@tcg;heyW{wlpJ1t`Ap!O0`Xz{YHqO zI1${8Hag^r!kA<2_~bYtM=<1YzQ#GGP+q?3T7zYbIjN6Ee^V^b&9en$8FI*NIFg9G zPG$OXjT0Ku?%L7fat8Mqbl1`azf1ltmKTa(HH$Dqlav|rU{zP;Tbnk-XkGFQ6d+gi z-PXh?_kEJl+K98&OrmzgPIijB4!Pozbxd0H1;Usy!;V>Yn6&pu*zW8aYx`SC!$*ti zSn+G9p=~w6V(fZZHc>m|PPfjK6IN4(o=IFu?pC?+`UZAUTw!e`052{P=8vqT^(VeG z=psASIhCv28Y(;7;TuYAe>}BPk5Qg=8$?wZj9lj>h2kwEfF_CpK=+O6Rq9pLn4W)# zeXCKCpi~jsfqw7Taa0;!B5_C;B}e56W1s8@p*)SPzA;Fd$Slsn^=!_&!mRHV*Lmt| zBGIDPuR>CgS4%cQ4wKdEyO&Z>2aHmja;Pz+n|7(#l%^2ZLCix%>@_mbnyPEbyrHaz z>j^4SIv;ZXF-Ftzz>*t4wyq)ng8%0d;(Z_ExZ-cxwei=8{(br-`JYO(f23Wae_MqE z3@{Mlf^%M5G1SIN&en1*| zH~ANY1h3&WNsBy$G9{T=`kcxI#-X|>zLX2r*^-FUF+m0{k)n#GTG_mhG&fJfLj~K& zU~~6othMlvMm9<*SUD2?RD+R17|Z4mgR$L*R3;nBbo&Vm@39&3xIg;^aSxHS>}gwR zmzs?h8oPnNVgET&dx5^7APYx6Vv6eou07Zveyd+^V6_LzI$>ic+pxD_8s~ zC<}ucul>UH<@$KM zT4oI=62M%7qQO{}re-jTFqo9Z;rJKD5!X5$iwUsh*+kcHVhID08MB5cQD4TBWB(rI zuWc%CA}}v|iH=9gQ?D$1#Gu!y3o~p7416n54&Hif`U-cV?VrUMJyEqo_NC4#{puzU zzXEE@UppeeRlS9W*^N$zS`SBBi<@tT+<%3l@KhOy^%MWB9(A#*J~DQ;+MK*$rxo6f zcx3$3mcx{tly!q(p2DQrxcih|)0do_ZY77pyHGE#Q(0k*t!HUmmMcYFq%l$-o6%lS zDb49W-E?rQ#Hl``C3YTEdGZjFi3R<>t)+NAda(r~f1cT5jY}s7-2^&Kvo&2DLTPYP zhVVo-HLwo*vl83mtQ9)PR#VBg)FN}+*8c-p8j`LnNUU*Olm1O1Qqe62D#$CF#?HrM zy(zkX|1oF}Z=T#3XMLWDrm(|m+{1&BMxHY7X@hM_+cV$5-t!8HT(dJi6m9{ja53Yw z3f^`yb6Q;(e|#JQIz~B*=!-GbQ4nNL-NL z@^NWF_#w-Cox@h62;r^;Y`NX8cs?l^LU;5IWE~yvU8TqIHij!X8ydbLlT0gwmzS9} z@5BccG?vO;rvCs$mse1*ANi-cYE6Iauz$Fbn3#|ToAt5v7IlYnt6RMQEYLldva{~s zvr>1L##zmeoYgvIXJ#>bbuCVuEv2ZvZ8I~PQUN3wjP0UC)!U+wn|&`V*8?)` zMSCuvnuGec>QL+i1nCPGDAm@XSMIo?A9~C?g2&G8aNKjWd2pDX{qZ?04+2 zeyLw}iEd4vkCAWwa$ zbrHlEf3hfN7^1g~aW^XwldSmx1v~1z(s=1az4-wl} z`mM+G95*N*&1EP#u3}*KwNrPIgw8Kpp((rdEOO;bT1;6ea~>>sK+?!;{hpJ3rR<6UJb`O8P4@{XGgV%63_fs%cG8L zk9Fszbdo4tS$g0IWP1>t@0)E%-&9yj%Q!fiL2vcuL;90fPm}M==<>}Q)&sp@STFCY z^p!RzmN+uXGdtPJj1Y-khNyCb6Y$Vs>eZyW zPaOV=HY_T@FwAlleZCFYl@5X<<7%5DoO(7S%Lbl55?{2vIr_;SXBCbPZ(up;pC6Wx={AZL?shYOuFxLx1*>62;2rP}g`UT5+BHg(ju z&7n5QSvSyXbioB9CJTB#x;pexicV|9oaOpiJ9VK6EvKhl4^Vsa(p6cIi$*Zr0UxQ z;$MPOZnNae2Duuce~7|2MCfhNg*hZ9{+8H3?ts9C8#xGaM&sN;2lriYkn9W>&Gry! z3b(Xx1x*FhQkD-~V+s~KBfr4M_#0{`=Yrh90yj}Ph~)Nx;1Y^8<418tu!$1<3?T*~ z7Dl0P3Uok-7w0MPFQexNG1P5;y~E8zEvE49>$(f|XWtkW2Mj`udPn)pb%} zrA%wRFp*xvDgC767w!9`0vx1=q!)w!G+9(-w&p*a@WXg{?T&%;qaVcHo>7ca%KX$B z^7|KBPo<2;kM{2mRnF8vKm`9qGV%|I{y!pKm8B(q^2V;;x2r!1VJ^Zz8bWa)!-7a8 zSRf@dqEPlsj!7}oNvFFAA)75})vTJUwQ03hD$I*j6_5xbtd_JkE2`IJD_fQ;a$EkO z{fQ{~e%PKgPJsD&PyEvDmg+Qf&p*-qu!#;1k2r_(H72{^(Z)htgh@F?VIgK#_&eS- z$~(qInec>)XIkv@+{o6^DJLpAb>!d}l1DK^(l%#OdD9tKK6#|_R?-%0V!`<9Hj z3w3chDwG*SFte@>Iqwq`J4M&{aHXzyigT620+Vf$X?3RFfeTcvx_e+(&Q*z)t>c0e zpZH$1Z3X%{^_vylHVOWT6tno=l&$3 z9^eQ@TwU#%WMQaFvaYp_we%_2-9=o{+ck zF{cKJCOjpW&qKQquyp2BXCAP920dcrZ}T1@piukx_NY;%2W>@Wca%=Ch~x5Oj58Hv z;D-_ALOZBF(Mqbcqjd}P3iDbek#Dwzu`WRs`;hRIr*n0PV7vT+%Io(t}8KZ zpp?uc2eW!v28ipep0XNDPZt7H2HJ6oey|J3z!ng#1H~x_k%35P+Cp%mqXJ~cV0xdd z^4m5^K_dQ^Sg?$P`))ccV=O>C{Ds(C2WxX$LMC5vy=*44pP&)X5DOPYfqE${)hDg< z3hcG%U%HZ39=`#Ko4Uctg&@PQLf>?0^D|4J(_1*TFMOMB!Vv1_mnOq$BzXQdOGqgy zOp#LBZ!c>bPjY1NTXksZmbAl0A^Y&(%a3W-k>bE&>K?px5Cm%AT2E<&)Y?O*?d80d zgI5l~&Mve;iXm88Q+Fw7{+`PtN4G7~mJWR^z7XmYQ>uoiV!{tL)hp|= zS(M)813PM`d<501>{NqaPo6BZ^T{KBaqEVH(2^Vjeq zgeMeMpd*1tE@@);hGjuoVzF>Cj;5dNNwh40CnU+0DSKb~GEMb_# zT8Z&gz%SkHq6!;_6dQFYE`+b`v4NT7&@P>cA1Z1xmXy<2htaDhm@XXMp!g($ zw(7iFoH2}WR`UjqjaqOQ$ecNt@c|K1H1kyBArTTjLp%-M`4nzOhkfE#}dOpcd;b#suq8cPJ&bf5`6Tq>ND(l zib{VrPZ>{KuaIg}Y$W>A+nrvMg+l4)-@2jpAQ5h(Tii%Ni^-UPVg{<1KGU2EIUNGaXcEkOedJOusFT9X3%Pz$R+-+W+LlRaY-a$5r?4V zbPzgQl22IPG+N*iBRDH%l{Zh$fv9$RN1sU@Hp3m=M}{rX%y#;4(x1KR2yCO7Pzo>rw(67E{^{yUR`91nX^&MxY@FwmJJbyPAoWZ9Z zcBS$r)&ogYBn{DOtD~tIVJUiq|1foX^*F~O4hlLp-g;Y2wKLLM=?(r3GDqsPmUo*? zwKMEi*%f)C_@?(&&hk>;m07F$X7&i?DEK|jdRK=CaaNu-)pX>n3}@%byPKVkpLzBq z{+Py&!`MZ^4@-;iY`I4#6G@aWMv{^2VTH7|WF^u?3vsB|jU3LgdX$}=v7#EHRN(im zI(3q-eU$s~r=S#EWqa_2!G?b~ z<&brq1vvUTJH380=gcNntZw%7UT8tLAr-W49;9y^=>TDaTC|cKA<(gah#2M|l~j)w zY8goo28gj$n&zcNgqX1Qn6=<8?R0`FVO)g4&QtJAbW3G#D)uNeac-7cH5W#6i!%BH z=}9}-f+FrtEkkrQ?nkoMQ1o-9_b+&=&C2^h!&mWFga#MCrm85hW;)1pDt;-uvQG^D zntSB?XA*0%TIhtWDS!KcI}kp3LT>!(Nlc(lQN?k^bS8Q^GGMfo}^|%7s;#r+pybl@?KA++|FJ zr%se9(B|g*ERQU96az%@4gYrxRRxaM2*b}jNsG|0dQi;Rw{0WM0E>rko!{QYAJJKY z)|sX0N$!8d9E|kND~v|f>3YE|uiAnqbkMn)hu$if4kUkzKqoNoh8v|S>VY1EKmgO} zR$0UU2o)4i4yc1inx3}brso+sio{)gfbLaEgLahj8(_Z#4R-v) zglqwI%`dsY+589a8$Mu7#7_%kN*ekHupQ#48DIN^uhDxblDg3R1yXMr^NmkR z7J_NWCY~fhg}h!_aXJ#?wsZF$q`JH>JWQ9`jbZzOBpS`}-A$Vgkq7+|=lPx9H7QZG z8i8guMN+yc4*H*ANr$Q-3I{FQ-^;8ezWS2b8rERp9TMOLBxiG9J*g5=?h)mIm3#CGi4JSq1ohFrcrxx@`**K5%T}qbaCGldV!t zVeM)!U3vbf5FOy;(h08JnhSGxm)8Kqxr9PsMeWi=b8b|m_&^@#A3lL;bVKTBx+0v8 zLZeWAxJ~N27lsOT2b|qyp$(CqzqgW@tyy?CgwOe~^i;ZH zlL``i4r!>i#EGBNxV_P@KpYFQLz4Bdq{#zA&sc)*@7Mxsh9u%e6Ke`?5Yz1jkTdND zR8!u_yw_$weBOU}24(&^Bm|(dSJ(v(cBct}87a^X(v>nVLIr%%D8r|&)mi+iBc;B;x;rKq zd8*X`r?SZsTNCPQqoFOrUz8nZO?225Z#z(B!4mEp#ZJBzwd7jW1!`sg*?hPMJ$o`T zR?KrN6OZA1H{9pA;p0cSSu;@6->8aJm1rrO-yDJ7)lxuk#npUk7WNER1Wwnpy%u zF=t6iHzWU(L&=vVSSc^&D_eYP3TM?HN!Tgq$SYC;pSIPWW;zeNm7Pgub#yZ@7WPw#f#Kl)W4%B>)+8%gpfoH1qZ;kZ*RqfXYeGXJ_ zk>2otbp+1By`x^1V!>6k5v8NAK@T;89$`hE0{Pc@Q$KhG0jOoKk--Qx!vS~lAiypV zCIJ&6B@24`!TxhJ4_QS*S5;;Pk#!f(qIR7*(c3dN*POKtQe)QvR{O2@QsM%ujEAWEm) z+PM=G9hSR>gQ`Bv2(k}RAv2+$7qq(mU`fQ+&}*i%-RtSUAha>70?G!>?w%F(b4k!$ zvm;E!)2`I?etmSUFW7WflJ@8Nx`m_vE2HF#)_BiD#FaNT|IY@!uUbd4v$wTglIbIX zblRy5=wp)VQzsn0_;KdM%g<8@>#;E?vypTf=F?3f@SSdZ;XpX~J@l1;p#}_veWHp>@Iq_T z@^7|h;EivPYv1&u0~l9(a~>dV9Uw10QqB6Dzu1G~-l{*7IktljpK<_L8m0|7VV_!S zRiE{u97(%R-<8oYJ{molUd>vlGaE-C|^<`hppdDz<7OS13$#J zZ+)(*rZIDSt^Q$}CRk0?pqT5PN5TT`Ya{q(BUg#&nAsg6apPMhLTno!SRq1e60fl6GvpnwDD4N> z9B=RrufY8+g3_`@PRg+(+gs2(bd;5#{uTZk96CWz#{=&h9+!{_m60xJxC%r&gd_N! z>h5UzVX%_7@CUeAA1XFg_AF%(uS&^1WD*VPS^jcC!M2v@RHZML;e(H-=(4(3O&bX- zI6>usJOS+?W&^S&DL{l|>51ZvCXUKlH2XKJPXnHjs*oMkNM#ZDLx!oaM5(%^)5XaP zk6&+P16sA>vyFe9v`Cp5qnbE#r#ltR5E+O3!WnKn`56Grs2;sqr3r# zp@Zp<^q`5iq8OqOlJ`pIuyK@3zPz&iJ0Jcc`hDQ1bqos2;}O|$i#}e@ua*x5VCSx zJAp}+?Hz++tm9dh3Fvm_bO6mQo38al#>^O0g)Lh^&l82+&x)*<n7^Sw-AJo9tEzZDwyJ7L^i7|BGqHu+ea6(&7jKpBq>~V z8CJxurD)WZ{5D0?s|KMi=e7A^JVNM6sdwg@1Eg_+Bw=9j&=+KO1PG|y(mP1@5~x>d z=@c{EWU_jTSjiJl)d(>`qEJ;@iOBm}alq8;OK;p(1AdH$)I9qHNmxxUArdzBW0t+Qeyl)m3?D09770g z)hzXEOy>2_{?o%2B%k%z4d23!pZcoxyW1Ik{|m7Q1>fm4`wsRrl)~h z_=Z*zYL+EG@DV1{6@5@(Ndu!Q$l_6Qlfoz@79q)Kmsf~J7t1)tl#`MD<;1&CAA zH8;i+oBm89dTTDl{aH`cmTPTt@^K-%*sV+t4X9q0Z{A~vEEa!&rRRr=0Rbz4NFCJr zLg2u=0QK@w9XGE=6(-JgeP}G#WG|R&tfHRA3a9*zh5wNTBAD;@YYGx%#E4{C#Wlfo z%-JuW9=FA_T6mR2-Vugk1uGZvJbFvVVWT@QOWz$;?u6+CbyQsbK$>O1APk|xgnh_8 zc)s@Mw7#0^wP6qTtyNq2G#s?5j~REyoU6^lT7dpX{T-rhZWHD%dik*=EA7bIJgOVf_Ga!yC8V^tkTOEHe+JK@Fh|$kfNxO^= z#lpV^(ZQ-3!^_BhV>aXY~GC9{8%1lOJ}6vzXDvPhC>JrtXwFBC+!3a*Z-%#9}i z#<5&0LLIa{q!rEIFSFc9)>{-_2^qbOg5;_A9 ztQ))C6#hxSA{f9R3Eh^`_f${pBJNe~pIQ`tZVR^wyp}=gLK}e5_vG@w+-mp#Fu>e| z*?qBp5CQ5zu+Fi}xAs)YY1;bKG!htqR~)DB$ILN6GaChoiy%Bq@i+1ZnANC0U&D z_4k$=YP47ng+0NhuEt}6C;9-JDd8i5S>`Ml==9wHDQFOsAlmtrVwurYDw_)Ihfk35 zJDBbe!*LUpg%4n>BExWz>KIQ9vexUu^d!7rc_kg#Bf= z7TLz|l*y*3d2vi@c|pX*@ybf!+Xk|2*z$@F4K#MT8Dt4zM_EcFmNp31#7qT6(@GG? zdd;sSY9HHuDb=w&|K%sm`bYX#%UHKY%R`3aLMO?{T#EI@FNNFNO>p@?W*i0z(g2dt z{=9Ofh80Oxv&)i35AQN>TPMjR^UID-T7H5A?GI{MD_VeXZ%;uo41dVm=uT&ne2h0i zv*xI%9vPtdEK@~1&V%p1sFc2AA`9?H)gPnRdlO~URx!fiSV)j?Tf5=5F>hnO=$d$x zzaIfr*wiIc!U1K*$JO@)gP4%xp!<*DvJSv7p}(uTLUb=MSb@7_yO+IsCj^`PsxEl& zIxsi}s3L?t+p+3FXYqujGhGwTx^WXgJ1}a@Yq5mwP0PvGEr*qu7@R$9j>@-q1rz5T zriz;B^(ex?=3Th6h;7U`8u2sDlfS{0YyydK=*>-(NOm9>S_{U|eg(J~C7O zIe{|LK=Y`hXiF_%jOM8Haw3UtaE{hWdzo3BbD6ud7br4cODBtN(~Hl+odP0SSWPw;I&^m)yLw+nd#}3#z}?UIcX3=SssI}`QwY=% zAEXTODk|MqTx}2DVG<|~(CxgLyi*A{m>M@1h^wiC)4Hy>1K7@|Z&_VPJsaQoS8=ex zDL&+AZdQa>ylxhT_Q$q=60D5&%pi6+qlY3$3c(~rsITX?>b;({FhU!7HOOhSP7>bmTkC8KM%!LRGI^~y3Ug+gh!QM=+NZXznM)?L3G=4=IMvFgX3BAlyJ z`~jjA;2z+65D$j5xbv9=IWQ^&-K3Yh`vC(1Qz2h2`o$>Cej@XRGff!it$n{@WEJ^N z41qk%Wm=}mA*iwCqU_6}Id!SQd13aFER3unXaJJXIsSnxvG2(hSCP{i&QH$tL&TPx zDYJsuk+%laN&OvKb-FHK$R4dy%M7hSB*yj#-nJy?S9tVoxAuDei{s}@+pNT!vLOIC z8g`-QQW8FKp3cPsX%{)0B+x+OhZ1=L7F-jizt|{+f1Ga7%+!BXqjCjH&x|3%?UbN# zh?$I1^YokvG$qFz5ySK+Ja5=mkR&p{F}ev**rWdKMko+Gj^?Or=UH?SCg#0F(&a_y zXOh}dPv0D9l0RVedq1~jCNV=8?vZfU-Xi|nkeE->;ohG3U7z+^0+HV17~-_Mv#mV` zzvwUJJ15v5wwKPv-)i@dsEo@#WEO9zie7mdRAbgL2kjbW4&lk$vxkbq=w5mGKZK6@ zjXWctDkCRx58NJD_Q7e}HX`SiV)TZMJ}~zY6P1(LWo`;yDynY_5_L?N-P`>ALfmyl z8C$a~FDkcwtzK9m$tof>(`Vu3#6r#+v8RGy#1D2)F;vnsiL&P-c^PO)^B-4VeJteLlT@25sPa z%W~q5>YMjj!mhN})p$47VA^v$Jo6_s{!y?}`+h+VM_SN`!11`|;C;B};B&Z<@%FOG z_YQVN+zFF|q5zKab&e4GH|B;sBbKimHt;K@tCH+S{7Ry~88`si7}S)1E{21nldiu5 z_4>;XTJa~Yd$m4A9{Qbd)KUAm7XNbZ4xHbg3a8-+1uf*$1PegabbmCzgC~1WB2F(W zYj5XhVos!X!QHuZXCatkRsdEsSCc+D2?*S7a+(v%toqyxhjz|`zdrUvsxQS{J>?c& zvx*rHw^8b|v^7wq8KWVofj&VUitbm*a&RU_ln#ZFA^3AKEf<#T%8I!Lg3XEsdH(A5 zlgh&M_XEoal)i#0tcq8c%Gs6`xu;vvP2u)D9p!&XNt z!TdF_H~;`g@fNXkO-*t<9~;iEv?)Nee%hVe!aW`N%$cFJ(Dy9+Xk*odyFj72T!(b%Vo5zvCGZ%3tkt$@Wcx8BWEkefI1-~C_3y*LjlQ5%WEz9WD8i^ z2MV$BHD$gdPJV4IaV)G9CIFwiV=ca0cfXdTdK7oRf@lgyPx;_7*RRFk=?@EOb9Gcz zg~VZrzo*Snp&EE{$CWr)JZW)Gr;{B2ka6B!&?aknM-FENcl%45#y?oq9QY z3^1Y5yn&^D67Da4lI}ljDcphaEZw2;tlYuzq?uB4b9Mt6!KTW&ptxd^vF;NbX=00T z@nE1lIBGgjqs?ES#P{ZfRb6f!At51vk%<0X%d_~NL5b8UyfQMPDtfU@>ijA0NP3UU zh{lCf`Wu7cX!go`kUG`1K=7NN@SRGjUKuo<^;@GS!%iDXbJs`o6e`v3O8-+7vRkFm z)nEa$sD#-v)*Jb>&Me+YIW3PsR1)h=-Su)))>-`aRcFJG-8icomO4J@60 zw10l}BYxi{eL+Uu0xJYk-Vc~BcR49Qyyq!7)PR27D`cqGrik=?k1Of>gY7q@&d&Ds zt7&WixP`9~jjHO`Cog~RA4Q%uMg+$z^Gt&vn+d3&>Ux{_c zm|bc;k|GKbhZLr-%p_f%dq$eiZ;n^NxoS-Nu*^Nx5vm46)*)=-Bf<;X#?`YC4tLK; z?;u?shFbXeks+dJ?^o$l#tg*1NA?(1iFff@I&j^<74S!o;SWR^Xi);DM%8XiWpLi0 zQE2dL9^a36|L5qC5+&Pf0%>l&qQ&)OU4vjd)%I6{|H+pw<0(a``9w(gKD&+o$8hOC zNAiShtc}e~ob2`gyVZx59y<6Fpl*$J41VJ-H*e-yECWaDMmPQi-N8XI3 z%iI@ljc+d}_okL1CGWffeaejlxWFVDWu%e=>H)XeZ|4{HlbgC-Uvof4ISYQzZ0Um> z#Ov{k1c*VoN^f(gfiueuag)`TbjL$XVq$)aCUBL_M`5>0>6Ska^*Knk__pw{0I>jA zzh}Kzg{@PNi)fcAk7jMAdi-_RO%x#LQszDMS@_>iFoB+zJ0Q#CQJzFGa8;pHFdi`^ zxnTC`G$7Rctm3G8t8!SY`GwFi4gF|+dAk7rh^rA{NXzc%39+xSYM~($L(pJ(8Zjs* zYdN_R^%~LiGHm9|ElV4kVZGA*T$o@YY4qpJOxGHlUi*S*A(MrgQ{&xoZQo+#PuYRs zv3a$*qoe9gBqbN|y|eaH=w^LE{>kpL!;$wRahY(hhzRY;d33W)m*dfem@)>pR54Qy z ze;^F?mwdU?K+=fBabokSls^6_6At#1Sh7W*y?r6Ss*dmZP{n;VB^LDxM1QWh;@H0J z!4S*_5j_;+@-NpO1KfQd&;C7T`9ak;X8DTRz$hDNcjG}xAfg%gwZSb^zhE~O);NMO zn2$fl7Evn%=Lk!*xsM#(y$mjukN?A&mzEw3W5>_o+6oh62kq=4-`e3B^$rG=XG}Kd zK$blh(%!9;@d@3& zGFO60j1Vf54S}+XD?%*uk7wW$f`4U3F*p7@I4Jg7f`Il}2H<{j5h?$DDe%wG7jZQL zI{mj?t?Hu>$|2UrPr5&QyK2l3mas?zzOk0DV30HgOQ|~xLXDQ8M3o#;CNKO8RK+M; zsOi%)js-MU>9H4%Q)#K_me}8OQC1u;f4!LO%|5toa1|u5Q@#mYy8nE9IXmR}b#sZK z3sD395q}*TDJJA9Er7N`y=w*S&tA;mv-)Sx4(k$fJBxXva0_;$G6!9bGBw13c_Uws zXks4u(8JA@0O9g5f?#V~qR5*u5aIe2HQO^)RW9TTcJk28l`Syl>Q#ZveEE4Em+{?%iz6=V3b>rCm9F zPQQm@-(hfNdo2%n?B)u_&Qh7^^@U>0qMBngH8}H|v+Ejg*Dd(Y#|jgJ-A zQ_bQscil%eY}8oN7ZL+2r|qv+iJY?*l)&3W_55T3GU;?@Om*(M`u0DXAsQ7HSl56> z4P!*(%&wRCb?a4HH&n;lAmr4rS=kMZb74Akha2U~Ktni>>cD$6jpugjULq)D?ea%b zk;UW0pAI~TH59P+o}*c5Ei5L-9OE;OIBt>^(;xw`>cN2`({Rzg71qrNaE=cAH^$wP zNrK9Glp^3a%m+ilQj0SnGq`okjzmE7<3I{JLD6Jn^+oas=h*4>Wvy=KXqVBa;K&ri z4(SVmMXPG}0-UTwa2-MJ=MTfM3K)b~DzSVq8+v-a0&Dsv>4B65{dBhD;(d44CaHSM zb!0ne(*<^Q%|nuaL`Gb3D4AvyO8wyygm=1;9#u5x*k0$UOwx?QxR*6Od8>+ujfyo0 zJ}>2FgW_iv(dBK2OWC-Y=Tw!UwIeOAOUUC;h95&S1hn$G#if+d;*dWL#j#YWswrz_ zMlV=z+zjZJ%SlDhxf)vv@`%~$Afd)T+MS1>ZE7V$Rj#;J*<9Ld=PrK0?qrazRJWx) z(BTLF@Wk279nh|G%ZY7_lK7=&j;x`bMND=zgh_>>-o@6%8_#Bz!FnF*onB@_k|YCF z?vu!s6#h9bL3@tPn$1;#k5=7#s*L;FLK#=M89K^|$3LICYWIbd^qguQp02w5>8p-H z+@J&+pP_^iF4Xu>`D>DcCnl8BUwwOlq6`XkjHNpi@B?OOd`4{dL?kH%lt78(-L}eah8?36zw9d-dI6D{$s{f=M7)1 zRH1M*-82}DoFF^Mi$r}bTB5r6y9>8hjL54%KfyHxn$LkW=AZ(WkHWR;tIWWr@+;^^ zVomjAWT)$+rn%g`LHB6ZSO@M3KBA? z+W7ThSBgpk`jZHZUrp`F;*%6M5kLWy6AW#T{jFHTiKXP9ITrMlEdti7@&AT_a-BA!jc(Kt zWk>IdY-2Zbz?U1)tk#n_Lsl?W;0q`;z|t9*g-xE!(}#$fScX2VkjSiboKWE~afu5d z2B@9mvT=o2fB_>Mnie=TDJB+l`GMKCy%2+NcFsbpv<9jS@$X37K_-Y!cvF5NEY`#p z3sWEc<7$E*X*fp+MqsOyMXO=<2>o8)E(T?#4KVQgt=qa%5FfUG_LE`n)PihCz2=iNUt7im)s@;mOc9SR&{`4s9Q6)U31mn?}Y?$k3kU z#h??JEgH-HGt`~%)1ZBhT9~uRi8br&;a5Y3K_Bl1G)-y(ytx?ok9S*Tz#5Vb=P~xH z^5*t_R2It95=!XDE6X{MjLYn4Eszj9Y91T2SFz@eYlx9Z9*hWaS$^5r7=W5|>sY8}mS(>e9Ez2qI1~wtlA$yv2e-Hjn&K*P z2zWSrC~_8Wrxxf#%QAL&f8iH2%R)E~IrQLgWFg8>`Vnyo?E=uiALoRP&qT{V2{$79 z%9R?*kW-7b#|}*~P#cA@q=V|+RC9=I;aK7Pju$K-n`EoGV^-8Mk=-?@$?O37evGKn z3NEgpo_4{s>=FB}sqx21d3*=gKq-Zk)U+bM%Q_}0`XGkYh*+jRaP+aDnRv#Zz*n$pGp zEU9omuYVXH{AEx>=kk}h2iKt!yqX=EHN)LF}z1j zJx((`CesN1HxTFZ7yrvA2jTPmKYVij>45{ZH2YtsHuGzIRotIFj?(8T@ZWUv{_%AI zgMZlB03C&FtgJqv9%(acqt9N)`4jy4PtYgnhqev!r$GTIOvLF5aZ{tW5MN@9BDGu* zBJzwW3sEJ~Oy8is`l6Ly3an7RPtRr^1Iu(D!B!0O241Xua>Jee;Rc7tWvj!%#yX#m z&pU*?=rTVD7pF6va1D@u@b#V@bShFr3 zMyMbNCZwT)E-%L-{%$3?n}>EN>ai7b$zR_>=l59mW;tfKj^oG)>_TGCJ#HbLBsNy$ zqAqPagZ3uQ(Gsv_-VrZmG&hHaOD#RB#6J8&sL=^iMFB=gH5AIJ+w@sTf7xa&Cnl}@ zxrtzoNq>t?=(+8bS)s2p3>jW}tye0z2aY_Dh@(18-vdfvn;D?sv<>UgL{Ti08$1Q+ zZI3q}yMA^LK=d?YVg({|v?d1|R?5 zL0S3fw)BZazRNNX|7P4rh7!+3tCG~O8l+m?H} z(CB>8(9LtKYIu3ohJ-9ecgk+L&!FX~Wuim&;v$>M4 zUfvn<=Eok(63Ubc>mZrd8d7(>8bG>J?PtOHih_xRYFu1Hg{t;%+hXu2#x%a%qzcab zv$X!ccoj)exoOnaco_jbGw7KryOtuf(SaR-VJ0nAe(1*AA}#QV1lMhGtzD>RoUZ;WA?~!K{8%chYn?ttlz17UpDLlhTkGcVfHY6R<2r4E{mU zq-}D?+*2gAkQYAKrk*rB%4WFC-B!eZZLg4(tR#@kUQHIzEqV48$9=Q(~J_0 zy1%LSCbkoOhRO!J+Oh#;bGuXe;~(bIE*!J@i<%_IcB7wjhB5iF#jBn5+u~fEECN2* z!QFh!m<(>%49H12Y33+?$JxKV3xW{xSs=gxkxW-@Xds^|O1`AmorDKrE8N2-@ospk z=Au%h=f!`_X|G^A;XWL}-_L@D6A~*4Yf!5RTTm$!t8y&fp5_oqvBjW{FufS`!)5m% z2g(=9Ap6Y2y(9OYOWuUVGp-K=6kqQ)kM0P^TQT{X{V$*sN$wbFb-DaUuJF*!?EJPl zJev!UsOB^UHZ2KppYTELh+kqDw+5dPFv&&;;C~=u$Mt+Ywga!8YkL2~@g67}3wAQP zrx^RaXb1(c7vwU8a2se75X(cX^$M{FH4AHS7d2}heqqg4F0!1|Na>UtAdT%3JnS!B)&zelTEj$^b0>Oyfw=P-y-Wd^#dEFRUN*C{!`aJIHi<_YA2?piC%^ zj!p}+ZnBrM?ErAM+D97B*7L8U$K zo(IR-&LF(85p+fuct9~VTSdRjs`d-m|6G;&PoWvC&s8z`TotPSoksp;RsL4VL@CHf z_3|Tn%`ObgRhLmr60<;ya-5wbh&t z#ycN_)3P_KZN5CRyG%LRO4`Ot)3vY#dNX9!f!`_>1%4Q`81E*2BRg~A-VcN7pcX#j zrbl@7`V%n z6J53(m?KRzKb)v?iCuYWbH*l6M77dY4keS!%>}*8n!@ROE4!|7mQ+YS4dff1JJC(t z6Fnuf^=dajqHpH1=|pb(po9Fr8it^;2dEk|Ro=$fxqK$^Yix{G($0m-{RCFQJ~LqUnO7jJcjr zl*N*!6WU;wtF=dLCWzD6kW;y)LEo=4wSXQDIcq5WttgE#%@*m><@H;~Q&GniA-$in z`sjWFLgychS1kIJmPtd-w6%iKkj&dGhtB%0)pyy0M<4HZ@ZY0PWLAd7FCrj&i|NRh?>hZj*&FYnyu%Ur`JdiTu&+n z78d3n)Rl6q&NwVj_jcr#s5G^d?VtV8bkkYco5lV0LiT+t8}98LW>d)|v|V3++zLbHC(NC@X#Hx?21J0M*gP2V`Yd^DYvVIr{C zSc4V)hZKf|OMSm%FVqSRC!phWSyuUAu%0fredf#TDR$|hMZihJ__F!)Nkh6z)d=NC z3q4V*K3JTetxCPgB2_)rhOSWhuXzu+%&>}*ARxUaDeRy{$xK(AC0I=9%X7dmc6?lZNqe-iM(`?Xn3x2Ov>sej6YVQJ9Q42>?4lil?X zew-S>tm{=@QC-zLtg*nh5mQojYnvVzf3!4TpXPuobW_*xYJs;9AokrXcs!Ay z;HK>#;G$*TPN2M!WxdH>oDY6k4A6S>BM0Nimf#LfboKxJXVBC=RBuO&g-=+@O-#0m zh*aPG16zY^tzQLNAF7L(IpGPa+mDsCeAK3k=IL6^LcE8l0o&)k@?dz!79yxUquQIe($zm5DG z5RdXTv)AjHaOPv6z%99mPsa#8OD@9=URvHoJ1hYnV2bG*2XYBgB!-GEoP&8fLmWGg z9NG^xl5D&3L^io&3iYweV*qhc=m+r7C#Jppo$Ygg;jO2yaFU8+F*RmPL` zYxfGKla_--I}YUT353k}nF1zt2NO?+kofR8Efl$Bb^&llgq+HV_UYJUH7M5IoN0sT z4;wDA0gs55ZI|FmJ0}^Pc}{Ji-|#jdR$`!s)Di4^g3b_Qr<*Qu2rz}R6!B^;`Lj3sKWzjMYjexX)-;f5Y+HfkctE{PstO-BZan0zdXPQ=V8 zS8cBhnQyy4oN?J~oK0zl!#S|v6h-nx5to7WkdEk0HKBm;?kcNO*A+u=%f~l&aY*+J z>%^Dz`EQ6!+SEX$>?d(~|MNWU-}JTrk}&`IR|Ske(G^iMdk04)Cxd@}{1=P0U*%L5 zMFH_$R+HUGGv|ju2Z>5x(-aIbVJLcH1S+(E#MNe9g;VZX{5f%_|Kv7|UY-CM(>vf= z!4m?QS+AL+rUyfGJ;~uJGp4{WhOOc%2ybVP68@QTwI(8kDuYf?#^xv zBmOHCZU8O(x)=GVFn%tg@TVW1)qJJ_bU}4e7i>&V?r zh-03>d3DFj&@}6t1y3*yOzllYQ++BO-q!)zsk`D(z||)y&}o%sZ-tUF>0KsiYKFg6 zTONq)P+uL5Vm0w{D5Gms^>H1qa&Z##*X31=58*r%Z@Ko=IMXX{;aiMUp-!$As3{sq z0EEk02MOsgGm7$}E%H1ys2$yftNbB%1rdo@?6~0!a8Ym*1f;jIgfcYEF(I_^+;Xdr z2a>&oc^dF3pm(UNpazXgVzuF<2|zdPGjrNUKpdb$HOgNp*V56XqH`~$c~oSiqx;8_ zEz3fHoU*aJUbFJ&?W)sZB3qOSS;OIZ=n-*#q{?PCXi?Mq4aY@=XvlNQdA;yVC0Vy+ z{Zk6OO!lMYWd`T#bS8FV(`%flEA9El;~WjZKU1YmZpG#49`ku`oV{Bdtvzyz3{k&7 zlG>ik>eL1P93F zd&!aXluU_qV1~sBQf$F%sM4kTfGx5MxO0zJy<#5Z&qzNfull=k1_CZivd-WAuIQf> zBT3&WR|VD|=nKelnp3Q@A~^d_jN3@$x2$f@E~e<$dk$L@06Paw$);l*ewndzL~LuU zq`>vfKb*+=uw`}NsM}~oY}gW%XFwy&A>bi{7s>@(cu4NM;!%ieP$8r6&6jfoq756W z$Y<`J*d7nK4`6t`sZ;l%Oen|+pk|Ry2`p9lri5VD!Gq`U#Ms}pgX3ylAFr8(?1#&dxrtJgB>VqrlWZf61(r`&zMXsV~l{UGjI7R@*NiMJLUoK*kY&gY9kC@^}Fj* zd^l6_t}%Ku<0PY71%zQL`@}L}48M!@=r)Q^Ie5AWhv%#l+Rhu6fRpvv$28TH;N7Cl z%I^4ffBqx@Pxpq|rTJV)$CnxUPOIn`u278s9#ukn>PL25VMv2mff)-RXV&r`Dwid7}TEZxXX1q(h{R6v6X z&x{S_tW%f)BHc!jHNbnrDRjGB@cam{i#zZK*_*xlW@-R3VDmp)<$}S%t*@VmYX;1h zFWmpXt@1xJlc15Yjs2&e%)d`fimRfi?+fS^BoTcrsew%e@T^}wyVv6NGDyMGHSKIQ zC>qFr4GY?#S#pq!%IM_AOf`#}tPoMn7JP8dHXm(v3UTq!aOfEXNRtEJ^4ED@jx%le zvUoUs-d|2(zBsrN0wE(Pj^g5wx{1YPg9FL1)V1JupsVaXNzq4fX+R!oVX+q3tG?L= z>=s38J_!$eSzy0m?om6Wv|ZCbYVHDH*J1_Ndajoh&?L7h&(CVii&rmLu+FcI;1qd_ zHDb3Vk=(`WV?Uq;<0NccEh0s`mBXcEtmwt6oN99RQt7MNER3`{snV$qBTp={Hn!zz z1gkYi#^;P8s!tQl(Y>|lvz{5$uiXsitTD^1YgCp+1%IMIRLiSP`sJru0oY-p!FPbI)!6{XM%)(_Dolh1;$HlghB-&e><;zU&pc=ujpa-(+S&Jj zX1n4T#DJDuG7NP;F5TkoG#qjjZ8NdXxF0l58RK?XO7?faM5*Z17stidTP|a%_N z^e$D?@~q#Pf+708cLSWCK|toT1YSHfXVIs9Dnh5R(}(I;7KhKB7RD>f%;H2X?Z9eR z{lUMuO~ffT!^ew= z7u13>STI4tZpCQ?yb9;tSM-(EGb?iW$a1eBy4-PVejgMXFIV_Ha^XB|F}zK_gzdhM z!)($XfrFHPf&uyFQf$EpcAfk83}91Y`JFJOiQ;v5ca?)a!IxOi36tGkPk4S6EW~eq z>WiK`Vu3D1DaZ}515nl6>;3#xo{GQp1(=uTXl1~ z4gdWxr-8a$L*_G^UVd&bqW_nzMM&SlNW$8|$lAfo@zb+P>2q?=+T^qNwblP*RsN?N zdZE%^Zs;yAwero1qaoqMp~|KL=&npffh981>2om!fseU(CtJ=bW7c6l{U5(07*e0~ zJRbid6?&psp)ilmYYR3ZIg;t;6?*>hoZ3uq7dvyyq-yq$zH$yyImjfhpQb@WKENSP zl;KPCE+KXzU5!)mu12~;2trrLfs&nlEVOndh9&!SAOdeYd}ugwpE-9OF|yQs(w@C9 zoXVX`LP~V>%$<(%~tE*bsq(EFm zU5z{H@Fs^>nm%m%wZs*hRl=KD%4W3|(@j!nJr{Mmkl`e_uR9fZ-E{JY7#s6i()WXB0g-b`R{2r@K{2h3T+a>82>722+$RM*?W5;Bmo6$X3+Ieg9&^TU(*F$Q3 zT572!;vJeBr-)x?cP;^w1zoAM`nWYVz^<6N>SkgG3s4MrNtzQO|A?odKurb6DGZffo>DP_)S0$#gGQ_vw@a9JDXs2}hV&c>$ zUT0;1@cY5kozKOcbN6)n5v)l#>nLFL_x?2NQgurQH(KH@gGe>F|$&@ zq@2A!EXcIsDdzf@cWqElI5~t z4cL9gg7{%~4@`ANXnVAi=JvSsj95-7V& zME3o-%9~2?cvlH#twW~99=-$C=+b5^Yv}Zh4;Mg-!LS zw>gqc=}CzS9>v5C?#re>JsRY!w|Mtv#%O3%Ydn=S9cQarqkZwaM4z(gL~1&oJZ;t; zA5+g3O6itCsu93!G1J_J%Icku>b3O6qBW$1Ej_oUWc@MI)| zQ~eyS-EAAnVZp}CQnvG0N>Kc$h^1DRJkE7xZqJ0>p<>9*apXgBMI-v87E0+PeJ-K& z#(8>P_W^h_kBkI;&e_{~!M+TXt@z8Po*!L^8XBn{of)knd-xp{heZh~@EunB2W)gd zAVTw6ZZasTi>((qpBFh(r4)k zz&@Mc@ZcI-4d639AfcOgHOU+YtpZ)rC%Bc5gw5o~+E-i+bMm(A6!uE>=>1M;V!Wl4 z<#~muol$FsY_qQC{JDc8b=$l6Y_@_!$av^08`czSm!Xan{l$@GO-zPq1s>WF)G=wv zDD8j~Ht1pFj)*-b7h>W)@O&m&VyYci&}K|0_Z*w`L>1jnGfCf@6p}Ef*?wdficVe_ zmPRUZ(C+YJU+hIj@_#IiM7+$4kH#VS5tM!Ksz01siPc-WUe9Y3|pb4u2qnn zRavJiRpa zq?tr&YV?yKt<@-kAFl3s&Kq#jag$hN+Y%%kX_ytvpCsElgFoN3SsZLC>0f|m#&Jhu zp7c1dV$55$+k78FI2q!FT}r|}cIV;zp~#6X2&}22$t6cHx_95FL~T~1XW21VFuatb zpM@6w>c^SJ>Pq6{L&f9()uy)TAWf;6LyHH3BUiJ8A4}od)9sriz~e7}l7Vr0e%(=>KG1Jay zW0azuWC`(|B?<6;R)2}aU`r@mt_#W2VrO{LcX$Hg9f4H#XpOsAOX02x^w9+xnLVAt z^~hv2guE-DElBG+`+`>PwXn5kuP_ZiOO3QuwoEr)ky;o$n7hFoh}Aq0@Ar<8`H!n} zspCC^EB=6>$q*gf&M2wj@zzfBl(w_@0;h^*fC#PW9!-kT-dt*e7^)OIU{Uw%U4d#g zL&o>6`hKQUps|G4F_5AuFU4wI)(%9(av7-u40(IaI|%ir@~w9-rLs&efOR@oQy)}{ z&T#Qf`!|52W0d+>G!h~5A}7VJky`C3^fkJzt3|M&xW~x-8rSi-uz=qBsgODqbl(W#f{Ew#ui(K)(Hr&xqZs` zfrK^2)tF#|U=K|_U@|r=M_Hb;qj1GJG=O=d`~#AFAccecIaq3U`(Ds1*f*TIs=IGL zp_vlaRUtFNK8(k;JEu&|i_m39c(HblQkF8g#l|?hPaUzH2kAAF1>>Yykva0;U@&oRV8w?5yEK??A0SBgh?@Pd zJg{O~4xURt7!a;$rz9%IMHQeEZHR8KgFQixarg+MfmM_OeX#~#&?mx44qe!wt`~dd zqyt^~ML>V>2Do$huU<7}EF2wy9^kJJSm6HoAD*sRz%a|aJWz_n6?bz99h)jNMp}3k ztPVbos1$lC1nX_OK0~h>=F&v^IfgBF{#BIi&HTL}O7H-t4+wwa)kf3AE2-Dx@#mTA z!0f`>vz+d3AF$NH_-JqkuK1C+5>yns0G;r5ApsU|a-w9^j4c+FS{#+7- zH%skr+TJ~W_8CK_j$T1b;$ql_+;q6W|D^BNK*A+W5XQBbJy|)(IDA=L9d>t1`KX2b zOX(Ffv*m?e>! zS3lc>XC@IqPf1g-%^4XyGl*1v0NWnwZTW?z4Y6sncXkaA{?NYna3(n@(+n+#sYm}A zGQS;*Li$4R(Ff{obl3#6pUsA0fKuWurQo$mWXMNPV5K66V!XYOyc})^>889Hg3I<{V^Lj9($B4Zu$xRr=89-lDz9x`+I8q(vEAimx1K{sTbs|5x7S zZ+7o$;9&9>@3K;5-DVzGw=kp7ez%1*kxhGytdLS>Q)=xUWv3k_x(IsS8we39Tijvr z`GKk>gkZTHSht;5q%fh9z?vk%sWO}KR04G9^jleJ^@ovWrob7{1xy7V=;S~dDVt%S za$Q#Th%6g1(hiP>hDe}7lcuI94K-2~Q0R3A1nsb7Y*Z!DtQ(Ic<0;TDKvc6%1kBdJ z$hF!{uALB0pa?B^TC}#N5gZ|CKjy|BnT$7eaKj;f>Alqdb_FA3yjZ4CCvm)D&ibL) zZRi91HC!TIAUl<|`rK_6avGh`!)TKk=j|8*W|!vb9>HLv^E%t$`@r@piI(6V8pqDG zBON7~=cf1ZWF6jc{qkKm;oYBtUpIdau6s+<-o^5qNi-p%L%xAtn9OktFd{@EjVAT% z#?-MJ5}Q9QiK_jYYWs+;I4&!N^(mb!%4zx7qO6oCEDn=8oL6#*9XIJ&iJ30O`0vsFy|fEVkw}*jd&B6!IYi+~Y)qv6QlM&V9g0 zh)@^BVDB|P&#X{31>G*nAT}Mz-j~zd>L{v{9AxrxKFw8j;ccQ$NE0PZCc(7fEt1xd z`(oR2!gX6}R+Z77VkDz^{I)@%&HQT5q+1xlf*3R^U8q%;IT8-B53&}dNA7GW`Ki&= z$lrdH zDCu;j$GxW<&v_4Te7=AE2J0u1NM_7Hl9$u{z(8#%8vvrx2P#R7AwnY|?#LbWmROa; zOJzU_*^+n(+k;Jd{e~So9>OF>fPx$Hb$?~K1ul2xr>>o@**n^6IMu8+o3rDp(X$cC z`wQt9qIS>yjA$K~bg{M%kJ00A)U4L+#*@$8UlS#lN3YA{R{7{-zu#n1>0@(#^eb_% zY|q}2)jOEM8t~9p$X5fpT7BZQ1bND#^Uyaa{mNcFWL|MoYb@>y`d{VwmsF&haoJuS2W7azZU0{tu#Jj_-^QRc35tjW~ae&zhKk!wD}#xR1WHu z_7Fys#bp&R?VXy$WYa$~!dMxt2@*(>@xS}5f-@6eoT%rwH zv_6}M?+piNE;BqaKzm1kK@?fTy$4k5cqYdN8x-<(o6KelwvkTqC3VW5HEnr+WGQlF zs`lcYEm=HPpmM4;Ich7A3a5Mb3YyQs7(Tuz-k4O0*-YGvl+2&V(B&L1F8qfR0@vQM-rF<2h-l9T12eL}3LnNAVyY_z51xVr$%@VQ-lS~wf3mnHc zoM({3Z<3+PpTFCRn_Y6cbxu9v>_>eTN0>hHPl_NQQuaK^Mhrv zX{q#80ot;ptt3#js3>kD&uNs{G0mQp>jyc0GG?=9wb33hm z`y2jL=J)T1JD7eX3xa4h$bG}2ev=?7f>-JmCj6){Upo&$k{2WA=%f;KB;X5e;JF3IjQBa4e-Gp~xv- z|In&Rad7LjJVz*q*+splCj|{7=kvQLw0F@$vPuw4m^z=B^7=A4asK_`%lEf_oIJ-O z{L)zi4bd#&g0w{p1$#I&@bz3QXu%Y)j46HAJKWVfRRB*oXo4lIy7BcVl4hRs<%&iQ zr|)Z^LUJ>qn>{6y`JdabfNNFPX7#3`x|uw+z@h<`x{J4&NlDjnknMf(VW_nKWT!Jh zo1iWBqT6^BR-{T=4Ybe+?6zxP_;A5Uo{}Xel%*=|zRGm1)pR43K39SZ=%{MDCS2d$~}PE-xPw4ZK6)H;Zc&0D5p!vjCn0wCe&rVIhchR9ql!p2`g0b@JsC^J#n_r*4lZ~u0UHKwo(HaHUJDHf^gdJhTdTW z3i7Zp_`xyKC&AI^#~JMVZj^9WsW}UR#nc#o+ifY<4`M+?Y9NTBT~p`ONtAFf8(ltr*ER-Ig!yRs2xke#NN zkyFcaQKYv>L8mQdrL+#rjgVY>Z2_$bIUz(kaqL}cYENh-2S6BQK-a(VNDa_UewSW` zMgHi<3`f!eHsyL6*^e^W7#l?V|42CfAjsgyiJsA`yNfAMB*lAsJj^K3EcCzm1KT zDU2+A5~X%ax-JJ@&7>m`T;;}(-e%gcYQtj}?ic<*gkv)X2-QJI5I0tA2`*zZRX(;6 zJ0dYfMbQ+{9Rn3T@Iu4+imx3Y%bcf2{uT4j-msZ~eO)5Z_T7NC|Nr3)|NWjomhv=E zXaVin)MY)`1QtDyO7mUCjG{5+o1jD_anyKn73uflH*ASA8rm+S=gIfgJ);>Zx*hNG z!)8DDCNOrbR#9M7Ud_1kf6BP)x^p(|_VWCJ+(WGDbYmnMLWc?O4zz#eiP3{NfP1UV z(n3vc-axE&vko^f+4nkF=XK-mnHHQ7>w05$Q}iv(kJc4O3TEvuIDM<=U9@`~WdKN* zp4e4R1ncR_kghW}>aE$@OOc~*aH5OOwB5U*Z)%{LRlhtHuigxH8KuDwvq5{3Zg{Vr zrd@)KPwVKFP2{rXho(>MTZZfkr$*alm_lltPob4N4MmhEkv`J(9NZFzA>q0Ch;!Ut zi@jS_=0%HAlN+$-IZGPi_6$)ap>Z{XQGt&@ZaJ(es!Po5*3}>R4x66WZNsjE4BVgn z>}xm=V?F#tx#e+pimNPH?Md5hV7>0pAg$K!?mpt@pXg6UW9c?gvzlNe0 z3QtIWmw$0raJkjQcbv-7Ri&eX6Ks@@EZ&53N|g7HU<;V1pkc&$3D#8k!coJ=^{=vf z-pCP;vr2#A+i#6VA?!hs6A4P@mN62XYY$#W9;MwNia~89i`=1GoFESI+%Mbrmwg*0 zbBq4^bA^XT#1MAOum)L&ARDXJ6S#G>&*72f50M1r5JAnM1p7GFIv$Kf9eVR(u$KLt z9&hQ{t^i16zL1c(tRa~?qr?lbSN;1k;%;p*#gw_BwHJRjcYPTj6>y-rw*dFTnEs95 z`%-AoPL!P16{=#RI0 zUb6#`KR|v^?6uNnY`zglZ#Wd|{*rZ(x&Hk8N6ob6mpX~e^qu5kxvh$2TLJA$M=rx zc!#ot+sS+-!O<0KR6+Lx&~zgEhCsbFY{i_DQCihspM?e z-V}HemMAvFzXR#fV~a=Xf-;tJ1edd}Mry@^=9BxON;dYr8vDEK<<{ zW~rg(ZspxuC&aJo$GTM!9_sXu(EaQJNkV9AC(ob#uA=b4*!Uf}B*@TK=*dBvKKPAF z%14J$S)s-ws9~qKsf>DseEW(ssVQ9__YNg}r9GGx3AJiZR@w_QBlGP>yYh0lQCBtf zx+G;mP+cMAg&b^7J!`SiBwC81M_r0X9kAr2y$0(Lf1gZK#>i!cbww(hn$;fLIxRf? z!AtkSZc-h76KGSGz%48Oe`8ZBHkSXeVb!TJt_VC>$m<#}(Z}!(3h631ltKb3CDMw^fTRy%Ia!b&at`^g7Ew-%WLT9(#V0OP9CE?uj62s>`GI3NA z!`$U+i<`;IQyNBkou4|-7^9^ylac-Xu!M+V5p5l0Ve?J0wTSV+$gYtoc=+Ve*OJUJ z$+uIGALW?}+M!J9+M&#bT=Hz@{R2o>NtNGu1yS({pyteyb>*sg4N`KAD?`u3F#C1y z2K4FKOAPASGZTep54PqyCG(h3?kqQQAxDSW@>T2d!n;9C8NGS;3A8YMRcL>b=<<%M zMiWf$jY;`Ojq5S{kA!?28o)v$;)5bTL<4eM-_^h4)F#eeC2Dj*S`$jl^yn#NjJOYT zx%yC5Ww@eX*zsM)P(5#wRd=0+3~&3pdIH7CxF_2iZSw@>kCyd z%M}$1p((Bidw4XNtk&`BTkU{-PG)SXIZ)yQ!Iol6u8l*SQ1^%zC72FP zLvG>_Z0SReMvB%)1@+et0S{<3hV@^SY3V~5IY(KUtTR{*^xJ^2NN{sIMD9Mr9$~(C$GLNlSpzS=fsbw-DtHb_T|{s z9OR|sx!{?F``H!gVUltY7l~dx^a(2;OUV^)7 z%@hg`8+r&xIxmzZ;Q&v0X%9P)U0SE@r@(lKP%TO(>6I_iF{?PX(bez6v8Gp!W_nd5 z<8)`1jcT)ImNZp-9rr4_1MQ|!?#8sJQx{`~7)QZ75I=DPAFD9Mt{zqFrcrXCU9MG8 zEuGcy;nZ?J#M3!3DWW?Zqv~dnN6ijlIjPfJx(#S0cs;Z=jDjKY|$w2s4*Xa1Iz953sN2Lt!Vmk|%ZwOOqj`sA--5Hiaq8!C%LV zvWZ=bxeRV(&%BffMJ_F~~*FdcjhRVNUXu)MS(S#67rDe%Ler=GS+WysC1I2=Bmbh3s6wdS}o$0 zz%H08#SPFY9JPdL6blGD$D-AaYi;X!#zqib`(XX*i<*eh+2UEPzU4}V4RlC3{<>-~ zadGA8lSm>b7Z!q;D_f9DT4i)Q_}ByElGl*Cy~zX%IzHp)@g-itZB6xM70psn z;AY8II99e6P2drgtTG5>`^|7qg`9MTp%T~|1N3tBqV}2zgow3TFAH{XPor0%=HrkXnKyxyozHlJ6 zd3}OWkl?H$l#yZqOzZbMI+lDLoH48;s10!m1!K87g;t}^+A3f3e&w{EYhVPR0Km*- zh5-ku$Z|Ss{2?4pGm(Rz!0OQb^_*N`)rW{z)^Cw_`a(_L9j=&HEJl(!4rQy1IS)>- zeTIr>hOii`gc(fgYF(cs$R8l@q{mJzpoB5`5r>|sG zBpsY}RkY(g5`bj~D>(;F8v*DyjX(#nVLSs>)XneWI&%Wo>a0u#4A?N<1SK4D}&V1oN)76 z%S>a2n3n>G`YY1>0Hvn&AMtMuI_?`5?4y3w2Hnq4Qa2YH5 zxKdfM;k467djL31Y$0kd9FCPbU=pHBp@zaIi`Xkd80;%&66zvSqsq6%aY)jZacfvw ztkWE{ZV6V2WL9e}Dvz|!d96KqVkJU@5ryp#rReeWu>mSrOJxY^tWC9wd0)$+lZc%{ zY=c4#%OSyQJvQUuy^u}s8DN8|8T%TajOuaY^)R-&8s@r9D`(Ic4NmEu)fg1f!u`xUb;9t#rM z>}cY=648@d5(9A;J)d{a^*ORdVtJrZ77!g~^lZ9@)|-ojvW#>)Jhe8$7W3mhmQh@S zU=CSO+1gSsQ+Tv=x-BD}*py_Ox@;%#hPb&tqXqyUW9jV+fonnuCyVw=?HR>dAB~Fg z^vl*~y*4|)WUW*9RC%~O1gHW~*tJb^a-j;ae2LRNo|0S2`RX>MYqGKB^_ng7YRc@! zFxg1X!VsvXkNuv^3mI`F2=x6$(pZdw=jfYt1ja3FY7a41T07FPdCqFhU6%o|Yb6Z4 zpBGa=(ao3vvhUv#*S{li|EyujXQPUV;0sa5!0Ut)>tPWyC9e0_9(=v*z`TV5OUCcx zT=w=^8#5u~7<}8Mepqln4lDv*-~g^VoV{(+*4w(q{At6d^E-Usa2`JXty++Oh~on^ z;;WHkJsk2jvh#N|?(2PLl+g!M0#z_A;(#Uy=TzL&{Ei5G9#V{JbhKV$Qmkm%5tn!CMA? z@hM=b@2DZWTQ6>&F6WCq6;~~WALiS#@{|I+ucCmD6|tBf&e;$_)%JL8$oIQ%!|Xih1v4A$=7xNO zZVz$G8;G5)rxyD+M0$20L$4yukA_D+)xmK3DMTH3Q+$N&L%qB)XwYx&s1gkh=%qGCCPwnwhbT4p%*3R)I}S#w7HK3W^E%4w z2+7ctHPx3Q97MFYB48HfD!xKKb(U^K_4)Bz(5dvwyl*R?)k;uHEYVi|{^rvh)w7}t z`tnH{v9nlVHj2ign|1an_wz0vO)*`3RaJc#;(W-Q6!P&>+@#fptCgtUSn4!@b7tW0&pE2Qj@7}f#ugu4*C)8_}AMRuz^WG zc)XDcOPQjRaGptRD^57B83B-2NKRo!j6TBAJntJPHNQG;^Oz}zt5F^kId~miK3J@l ztc-IKp6qL!?u~q?qfGP0I~$5gvq#-0;R(oLU@sYayr*QH95fnrYA*E|n%&FP@Cz`a zSdJ~(c@O^>qaO`m9IQ8sd8!L<+)GPJDrL7{4{ko2gWOZel^3!($Gjt|B&$4dtfTmBmC>V`R&&6$wpgvdmns zxcmfS%9_ZoN>F~azvLFtA(9Q5HYT#A(byGkESnt{$Tu<73$W~reB4&KF^JBsoqJ6b zS?$D7DoUgzLO-?P`V?5_ub$nf1p0mF?I)StvPomT{uYjy!w&z$t~j&en=F~hw|O(1 zlV9$arQmKTc$L)Kupwz_zA~deT+-0WX6NzFPh&d+ly*3$%#?Ca9Z9lOJsGVoQ&1HNg+)tJ_sw)%oo*DK)iU~n zvL``LqTe=r=7SwZ@LB)9|3QB5`0(B9r(iR}0nUwJss-v=dXnwMRQFYSRK1blS#^g(3@z{`=8_CGDm!LESTWig zzm1{?AG&7`uYJ;PoFO$o8RWuYsV26V{>D-iYTnvq7igWx9@w$EC*FV^vpvDl@i9yp zPIqiX@hEZF4VqzI3Y)CHhR`xKN8poL&~ak|wgbE4zR%Dm(a@?bw%(7(!^>CM!^4@J z6Z)KhoQP;WBq_Z_&<@i2t2&xq>N>b;Np2rX?yK|-!14iE2T}E|jC+=wYe~`y38g3J z8QGZquvqBaG!vw&VtdXWX5*i5*% zJP~7h{?&E|<#l{klGPaun`IgAJ4;RlbRqgJz5rmHF>MtJHbfqyyZi53?Lhj=(Ku#& z__ubmZIxzSq3F90Xur!1)Vqe6b@!ueHA!93H~jdHmaS5Q^CULso}^poy)0Op6!{^9 zWyCyyIrdBP4fkliZ%*g+J-A!6VFSRF6Liu6G^^=W>cn81>4&7(c7(6vCGSAJ zQZ|S3mb|^Wf=yJ(h~rq`iiW~|n#$+KcblIR<@|lDtm!&NBzSG-1;7#YaU+-@=xIm4 zE}edTYd~e&_%+`dIqqgFntL-FxL3!m4yTNt<(^Vt9c6F(`?9`u>$oNxoKB29<}9FE zgf)VK!*F}nW?}l95%RRk8N4^Rf8)Xf;drT4<|lUDLPj^NPMrBPL;MX&0oGCsS za3}vWcF(IPx&W6{s%zwX{UxHX2&xLGfT{d9bWP!g;Lg#etpuno$}tHoG<4Kd*=kpU z;4%y(<^yj(UlG%l-7E9z_Kh2KoQ19qT3CR@Ghr>BAgr3Vniz3LmpC4g=g|A3968yD2KD$P7v$ zx9Q8`2&qH3&y-iv0#0+jur@}k`6C%7fKbCr|tHX2&O%r?rBpg`YNy~2m+ z*L7dP$RANzVUsG_Lb>=__``6vA*xpUecuGsL+AW?BeSwyoQfDlXe8R1*R1M{0#M?M zF+m19`3<`gM{+GpgW^=UmuK*yMh3}x)7P738wL8r@(Na6%ULPgbPVTa6gh5Q(SR0f znr6kdRpe^(LVM;6Rt(Z@Lsz3EX*ry6(WZ?w>#ZRelx)N%sE+MN>5G|Z8{%@b&D+Ov zPU{shc9}%;G7l;qbonIb_1m^Qc8ez}gTC-k02G8Rl?7={9zBz8uRX2{XJQ{vZhs67avlRn| zgRtWl0Lhjet&!YC47GIm%1gdq%T24_^@!W3pCywc89X4I5pnBCZDn(%!$lOGvS*`0!AoMtqxNPFgaMR zwoW$p;8l6v%a)vaNsesED3f}$%(>zICnoE|5JwP&+0XI}JxPccd+D^gx`g`=GsUc0 z9Uad|C+_@_0%JmcObGnS@3+J^0P!tg+fUZ_w#4rk#TlJYPXJiO>SBxzs9(J;XV9d{ zmTQE1(K8EYaz9p^XLbdWudyIPJlGPo0U*)fAh-jnbfm@SYD_2+?|DJ-^P+ojG{2{6 z>HJtedEjO@j_tqZ4;Zq1t5*5cWm~W?HGP!@_f6m#btM@46cEMhhK{(yI&jG)fwL1W z^n_?o@G8a-jYt!}$H*;{0#z8lANlo!9b@!c5K8<(#lPlpE!z86Yq#>WT&2} z;;G1$pD%iNoj#Z=&kij5&V1KHIhN-h<;{HC5wD)PvkF>CzlQOEx_0;-TJ*!#&{Wzt zKcvq^SZIdop}y~iouNqtU7K7+?eIz-v_rfNM>t#i+dD$s_`M;sjGubTdP)WI*uL@xPOLHt#~T<@Yz>xt50ZoTw;a(a}lNiDN-J${gOdE zx?8LOA|tv{Mb}=TTR=LcqMqbCJkKj+@;4Mu)Cu0{`~ohix6E$g&tff)aHeUAQQ%M? zIN4uSUTzC1iMEWL*W-in1y)C`E+R8j?4_?X4&2Zv5?QdkNMz(k} zw##^Ikx`#_s>i&CO_mu@vJJ*|3ePRDl5pq$9V^>D;g0R%l>lw;ttyM6Sy`NBF{)Lr zSk)V>mZr96+aHY%vTLLt%vO-+juw6^SO_ zYGJaGeWX6W(TOQx=5oTGXOFqMMU*uZyt>MR-Y`vxW#^&)H zk0!F8f*@v6NO@Z*@Qo)+hlX40EWcj~j9dGrLaq%1;DE_%#lffXCcJ;!ZyyyZTz74Q zb2WSly6sX{`gQeToQsi1-()5EJ1nJ*kXGD`xpXr~?F#V^sxE3qSOwRSaC9x9oa~jJ zTG9`E|q zC5Qs1xh}jzb5UPYF`3N9YuMnI7xsZ41P;?@c|%w zl=OxLr6sMGR+`LStLvh)g?fA5p|xbUD;yFAMQg&!PEDYxVYDfA>oTY;CFt`cg?Li1 z0b})!9Rvw&j#*&+D2))kXLL z0+j=?7?#~_}N-qdEIP>DQaZh#F(#e0WNLzwUAj@r694VJ8?Dr5_io2X49XYsG^ zREt0$HiNI~6VV!ycvao+0v7uT$_ilKCvsC+VDNg7yG1X+eNe^3D^S==F3ByiW0T^F zH6EsH^}Uj^VPIE&m)xlmOScYR(w750>hclqH~~dM2+;%GDXT`u4zG!p((*`Hwx41M z4KB+`hfT(YA%W)Ve(n+Gu9kuXWKzxg{1ff^xNQw>w%L-)RySTk9kAS92(X0Shg^Q? zx1YXg_TLC^?h6!4mBqZ9pKhXByu|u~gF%`%`vdoaGBN3^j4l!4x?Bw4Jd)Z4^di}! zXlG1;hFvc>H?bmmu1E7Vx=%vahd!P1#ZGJOJYNbaek^$DHt`EOE|Hlij+hX>ocQFSLVu|wz`|KVl@Oa;m2k6b*mNK2Vo{~l9>Qa3@B7G7#k?)aLx;w6U ze8bBq%vF?5v>#TspEoaII!N}sRT~>bh-VWJ7Q*1qsz%|G)CFmnttbq$Ogb{~YK_=! z{{0vhlW@g!$>|}$&4E3@k`KPElW6x#tSX&dfle>o!irek$NAbDzdd2pVeNzk4&qgJ zXvNF0$R96~g0x+R1igR=Xu&X_Hc5;!Ze&C)eUTB$9wW&?$&o8Yxhm5s(S`;?{> z*F?9Gr0|!OiKA>Rq-ae=_okB6&yMR?!JDer{@iQgIn=cGxs-u^!8Q$+N&pfg2WM&Z zulHu=Uh~U>fS{=Nm0x>ACvG*4R`Dx^kJ65&Vvfj`rSCV$5>c04N26Rt2S?*kh3JKq z9(3}5T?*x*AP(X2Ukftym0XOvg~r6Ms$2x&R&#}Sz23aMGU&7sU-cFvE3Eq`NBJe84VoftWF#v7PDAp`@V zRFCS24_k~;@~R*L)eCx@Q9EYmM)Sn}HLbVMyxx%{XnMBDc-YZ<(DXDBYUt8$u5Zh} zBK~=M9cG$?_m_M61YG+#|9Vef7LfbH>(C21&aC)x$^Lg}fa#SF){RX|?-xZjSOrn# z2ZAwUF)$VB<&S;R3FhNSQOV~8w%A`V9dWyLiy zgt7G=Z4t|zU3!dh5|s(@XyS|waBr$>@=^Dspmem8)@L`Ns{xl%rGdX!R(BiC5C7Vo zXetb$oC_iXS}2x_Hy}T(hUUNbO47Q@+^4Q`h>(R-;OxCyW#eoOeC51jzxnM1yxBrp zz6}z`(=cngs6X05e79o_B7@3K|Qpe3n38Py_~ zpi?^rj!`pq!7PHGliC$`-8A^Ib?2qgJJCW+(&TfOnFGJ+@-<<~`7BR0f4oSINBq&R z2CM`0%WLg_Duw^1SPwj-{?BUl2Y=M4e+7yL1{C&&f&zjF06#xf>VdLozgNye(BNgSD`=fFbBy0HIosLl@JwCQl^s;eTnc( z3!r8G=K>zb`|bLLI0N|eFJk%s)B>oJ^M@AQzqR;HUjLsOqW<0v>1ksT_#24*U@R3HJu*A^#1o#P3%3_jq>icD@<`tqU6ICEgZrME(xX#?i^Z z%Id$_uyQGlFD-CcaiRtRdGn|K`Lq5L-rx7`vYYGH7I=eLfHRozPiUtSe~Tt;IN2^gCXmf2#D~g2@9bhzK}3nphhG%d?V7+Zq{I2?Gt*!NSn_r~dd$ zqkUOg{U=MI?Ehx@`(X%rQB?LP=CjJ*V!rec{#0W2WshH$X#9zep!K)tzZoge*LYd5 z@g?-j5_mtMp>_WW`p*UNUZTFN{_+#m*bJzt{hvAdkF{W40{#L3w6gzPztnsA_4?&0 z(+>pv!zB16rR-(nm(^c>Z(its{ny677vT8sF564^mlZvJ!h65}OW%Hn|2OXbOQM%b z{6C54Z2v;^hyMQ;UH+HwFD2!F!VlQ}6Z{L0_9g5~CH0@Mqz?ZC`^QkhOU#$Lx<4`B zyZsa9uPF!rZDo8ZVfzzR#raQ>5|)k~_Ef*wDqG^76o)j!C4 zykvT*o$!-MBko@?{b~*Zf2*YMlImrK`cEp|#D7f%Twm<|C|dWD \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index 6d57edc..0000000 --- a/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/src/main/java/com/cburch/draw/actions/ModelAction.java b/src/main/java/com/cburch/draw/actions/ModelAction.java index 9cdadfc..afb837b 100644 --- a/src/main/java/com/cburch/draw/actions/ModelAction.java +++ b/src/main/java/com/cburch/draw/actions/ModelAction.java @@ -11,17 +11,17 @@ public abstract class ModelAction extends Action { - private CanvasModel model; + private final CanvasModel model; public ModelAction(CanvasModel model) { this.model = model; } - static String getShapesName(Collection coll) { - if (coll.size() != 1) { + static String getShapesName(Collection collection) { + if (collection.size() != 1) { return Strings.get("shapeMultiple"); } else { - CanvasObject shape = coll.iterator().next(); + CanvasObject shape = collection.iterator().next(); return shape.getDisplayName(); } } diff --git a/src/main/java/com/cburch/draw/actions/ModelAddAction.java b/src/main/java/com/cburch/draw/actions/ModelAddAction.java index f627559..a3a69ac 100644 --- a/src/main/java/com/cburch/draw/actions/ModelAddAction.java +++ b/src/main/java/com/cburch/draw/actions/ModelAddAction.java @@ -11,8 +11,8 @@ public class ModelAddAction extends ModelAction { - private ArrayList added; - private int addIndex; + private final ArrayList added; + private final int addIndex; public ModelAddAction(CanvasModel model, CanvasObject added) { this(model, Collections.singleton(added)); diff --git a/src/main/java/com/cburch/draw/actions/ModelChangeAttributeAction.java b/src/main/java/com/cburch/draw/actions/ModelChangeAttributeAction.java index dc1c5b5..12a8a63 100644 --- a/src/main/java/com/cburch/draw/actions/ModelChangeAttributeAction.java +++ b/src/main/java/com/cburch/draw/actions/ModelChangeAttributeAction.java @@ -14,13 +14,13 @@ public class ModelChangeAttributeAction extends ModelAction { - private Map oldValues; - private Map newValues; + private final Map oldValues; + private final Map newValues; private Attribute attribute; public ModelChangeAttributeAction(CanvasModel model, - Map oldValues, - Map newValues) { + Map oldValues, + Map newValues) { super(model); this.oldValues = oldValues; this.newValues = newValues; diff --git a/src/main/java/com/cburch/draw/actions/ModelDeleteHandleAction.java b/src/main/java/com/cburch/draw/actions/ModelDeleteHandleAction.java index e7a2287..d5c04d8 100644 --- a/src/main/java/com/cburch/draw/actions/ModelDeleteHandleAction.java +++ b/src/main/java/com/cburch/draw/actions/ModelDeleteHandleAction.java @@ -11,7 +11,7 @@ public class ModelDeleteHandleAction extends ModelAction { - private Handle handle; + private final Handle handle; private Handle previous; public ModelDeleteHandleAction(CanvasModel model, Handle handle) { diff --git a/src/main/java/com/cburch/draw/actions/ModelEditTextAction.java b/src/main/java/com/cburch/draw/actions/ModelEditTextAction.java index 1eaba42..51e4936 100644 --- a/src/main/java/com/cburch/draw/actions/ModelEditTextAction.java +++ b/src/main/java/com/cburch/draw/actions/ModelEditTextAction.java @@ -11,9 +11,9 @@ public class ModelEditTextAction extends ModelAction { - private Text text; - private String oldValue; - private String newValue; + private final Text text; + private final String oldValue; + private final String newValue; public ModelEditTextAction(CanvasModel model, Text text, String newValue) { super(model); diff --git a/src/main/java/com/cburch/draw/actions/ModelInsertHandleAction.java b/src/main/java/com/cburch/draw/actions/ModelInsertHandleAction.java index b4afb7a..d46cfc6 100644 --- a/src/main/java/com/cburch/draw/actions/ModelInsertHandleAction.java +++ b/src/main/java/com/cburch/draw/actions/ModelInsertHandleAction.java @@ -11,7 +11,7 @@ public class ModelInsertHandleAction extends ModelAction { - private Handle desired; + private final Handle desired; public ModelInsertHandleAction(CanvasModel model, Handle desired) { super(model); diff --git a/src/main/java/com/cburch/draw/actions/ModelMoveHandleAction.java b/src/main/java/com/cburch/draw/actions/ModelMoveHandleAction.java index 205a18a..53cfbf4 100644 --- a/src/main/java/com/cburch/draw/actions/ModelMoveHandleAction.java +++ b/src/main/java/com/cburch/draw/actions/ModelMoveHandleAction.java @@ -12,7 +12,7 @@ public class ModelMoveHandleAction extends ModelAction { - private HandleGesture gesture; + private final HandleGesture gesture; private Handle newHandle; public ModelMoveHandleAction(CanvasModel model, HandleGesture gesture) { diff --git a/src/main/java/com/cburch/draw/actions/ModelRemoveAction.java b/src/main/java/com/cburch/draw/actions/ModelRemoveAction.java index 7803311..47debad 100644 --- a/src/main/java/com/cburch/draw/actions/ModelRemoveAction.java +++ b/src/main/java/com/cburch/draw/actions/ModelRemoveAction.java @@ -12,7 +12,7 @@ public class ModelRemoveAction extends ModelAction { - private Map removed; + private final Map removed; public ModelRemoveAction(CanvasModel model, CanvasObject removed) { this(model, Collections.singleton(removed)); diff --git a/src/main/java/com/cburch/draw/actions/ModelReorderAction.java b/src/main/java/com/cburch/draw/actions/ModelReorderAction.java index 03b7e4e..24f92c2 100644 --- a/src/main/java/com/cburch/draw/actions/ModelReorderAction.java +++ b/src/main/java/com/cburch/draw/actions/ModelReorderAction.java @@ -15,9 +15,9 @@ public class ModelReorderAction extends ModelAction { - private ArrayList requests; - private ArrayList objects; - private int type; + private final ArrayList requests; + private final ArrayList objects; + private final int type; public ModelReorderAction(CanvasModel model, List requests) { super(model); diff --git a/src/main/java/com/cburch/draw/actions/ModelTranslateAction.java b/src/main/java/com/cburch/draw/actions/ModelTranslateAction.java index b22e02a..d1c7069 100644 --- a/src/main/java/com/cburch/draw/actions/ModelTranslateAction.java +++ b/src/main/java/com/cburch/draw/actions/ModelTranslateAction.java @@ -12,12 +12,12 @@ public class ModelTranslateAction extends ModelAction { - private HashSet moved; - private int dx; - private int dy; + private final HashSet moved; + private final int dx; + private final int dy; public ModelTranslateAction(CanvasModel model, - Collection moved, int dx, int dy) { + Collection moved, int dx, int dy) { super(model); this.moved = new HashSet<>(moved); this.dx = dx; diff --git a/src/main/java/com/cburch/draw/actions/Strings.java b/src/main/java/com/cburch/draw/actions/Strings.java index 3d501c3..be118b0 100644 --- a/src/main/java/com/cburch/draw/actions/Strings.java +++ b/src/main/java/com/cburch/draw/actions/Strings.java @@ -9,7 +9,7 @@ class Strings { - private static LocaleManager source = new LocaleManager("logisim", "draw"); + private static final LocaleManager source = new LocaleManager("logisim", "draw"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/draw/canvas/Canvas.java b/src/main/java/com/cburch/draw/canvas/Canvas.java index 092f47e..ef3849d 100644 --- a/src/main/java/com/cburch/draw/canvas/Canvas.java +++ b/src/main/java/com/cburch/draw/canvas/Canvas.java @@ -17,10 +17,9 @@ public class Canvas extends JComponent { public static final String TOOL_PROPERTY = "tool"; public static final String MODEL_PROPERTY = "model"; - + private final CanvasListener listener; private CanvasModel model; private ActionDispatcher dispatcher; - private CanvasListener listener; private Selection selection; public Canvas() { diff --git a/src/main/java/com/cburch/draw/canvas/CanvasListener.java b/src/main/java/com/cburch/draw/canvas/CanvasListener.java index 72d69f3..2d1d57e 100644 --- a/src/main/java/com/cburch/draw/canvas/CanvasListener.java +++ b/src/main/java/com/cburch/draw/canvas/CanvasListener.java @@ -17,7 +17,7 @@ class CanvasListener implements MouseListener, MouseMotionListener, KeyListener, CanvasModelListener { - private Canvas canvas; + private final Canvas canvas; private CanvasTool tool; public CanvasListener(Canvas canvas) { diff --git a/src/main/java/com/cburch/draw/canvas/Selection.java b/src/main/java/com/cburch/draw/canvas/Selection.java index fd6ab56..b5d0a22 100644 --- a/src/main/java/com/cburch/draw/canvas/Selection.java +++ b/src/main/java/com/cburch/draw/canvas/Selection.java @@ -23,11 +23,11 @@ public class Selection { private static final String TRANSLATING = "translating"; private static final String HIDDEN = "hidden"; - private ArrayList listeners; - private HashSet selected; - private Set selectedView; - private HashMap suppressed; - private Set suppressedView; + private final ArrayList listeners; + private final HashSet selected; + private final Set selectedView; + private final HashMap suppressed; + private final Set suppressedView; private Handle selectedHandle; private HandleGesture currentHandleGesture; private int moveDx; diff --git a/src/main/java/com/cburch/draw/canvas/SelectionEvent.java b/src/main/java/com/cburch/draw/canvas/SelectionEvent.java index ac24f56..786f589 100644 --- a/src/main/java/com/cburch/draw/canvas/SelectionEvent.java +++ b/src/main/java/com/cburch/draw/canvas/SelectionEvent.java @@ -13,8 +13,8 @@ public class SelectionEvent extends EventObject { public static final int ACTION_REMOVED = 1; public static final int ACTION_HANDLE = 2; - private int action; - private Collection affected; + private final int action; + private final Collection affected; public SelectionEvent(Selection source, int action, Collection affected) { super(source); diff --git a/src/main/java/com/cburch/draw/gui/AttrTableDrawManager.java b/src/main/java/com/cburch/draw/gui/AttrTableDrawManager.java index 0118c3f..e79c3ec 100644 --- a/src/main/java/com/cburch/draw/gui/AttrTableDrawManager.java +++ b/src/main/java/com/cburch/draw/gui/AttrTableDrawManager.java @@ -4,6 +4,7 @@ package com.cburch.draw.gui; import com.cburch.draw.canvas.Canvas; +import com.cburch.draw.canvas.CanvasTool; import com.cburch.draw.tools.AbstractTool; import com.cburch.draw.tools.DrawingAttributeSet; import com.cburch.draw.tools.SelectTool; @@ -13,10 +14,10 @@ public class AttrTableDrawManager implements PropertyChangeListener { - private Canvas canvas; - private AttrTable table; - private AttrTableSelectionModel selectionModel; - private AttrTableToolModel toolModel; + private final Canvas canvas; + private final AttrTable table; + private final AttrTableSelectionModel selectionModel; + private final AttrTableToolModel toolModel; public AttrTableDrawManager(Canvas canvas, AttrTable table, DrawingAttributeSet attributes) { this.canvas = canvas; @@ -43,7 +44,7 @@ public void propertyChange(PropertyChangeEvent event) { } private void updateToolAttributes() { - Object tool = canvas.getTool(); + CanvasTool tool = canvas.getTool(); if (tool instanceof SelectTool) { table.setAttrTableModel(selectionModel); } else if (tool instanceof AbstractTool) { diff --git a/src/main/java/com/cburch/draw/gui/AttrTableSelectionModel.java b/src/main/java/com/cburch/draw/gui/AttrTableSelectionModel.java index 75fb909..4cd5f91 100644 --- a/src/main/java/com/cburch/draw/gui/AttrTableSelectionModel.java +++ b/src/main/java/com/cburch/draw/gui/AttrTableSelectionModel.java @@ -19,7 +19,7 @@ class AttrTableSelectionModel extends AttributeSetTableModel implements SelectionListener { - private Canvas canvas; + private final Canvas canvas; public AttrTableSelectionModel(Canvas canvas) { super(new SelectionAttributes(canvas.getSelection())); diff --git a/src/main/java/com/cburch/draw/gui/AttrTableToolModel.java b/src/main/java/com/cburch/draw/gui/AttrTableToolModel.java index 2e8ae09..de93922 100644 --- a/src/main/java/com/cburch/draw/gui/AttrTableToolModel.java +++ b/src/main/java/com/cburch/draw/gui/AttrTableToolModel.java @@ -10,7 +10,7 @@ class AttrTableToolModel extends AttributeSetTableModel { - private DrawingAttributeSet defaults; + private final DrawingAttributeSet defaults; private AbstractTool currentTool; public AttrTableToolModel(DrawingAttributeSet defaults, AbstractTool tool) { diff --git a/src/main/java/com/cburch/draw/gui/Main.java b/src/main/java/com/cburch/draw/gui/Main.java index 8f14c07..cd94928 100644 --- a/src/main/java/com/cburch/draw/gui/Main.java +++ b/src/main/java/com/cburch/draw/gui/Main.java @@ -14,8 +14,10 @@ import com.cburch.logisim.util.HorizontalSplitPane; import com.cburch.logisim.util.VerticalSplitPane; import java.awt.BorderLayout; +import java.awt.Color; import java.util.Collections; import javax.swing.JFrame; +import javax.swing.border.LineBorder; public class Main { @@ -37,6 +39,7 @@ private static void showFrame(Drawing drawing, String title) { Toolbar toolbar = new Toolbar(canvas, attributes); canvas.setModel(drawing, new UndoLogDispatcher(new UndoLog())); canvas.setTool(toolbar.getDefaultTool()); + canvas.setBorder(new LineBorder(Color.BLACK)); AttrTable table = new AttrTable(frame); AttrTableDrawManager manager = new AttrTableDrawManager(canvas, table, attributes); diff --git a/src/main/java/com/cburch/draw/gui/SelectionAttributes.java b/src/main/java/com/cburch/draw/gui/SelectionAttributes.java index 515f740..78d0bf7 100644 --- a/src/main/java/com/cburch/draw/gui/SelectionAttributes.java +++ b/src/main/java/com/cburch/draw/gui/SelectionAttributes.java @@ -25,7 +25,7 @@ public class SelectionAttributes extends AbstractAttributeSet { - private Selection selection; + private final Selection selection; private Listener listener; private Map selected; private Attribute[] selectedAttributes; @@ -64,8 +64,7 @@ private static Object getSelectionValue(Attribute attribute, Set> entries() { Set> raw = selected.entrySet(); - ArrayList> ret = new ArrayList<>(raw); - return ret; + return new ArrayList<>(raw); } // diff --git a/src/main/java/com/cburch/draw/gui/Strings.java b/src/main/java/com/cburch/draw/gui/Strings.java index 1dd8881..2329575 100644 --- a/src/main/java/com/cburch/draw/gui/Strings.java +++ b/src/main/java/com/cburch/draw/gui/Strings.java @@ -9,7 +9,7 @@ class Strings { - private static LocaleManager source = new LocaleManager("logisim", "draw"); + private static final LocaleManager source = new LocaleManager("logisim", "draw"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/draw/gui/Toolbar.java b/src/main/java/com/cburch/draw/gui/Toolbar.java index 43bfc95..3b8c7df 100644 --- a/src/main/java/com/cburch/draw/gui/Toolbar.java +++ b/src/main/java/com/cburch/draw/gui/Toolbar.java @@ -19,12 +19,12 @@ class Toolbar extends JComponent { - private static int ICON_WIDTH = 16; - private static int ICON_HEIGHT = 16; - private static int ICON_SEPARATION = 4; - private Canvas canvas; + private static final int ICON_WIDTH = 16; + private static final int ICON_HEIGHT = 16; + private static final int ICON_SEPARATION = 4; + private final Canvas canvas; + private final Listener listener; private AbstractTool[][] tools; - private Listener listener; public Toolbar(Canvas canvas, DrawingAttributeSet attributes) { this.canvas = canvas; @@ -40,7 +40,7 @@ public Toolbar(Canvas canvas, DrawingAttributeSet attributes) { } setPreferredSize(new Dimension(3 * ICON_SEPARATION + 2 * ICON_WIDTH, - ICON_SEPARATION + tools[0].length * (ICON_HEIGHT + ICON_SEPARATION))); + ICON_SEPARATION + tools[0].length * (ICON_HEIGHT + ICON_SEPARATION))); addMouseListener(listener); addMouseMotionListener(listener); } @@ -103,9 +103,9 @@ public void mousePressed(MouseEvent event) { int y0 = ICON_SEPARATION + row * (ICON_SEPARATION + ICON_HEIGHT); if (mx >= x0 && mx < x0 + ICON_WIDTH - && my >= y0 && my < y0 + ICON_HEIGHT - && column >= 0 && column < tools.length - && row >= 0 && row < tools[column].length) { + && my >= y0 && my < y0 + ICON_HEIGHT + && column >= 0 && column < tools.length + && row >= 0 && row < tools[column].length) { toolPressed = tools[column][row]; inTool = true; toolX = x0; @@ -134,9 +134,7 @@ public void mouseDragged(MouseEvent event) { int y0 = toolY; boolean wasInTool = inTool; - boolean isInTool = toolPressed != null - && mx >= x0 && mx < x0 + ICON_WIDTH - && my >= y0 && my < y0 + ICON_HEIGHT; + boolean isInTool = toolPressed != null && mx >= x0 && mx < x0 + ICON_WIDTH && my >= y0 && my < y0 + ICON_HEIGHT; if (wasInTool != isInTool) { inTool = isInTool; repaint(); diff --git a/src/main/java/com/cburch/draw/model/AbstractCanvasObject.java b/src/main/java/com/cburch/draw/model/AbstractCanvasObject.java index 0f27608..0b3361d 100644 --- a/src/main/java/com/cburch/draw/model/AbstractCanvasObject.java +++ b/src/main/java/com/cburch/draw/model/AbstractCanvasObject.java @@ -20,7 +20,7 @@ import org.w3c.dom.Element; public abstract class AbstractCanvasObject - implements AttributeSet, CanvasObject, Cloneable { + implements AttributeSet, CanvasObject, Cloneable { private static final int OVERLAP_TRIES = 50; private static final int GENERATE_RANDOM_TRIES = 20; diff --git a/src/main/java/com/cburch/draw/model/AttributeMapKey.java b/src/main/java/com/cburch/draw/model/AttributeMapKey.java index a43dc5d..95cfaff 100644 --- a/src/main/java/com/cburch/draw/model/AttributeMapKey.java +++ b/src/main/java/com/cburch/draw/model/AttributeMapKey.java @@ -8,8 +8,8 @@ public class AttributeMapKey { - private Attribute attribute; - private CanvasObject object; + private final Attribute attribute; + private final CanvasObject object; public AttributeMapKey(Attribute attribute, CanvasObject object) { this.attribute = attribute; diff --git a/src/main/java/com/cburch/draw/model/CanvasModelEvent.java b/src/main/java/com/cburch/draw/model/CanvasModelEvent.java index 7c47a9e..81caad8 100644 --- a/src/main/java/com/cburch/draw/model/CanvasModelEvent.java +++ b/src/main/java/com/cburch/draw/model/CanvasModelEvent.java @@ -22,7 +22,7 @@ public class CanvasModelEvent extends EventObject { public static final int ACTION_HANDLE_DELETED = 6; public static final int ACTION_ATTRIBUTES_CHANGED = 7; public static final int ACTION_TEXT_CHANGED = 8; - private int action; + private final int action; private Collection affected; private int deltaX; private int deltaY; @@ -35,7 +35,7 @@ public class CanvasModelEvent extends EventObject { private String newText; private CanvasModelEvent(CanvasModel source, int action, - Collection affected) { + Collection affected) { super(source); this.action = action; @@ -52,7 +52,7 @@ private CanvasModelEvent(CanvasModel source, int action, } private CanvasModelEvent(CanvasModel source, int action, Collection affected, int deltaX, - int deltaY) { + int deltaY) { this(source, action, affected); this.deltaX = deltaX; @@ -71,8 +71,8 @@ private CanvasModelEvent(CanvasModel source, int action, HandleGesture gesture) this.gesture = gesture; } - private CanvasModelEvent(CanvasModel source, int action, Map oldValues, - Map newValues) { + private CanvasModelEvent(CanvasModel source, int action, Map oldValues, Map newValues) { this(source, action, Collections.emptySet()); HashSet affected = new HashSet<>(newValues.size()); @@ -89,7 +89,7 @@ private CanvasModelEvent(CanvasModel source, int action, Map affected, String oldText, - String newText) { + String newText) { this(source, action, affected); this.oldText = oldText; this.newText = newText; @@ -118,7 +118,7 @@ public static CanvasModelEvent forRemove(CanvasModel source, Collection affected, int deltaX, - int deltaY) { + int deltaY) { return new CanvasModelEvent(source, ACTION_TRANSLATED, affected, deltaX, deltaY); } @@ -139,9 +139,8 @@ public static CanvasModelEvent forMoveHandle(CanvasModel source, HandleGesture g } public static CanvasModelEvent forChangeAttributes(CanvasModel source, Map oldValues, - Map newValues) { - return new CanvasModelEvent(source, ACTION_ATTRIBUTES_CHANGED, - oldValues, newValues); + Map newValues) { + return new CanvasModelEvent(source, ACTION_ATTRIBUTES_CHANGED, oldValues, newValues); } public static CanvasModelEvent forChangeText(CanvasModel source, CanvasObject obj, String oldText, String newText) { diff --git a/src/main/java/com/cburch/draw/model/Drawing.java b/src/main/java/com/cburch/draw/model/Drawing.java index 970d687..804c9bc 100644 --- a/src/main/java/com/cburch/draw/model/Drawing.java +++ b/src/main/java/com/cburch/draw/model/Drawing.java @@ -20,9 +20,9 @@ public class Drawing implements CanvasModel { - private EventSourceWeakSupport listeners; - private ArrayList canvasObjects; - private DrawingOverlaps overlaps; + private final EventSourceWeakSupport listeners; + private final ArrayList canvasObjects; + private final DrawingOverlaps overlaps; public Drawing() { listeners = new EventSourceWeakSupport<>(); @@ -172,7 +172,7 @@ public Handle moveHandle(HandleGesture gesture) { CanvasModelEvent event = CanvasModelEvent.forMoveHandle(this, gesture); CanvasObject object = gesture.getHandle().getObject(); if (canvasObjects.contains(object) && (gesture.getDeltaX() != 0 || gesture.getDeltaY() != 0) && isChangeAllowed( - event)) { + event)) { Handle moveHandle = object.moveHandle(gesture); gesture.setResultingHandle(moveHandle); overlaps.invalidateShape(object); diff --git a/src/main/java/com/cburch/draw/model/DrawingOverlaps.java b/src/main/java/com/cburch/draw/model/DrawingOverlaps.java index c55dd0c..8af7323 100644 --- a/src/main/java/com/cburch/draw/model/DrawingOverlaps.java +++ b/src/main/java/com/cburch/draw/model/DrawingOverlaps.java @@ -14,8 +14,8 @@ class DrawingOverlaps { - private Map> map; - private Set untested; + private final Map> map; + private final Set untested; public DrawingOverlaps() { map = new HashMap<>(); diff --git a/src/main/java/com/cburch/draw/model/Handle.java b/src/main/java/com/cburch/draw/model/Handle.java index 6696594..f53e308 100644 --- a/src/main/java/com/cburch/draw/model/Handle.java +++ b/src/main/java/com/cburch/draw/model/Handle.java @@ -7,9 +7,9 @@ public class Handle { - private CanvasObject object; - private int x; - private int y; + private final CanvasObject object; + private final int x; + private final int y; public Handle(CanvasObject object, int x, int y) { this.object = object; diff --git a/src/main/java/com/cburch/draw/model/HandleGesture.java b/src/main/java/com/cburch/draw/model/HandleGesture.java index a09896e..e641e6e 100644 --- a/src/main/java/com/cburch/draw/model/HandleGesture.java +++ b/src/main/java/com/cburch/draw/model/HandleGesture.java @@ -7,10 +7,10 @@ public class HandleGesture { - private Handle handle; - private int deltaX; - private int deltaY; - private int modifiersEx; + private final Handle handle; + private final int deltaX; + private final int deltaY; + private final int modifiersEx; private Handle resultingHandle; public HandleGesture(Handle handle, int deltaX, int deltaY, int modifiersEx) { @@ -23,7 +23,7 @@ public HandleGesture(Handle handle, int deltaX, int deltaY, int modifiersEx) { @Override public String toString() { return "HandleGesture[" + deltaX + "," + deltaY + ":" + handle.getObject() + "/" + handle.getX() + "," + handle.getY() - + "]"; + + "]"; } public Handle getHandle() { diff --git a/src/main/java/com/cburch/draw/model/ReorderRequest.java b/src/main/java/com/cburch/draw/model/ReorderRequest.java index 4ae4815..de38b24 100644 --- a/src/main/java/com/cburch/draw/model/ReorderRequest.java +++ b/src/main/java/com/cburch/draw/model/ReorderRequest.java @@ -13,9 +13,9 @@ public class ReorderRequest { public static final Comparator DESCENDING_FROM = new Compare(true, true); public static final Comparator ASCENDING_TO = new Compare(true, true); public static final Comparator DESCENDING_TO = new Compare(true, true); - private CanvasObject object; - private int fromIndex; - private int toIndex; + private final CanvasObject object; + private final int fromIndex; + private final int toIndex; public ReorderRequest(CanvasObject object, int fromIndex, int toIndex) { this.object = object; @@ -37,8 +37,8 @@ public int getToIndex() { private static class Compare implements Comparator { - private boolean onFrom; - private boolean asc; + private final boolean onFrom; + private final boolean asc; private Compare(boolean onFrom, boolean asc) { this.onFrom = onFrom; diff --git a/src/main/java/com/cburch/draw/shapes/Curve.java b/src/main/java/com/cburch/draw/shapes/Curve.java index 4b95c0d..ddbf87c 100644 --- a/src/main/java/com/cburch/draw/shapes/Curve.java +++ b/src/main/java/com/cburch/draw/shapes/Curve.java @@ -114,7 +114,7 @@ public boolean contains(Location location, boolean assumeFilled) { threshold = stroke / 2; } if (LineUtil.distanceSquared(nearestPoint[0], nearestPoint[1], locations[0], locations[1]) - < threshold * threshold) { + < threshold * threshold) { return true; } } @@ -145,13 +145,13 @@ public List getHandles(HandleGesture gesture) { private Handle[] getHandleArray(HandleGesture gesture) { if (gesture == null) { return new Handle[]{new Handle(this, p0), new Handle(this, p1), - new Handle(this, p2)}; + new Handle(this, p2)}; } else { Handle gestureHandle = gesture.getHandle(); int gx = gestureHandle.getX() + gesture.getDeltaX(); int gy = gestureHandle.getY() + gesture.getDeltaY(); Handle[] handles = {new Handle(this, p0), new Handle(this, p1), - new Handle(this, p2)}; + new Handle(this, p2)}; if (gestureHandle.isAt(p0)) { if (gesture.isShiftDown()) { Location point = LineUtil.snapTo8Cardinals(p2, gx, gy); @@ -177,7 +177,7 @@ private Handle[] getHandleArray(HandleGesture gesture) { double deltaX = x1 - x0; double deltaY = y1 - y0; double[] p = LineUtil.nearestPointInfinite(gx, gy, - midPointX, midPointY, midPointX - deltaY, midPointY + deltaX); + midPointX, midPointY, midPointX - deltaY, midPointY + deltaX); gx = (int) Math.round(p[0]); gy = (int) Math.round(p[1]); } @@ -234,6 +234,6 @@ public void paint(Graphics graphics, HandleGesture gesture) { private QuadCurve2D getCurve(HandleGesture gesture) { Handle[] handles = getHandleArray(gesture); return new QuadCurve2D.Double(handles[0].getX(), handles[0].getY(), handles[1].getX(), handles[1].getY(), - handles[2].getX(), handles[2].getY()); + handles[2].getX(), handles[2].getY()); } } diff --git a/src/main/java/com/cburch/draw/shapes/CurveUtil.java b/src/main/java/com/cburch/draw/shapes/CurveUtil.java index 47504e9..2312d1b 100644 --- a/src/main/java/com/cburch/draw/shapes/CurveUtil.java +++ b/src/main/java/com/cburch/draw/shapes/CurveUtil.java @@ -64,16 +64,13 @@ private static double[] computeA(double[] p0, double[] p1) { } private static double[] computeB(double[] p0, double[] p1, double[] p2) { - return new double[]{ - p0[0] - 2 * p1[0] + p2[0], - p0[1] - 2 * p1[1] + p2[1]}; + return new double[]{p0[0] - 2 * p1[0] + p2[0], p0[1] - 2 * p1[1] + p2[1]}; } // returns { t:Number, pos:Point, dist:Number, nor:Point } // (costs about 80 multiplications +additions) // note: p0 and p2 are endpoints, p1 is control point - public static double[] findNearestPoint(double[] q, - double[] p0, double[] p1, double[] p2) { + public static double[] findNearestPoint(double[] q, double[] p0, double[] p1, double[] p2) { double[] A = computeA(p0, p1); double[] B = computeB(p0, p1, p2); @@ -125,7 +122,7 @@ public static double[] findNearestPoint(double[] q, } private static void getPos(double[] result, double t, - double[] p0, double[] p1, double[] p2) { + double[] p0, double[] p1, double[] p2) { double a = (1 - t) * (1 - t); double b = 2 * t * (1 - t); double c = t * t; @@ -162,9 +159,9 @@ private static double[] solveCubic(double a, double b, double c, double d) { double u = 2 * Math.sqrt(-p / 3); double v = Math.acos(-Math.sqrt(-27 / p3) * q / 2) / 3; return new double[]{ - u * Math.cos(v) + offset, - u * Math.cos(v + 2 * Math.PI / 3) + offset, - u * Math.cos(v + 4 * Math.PI / 3) + offset}; + u * Math.cos(v) + offset, + u * Math.cos(v + 2 * Math.PI / 3) + offset, + u * Math.cos(v + 4 * Math.PI / 3) + offset}; } else { // D zero double u; @@ -173,9 +170,7 @@ private static double[] solveCubic(double a, double b, double c, double d) { } else { u = -Math.pow(q / 2, 1. / 3); } - return new double[]{ - 2 * u + offset, - -u + offset}; + return new double[]{2 * u + offset, -u + offset}; } } else if (Math.abs(b) > zeroMax) { // a = 0, then actually a 2nd degree equation: @@ -191,8 +186,8 @@ private static double[] solveCubic(double a, double b, double c, double d) { // D positive D = Math.sqrt(D); return new double[]{ - (-b - D) / (2 * a), - (-b + D) / (2 * a)}; + (-b - D) / (2 * a), + (-b + D) / (2 * a)}; } else { // D zero return new double[]{-b / (2 * a)}; @@ -227,8 +222,7 @@ public static double[] interpolate(double[] end0, double[] end1, double[] mid) { double d1 = Math.sqrt(dx * dx + dy * dy); if (d0 < zeroMax || d1 < zeroMax) { - return new double[]{(end0[0] + end1[0]) / 2, - (end0[1] + end1[1]) / 2}; + return new double[]{(end0[0] + end1[0]) / 2, (end0[1] + end1[1]) / 2}; } double t = d0 / (d0 + d1); @@ -241,4 +235,4 @@ public static double[] interpolate(double[] end0, double[] end1, double[] mid) { double yNum = mid[1] - u2 * end0[1] - t2 * end1[1]; return new double[]{xNum / den, yNum / den}; } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/draw/shapes/DrawAttr.java b/src/main/java/com/cburch/draw/shapes/DrawAttr.java index 64ec3c7..a4681f9 100644 --- a/src/main/java/com/cburch/draw/shapes/DrawAttr.java +++ b/src/main/java/com/cburch/draw/shapes/DrawAttr.java @@ -15,68 +15,68 @@ public class DrawAttr { public static final Font DEFAULT_FONT - = new Font("SansSerif", Font.PLAIN, 12); + = new Font("SansSerif", Font.PLAIN, 12); public static final AttributeOption ALIGN_LEFT - = new AttributeOption(EditableLabel.LEFT, Strings.getter("alignStart")); + = new AttributeOption(EditableLabel.LEFT, Strings.getter("alignStart")); public static final AttributeOption ALIGN_CENTER - = new AttributeOption(EditableLabel.CENTER, Strings.getter("alignMiddle")); + = new AttributeOption(EditableLabel.CENTER, Strings.getter("alignMiddle")); public static final AttributeOption ALIGN_RIGHT - = new AttributeOption(EditableLabel.RIGHT, Strings.getter("alignEnd")); + = new AttributeOption(EditableLabel.RIGHT, Strings.getter("alignEnd")); public static final AttributeOption PAINT_STROKE - = new AttributeOption("stroke", Strings.getter("paintStroke")); + = new AttributeOption("stroke", Strings.getter("paintStroke")); public static final AttributeOption PAINT_FILL - = new AttributeOption("fill", Strings.getter("paintFill")); + = new AttributeOption("fill", Strings.getter("paintFill")); public static final AttributeOption PAINT_STROKE_FILL - = new AttributeOption("both", Strings.getter("paintBoth")); + = new AttributeOption("both", Strings.getter("paintBoth")); public static final Attribute FONT - = Attributes.forFont("font", Strings.getter("attrFont")); + = Attributes.forFont("font", Strings.getter("attrFont")); public static final Attribute ALIGNMENT - = Attributes.forOption("align", Strings.getter("attrAlign"), - new AttributeOption[]{ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT}); + = Attributes.forOption("align", Strings.getter("attrAlign"), + new AttributeOption[]{ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT}); public static final Attribute PAINT_TYPE - = Attributes.forOption("paintType", Strings.getter("attrPaint"), - new AttributeOption[]{PAINT_STROKE, PAINT_FILL, PAINT_STROKE_FILL}); + = Attributes.forOption("paintType", Strings.getter("attrPaint"), + new AttributeOption[]{PAINT_STROKE, PAINT_FILL, PAINT_STROKE_FILL}); public static final Attribute STROKE_WIDTH - = Attributes.forIntegerRange("stroke-width", Strings.getter("attrStrokeWidth"), 1, 8); + = Attributes.forIntegerRange("stroke-width", Strings.getter("attrStrokeWidth"), 1, 8); public static final Attribute STROKE_COLOR - = Attributes.forColor("stroke", Strings.getter("attrStroke")); + = Attributes.forColor("stroke", Strings.getter("attrStroke")); public static final Attribute FILL_COLOR - = Attributes.forColor("fill", Strings.getter("attrFill")); + = Attributes.forColor("fill", Strings.getter("attrFill")); public static final Attribute TEXT_DEFAULT_FILL - = Attributes.forColor("fill", Strings.getter("attrFill")); + = Attributes.forColor("fill", Strings.getter("attrFill")); public static final Attribute CORNER_RADIUS - = Attributes.forIntegerRange("rx", Strings.getter("attrRx"), 1, 1000); + = Attributes.forIntegerRange("rx", Strings.getter("attrRx"), 1, 1000); public static final List> ATTRS_TEXT // for text - = createAttributes(new Attribute[]{FONT, ALIGNMENT, FILL_COLOR}); + = createAttributes(new Attribute[]{FONT, ALIGNMENT, FILL_COLOR}); public static final List> ATTRS_TEXT_TOOL // for text tool - = createAttributes(new Attribute[]{FONT, ALIGNMENT, TEXT_DEFAULT_FILL}); + = createAttributes(new Attribute[]{FONT, ALIGNMENT, TEXT_DEFAULT_FILL}); public static final List> ATTRIBUTES_STROKE // for line, polyline - = createAttributes(new Attribute[]{STROKE_WIDTH, STROKE_COLOR}); + = createAttributes(new Attribute[]{STROKE_WIDTH, STROKE_COLOR}); // attribute lists for rectangle, oval, polygon private static final List> ATTRS_FILL_STROKE - = createAttributes(new Attribute[]{PAINT_TYPE, - STROKE_WIDTH, STROKE_COLOR}); + = createAttributes(new Attribute[]{PAINT_TYPE, + STROKE_WIDTH, STROKE_COLOR}); private static final List> ATTRS_FILL_FILL - = createAttributes(new Attribute[]{PAINT_TYPE, FILL_COLOR}); + = createAttributes(new Attribute[]{PAINT_TYPE, FILL_COLOR}); private static final List> ATTRS_FILL_BOTH - = createAttributes(new Attribute[]{PAINT_TYPE, - STROKE_WIDTH, STROKE_COLOR, FILL_COLOR}); + = createAttributes(new Attribute[]{PAINT_TYPE, + STROKE_WIDTH, STROKE_COLOR, FILL_COLOR}); // attribute lists for rounded rectangle private static final List> ATTRS_RRECT_STROKE - = createAttributes(new Attribute[]{PAINT_TYPE, - STROKE_WIDTH, STROKE_COLOR, CORNER_RADIUS}); + = createAttributes(new Attribute[]{PAINT_TYPE, + STROKE_WIDTH, STROKE_COLOR, CORNER_RADIUS}); private static final List> ATTRS_RRECT_FILL - = createAttributes(new Attribute[]{PAINT_TYPE, - FILL_COLOR, CORNER_RADIUS}); + = createAttributes(new Attribute[]{PAINT_TYPE, + FILL_COLOR, CORNER_RADIUS}); private static final List> ATTRS_RRECT_BOTH - = createAttributes(new Attribute[]{PAINT_TYPE, - STROKE_WIDTH, STROKE_COLOR, FILL_COLOR, CORNER_RADIUS}); + = createAttributes(new Attribute[]{PAINT_TYPE, + STROKE_WIDTH, STROKE_COLOR, FILL_COLOR, CORNER_RADIUS}); private static List> createAttributes(Attribute[] values) { return UnmodifiableList.create(values); diff --git a/src/main/java/com/cburch/draw/shapes/FillableCanvasObject.java b/src/main/java/com/cburch/draw/shapes/FillableCanvasObject.java index 3556a91..f877c58 100644 --- a/src/main/java/com/cburch/draw/shapes/FillableCanvasObject.java +++ b/src/main/java/com/cburch/draw/shapes/FillableCanvasObject.java @@ -29,8 +29,7 @@ public boolean matches(CanvasObject object) { FillableCanvasObject that = (FillableCanvasObject) object; boolean isSame = this.paintType == that.paintType; if (isSame && this.paintType != DrawAttr.PAINT_FILL) { - isSame = isSame && this.strokeWidth == that.strokeWidth - && this.strokeColor.equals(that.strokeColor); + isSame = isSame && this.strokeWidth == that.strokeWidth && this.strokeColor.equals(that.strokeColor); } if (isSame && this.paintType != DrawAttr.PAINT_STROKE) { isSame = isSame && this.fillColor.equals(that.fillColor); diff --git a/src/main/java/com/cburch/draw/shapes/Line.java b/src/main/java/com/cburch/draw/shapes/Line.java index a64f3c9..7e867c7 100644 --- a/src/main/java/com/cburch/draw/shapes/Line.java +++ b/src/main/java/com/cburch/draw/shapes/Line.java @@ -45,11 +45,11 @@ public boolean matches(CanvasObject object) { if (object instanceof Line) { Line that = (Line) object; return this.x0 == that.x0 - && this.y0 == that.x1 - && this.x1 == that.y0 - && this.y1 == that.y1 - && this.strokeWidth == that.strokeWidth - && this.strokeColor.equals(that.strokeColor); + && this.y0 == that.x1 + && this.x1 == that.y0 + && this.y1 == that.y1 + && this.strokeWidth == that.strokeWidth + && this.strokeColor.equals(that.strokeColor); } else { return false; } @@ -150,18 +150,15 @@ public List getHandles() { @Override public List getHandles(HandleGesture gesture) { if (gesture == null) { - return UnmodifiableList.create(new Handle[]{ - new Handle(this, x0, y0), new Handle(this, x1, y1)}); + return UnmodifiableList.create(new Handle[]{new Handle(this, x0, y0), new Handle(this, x1, y1)}); } else { Handle h = gesture.getHandle(); int dx = gesture.getDeltaX(); int dy = gesture.getDeltaY(); - Handle[] ret = new Handle[2]; - ret[0] = new Handle(this, h.isAt(x0, y0) - ? Location.create(x0 + dx, y0 + dy) : Location.create(x0, y0)); - ret[1] = new Handle(this, h.isAt(x1, y1) - ? Location.create(x1 + dx, y1 + dy) : Location.create(x1, y1)); - return UnmodifiableList.create(ret); + Handle[] handles = new Handle[2]; + handles[0] = new Handle(this, h.isAt(x0, y0) ? Location.create(x0 + dx, y0 + dy) : Location.create(x0, y0)); + handles[1] = new Handle(this, h.isAt(x1, y1) ? Location.create(x1 + dx, y1 + dy) : Location.create(x1, y1)); + return UnmodifiableList.create(handles); } } diff --git a/src/main/java/com/cburch/draw/shapes/Poly.java b/src/main/java/com/cburch/draw/shapes/Poly.java index d69107a..b18a3c4 100644 --- a/src/main/java/com/cburch/draw/shapes/Poly.java +++ b/src/main/java/com/cburch/draw/shapes/Poly.java @@ -19,7 +19,7 @@ public class Poly extends FillableCanvasObject { - private boolean closed; + private final boolean closed; // "handles" should be immutable - create a new array and change using // setHandles rather than changing contents private Handle[] handles; @@ -124,7 +124,7 @@ public final boolean contains(Location location, boolean assumeFilled) { } int width = getStrokeWidth(); PolyUtil.ClosestResult result = PolyUtil.getClosestPoint(location, - closed, handles); + closed, handles); assert result != null; return result.getDistanceSq() < (width * width) / 4.0; } @@ -304,7 +304,7 @@ public void insertHandle(Handle desired, Handle previous) { Handle[] handles = this.handles; if (previous == null) { PolyUtil.ClosestResult result = PolyUtil.getClosestPoint(location, - closed, handles); + closed, handles); previous = result != null ? result.getPreviousHandle() : null; } Handle[] is = new Handle[handles.length + 1]; diff --git a/src/main/java/com/cburch/draw/shapes/Rectangular.java b/src/main/java/com/cburch/draw/shapes/Rectangular.java index b25f7e6..0d6b8b3 100644 --- a/src/main/java/com/cburch/draw/shapes/Rectangular.java +++ b/src/main/java/com/cburch/draw/shapes/Rectangular.java @@ -80,8 +80,8 @@ private Handle[] getHandleArray(HandleGesture gesture) { int y1 = y0 + bounds.getHeight(); if (gesture == null) { return new Handle[]{new Handle(this, x0, y0), - new Handle(this, x1, y0), new Handle(this, x1, y1), - new Handle(this, x0, y1)}; + new Handle(this, x1, y0), new Handle(this, x1, y1), + new Handle(this, x0, y1)}; } else { int handleX = gesture.getHandle().getX(); int heightY = gesture.getHandle().getY(); @@ -154,8 +154,8 @@ private Handle[] getHandleArray(HandleGesture gesture) { } return new Handle[]{new Handle(this, newX0, newY0), - new Handle(this, newX1, newY0), new Handle(this, newX1, newY1), - new Handle(this, newX0, newY1)}; + new Handle(this, newX1, newY0), new Handle(this, newX1, newY1), + new Handle(this, newX0, newY1)}; } } @@ -247,13 +247,13 @@ public boolean contains(Location location, boolean assumeFilled) { int tol2 = Math.max(2 * Line.ON_LINE_THRESH, stroke); int tol = tol2 / 2; return isInRectangle(qx, qy, x - tol, y - tol, width + tol2, height + tol2) - && contains(x - tol, y - tol, width + tol2, height + tol2, location) - && !contains(x + tol, y + tol, width - tol2, height - tol2, location); + && contains(x - tol, y - tol, width + tol2, height + tol2, location) + && !contains(x + tol, y + tol, width - tol2, height - tol2, location); } else if (type == DrawAttr.PAINT_STROKE_FILL) { int stroke = getStrokeWidth(); int tol = stroke / 2; return isInRectangle(qx, qy, x - tol, y - tol, width + stroke, height + stroke) - && contains(x - tol, y - tol, width + stroke, height + stroke, location); + && contains(x - tol, y - tol, width + stroke, height + stroke, location); } else { return false; } diff --git a/src/main/java/com/cburch/draw/shapes/Strings.java b/src/main/java/com/cburch/draw/shapes/Strings.java index e21f576..e40ec8c 100644 --- a/src/main/java/com/cburch/draw/shapes/Strings.java +++ b/src/main/java/com/cburch/draw/shapes/Strings.java @@ -8,7 +8,7 @@ class Strings { - private static LocaleManager source = new LocaleManager("logisim", "draw"); + private static final LocaleManager source = new LocaleManager("logisim", "draw"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/draw/shapes/SvgCreator.java b/src/main/java/com/cburch/draw/shapes/SvgCreator.java index dd6d18d..33bef60 100644 --- a/src/main/java/com/cburch/draw/shapes/SvgCreator.java +++ b/src/main/java/com/cburch/draw/shapes/SvgCreator.java @@ -70,9 +70,8 @@ public static Element createCurve(Document document, Curve curve) { Location end0 = curve.getEnd0(); Location end1 = curve.getEnd1(); Location control = curve.getControl(); - element.setAttribute("d", "M" + end0.getX() + "," + end0.getY() - + " Q" + control.getX() + "," + control.getY() - + " " + end1.getX() + "," + end1.getY()); + element.setAttribute("d", "M" + end0.getX() + "," + end0.getY() + " Q" + control.getX() + "," + + control.getY() + " " + end1.getX() + "," + end1.getY()); populateFill(element, curve); return element; } diff --git a/src/main/java/com/cburch/draw/shapes/SvgReader.java b/src/main/java/com/cburch/draw/shapes/SvgReader.java index e0e64bb..ac5d4b3 100644 --- a/src/main/java/com/cburch/draw/shapes/SvgReader.java +++ b/src/main/java/com/cburch/draw/shapes/SvgReader.java @@ -141,7 +141,7 @@ private static AbstractCanvasObject createText(Element element) { String fontStyle = element.getAttribute("font-style"); String fontWeight = element.getAttribute("font-weight"); String fontSize = element.getAttribute("font-size"); - int styleFlags = 0; + int styleFlags = Font.PLAIN; if (fontStyle.equals("italic")) { styleFlags |= Font.ITALIC; } @@ -220,7 +220,7 @@ private static AbstractCanvasObject createPath(Element element) { if (type == 1) { if (tokens.size() == 8 && tokens.get(0).equals("M") - && tokens.get(3).toUpperCase().equals("Q")) { + && tokens.get(3).equalsIgnoreCase("Q")) { int x0 = Integer.parseInt(tokens.get(1)); int y0 = Integer.parseInt(tokens.get(2)); int x1 = Integer.parseInt(tokens.get(4)); diff --git a/src/main/java/com/cburch/draw/shapes/Text.java b/src/main/java/com/cburch/draw/shapes/Text.java index 8cd4d3e..e6ab9b7 100644 --- a/src/main/java/com/cburch/draw/shapes/Text.java +++ b/src/main/java/com/cburch/draw/shapes/Text.java @@ -145,8 +145,8 @@ public List getHandles() { int width = bounds.getWidth(); int height = bounds.getHeight(); return UnmodifiableList.create(new Handle[]{ - new Handle(this, x, y), new Handle(this, x + width, y), - new Handle(this, x + width, y + height), new Handle(this, x, y + height)}); + new Handle(this, x, y), new Handle(this, x + width, y), + new Handle(this, x + width, y + height), new Handle(this, x, y + height)}); } @Override diff --git a/src/main/java/com/cburch/draw/toolbar/AbstractToolbarModel.java b/src/main/java/com/cburch/draw/toolbar/AbstractToolbarModel.java index bf0a0b1..1ee9c62 100644 --- a/src/main/java/com/cburch/draw/toolbar/AbstractToolbarModel.java +++ b/src/main/java/com/cburch/draw/toolbar/AbstractToolbarModel.java @@ -8,7 +8,7 @@ public abstract class AbstractToolbarModel implements ToolbarModel { - private List listeners; + private final List listeners; protected AbstractToolbarModel() { listeners = new ArrayList<>(); diff --git a/src/main/java/com/cburch/draw/toolbar/Toolbar.java b/src/main/java/com/cburch/draw/toolbar/Toolbar.java index fa9694c..c542b4d 100644 --- a/src/main/java/com/cburch/draw/toolbar/Toolbar.java +++ b/src/main/java/com/cburch/draw/toolbar/Toolbar.java @@ -12,10 +12,10 @@ public class Toolbar extends JPanel { public static final Object VERTICAL = new Object(); public static final Object HORIZONTAL = new Object(); + private final JPanel subPanel; + private final MyListener myListener; private ToolbarModel model; - private JPanel subPanel; private Object orientation; - private MyListener myListener; private ToolbarButton currentlyPressed; public Toolbar(ToolbarModel model) { diff --git a/src/main/java/com/cburch/draw/toolbar/ToolbarButton.java b/src/main/java/com/cburch/draw/toolbar/ToolbarButton.java index 7d69b3f..b85678d 100644 --- a/src/main/java/com/cburch/draw/toolbar/ToolbarButton.java +++ b/src/main/java/com/cburch/draw/toolbar/ToolbarButton.java @@ -15,8 +15,8 @@ class ToolbarButton extends JComponent implements MouseListener { private static final int BORDER = 2; - private Toolbar toolbar; - private ToolbarItem item; + private final Toolbar toolbar; + private final ToolbarItem item; ToolbarButton(Toolbar toolbar, ToolbarItem item) { this.toolbar = toolbar; diff --git a/src/main/java/com/cburch/draw/toolbar/ToolbarSeparator.java b/src/main/java/com/cburch/draw/toolbar/ToolbarSeparator.java index d5bfd94..eae9dd4 100644 --- a/src/main/java/com/cburch/draw/toolbar/ToolbarSeparator.java +++ b/src/main/java/com/cburch/draw/toolbar/ToolbarSeparator.java @@ -10,7 +10,7 @@ public class ToolbarSeparator implements ToolbarItem { - private int size; + private final int size; public ToolbarSeparator(int size) { this.size = size; diff --git a/src/main/java/com/cburch/draw/tools/AbstractTool.java b/src/main/java/com/cburch/draw/tools/AbstractTool.java index e8fd5f8..57740ef 100644 --- a/src/main/java/com/cburch/draw/tools/AbstractTool.java +++ b/src/main/java/com/cburch/draw/tools/AbstractTool.java @@ -17,14 +17,14 @@ public abstract class AbstractTool extends CanvasTool { public static AbstractTool[] getTools(DrawingAttributeSet attributes) { return new AbstractTool[]{ - new SelectTool(), - new LineTool(attributes), - new CurveTool(attributes), - new PolyTool(false, attributes), - new RectangleTool(attributes), - new RoundRectangleTool(attributes), - new OvalTool(attributes), - new PolyTool(true, attributes), + new SelectTool(), + new LineTool(attributes), + new CurveTool(attributes), + new PolyTool(false, attributes), + new RectangleTool(attributes), + new RoundRectangleTool(attributes), + new OvalTool(attributes), + new PolyTool(true, attributes), }; } diff --git a/src/main/java/com/cburch/draw/tools/CurveTool.java b/src/main/java/com/cburch/draw/tools/CurveTool.java index 7d26911..4c8f813 100644 --- a/src/main/java/com/cburch/draw/tools/CurveTool.java +++ b/src/main/java/com/cburch/draw/tools/CurveTool.java @@ -29,7 +29,7 @@ public class CurveTool extends AbstractTool { private static final int ENDPOINT_DRAG = 1; private static final int CONTROL_DRAG = 2; - private DrawingAttributeSet attributes; + private final DrawingAttributeSet attributes; private int state; private Location end0; private Location end1; @@ -175,7 +175,7 @@ private Curve updateMouse(Canvas canvas, int mouseX, int mouseY, int mods) { double deltaX = x1 - x0; double deltaY = y1 - y0; double[] p = LineUtil - .nearestPointInfinite(cx, cy, midPointX, midPointY, midPointX - deltaY, midPointY + deltaX); + .nearestPointInfinite(cx, cy, midPointX, midPointY, midPointX - deltaY, midPointY + deltaX); cx = (int) Math.round(p[0]); cy = (int) Math.round(p[1]); } diff --git a/src/main/java/com/cburch/draw/tools/DrawingAttributeSet.java b/src/main/java/com/cburch/draw/tools/DrawingAttributeSet.java index fdfe169..142a36f 100644 --- a/src/main/java/com/cburch/draw/tools/DrawingAttributeSet.java +++ b/src/main/java/com/cburch/draw/tools/DrawingAttributeSet.java @@ -23,20 +23,29 @@ public class DrawingAttributeSet implements AttributeSet, Cloneable { - private static final List> ATTRIBUTES_ALL - = UnmodifiableList.create(new Attribute[]{ - DrawAttr.FONT, DrawAttr.ALIGNMENT, + private static final List> ATTRIBUTES_ALL = UnmodifiableList.create( + new Attribute[]{ + DrawAttr.FONT, + DrawAttr.ALIGNMENT, DrawAttr.PAINT_TYPE, - DrawAttr.STROKE_WIDTH, DrawAttr.STROKE_COLOR, - DrawAttr.FILL_COLOR, DrawAttr.TEXT_DEFAULT_FILL, - DrawAttr.CORNER_RADIUS}); - private static final List DEFAULTS_ALL - = Arrays.asList(DrawAttr.DEFAULT_FONT, DrawAttr.ALIGN_CENTER, - DrawAttr.PAINT_STROKE, - 1, Color.BLACK, - Color.WHITE, Color.BLACK, 10); + DrawAttr.STROKE_WIDTH, + DrawAttr.STROKE_COLOR, + DrawAttr.FILL_COLOR, + DrawAttr.TEXT_DEFAULT_FILL, + DrawAttr.CORNER_RADIUS + } + ); + private static final List DEFAULTS_ALL = Arrays.asList( + DrawAttr.DEFAULT_FONT, + DrawAttr.ALIGN_CENTER, + DrawAttr.PAINT_STROKE, + 1, + Color.BLACK, + Color.WHITE, + Color.BLACK, 10 + ); + private final List> attributes; private EventSourceWeakSupport listeners; - private List> attributes; private List values; public DrawingAttributeSet() { @@ -155,9 +164,9 @@ public E applyTo(E drawable) { } private class Restriction extends AbstractAttributeSet - implements AttributeListener { + implements AttributeListener { - private AbstractTool tool; + private final AbstractTool tool; private List> selectedAttributes; private List> selectedView; diff --git a/src/main/java/com/cburch/draw/tools/LineTool.java b/src/main/java/com/cburch/draw/tools/LineTool.java index e397de7..bceabdb 100644 --- a/src/main/java/com/cburch/draw/tools/LineTool.java +++ b/src/main/java/com/cburch/draw/tools/LineTool.java @@ -25,7 +25,7 @@ public class LineTool extends AbstractTool { - private DrawingAttributeSet attributeSet; + private final DrawingAttributeSet attributeSet; private boolean isActive; private Location mouseStart; private Location mouseEnd; diff --git a/src/main/java/com/cburch/draw/tools/OvalTool.java b/src/main/java/com/cburch/draw/tools/OvalTool.java index 1711b49..0139b16 100644 --- a/src/main/java/com/cburch/draw/tools/OvalTool.java +++ b/src/main/java/com/cburch/draw/tools/OvalTool.java @@ -14,7 +14,7 @@ public class OvalTool extends RectangularTool { - private DrawingAttributeSet attributeSet; + private final DrawingAttributeSet attributeSet; public OvalTool(DrawingAttributeSet attributeSet) { this.attributeSet = attributeSet; diff --git a/src/main/java/com/cburch/draw/tools/PolyTool.java b/src/main/java/com/cburch/draw/tools/PolyTool.java index 944c34c..ab512ac 100644 --- a/src/main/java/com/cburch/draw/tools/PolyTool.java +++ b/src/main/java/com/cburch/draw/tools/PolyTool.java @@ -28,10 +28,10 @@ public class PolyTool extends AbstractTool { // how close we need to be to the start point to count as "closing the loop" private static final int CLOSE_TOLERANCE = 2; - private boolean isClosed; // whether we are drawing polygons or polylines - private DrawingAttributeSet attributeSet; + private final boolean isClosed; // whether we are drawing polygons or polylines + private final DrawingAttributeSet attributeSet; + private final ArrayList locations; private boolean isActive; - private ArrayList locations; private boolean isMouseDown; private int lastMouseX; private int lastMouseY; diff --git a/src/main/java/com/cburch/draw/tools/RectangleTool.java b/src/main/java/com/cburch/draw/tools/RectangleTool.java index 2f50ab8..db1f2c8 100644 --- a/src/main/java/com/cburch/draw/tools/RectangleTool.java +++ b/src/main/java/com/cburch/draw/tools/RectangleTool.java @@ -14,7 +14,7 @@ public class RectangleTool extends RectangularTool { - private DrawingAttributeSet attributeSet; + private final DrawingAttributeSet attributeSet; public RectangleTool(DrawingAttributeSet attributeSet) { this.attributeSet = attributeSet; diff --git a/src/main/java/com/cburch/draw/tools/RectangularTool.java b/src/main/java/com/cburch/draw/tools/RectangularTool.java index bb6de8e..a2b062a 100644 --- a/src/main/java/com/cburch/draw/tools/RectangularTool.java +++ b/src/main/java/com/cburch/draw/tools/RectangularTool.java @@ -177,7 +177,7 @@ public void draw(Canvas canvas, Graphics graphics) { if (isActive && currentBounds != null && currentBounds != Bounds.EMPTY_BOUNDS) { graphics.setColor(Color.GRAY); drawShape(graphics, currentBounds.getX(), currentBounds.getY(), currentBounds.getWidth(), - currentBounds.getHeight()); + currentBounds.getHeight()); } } diff --git a/src/main/java/com/cburch/draw/tools/RoundRectangleTool.java b/src/main/java/com/cburch/draw/tools/RoundRectangleTool.java index bfb5519..0a8cb4e 100644 --- a/src/main/java/com/cburch/draw/tools/RoundRectangleTool.java +++ b/src/main/java/com/cburch/draw/tools/RoundRectangleTool.java @@ -14,7 +14,7 @@ public class RoundRectangleTool extends RectangularTool { - private DrawingAttributeSet attributeSet; + private final DrawingAttributeSet attributeSet; public RoundRectangleTool(DrawingAttributeSet attributeSet) { this.attributeSet = attributeSet; diff --git a/src/main/java/com/cburch/draw/tools/SelectTool.java b/src/main/java/com/cburch/draw/tools/SelectTool.java index 8439674..c4bca31 100644 --- a/src/main/java/com/cburch/draw/tools/SelectTool.java +++ b/src/main/java/com/cburch/draw/tools/SelectTool.java @@ -128,11 +128,11 @@ public void mousePressed(Canvas canvas, MouseEvent event) { int dx = han.getX() - mouseX; int dy = han.getY() - mouseY; if (dx >= -halfSize && dx <= halfSize - && dy >= -halfSize && dy <= halfSize) { + && dy >= -halfSize && dy <= halfSize) { if (shape.canMoveHandle(han)) { currentAction = MOVE_HANDLE; currentGesture = new HandleGesture(han, 0, 0, - event.getModifiersEx()); + event.getModifiersEx()); repaintArea(canvas); return; } else if (clicked == null) { diff --git a/src/main/java/com/cburch/draw/tools/TextTool.java b/src/main/java/com/cburch/draw/tools/TextTool.java index 05f059c..a8e76a2 100644 --- a/src/main/java/com/cburch/draw/tools/TextTool.java +++ b/src/main/java/com/cburch/draw/tools/TextTool.java @@ -32,9 +32,9 @@ public class TextTool extends AbstractTool { - private DrawingAttributeSet attributeSet; - private EditableLabelField field; - private FieldListener fieldListener; + private final DrawingAttributeSet attributeSet; + private final EditableLabelField field; + private final FieldListener fieldListener; private Text currentText; private Canvas currentCanvas; private boolean isTextNew; diff --git a/src/main/java/com/cburch/draw/tools/ToolbarToolItem.java b/src/main/java/com/cburch/draw/tools/ToolbarToolItem.java index 6f599d5..5ed6017 100644 --- a/src/main/java/com/cburch/draw/tools/ToolbarToolItem.java +++ b/src/main/java/com/cburch/draw/tools/ToolbarToolItem.java @@ -12,8 +12,8 @@ public class ToolbarToolItem implements ToolbarItem { - private AbstractTool tool; - private Icon icon; + private final AbstractTool tool; + private final Icon icon; public ToolbarToolItem(AbstractTool tool) { this.tool = tool; diff --git a/src/main/java/com/cburch/draw/undo/ActionUnion.java b/src/main/java/com/cburch/draw/undo/ActionUnion.java index a7fd042..e4dbad2 100644 --- a/src/main/java/com/cburch/draw/undo/ActionUnion.java +++ b/src/main/java/com/cburch/draw/undo/ActionUnion.java @@ -5,8 +5,8 @@ class ActionUnion extends Action { - private Action first; - private Action second; + private final Action first; + private final Action second; ActionUnion(Action first, Action second) { this.first = first; diff --git a/src/main/java/com/cburch/draw/undo/UndoLog.java b/src/main/java/com/cburch/draw/undo/UndoLog.java index d6a7b33..fc143e9 100644 --- a/src/main/java/com/cburch/draw/undo/UndoLog.java +++ b/src/main/java/com/cburch/draw/undo/UndoLog.java @@ -10,9 +10,9 @@ public class UndoLog { private static final int MAX_UNDO_SIZE = 64; - private EventSourceWeakSupport listeners; - private LinkedList undoLog; - private LinkedList redoLog; + private final EventSourceWeakSupport listeners; + private final LinkedList undoLog; + private final LinkedList redoLog; private int modCount; public UndoLog() { diff --git a/src/main/java/com/cburch/draw/undo/UndoLogDispatcher.java b/src/main/java/com/cburch/draw/undo/UndoLogDispatcher.java index bcfb3a7..05609b0 100644 --- a/src/main/java/com/cburch/draw/undo/UndoLogDispatcher.java +++ b/src/main/java/com/cburch/draw/undo/UndoLogDispatcher.java @@ -7,7 +7,7 @@ public class UndoLogDispatcher implements ActionDispatcher { - private UndoLog log; + private final UndoLog log; public UndoLogDispatcher(UndoLog log) { this.log = log; diff --git a/src/main/java/com/cburch/draw/undo/UndoLogEvent.java b/src/main/java/com/cburch/draw/undo/UndoLogEvent.java index 504cd0d..85b8557 100644 --- a/src/main/java/com/cburch/draw/undo/UndoLogEvent.java +++ b/src/main/java/com/cburch/draw/undo/UndoLogEvent.java @@ -10,8 +10,8 @@ public class UndoLogEvent extends EventObject { public static final int ACTION_DONE = 0; public static final int ACTION_UNDONE = 1; - private int action; - private Action actionObject; + private final int action; + private final Action actionObject; public UndoLogEvent(UndoLog source, int action, Action actionObject) { super(source); diff --git a/src/main/java/com/cburch/draw/util/EditableLabel.java b/src/main/java/com/cburch/draw/util/EditableLabel.java index dc06f2d..2e28229 100644 --- a/src/main/java/com/cburch/draw/util/EditableLabel.java +++ b/src/main/java/com/cburch/draw/util/EditableLabel.java @@ -17,7 +17,8 @@ import java.util.Arrays; import javax.swing.JTextField; -public class EditableLabel implements Cloneable { +public class +EditableLabel implements Cloneable { public static final int LEFT = JTextField.LEFT; public static final int RIGHT = JTextField.RIGHT; @@ -27,12 +28,11 @@ public class EditableLabel implements Cloneable { public static final int MIDDLE = 9; public static final int BASELINE = 10; public static final int BOTTOM = 11; - + public Color color; private int x; private int y; private String text; private Font font; - public Color color; private int horizontalAlignment; private int verticalAlignment; private boolean areDimensionsKnown; @@ -67,10 +67,10 @@ public boolean equals(Object other) { if (other instanceof EditableLabel) { EditableLabel that = (EditableLabel) other; return this.x == that.x && this.y == that.y - && this.text.equals(that.text) && this.font.equals(that.font) - && this.color.equals(that.color) - && this.horizontalAlignment == that.horizontalAlignment - && this.verticalAlignment == that.verticalAlignment; + && this.text.equals(that.text) && this.font.equals(that.font) + && this.color.equals(that.color) + && this.horizontalAlignment == that.horizontalAlignment + && this.verticalAlignment == that.verticalAlignment; } else { return false; } @@ -147,7 +147,7 @@ public int getVerticalAlignment() { public void setVerticalAlignment(int verticalAlignment) { if (verticalAlignment != TOP && verticalAlignment != MIDDLE && verticalAlignment != BASELINE - && verticalAlignment != BOTTOM) { + && verticalAlignment != BOTTOM) { throw new IllegalArgumentException("argument must be TOP, MIDDLE, BASELINE, or BOTTOM"); } this.verticalAlignment = verticalAlignment; @@ -169,7 +169,7 @@ public boolean contains(int qx, int qy) { int x0 = getLeftX(); int y0 = getBaseY(); if (qx >= x0 && qx < x0 + width - && qy >= y0 - ascent && qy < y0 + descent) { + && qy >= y0 - ascent && qy < y0 + descent) { int[] xs = charX; int[] ys = charY; if (xs == null || ys == null) { diff --git a/src/main/java/com/cburch/draw/util/EditableLabelField.java b/src/main/java/com/cburch/draw/util/EditableLabelField.java index 3fdf9b2..aa85ee8 100644 --- a/src/main/java/com/cburch/draw/util/EditableLabelField.java +++ b/src/main/java/com/cburch/draw/util/EditableLabelField.java @@ -3,8 +3,11 @@ package com.cburch.draw.util; -import javax.swing.*; -import java.awt.*; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Point; +import javax.swing.BorderFactory; +import javax.swing.JTextField; public class EditableLabelField extends JTextField { @@ -15,7 +18,7 @@ public EditableLabelField() { setBackground(new Color(255, 255, 255, 128)); setOpaque(false); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK), - BorderFactory.createEmptyBorder(1, 1, 1, 1))); + BorderFactory.createEmptyBorder(1, 1, 1, 1))); } @Override diff --git a/src/main/java/com/cburch/draw/util/MatchingSet.java b/src/main/java/com/cburch/draw/util/MatchingSet.java index f0f75d0..644bede 100644 --- a/src/main/java/com/cburch/draw/util/MatchingSet.java +++ b/src/main/java/com/cburch/draw/util/MatchingSet.java @@ -11,7 +11,7 @@ public class MatchingSet extends AbstractSet { - private HashSet> set; + private final HashSet> set; public MatchingSet() { set = new HashSet<>(); @@ -76,7 +76,7 @@ public int hashCode() { private static class MatchIterator implements Iterator { - private Iterator> iterator; + private final Iterator> iterator; private MatchIterator(Iterator> iterator) { this.iterator = iterator; diff --git a/src/main/java/com/cburch/draw/util/ZOrder.java b/src/main/java/com/cburch/draw/util/ZOrder.java index 3417b83..35ece88 100644 --- a/src/main/java/com/cburch/draw/util/ZOrder.java +++ b/src/main/java/com/cburch/draw/util/ZOrder.java @@ -26,7 +26,7 @@ public static int getZIndex(CanvasObject query, CanvasModel model) { } public static Map getZIndex( - Collection query, CanvasModel model) { + Collection query, CanvasModel model) { // returns 0 for bottommost element, large number for topmost, ordered // from the bottom up. if (query == null) { @@ -47,17 +47,17 @@ public static Map getZIndex( } public static List sortTopFirst( - Collection objects, CanvasModel model) { + Collection objects, CanvasModel model) { return sortXFirst(objects, model, model.getObjectsFromBottom()); } public static List sortBottomFirst( - Collection objects, CanvasModel model) { + Collection objects, CanvasModel model) { return sortXFirst(objects, model, model.getObjectsFromTop()); } private static List sortXFirst( - Collection objects, CanvasModel model, Collection objs) { + Collection objects, CanvasModel model, Collection objs) { Set set = toSet(objects); ArrayList ret = new ArrayList<>(objects.size()); for (CanvasObject o : objs) { @@ -80,19 +80,19 @@ private static Set toSet(Collection objects) { // returns first object above query in the z-order that overlaps query public static CanvasObject getObjectAbove(CanvasObject query, - CanvasModel model, Collection ignore) { + CanvasModel model, Collection ignore) { return getPrevious(query, model.getObjectsFromTop(), model, ignore); } // returns first object below query in the z-order that overlaps query public static CanvasObject getObjectBelow(CanvasObject query, - CanvasModel model, Collection ignore) { + CanvasModel model, Collection ignore) { return getPrevious(query, model.getObjectsFromBottom(), model, ignore); } private static CanvasObject getPrevious(CanvasObject query, - List objs, CanvasModel model, - Collection ignore) { + List objs, CanvasModel model, + Collection ignore) { int index = getIndex(query, objs); if (index <= 0) { return null; diff --git a/src/main/java/com/cburch/gray/Components.java b/src/main/java/com/cburch/gray/Components.java index 112403d..52e18db 100644 --- a/src/main/java/com/cburch/gray/Components.java +++ b/src/main/java/com/cburch/gray/Components.java @@ -19,7 +19,7 @@ public class Components extends Library { * than components; practically speaking, though, you'll most often want * to create AddTools for new components that can be added into the circuit. */ - private List tools; + private final List tools; /** * Constructs an instance of this library. This constructor is how @@ -28,7 +28,7 @@ public class Components extends Library { */ public Components() { tools = Arrays.asList(new AddTool(new GrayIncrementer()), new AddTool(new SimpleGrayCounter()), - new AddTool(new GrayCounter())); + new AddTool(new GrayCounter())); } /** diff --git a/src/main/java/com/cburch/gray/CounterPoker.java b/src/main/java/com/cburch/gray/CounterPoker.java index 101d4c9..e0c8c1e 100644 --- a/src/main/java/com/cburch/gray/CounterPoker.java +++ b/src/main/java/com/cburch/gray/CounterPoker.java @@ -52,7 +52,7 @@ public void paint(InstancePainter painter) { int width = 7 * length + 2; // width of caret rectangle int height = 16; // height of caret rectangle graphics.drawRect(bounds.getX() + (bounds.getWidth() - width) / 2, bounds.getY() + (bounds.getHeight() - height) / 2, - width, height); + width, height); graphics.setColor(Color.BLACK); } diff --git a/src/main/java/com/cburch/gray/GrayCounter.java b/src/main/java/com/cburch/gray/GrayCounter.java index 5ae107b..dc3f9ef 100644 --- a/src/main/java/com/cburch/gray/GrayCounter.java +++ b/src/main/java/com/cburch/gray/GrayCounter.java @@ -28,8 +28,8 @@ public GrayCounter() { super("Gray Counter"); setOffsetBounds(Bounds.create(-30, -15, 30, 30)); setPorts(new Port[]{ - new Port(-30, 0, Port.INPUT, 1), - new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH), + new Port(-30, 0, Port.INPUT, 1), + new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH), }); // We'll have width, label, and label font attributes. The latter two @@ -37,8 +37,16 @@ public GrayCounter() { // we'll also need configureNewInstance to configure the label's // location). setAttributes( - new Attribute[]{StdAttr.WIDTH, StdAttr.LABEL, StdAttr.LABEL_FONT}, - new Object[]{BitWidth.create(4), "", StdAttr.DEFAULT_LABEL_FONT}); + new Attribute[]{ + StdAttr.WIDTH, + StdAttr.LABEL, + StdAttr.LABEL_FONT + }, new Object[]{ + BitWidth.create(4), + "", + StdAttr.DEFAULT_LABEL_FONT + } + ); // The following method invocation sets things up so that the instance's // state can be manipulated using the Poke Tool. @@ -65,8 +73,8 @@ public GrayCounter() { protected void configureNewInstance(Instance instance) { Bounds bounds = instance.getBounds(); instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, - bounds.getX() + bounds.getWidth() / 2, bounds.getY() - 3, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + bounds.getX() + bounds.getWidth() / 2, bounds.getY() - 3, + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); } @Override @@ -96,9 +104,9 @@ public void paintInstance(InstancePainter painter) { CounterData counterData = CounterData.get(painter, bitWidth); Bounds bounds = painter.getBounds(); GraphicsUtil.drawCenteredText(painter.getGraphics(), - StringUtil.toHexString(bitWidth.getWidth(), counterData.getValue().toIntValue()), - bounds.getX() + bounds.getWidth() / 2, - bounds.getY() + bounds.getHeight() / 2); + StringUtil.toHexString(bitWidth.getWidth(), counterData.getValue().toIntValue()), + bounds.getX() + bounds.getWidth() / 2, + bounds.getY() + bounds.getHeight() / 2); } } } diff --git a/src/main/java/com/cburch/gray/GrayIncrementer.java b/src/main/java/com/cburch/gray/GrayIncrementer.java index a2a9ef4..1a3c63b 100644 --- a/src/main/java/com/cburch/gray/GrayIncrementer.java +++ b/src/main/java/com/cburch/gray/GrayIncrementer.java @@ -37,8 +37,13 @@ class GrayIncrementer extends InstanceFactory { * StdAttr attributes when appropriate: A user can then select several * components (even from differing factories) with the same attribute * and modify them all at once. */ - setAttributes(new Attribute[]{StdAttr.WIDTH}, - new Object[]{BitWidth.create(4)}); + setAttributes( + new Attribute[]{ + StdAttr.WIDTH + }, new Object[]{ + BitWidth.create(4) + } + ); /* The "offset bounds" is the location of the bounding rectangle * relative to the mouse location. Here, we're choosing the component to @@ -55,8 +60,8 @@ class GrayIncrementer extends InstanceFactory { * The bit width can be a constant (like 1) or an attribute (as here). */ setPorts(new Port[]{ - new Port(-30, 0, Port.INPUT, StdAttr.WIDTH), - new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH), + new Port(-30, 0, Port.INPUT, StdAttr.WIDTH), + new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH), }); } diff --git a/src/main/java/com/cburch/gray/SimpleGrayCounter.java b/src/main/java/com/cburch/gray/SimpleGrayCounter.java index 0d0e5b0..43a56a4 100644 --- a/src/main/java/com/cburch/gray/SimpleGrayCounter.java +++ b/src/main/java/com/cburch/gray/SimpleGrayCounter.java @@ -31,8 +31,8 @@ public SimpleGrayCounter() { super("Gray Counter (Simple)"); setOffsetBounds(Bounds.create(-30, -15, 30, 30)); setPorts(new Port[]{ - new Port(-30, 0, Port.INPUT, 1), - new Port(0, 0, Port.OUTPUT, BIT_WIDTH.getWidth()), + new Port(-30, 0, Port.INPUT, 1), + new Port(0, 0, Port.OUTPUT, BIT_WIDTH.getWidth()), }); } @@ -70,9 +70,9 @@ public void paintInstance(InstancePainter painter) { CounterData state = CounterData.get(painter, BIT_WIDTH); Bounds bounds = painter.getBounds(); GraphicsUtil.drawCenteredText(painter.getGraphics(), - StringUtil.toHexString(BIT_WIDTH.getWidth(), state.getValue().toIntValue()), - bounds.getX() + bounds.getWidth() / 2, - bounds.getY() + bounds.getHeight() / 2); + StringUtil.toHexString(BIT_WIDTH.getWidth(), state.getValue().toIntValue()), + bounds.getX() + bounds.getWidth() / 2, + bounds.getY() + bounds.getHeight() / 2); } } } diff --git a/src/main/java/com/cburch/hex/Caret.java b/src/main/java/com/cburch/hex/Caret.java index 4b66240..4cda630 100644 --- a/src/main/java/com/cburch/hex/Caret.java +++ b/src/main/java/com/cburch/hex/Caret.java @@ -29,8 +29,8 @@ public class Caret { private static final Stroke CURSOR_STROKE = new BasicStroke(2.0f); private static final Color SELECT_COLOR = new Color(192, 192, 255); - private HexEditor hex; - private ArrayList listeners; + private final HexEditor hex; + private final ArrayList listeners; private long mark; private long cursor; private Object highlight; @@ -138,7 +138,7 @@ void paintForeground(Graphics graphics, long start, long end) { } private class Listener implements MouseListener, MouseMotionListener, - KeyListener, FocusListener { + KeyListener, FocusListener { public void mouseClicked(MouseEvent event) { } diff --git a/src/main/java/com/cburch/hex/HexEditor.java b/src/main/java/com/cburch/hex/HexEditor.java index dcfcc52..8986dd3 100644 --- a/src/main/java/com/cburch/hex/HexEditor.java +++ b/src/main/java/com/cburch/hex/HexEditor.java @@ -15,11 +15,11 @@ public class HexEditor extends JComponent implements Scrollable { + private final Listener listener; + private final Measures measures; + private final Caret caret; + private final Highlighter highlighter; private HexModel model; - private Listener listener; - private Measures measures; - private Caret caret; - private Highlighter highlighter; public HexEditor(HexModel model) { this.model = model; @@ -255,7 +255,7 @@ public void metaInfoChanged(HexModel source) { public void bytesChanged(HexModel source, long start, long numBytes, int[] oldValues) { repaint(0, measures.toY(start), - getWidth(), measures.toY(start + numBytes) + measures.getCellHeight()); + getWidth(), measures.toY(start + numBytes) + measures.getCellHeight()); } } } diff --git a/src/main/java/com/cburch/hex/Highlighter.java b/src/main/java/com/cburch/hex/Highlighter.java index 6e3ad7c..9250e6d 100644 --- a/src/main/java/com/cburch/hex/Highlighter.java +++ b/src/main/java/com/cburch/hex/Highlighter.java @@ -9,7 +9,7 @@ class Highlighter { - private HexEditor hex; + private final HexEditor hex; private ArrayList entries; Highlighter(HexEditor hex) { @@ -108,9 +108,9 @@ synchronized void paint(Graphics g, long start, long end) { private static class Entry { - private long start; - private long end; - private Color color; + private final long start; + private final long end; + private final Color color; Entry(long start, long end, Color color) { this.start = start; diff --git a/src/main/java/com/cburch/hex/Measures.java b/src/main/java/com/cburch/hex/Measures.java index faaab1d..69ac8fb 100644 --- a/src/main/java/com/cburch/hex/Measures.java +++ b/src/main/java/com/cburch/hex/Measures.java @@ -10,7 +10,7 @@ class Measures { - private HexEditor hex; + private final HexEditor hex; private int headerChars; private int cellChars; private int headerWidth; @@ -144,7 +144,7 @@ void widthChanged() { } } int lineWidth = headerWidth + columns * cellWidth - + ((columns / 4) - 1) * spacerWidth; + + ((columns / 4) - 1) * spacerWidth; int newBase = headerWidth + Math.max(0, (width - lineWidth) / 2); if (baseX != newBase) { baseX = newBase; diff --git a/src/main/java/com/cburch/hex/Test.java b/src/main/java/com/cburch/hex/Test.java index 0052f0a..85b35f2 100644 --- a/src/main/java/com/cburch/hex/Test.java +++ b/src/main/java/com/cburch/hex/Test.java @@ -23,8 +23,8 @@ public static void main(String[] args) { private static class Model implements HexModel { - private ArrayList listeners = new ArrayList<>(); - private int[] data = new int[924]; + private final ArrayList listeners = new ArrayList<>(); + private final int[] data = new int[924]; public void addHexModelListener(HexModelListener listener) { listeners.add(listener); diff --git a/src/main/java/com/cburch/logisim/LogisimVersion.java b/src/main/java/com/cburch/logisim/LogisimVersion.java index 76820f7..0a41570 100644 --- a/src/main/java/com/cburch/logisim/LogisimVersion.java +++ b/src/main/java/com/cburch/logisim/LogisimVersion.java @@ -6,10 +6,10 @@ public class LogisimVersion { private static final int FINAL_REVISION = Integer.MAX_VALUE / 4; - private int major; - private int minor; - private int release; - private int revision; + private final int major; + private final int minor; + private final int release; + private final int revision; private String repr; private LogisimVersion(int major, int minor, int release, int revision) { @@ -65,7 +65,7 @@ public boolean equals(Object other) { if (other instanceof LogisimVersion) { LogisimVersion o = (LogisimVersion) other; return this.major == o.major && this.minor == o.minor - && this.release == o.release && this.revision == o.revision; + && this.release == o.release && this.revision == o.revision; } else { return false; } diff --git a/src/main/java/com/cburch/logisim/Main.java b/src/main/java/com/cburch/logisim/Main.java index 765ea8b..35343ce 100644 --- a/src/main/java/com/cburch/logisim/Main.java +++ b/src/main/java/com/cburch/logisim/Main.java @@ -27,11 +27,10 @@ public class Main { public static final LogisimVersion VERSION = LogisimVersion.get(2, 8, 0); public static final String VERSION_NAME = VERSION.toString(); - public static final int COPYRIGHT_YEAR = 2019; - public static final Release RELEASE_TYPE = Release.ALPHA; + public static final int COPYRIGHT_YEAR = 2021; + public static final Release RELEASE_TYPE = Release.RELEASE; public static void main(String[] args) { -// Logger.start(); // Start the logger Startup startup = Startup.parseArgs(args); if (startup == null) { diff --git a/src/main/java/com/cburch/logisim/analyze/gui/Analyzer.java b/src/main/java/com/cburch/logisim/analyze/gui/Analyzer.java index ac3a093..91dec05 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/Analyzer.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/Analyzer.java @@ -25,6 +25,9 @@ import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; +/** + * Circuit analyzer gui + */ public class Analyzer extends LFrame { // used by circuit analysis to select the relevant tab automatically. @@ -33,16 +36,16 @@ public class Analyzer extends LFrame { public static final int TABLE_TAB = 2; public static final int EXPRESSION_TAB = 3; public static final int MINIMIZED_TAB = 4; - private MyListener myListener = new MyListener(); - private EditListener editListener = new EditListener(); - private AnalyzerModel model = new AnalyzerModel(); + private final MyListener myListener = new MyListener(); + private final EditListener editListener = new EditListener(); + private final AnalyzerModel model = new AnalyzerModel(); + private final VariableTab inputsPanel; + private final VariableTab outputsPanel; + private final TableTab truthTablePanel; + private final ExpressionTab expressionPanel; + private final MinimizedTab minimizedPanel; + private final BuildCircuitButton buildCircuit; private JTabbedPane tabbedPane = new JTabbedPane(); - private VariableTab inputsPanel; - private VariableTab outputsPanel; - private TableTab truthTablePanel; - private ExpressionTab expressionPanel; - private MinimizedTab minimizedPanel; - private BuildCircuitButton buildCircuit; Analyzer() { inputsPanel = new VariableTab(model.getInputs()); @@ -62,14 +65,14 @@ public class Analyzer extends LFrame { addTab(MINIMIZED_TAB, minimizedPanel); Container contents = getContentPane(); - JPanel vertStrut = new JPanel(null); - vertStrut.setPreferredSize(new Dimension(0, 300)); - JPanel horzStrut = new JPanel(null); - horzStrut.setPreferredSize(new Dimension(450, 0)); + JPanel verticalStrut = new JPanel(null); + verticalStrut.setPreferredSize(new Dimension(0, 300)); + JPanel horizontalStrut = new JPanel(null); + horizontalStrut.setPreferredSize(new Dimension(450, 0)); JPanel buttonPanel = new JPanel(); buttonPanel.add(buildCircuit); - contents.add(vertStrut, BorderLayout.WEST); - contents.add(horzStrut, BorderLayout.NORTH); + contents.add(verticalStrut, BorderLayout.WEST); + contents.add(horizontalStrut, BorderLayout.NORTH); contents.add(tabbedPane, BorderLayout.CENTER); contents.add(buttonPanel, BorderLayout.SOUTH); @@ -95,8 +98,8 @@ public static void main(String[] args) { private void addTab(int index, final JComponent comp) { final JScrollPane pane = new JScrollPane(comp, - ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); if (comp instanceof TableTab) { pane.setVerticalScrollBar(((TableTab) comp).getVerticalScrollBar()); } @@ -166,16 +169,16 @@ private void register(LogisimMenuBar menubar) { enableItems(menubar); } - public void actionPerformed(ActionEvent e) { - Object src = e.getSource(); - Component c = tabbedPane.getSelectedComponent(); - if (c instanceof JScrollPane) { - c = ((JScrollPane) c).getViewport().getView(); + public void actionPerformed(ActionEvent event) { + Object src = event.getSource(); + Component component = tabbedPane.getSelectedComponent(); + if (component instanceof JScrollPane) { + component = ((JScrollPane) component).getViewport().getView(); } - if (!(c instanceof TabInterface)) { + if (!(component instanceof TabInterface)) { return; } - TabInterface tab = (TabInterface) c; + TabInterface tab = (TabInterface) component; if (src == LogisimMenuBar.CUT) { tab.copy(); tab.delete(); diff --git a/src/main/java/com/cburch/logisim/analyze/gui/AnalyzerManager.java b/src/main/java/com/cburch/logisim/analyze/gui/AnalyzerManager.java index e904f89..e907835 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/AnalyzerManager.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/AnalyzerManager.java @@ -9,7 +9,7 @@ import javax.swing.JFrame; public class AnalyzerManager extends WindowMenuItemManager - implements LocaleListener { + implements LocaleListener { private static Analyzer analysisWindow = null; private static AnalyzerManager analysisManager = null; diff --git a/src/main/java/com/cburch/logisim/analyze/gui/BuildCircuitButton.java b/src/main/java/com/cburch/logisim/analyze/gui/BuildCircuitButton.java index 54596c9..947301d 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/BuildCircuitButton.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/BuildCircuitButton.java @@ -29,9 +29,9 @@ class BuildCircuitButton extends JButton { - private MyListener myListener = new MyListener(); - private JFrame parent; - private AnalyzerModel model; + private final MyListener myListener = new MyListener(); + private final JFrame parent; + private final AnalyzerModel model; BuildCircuitButton(JFrame parent, AnalyzerModel model) { this.parent = parent; @@ -44,24 +44,23 @@ void localeChanged() { } private void performAction(Project dest, String name, boolean replace, - final boolean twoInputs, final boolean useNands) { + final boolean twoInputs, final boolean useNands) { if (replace) { final Circuit circuit = dest.getLogisimFile().getCircuit(name); if (circuit == null) { JOptionPane.showMessageDialog(parent, - "Internal error prevents replacing circuit.", - "Internal Error", JOptionPane.ERROR_MESSAGE); + "Internal error prevents replacing circuit.", + "Internal Error", JOptionPane.ERROR_MESSAGE); return; } CircuitMutation xn = CircuitBuilder.build(circuit, model, twoInputs, - useNands); + useNands); dest.doAction(xn.toAction(Strings.getter("replaceCircuitAction"))); } else { // add the circuit Circuit circuit = new Circuit(name); - CircuitMutation xn = CircuitBuilder.build(circuit, model, twoInputs, - useNands); + CircuitMutation xn = CircuitBuilder.build(circuit, model, twoInputs, useNands); xn.execute(); dest.doAction(LogisimFileActions.addCircuit(circuit)); dest.setCurrentCircuit(circuit); @@ -84,12 +83,12 @@ public String toString() { private class DialogPanel extends JPanel { - private JLabel projectLabel = new JLabel(); - private JComboBox project; - private JLabel nameLabel = new JLabel(); - private JTextField name = new JTextField(10); - private JCheckBox twoInputs = new JCheckBox(); - private JCheckBox nands = new JCheckBox(); + private final JLabel projectLabel = new JLabel(); + private final JComboBox project; + private final JLabel nameLabel = new JLabel(); + private final JTextField name = new JTextField(10); + private final JCheckBox twoInputs = new JCheckBox(); + private final JCheckBox nands = new JCheckBox(); DialogPanel() { List projects = Projects.getOpenProjects(); @@ -102,7 +101,7 @@ private class DialogPanel extends JPanel { initialSelection = options[i]; } } - project = new JComboBox(options); + project = new JComboBox<>(options); if (options.length == 1) { project.setSelectedItem(options[0]); project.setEnabled(false); @@ -171,44 +170,44 @@ public void actionPerformed(ActionEvent event) { boolean useNands = false; boolean replace = false; - boolean ok = false; - while (!ok) { - DialogPanel dlog = new DialogPanel(); + boolean isOkay = false; + while (!isOkay) { + DialogPanel dialog = new DialogPanel(); int action = JOptionPane.showConfirmDialog(parent, - dlog, Strings.get("buildDialogTitle"), JOptionPane.OK_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE); + dialog, Strings.get("buildDialogTitle"), JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); if (action != JOptionPane.OK_OPTION) { return; } - ProjectItem projectItem = (ProjectItem) dlog.project.getSelectedItem(); + ProjectItem projectItem = (ProjectItem) dialog.project.getSelectedItem(); if (projectItem == null) { JOptionPane.showMessageDialog(parent, Strings.get("buildNeedProjectError"), - Strings.get("buildDialogErrorTitle"), JOptionPane.ERROR_MESSAGE); + Strings.get("buildDialogErrorTitle"), JOptionPane.ERROR_MESSAGE); continue; } dest = projectItem.project; - name = dlog.name.getText().trim(); + name = dialog.name.getText().trim(); if (name.equals("")) { JOptionPane.showMessageDialog(parent, Strings.get("buildNeedCircuitError"), - Strings.get("buildDialogErrorTitle"), JOptionPane.ERROR_MESSAGE); + Strings.get("buildDialogErrorTitle"), JOptionPane.ERROR_MESSAGE); continue; } if (dest.getLogisimFile().getCircuit(name) != null) { int choice = JOptionPane.showConfirmDialog(parent, - StringUtil.format(Strings.get("buildConfirmReplaceMessage"), name), - Strings.get("buildConfirmReplaceTitle"), JOptionPane.YES_NO_OPTION); + StringUtil.format(Strings.get("buildConfirmReplaceMessage"), name), + Strings.get("buildConfirmReplaceTitle"), JOptionPane.YES_NO_OPTION); if (choice != JOptionPane.YES_OPTION) { continue; } replace = true; } - twoInputs = dlog.twoInputs.isSelected(); - useNands = dlog.nands.isSelected(); - ok = true; + twoInputs = dialog.twoInputs.isSelected(); + useNands = dialog.nands.isSelected(); + isOkay = true; } performAction(dest, name, replace, twoInputs, useNands); diff --git a/src/main/java/com/cburch/logisim/analyze/gui/DefaultRegistry.java b/src/main/java/com/cburch/logisim/analyze/gui/DefaultRegistry.java index 3355296..d083415 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/DefaultRegistry.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/DefaultRegistry.java @@ -11,7 +11,7 @@ class DefaultRegistry { - private JRootPane rootPane; + private final JRootPane rootPane; public DefaultRegistry(JRootPane rootPane) { this.rootPane = rootPane; @@ -24,7 +24,7 @@ public void registerDefaultButton(JComponent component, JButton button) { private class MyListener implements FocusListener { - private JButton defaultButton; + private final JButton defaultButton; private MyListener(JButton defaultButton) { this.defaultButton = defaultButton; diff --git a/src/main/java/com/cburch/logisim/analyze/gui/ExpressionTab.java b/src/main/java/com/cburch/logisim/analyze/gui/ExpressionTab.java index 54e70f7..685f3ac 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/ExpressionTab.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/ExpressionTab.java @@ -31,16 +31,16 @@ class ExpressionTab extends AnalyzerTab implements TabInterface { - private OutputSelector selector; - private ExpressionView prettyView = new ExpressionView(); - private JTextArea field = new JTextArea(4, 25); - private JButton clear = new JButton(); - private JButton revert = new JButton(); - private JButton enter = new JButton(); - private JLabel error = new JLabel(); - private MyListener myListener = new MyListener(); - private AnalyzerModel model; - private int curExprStringLength = 0; + private final OutputSelector selector; + private final ExpressionView prettyView = new ExpressionView(); + private final JTextArea textArea = new JTextArea(4, 25); + private final JButton clearButton = new JButton(); + private final JButton revertButton = new JButton(); + private final JButton enterButton = new JButton(); + private final JLabel errorLabel = new JLabel(); + private final MyListener myListener = new MyListener(); + private final AnalyzerModel model; + private int currentExpressionStringLength = 0; private StringGetter errorMessage; public ExpressionTab(AnalyzerModel model) { @@ -49,19 +49,19 @@ public ExpressionTab(AnalyzerModel model) { model.getOutputExpressions().addOutputExpressionsListener(myListener); selector.addItemListener(myListener); - clear.addActionListener(myListener); - revert.addActionListener(myListener); - enter.addActionListener(myListener); - field.setLineWrap(true); - field.setWrapStyleWord(true); - field.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), myListener); - field.getDocument().addDocumentListener(myListener); - field.setFont(new Font("Monospaced", Font.PLAIN, 14)); + clearButton.addActionListener(myListener); + revertButton.addActionListener(myListener); + enterButton.addActionListener(myListener); + textArea.setLineWrap(true); + textArea.setWrapStyleWord(true); + textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), myListener); + textArea.getDocument().addDocumentListener(myListener); + textArea.setFont(new Font("Monospaced", Font.PLAIN, 14)); JPanel buttons = new JPanel(); - buttons.add(clear); - buttons.add(revert); - buttons.add(enter); + buttons.add(clearButton); + buttons.add(revertButton); + buttons.add(enterButton); GridBagLayout gb = new GridBagLayout(); GridBagConstraints gc = new GridBagConstraints(); @@ -78,9 +78,10 @@ public ExpressionTab(AnalyzerModel model) { add(prettyView); Insets oldInsets = gc.insets; gc.insets = new Insets(10, 10, 0, 10); - JScrollPane fieldPane = new JScrollPane(field, - ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + JScrollPane fieldPane = new JScrollPane(textArea, + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER + ); gb.setConstraints(fieldPane, gc); add(fieldPane); gc.insets = oldInsets; @@ -89,22 +90,22 @@ public ExpressionTab(AnalyzerModel model) { gb.setConstraints(buttons, gc); add(buttons); gc.fill = GridBagConstraints.BOTH; - gb.setConstraints(error, gc); - add(error); + gb.setConstraints(errorLabel, gc); + add(errorLabel); myListener.insertUpdate(null); - setError(null); + setErrorLabel(null); } @Override void localeChanged() { selector.localeChanged(); prettyView.localeChanged(); - clear.setText(Strings.get("exprClearButton")); - revert.setText(Strings.get("exprRevertButton")); - enter.setText(Strings.get("exprEnterButton")); + clearButton.setText(Strings.get("exprClearButton")); + revertButton.setText(Strings.get("exprRevertButton")); + enterButton.setText(Strings.get("exprEnterButton")); if (errorMessage != null) { - error.setText(errorMessage.get()); + errorLabel.setText(errorMessage.get()); } } @@ -116,92 +117,89 @@ void updateTab() { } void registerDefaultButtons(DefaultRegistry registry) { - registry.registerDefaultButton(field, enter); + registry.registerDefaultButton(textArea, enterButton); } String getCurrentVariable() { return selector.getSelectedOutput(); } - private void setError(StringGetter msg) { - if (msg == null) { + private void setErrorLabel(StringGetter message) { + if (message == null) { errorMessage = null; - error.setText(" "); + errorLabel.setText(" "); } else { - errorMessage = msg; - error.setText(msg.get()); + errorMessage = message; + errorLabel.setText(message.get()); } } public void copy() { - field.requestFocus(); - field.copy(); + textArea.requestFocus(); + textArea.copy(); } public void paste() { - field.requestFocus(); - field.paste(); + textArea.requestFocus(); + textArea.paste(); } public void delete() { - field.requestFocus(); - field.replaceSelection(""); + textArea.requestFocus(); + textArea.replaceSelection(""); } public void selectAll() { - field.requestFocus(); - field.selectAll(); + textArea.requestFocus(); + textArea.selectAll(); } - private class MyListener extends AbstractAction - implements DocumentListener, - OutputExpressionsListener, ItemListener { - - boolean edited = false; - - public void actionPerformed(ActionEvent event) { - Object src = event.getSource(); - if (src == clear) { - setError(null); - field.setText(""); - field.grabFocus(); - } else if (src == revert) { - setError(null); - field.setText(getCurrentString()); - field.grabFocus(); - } else if ((src == field || src == enter) && enter.isEnabled()) { + private class MyListener extends AbstractAction implements DocumentListener, OutputExpressionsListener, ItemListener { + + boolean isEdited = false; + + public void actionPerformed(ActionEvent e) { + Object source = e.getSource(); + if (source == clearButton) { + setErrorLabel(null); + textArea.setText(""); + textArea.grabFocus(); + } else if (source == revertButton) { + setErrorLabel(null); + textArea.setText(getCurrentString()); + textArea.grabFocus(); + } else if ((source == textArea || source == enterButton) && enterButton.isEnabled()) { try { - String exprString = field.getText(); - Expression expr = Parser.parse(field.getText(), model); - setError(null); - model.getOutputExpressions().setExpression(getCurrentVariable(), expr, exprString); + String expressionString = textArea.getText(); + Expression expression = Parser.parse(textArea.getText(), model); + setErrorLabel(null); + model.getOutputExpressions().setExpression(getCurrentVariable(), expression, expressionString); insertUpdate(null); } catch (ParserException ex) { - setError(ex.getMessageGetter()); - field.setCaretPosition(ex.getOffset()); - field.moveCaretPosition(ex.getEndOffset()); + setErrorLabel(ex.getMessageGetter()); + textArea.setCaretPosition(ex.getOffset()); + textArea.moveCaretPosition(ex.getEndOffset()); } - field.grabFocus(); + textArea.grabFocus(); } } - public void insertUpdate(DocumentEvent event) { - String curText = field.getText(); - edited = curText.length() != curExprStringLength - || !curText.equals(getCurrentString()); + public void insertUpdate(DocumentEvent e) { + String curText = textArea.getText(); + isEdited = curText.length() != currentExpressionStringLength || !curText.equals(getCurrentString()); - boolean enable = (edited && getCurrentVariable() != null); - clear.setEnabled(curText.length() > 0); - revert.setEnabled(enable); - enter.setEnabled(enable); + boolean enable = (isEdited && getCurrentVariable() != null); + clearButton.setEnabled(curText.length() > 0); + revertButton.setEnabled(enable); + enterButton.setEnabled(enable); } - public void removeUpdate(DocumentEvent event) { - insertUpdate(event); + public void removeUpdate(DocumentEvent e) { + insertUpdate(e); } - public void changedUpdate(DocumentEvent event) { - insertUpdate(event); + public void changedUpdate(DocumentEvent e) { + insertUpdate(e); } public void expressionChanged(OutputExpressionsEvent event) { @@ -214,26 +212,25 @@ public void expressionChanged(OutputExpressionsEvent event) { } } - public void itemStateChanged(ItemEvent event) { + public void itemStateChanged(ItemEvent e) { updateTab(); } private String getCurrentString() { String output = getCurrentVariable(); - return output == null ? "" - : model.getOutputExpressions().getExpressionString(output); + return output == null ? "" : model.getOutputExpressions().getExpressionString(output); } private void currentStringChanged() { String output = getCurrentVariable(); - String exprString = model.getOutputExpressions().getExpressionString(output); - curExprStringLength = exprString.length(); - if (!edited) { - setError(null); - field.setText(getCurrentString()); + String expressionString = model.getOutputExpressions().getExpressionString(output); + currentExpressionStringLength = expressionString.length(); + if (!isEdited) { + setErrorLabel(null); + textArea.setText(getCurrentString()); } else { insertUpdate(null); } } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/analyze/gui/ExpressionView.java b/src/main/java/com/cburch/logisim/analyze/gui/ExpressionView.java index 5a9f8c2..72b296c 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/ExpressionView.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/ExpressionView.java @@ -27,7 +27,7 @@ class ExpressionView extends JPanel { private static final int NOT_SEP = 3; private static final int EXTRA_LEADING = 4; private static final int MINIMUM_HEIGHT = 25; - private MyListener myListener = new MyListener(); + private final MyListener myListener = new MyListener(); private RenderData renderData; public ExpressionView() { @@ -35,11 +35,11 @@ public ExpressionView() { setExpression(null); } - public void setExpression(Expression expr) { - ExpressionData exprData = new ExpressionData(expr); + public void setExpression(Expression expression) { + ExpressionData data = new ExpressionData(expression); Graphics g = getGraphics(); FontMetrics fm = g == null ? null : g.getFontMetrics(); - renderData = new RenderData(exprData, getWidth(), fm); + renderData = new RenderData(data, getWidth(), fm); setPreferredSize(renderData.getPreferredSize()); revalidate(); repaint(); @@ -50,7 +50,7 @@ public void paintComponent(Graphics g) { super.paintComponent(g); if (renderData != null) { - int x = Math.max(0, (getWidth() - renderData.prefWidth) / 2); + int x = Math.max(0, (getWidth() - renderData.preferredWidth) / 2); int y = Math.max(0, (getHeight() - renderData.height) / 2); renderData.paint(g, x, y); } @@ -117,11 +117,11 @@ private Object binary(Expression a, Expression b, int level, String op) { return null; } - public Object visitNot(Expression a) { + public Object visitNot(Expression expression) { NotData notData = new NotData(); notData.startIndex = text.length(); nots.add(notData); - a.visit(this); + expression.visit(this); notData.stopIndex = text.length(); return null; } @@ -132,7 +132,7 @@ public Object visitVariable(String name) { } public Object visitConstant(int value) { - text.append("" + Integer.toString(value, 16)); + text.append(Integer.toString(value, 16)); return null; } }); @@ -147,81 +147,80 @@ private void computeBadnesses() { } badness[0] = Integer.MAX_VALUE; - NotData curNot = nots.isEmpty() ? null : nots.get(0); - int curNotIndex = 0; - char prev = text.charAt(0); + NotData currentNot = nots.isEmpty() ? null : nots.get(0); + int currentNotIndex = 0; + char previous = text.charAt(0); for (int i = 1; i < text.length(); i++) { - // invariant: curNot.stopIndex >= i (and is first such), - // or curNot == null if none such exists - char cur = text.charAt(i); - if (cur == ' ') { + // invariant: currentNot.stopIndex >= i (and is first such), + // or currentNot == null if none such exists + char current = text.charAt(i); + if (current == ' ') { badness[i] = BADNESS_BEFORE_SPACE; - } else if (Character.isJavaIdentifierPart(cur)) { - if (Character.isJavaIdentifierPart(prev)) { + } else if (Character.isJavaIdentifierPart(current)) { + if (Character.isJavaIdentifierPart(previous)) { badness[i] = BADNESS_IDENT_BREAK; } else { badness[i] = BADNESS_BEFORE_AND; } - } else if (cur == '+') { + } else if (current == '+') { badness[i] = BADNESS_BEFORE_OR; - } else if (cur == '^') { + } else if (current == '^') { badness[i] = BADNESS_BEFORE_XOR; - } else if (cur == ')') { + } else if (current == ')') { badness[i] = BADNESS_BEFORE_SPACE; - } else { // cur == '(' + } else { // current == '(' badness[i] = BADNESS_BEFORE_AND; } - while (curNot != null && curNot.stopIndex <= i) { - ++curNotIndex; - curNot = (curNotIndex >= nots.size() ? null - : nots.get(curNotIndex)); + while (currentNot != null && currentNot.stopIndex <= i) { + ++currentNotIndex; + currentNot = (currentNotIndex >= nots.size() ? null : nots.get(currentNotIndex)); } - if (curNot != null && badness[i] < BADNESS_IDENT_BREAK) { + if (currentNot != null && badness[i] < BADNESS_IDENT_BREAK) { int depth = 0; - NotData nd = curNot; - int ndi = curNotIndex; - while (nd != null && nd.startIndex < i) { - if (nd.stopIndex > i) { + NotData notData = currentNot; + int notDataIndex = currentNotIndex; + while (notData != null && notData.startIndex < i) { + if (notData.stopIndex > i) { ++depth; } - ++ndi; - nd = ndi < nots.size() ? nots.get(ndi) : null; + ++notDataIndex; + notData = notDataIndex < nots.size() ? nots.get(notDataIndex) : null; } if (depth > 0) { badness[i] += BADNESS_NOT_BREAK + (depth - 1) * BADNESS_PER_NOT_BREAK; } } - prev = cur; + previous = current; } } } private static class RenderData { - ExpressionData exprData; - int prefWidth; + ExpressionData expressionData; + int preferredWidth; int width; int height; String[] lineText; ArrayList> lineNots; int[] lineY; - RenderData(ExpressionData exprData, int width, FontMetrics fm) { - this.exprData = exprData; + RenderData(ExpressionData expressionData, int width, FontMetrics fm) { + this.expressionData = expressionData; this.width = width; height = MINIMUM_HEIGHT; if (fm == null) { - lineText = new String[]{exprData.text}; + lineText = new String[]{expressionData.text}; lineNots = new ArrayList<>(); - lineNots.add(exprData.nots); + lineNots.add(expressionData.nots); computeNotDepths(); lineY = new int[]{MINIMUM_HEIGHT}; } else { - if (exprData.text.length() == 0) { + if (expressionData.text.length() == 0) { lineText = new String[]{Strings.get("expressionEmpty")}; lineNots = new ArrayList<>(); lineNots.add(new ArrayList<>()); @@ -231,73 +230,70 @@ private static class RenderData { computeNotDepths(); } computeLineY(fm); - prefWidth = lineText.length > 1 ? width - : fm.stringWidth(lineText[0]); + preferredWidth = lineText.length > 1 ? width : fm.stringWidth(lineText[0]); } } private void computeLineText(FontMetrics fm) { - String text = exprData.text; - int[] badness = exprData.badness; + String text = expressionData.text; + int[] badness = expressionData.badness; if (fm.stringWidth(text) <= width) { lineText = new String[]{text}; return; } - int startPos = 0; + int startPosition = 0; ArrayList lines = new ArrayList<>(); - while (startPos < text.length()) { - int stopPos = startPos + 1; - String bestLine = text.substring(startPos, stopPos); - if (stopPos >= text.length()) { + while (startPosition < text.length()) { + int stopPosition = startPosition + 1; + String bestLine = text.substring(startPosition, stopPosition); + if (stopPosition >= text.length()) { lines.add(bestLine); break; } - int bestStopPos = stopPos; + int bestStopPosition = stopPosition; int lineWidth = fm.stringWidth(bestLine); - int bestBadness = badness[stopPos] - + (width - lineWidth) * BADNESS_PER_PIXEL; - while (stopPos < text.length()) { - ++stopPos; - String line = text.substring(startPos, stopPos); + int bestBadness = badness[stopPosition] + (width - lineWidth) * BADNESS_PER_PIXEL; + while (stopPosition < text.length()) { + ++stopPosition; + String line = text.substring(startPosition, stopPosition); lineWidth = fm.stringWidth(line); if (lineWidth > width) { break; } - int lineBadness = badness[stopPos] - + (width - lineWidth) * BADNESS_PER_PIXEL; + int lineBadness = badness[stopPosition] + (width - lineWidth) * BADNESS_PER_PIXEL; if (lineBadness < bestBadness) { bestBadness = lineBadness; - bestStopPos = stopPos; + bestStopPosition = stopPosition; bestLine = line; } } lines.add(bestLine); - startPos = bestStopPos; + startPosition = bestStopPosition; } - lineText = lines.toArray(new String[lines.size()]); + lineText = lines.toArray(new String[0]); } private void computeLineNots() { - ArrayList allNots = exprData.nots; + ArrayList allNots = expressionData.nots; lineNots = new ArrayList<>(); for (int i = 0; i < lineText.length; i++) { lineNots.add(new ArrayList<>()); } - for (NotData nd : allNots) { - int pos = 0; - for (int j = 0; j < lineNots.size() && pos < nd.stopIndex; j++) { + for (NotData notData : allNots) { + int position = 0; + for (int j = 0; j < lineNots.size() && position < notData.stopIndex; j++) { String line = lineText[j]; - int nextPos = pos + line.length(); - if (nextPos > nd.startIndex) { + int nextPosition = position + line.length(); + if (nextPosition > notData.startIndex) { NotData toAdd = new NotData(); - toAdd.startIndex = Math.max(pos, nd.startIndex) - pos; - toAdd.stopIndex = Math.min(nextPos, nd.stopIndex) - pos; + toAdd.startIndex = Math.max(position, notData.startIndex) - position; + toAdd.stopIndex = Math.min(nextPosition, notData.stopIndex) - position; lineNots.get(j).add(toAdd); } - pos = nextPos; + position = nextPosition; } } } @@ -307,32 +303,32 @@ private void computeNotDepths() { int n = nots.size(); int[] stack = new int[n]; for (int i = 0; i < nots.size(); i++) { - NotData nd = nots.get(i); + NotData notData = nots.get(i); int depth = 0; int top = 0; - stack[0] = nd.stopIndex; + stack[0] = notData.stopIndex; for (int j = i + 1; j < nots.size(); j++) { - NotData nd2 = nots.get(j); - if (nd2.startIndex >= nd.stopIndex) { + NotData notData2 = nots.get(j); + if (notData2.startIndex >= notData.stopIndex) { break; } - while (nd2.startIndex >= stack[top]) { + while (notData2.startIndex >= stack[top]) { top--; } ++top; - stack[top] = nd2.stopIndex; + stack[top] = notData2.stopIndex; if (top > depth) { depth = top; } } - nd.depth = depth; + notData.depth = depth; } } } private void computeLineY(FontMetrics fm) { lineY = new int[lineNots.size()]; - int curY = 0; + int currentY = 0; for (int i = 0; i < lineY.length; i++) { int maxDepth = -1; ArrayList nots = lineNots.get(i); @@ -341,11 +337,11 @@ private void computeLineY(FontMetrics fm) { maxDepth = nd.depth; } } - lineY[i] = curY + maxDepth * NOT_SEP; - curY = lineY[i] + fm.getHeight() + EXTRA_LEADING; + lineY[i] = currentY + maxDepth * NOT_SEP; + currentY = lineY[i] + fm.getHeight() + EXTRA_LEADING; } height = Math.max(MINIMUM_HEIGHT, - curY - fm.getLeading() - EXTRA_LEADING); + currentY - fm.getLeading() - EXTRA_LEADING); } public Dimension getPreferredSize() { @@ -361,11 +357,11 @@ public void paint(Graphics g, int x, int y) { ArrayList nots = lineNots.get(i); int j = -1; - for (NotData nd : nots) { + for (NotData notData : nots) { j++; - int notY = y + lineY[i] - nd.depth * NOT_SEP; - int startX = x + fm.stringWidth(line.substring(0, nd.startIndex)); - int stopX = x + fm.stringWidth(line.substring(0, nd.stopIndex)); + int notY = y + lineY[i] - notData.depth * NOT_SEP; + int startX = x + fm.stringWidth(line.substring(0, notData.startIndex)); + int stopX = x + fm.stringWidth(line.substring(0, notData.stopIndex)); g.drawLine(startX, notY, stopX, notY); } } @@ -379,7 +375,7 @@ public void componentResized(ComponentEvent arg0) { if (renderData != null && Math.abs(renderData.width - width) > 2) { Graphics g = getGraphics(); FontMetrics fm = g == null ? null : g.getFontMetrics(); - renderData = new RenderData(renderData.exprData, width, fm); + renderData = new RenderData(renderData.expressionData, width, fm); setPreferredSize(renderData.getPreferredSize()); revalidate(); repaint(); diff --git a/src/main/java/com/cburch/logisim/analyze/gui/KarnaughMapPanel.java b/src/main/java/com/cburch/logisim/analyze/gui/KarnaughMapPanel.java index 9252d76..1977ea8 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/KarnaughMapPanel.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/KarnaughMapPanel.java @@ -29,10 +29,10 @@ class KarnaughMapPanel extends JPanel implements TruthTablePanel { private static final Font HEAD_FONT = new Font("Serif", Font.BOLD, 14); private static final Font BODY_FONT = new Font("Serif", Font.PLAIN, 14); private static final Color[] IMP_COLORS = new Color[]{ - new Color(255, 0, 0, 128), - new Color(0, 150, 0, 128), - new Color(0, 0, 255, 128), - new Color(255, 0, 255, 128), + new Color(255, 0, 0, 128), + new Color(0, 150, 0, 128), + new Color(0, 0, 255, 128), + new Color(255, 0, 255, 128), }; private static final int MAX_VARS = 4; @@ -43,10 +43,10 @@ class KarnaughMapPanel extends JPanel implements TruthTablePanel { private static final int CELL_VERTICAL_SEPARATION = 10; private static final int IMPLICANT_INSET = 4; private static final int IMP_RADIUS = 5; + private final AnalyzerModel model; private Entry provisionalValue = null; private int cellHeight = 1; private int cellWidth = 1; - private AnalyzerModel model; private int headHeight; private int provisionalX; private int provisionalY; @@ -226,15 +226,11 @@ public void paintComponent(Graphics graphics) { int deltaY = (cellHeight + fontMetrics.getAscent()) / 2; for (int i = 0; i < columns; i++) { String label = label(i, columns); - graphics.drawString(label, - x + (i + 1) * cellWidth + (cellWidth - fontMetrics.stringWidth(label)) / 2, - y + deltaY); + graphics.drawString(label, x + (i + 1) * cellWidth + (cellWidth - fontMetrics.stringWidth(label)) / 2, y + deltaY); } for (int i = 0; i < rows; i++) { String label = label(i, rows); - graphics.drawString(label, - x + (cellWidth - fontMetrics.stringWidth(label)) / 2, - y + (i + 1) * cellHeight + deltaY); + graphics.drawString(label, x + (cellWidth - fontMetrics.stringWidth(label)) / 2, y + (i + 1) * cellHeight + deltaY); } int outputColumn = table.getOutputIndex(output); @@ -245,8 +241,7 @@ public void paintComponent(Graphics graphics) { for (int j = 0; j < columns; j++) { int row = getTableRow(i, j, rows, columns); Entry entry = table.getOutputEntry(row, outputColumn); - if (provisionalValue != null && row == provisionalY - && outputColumn == provisionalX) { + if (provisionalValue != null && row == provisionalY && outputColumn == provisionalX) { entry = provisionalValue; } if (entry.isError()) { @@ -281,26 +276,23 @@ public void paintComponent(Graphics graphics) { for (int j = 0; j < columns; j++) { int row = getTableRow(i, j, rows, columns); if (provisionalValue != null && row == provisionalY - && outputColumn == provisionalX) { + && outputColumn == provisionalX) { String text = provisionalValue.getDescription(); graphics.setColor(Color.GREEN); - graphics.drawString(text, - x + j * cellWidth + (cellWidth - fontMetrics.stringWidth(text)) / 2, - y + i * cellHeight + deltaY); + graphics.drawString(text, x + j * cellWidth + (cellWidth - fontMetrics.stringWidth(text)) / 2, + y + i * cellHeight + deltaY); graphics.setColor(Color.BLACK); } else { Entry entry = table.getOutputEntry(row, outputColumn); String text = entry.getDescription(); - graphics.drawString(text, - x + j * cellWidth + (cellWidth - fontMetrics.stringWidth(text)) / 2, - y + i * cellHeight + deltaY); + graphics.drawString(text, x + j * cellWidth + (cellWidth - fontMetrics.stringWidth(text)) / 2, + y + i * cellHeight + deltaY); } } } } - private void paintImplicant(Graphics graphics, Implicant implicant, int x, int y, - int rows, int columns) { + private void paintImplicant(Graphics graphics, Implicant implicant, int x, int y, int rows, int columns) { int rowMax = -1; int rowMin = rows; int columnMax = -1; @@ -334,11 +326,8 @@ private void paintImplicant(Graphics graphics, Implicant implicant, int x, int y int covered = numColumns * numRows; int diameter = 2 * IMP_RADIUS; if (covered == count) { - graphics.fillRoundRect(x + columnMin * cellWidth + IMPLICANT_INSET, - y + rowMin * cellHeight + IMPLICANT_INSET, - numColumns * cellWidth - 2 * IMPLICANT_INSET, - numRows * cellHeight - 2 * IMPLICANT_INSET, - diameter, diameter); + graphics.fillRoundRect(x + columnMin * cellWidth + IMPLICANT_INSET, y + rowMin * cellHeight + IMPLICANT_INSET, + numColumns * cellWidth - 2 * IMPLICANT_INSET, numRows * cellHeight - 2 * IMPLICANT_INSET, diameter, diameter); } else if (covered == 16) { if (count == 4) { int width = cellWidth - IMPLICANT_INSET; @@ -484,12 +473,10 @@ private int computeMargin(int compDimension, int tableDimension) { return ret >= 0 ? ret : Math.max(-headHeight, compDimension - tableDimension); } - private class MyListener - implements OutputExpressionsListener, TruthTableListener { + private class MyListener implements OutputExpressionsListener, TruthTableListener { public void expressionChanged(OutputExpressionsEvent event) { - if (event.getType() == OutputExpressionsEvent.OUTPUT_MINIMAL - && event.getVariable().equals(output)) { + if (event.getType() == OutputExpressionsEvent.OUTPUT_MINIMAL && event.getVariable().equals(output)) { repaint(); } } diff --git a/src/main/java/com/cburch/logisim/analyze/gui/MinimizedTab.java b/src/main/java/com/cburch/logisim/analyze/gui/MinimizedTab.java index f6ff24a..b730c8b 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/MinimizedTab.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/MinimizedTab.java @@ -24,20 +24,20 @@ class MinimizedTab extends AnalyzerTab { - private OutputSelector selector; - private KarnaughMapPanel karnaughMap; - private JLabel formatLabel = new JLabel(); - private JComboBox formatChoice = new JComboBox(new FormatModel()); - private ExpressionView minimizedExpr = new ExpressionView(); - private JButton setAsExpr = new JButton(); - private MyListener myListener = new MyListener(); - private AnalyzerModel model; - private OutputExpressions outputExprs; + private final OutputSelector selector; + private final KarnaughMapPanel karnaughMap; + private final JLabel formatLabel = new JLabel(); + private final JComboBox formatChoice = new JComboBox<>(new FormatModel()); + private final ExpressionView minimizedExpr = new ExpressionView(); + private final JButton setAsExpr = new JButton(); + private final AnalyzerModel model; + private final OutputExpressions outputExpressions; public MinimizedTab(AnalyzerModel model) { this.model = model; - this.outputExprs = model.getOutputExpressions(); - outputExprs.addOutputExpressionsListener(myListener); + this.outputExpressions = model.getOutputExpressions(); + MyListener myListener = new MyListener(); + outputExpressions.addOutputExpressionsListener(myListener); selector = new OutputSelector(model); selector.addItemListener(myListener); @@ -80,11 +80,10 @@ public MinimizedTab(AnalyzerModel model) { String selected = selector.getSelectedOutput(); setAsExpr.setEnabled(selected != null - && !outputExprs.isExpressionMinimal(selected)); + && !outputExpressions.isExpressionMinimal(selected)); } - private void addRow(GridBagLayout gb, GridBagConstraints gc, - JLabel label, JComboBox choice) { + private void addRow(GridBagLayout gb, GridBagConstraints gc, JLabel label, JComboBox choice) { Insets oldInsets = gc.insets; gc.weightx = 0.0; gc.gridx = 0; @@ -115,20 +114,19 @@ void localeChanged() { void updateTab() { String output = getCurrentVariable(); karnaughMap.setOutput(output); - int format = outputExprs.getMinimizedFormat(output); + int format = outputExpressions.getMinimizedFormat(output); formatChoice.setSelectedIndex(FormatModel.getFormatIndex(format)); - minimizedExpr.setExpression(outputExprs.getMinimalExpression(output)); - setAsExpr.setEnabled(output != null && !outputExprs.isExpressionMinimal(output)); + minimizedExpr.setExpression(outputExpressions.getMinimalExpression(output)); + setAsExpr.setEnabled(output != null && !outputExpressions.isExpressionMinimal(output)); } private String getCurrentVariable() { return selector.getSelectedOutput(); } - private static class FormatModel extends AbstractListModel - implements ComboBoxModel { + private static class FormatModel extends AbstractListModel implements ComboBoxModel { - private String[] choices; + private final String[] choices; private int selected; private FormatModel() { @@ -138,12 +136,10 @@ private FormatModel() { } static int getFormatIndex(int choice) { - switch (choice) { - case AnalyzerModel.FORMAT_PRODUCT_OF_SUMS: - return 1; - default: - return 0; + if (choice == AnalyzerModel.FORMAT_PRODUCT_OF_SUMS) { + return 1; } + return 0; } void localeChanged() { @@ -153,12 +149,10 @@ void localeChanged() { } int getSelectedFormat() { - switch (selected) { - case 1: - return AnalyzerModel.FORMAT_PRODUCT_OF_SUMS; - default: - return AnalyzerModel.FORMAT_SUM_OF_PRODUCTS; + if (selected == 1) { + return AnalyzerModel.FORMAT_PRODUCT_OF_SUMS; } + return AnalyzerModel.FORMAT_SUM_OF_PRODUCTS; } public int getSize() { @@ -183,32 +177,32 @@ public void setSelectedItem(Object value) { } private class MyListener - implements OutputExpressionsListener, ActionListener, ItemListener { + implements OutputExpressionsListener, ActionListener, ItemListener { public void expressionChanged(OutputExpressionsEvent event) { String output = getCurrentVariable(); if (event.getType() == OutputExpressionsEvent.OUTPUT_MINIMAL - && event.getVariable().equals(output)) { - minimizedExpr.setExpression(outputExprs.getMinimalExpression(output)); + && event.getVariable().equals(output)) { + minimizedExpr.setExpression(outputExpressions.getMinimalExpression(output)); MinimizedTab.this.validate(); } - setAsExpr.setEnabled(output != null && !outputExprs.isExpressionMinimal(output)); - int format = outputExprs.getMinimizedFormat(output); + setAsExpr.setEnabled(output != null && !outputExpressions.isExpressionMinimal(output)); + int format = outputExpressions.getMinimizedFormat(output); formatChoice.setSelectedIndex(FormatModel.getFormatIndex(format)); } public void actionPerformed(ActionEvent event) { String output = getCurrentVariable(); - int format = outputExprs.getMinimizedFormat(output); + int format = outputExpressions.getMinimizedFormat(output); formatChoice.setSelectedIndex(FormatModel.getFormatIndex(format)); - outputExprs.setExpression(output, outputExprs.getMinimalExpression(output)); + outputExpressions.setExpression(output, outputExpressions.getMinimalExpression(output)); } public void itemStateChanged(ItemEvent event) { if (event.getSource() == formatChoice) { String output = getCurrentVariable(); FormatModel model = (FormatModel) formatChoice.getModel(); - outputExprs.setMinimizedFormat(output, model.getSelectedFormat()); + outputExpressions.setMinimizedFormat(output, model.getSelectedFormat()); } else { updateTab(); } diff --git a/src/main/java/com/cburch/logisim/analyze/gui/OutputSelector.java b/src/main/java/com/cburch/logisim/analyze/gui/OutputSelector.java index 39d843c..f18536f 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/OutputSelector.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/OutputSelector.java @@ -16,9 +16,9 @@ class OutputSelector { - private VariableList source; - private JLabel label = new JLabel(); - private JComboBox select = new JComboBox(); + private final VariableList source; + private final JLabel label = new JLabel(); + private final JComboBox select = new JComboBox<>(); private String prototypeValue = null; public OutputSelector(AnalyzerModel model) { @@ -40,7 +40,7 @@ public JLabel getLabel() { return label; } - public JComboBox getComboBox() { + public JComboBox getComboBox() { return select; } @@ -89,8 +89,7 @@ private void computePrototypeValue() { } } - private class Model extends AbstractListModel - implements ComboBoxModel, VariableListListener { + private class Model extends AbstractListModel implements ComboBoxModel, VariableListListener { private Object selected; diff --git a/src/main/java/com/cburch/logisim/analyze/gui/TableTabCaret.java b/src/main/java/com/cburch/logisim/analyze/gui/TableTabCaret.java index 01c23ec..f63561b 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/TableTabCaret.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/TableTabCaret.java @@ -27,10 +27,10 @@ class TableTabCaret { - private static Color SELECT_COLOR = new Color(192, 192, 255); + private static final Color SELECT_COLOR = new Color(192, 192, 255); - private Listener listener = new Listener(); - private TableTab table; + private final Listener listener = new Listener(); + private final TableTab table; private int cursorRow; private int cursorCol; private int markRow; @@ -107,8 +107,7 @@ private void setCursor(int row, int col, boolean keepMark) { col = cols - 1; } - if (row == cursorRow && col == cursorCol - && (keepMark || (row == markRow && col == markCol))) { + if (row == cursorRow && col == cursorCol && (keepMark || (row == markRow && col == markCol))) { // nothing is changing, so do nothing } else if (!keepMark && markRow == cursorRow && markCol == cursorCol) { int oldRow = cursorRow; @@ -152,15 +151,15 @@ private void expose(int row, int col) { if (row >= 0) { int x0 = table.getX(0); int x1 = table.getX(table.getColumnCount() - 1) - + table.getCellWidth(); + + table.getCellWidth(); table.repaint(x0 - 2, table.getY(row) - 2, - (x1 - x0) + 4, table.getCellHeight() + 4); + (x1 - x0) + 4, table.getCellHeight() + 4); } } void paintBackground(Graphics g) { if (cursorRow >= 0 && cursorCol >= 0 - && (cursorRow != markRow || cursorCol != markCol)) { + && (cursorRow != markRow || cursorCol != markCol)) { g.setColor(SELECT_COLOR); int r0 = cursorRow; @@ -199,7 +198,7 @@ void paintForeground(Graphics g) { } private class Listener implements MouseListener, MouseMotionListener, - KeyListener, FocusListener, TruthTableListener { + KeyListener, FocusListener, TruthTableListener { public void mouseClicked(MouseEvent e) { } @@ -208,7 +207,7 @@ public void mousePressed(MouseEvent e) { table.requestFocus(); int row = table.getRow(e); int col = table.getColumn(e); - setCursor(row, col, (e.getModifiers() & InputEvent.SHIFT_MASK) != 0); + setCursor(row, col, (e.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) != 0); } public void mouseReleased(MouseEvent e) { @@ -231,8 +230,8 @@ public void mouseMoved(MouseEvent e) { } public void keyTyped(KeyEvent e) { - int mask = e.getModifiers(); - if ((mask & ~InputEvent.SHIFT_MASK) != 0) { + int mask = e.getModifiersEx(); + if ((mask & ~InputEvent.SHIFT_DOWN_MASK) != 0) { return; } @@ -267,11 +266,11 @@ public void keyTyped(KeyEvent e) { break; case '\n': setCursor(cursorRow + 1, table.getTruthTable().getInputColumnCount(), - (mask & InputEvent.SHIFT_MASK) != 0); + (mask & InputEvent.SHIFT_DOWN_MASK) != 0); break; case '\u0008': case '\u007f': - setCursor(cursorRow, cursorCol - 1, (mask & InputEvent.SHIFT_MASK) != 0); + setCursor(cursorRow, cursorCol - 1, (mask & InputEvent.SHIFT_DOWN_MASK) != 0); break; default: } @@ -299,7 +298,7 @@ public void keyPressed(KeyEvent e) { int inputs = model.getInputColumnCount(); int outputs = model.getOutputColumnCount(); int cols = inputs + outputs; - boolean shift = (e.getModifiers() & InputEvent.SHIFT_MASK) != 0; + boolean shift = (e.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) != 0; switch (e.getKeyCode()) { case KeyEvent.VK_UP: setCursor(cursorRow - 1, cursorCol, shift); diff --git a/src/main/java/com/cburch/logisim/analyze/gui/VariableTab.java b/src/main/java/com/cburch/logisim/analyze/gui/VariableTab.java index cb72d91..b3fd135 100644 --- a/src/main/java/com/cburch/logisim/analyze/gui/VariableTab.java +++ b/src/main/java/com/cburch/logisim/analyze/gui/VariableTab.java @@ -30,16 +30,16 @@ class VariableTab extends AnalyzerTab implements TabInterface { - private VariableList data; - private MyListener myListener = new MyListener(); - private JList list = new JList(); - private JTextField field = new JTextField(); - private JButton remove = new JButton(); - private JButton moveUp = new JButton(); - private JButton moveDown = new JButton(); - private JButton add = new JButton(); - private JButton rename = new JButton(); - private JLabel error = new JLabel(" "); + private final VariableList data; + private final MyListener myListener = new MyListener(); + private final JList list = new JList<>(); + private final JTextField field = new JTextField(); + private final JButton remove = new JButton(); + private final JButton moveUp = new JButton(); + private final JButton moveDown = new JButton(); + private final JButton add = new JButton(); + private final JButton rename = new JButton(); + private final JLabel error = new JLabel(" "); VariableTab(VariableList data) { this.data = data; @@ -56,8 +56,8 @@ class VariableTab extends AnalyzerTab implements TabInterface { field.getDocument().addDocumentListener(myListener); JScrollPane listPane = new JScrollPane(list, - ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); listPane.setPreferredSize(new Dimension(100, 100)); JPanel topPanel = new JPanel(new GridLayout(3, 1)); @@ -173,8 +173,7 @@ private boolean validateInput() { } if (ok || !errorShown) { if (data.size() >= data.getMaximumSize()) { - error.setText(StringUtil.format(Strings.get("variableMaximumError"), - "" + data.getMaximumSize())); + error.setText(StringUtil.format(Strings.get("variableMaximumError"), "" + data.getMaximumSize())); } else { error.setText(" "); } @@ -202,10 +201,9 @@ public void selectAll() { field.selectAll(); } - private static class VariableListModel extends AbstractListModel - implements VariableListListener { + private static class VariableListModel extends AbstractListModel implements VariableListListener { - private VariableList list; + private final VariableList list; private String[] listCopy; public VariableListModel(VariableList list) { @@ -254,13 +252,12 @@ public void listChanged(VariableListEvent event) { case VariableListEvent.REPLACE: index = (Integer) event.getData(); fireContentsChanged(this, index, index); - return; } } } private class MyListener - implements ActionListener, DocumentListener, ListSelectionListener { + implements ActionListener, DocumentListener, ListSelectionListener { public void actionPerformed(ActionEvent event) { Object src = event.getSource(); diff --git a/src/main/java/com/cburch/logisim/analyze/model/AnalyzerModel.java b/src/main/java/com/cburch/logisim/analyze/model/AnalyzerModel.java index fc18710..4f70259 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/AnalyzerModel.java +++ b/src/main/java/com/cburch/logisim/analyze/model/AnalyzerModel.java @@ -15,10 +15,10 @@ public class AnalyzerModel { public static final int FORMAT_SUM_OF_PRODUCTS = 0; public static final int FORMAT_PRODUCT_OF_SUMS = 1; - private VariableList inputs = new VariableList(MAX_INPUTS); - private VariableList outputs = new VariableList(MAX_OUTPUTS); - private TruthTable table; - private OutputExpressions outputExpressions; + private final VariableList inputs = new VariableList(MAX_INPUTS); + private final VariableList outputs = new VariableList(MAX_OUTPUTS); + private final TruthTable table; + private final OutputExpressions outputExpressions; private Project currentProject = null; private Circuit currentCircuit = null; diff --git a/src/main/java/com/cburch/logisim/analyze/model/Assignments.java b/src/main/java/com/cburch/logisim/analyze/model/Assignments.java index 87670c3..e170034 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/Assignments.java +++ b/src/main/java/com/cburch/logisim/analyze/model/Assignments.java @@ -8,7 +8,7 @@ class Assignments { - private Map map = new HashMap<>(); + private final Map map = new HashMap<>(); public Assignments() { } diff --git a/src/main/java/com/cburch/logisim/analyze/model/Entry.java b/src/main/java/com/cburch/logisim/analyze/model/Entry.java index ad8f190..67d84bb 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/Entry.java +++ b/src/main/java/com/cburch/logisim/analyze/model/Entry.java @@ -12,8 +12,8 @@ public class Entry { public static final Entry DONT_CARE = new Entry("x"); public static final Entry BUS_ERROR = new Entry(Strings.getter("busError")); public static final Entry OSCILLATE_ERROR = new Entry(Strings.getter("oscillateError")); - private String description; - private StringGetter errorMessage; + private final String description; + private final StringGetter errorMessage; private Entry(String description) { this.description = description; diff --git a/src/main/java/com/cburch/logisim/analyze/model/Expressions.java b/src/main/java/com/cburch/logisim/analyze/model/Expressions.java index 1508467..4aa7279 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/Expressions.java +++ b/src/main/java/com/cburch/logisim/analyze/model/Expressions.java @@ -79,7 +79,7 @@ public boolean equals(Object other) { @Override public int hashCode() { return 31 * (31 * getClass().hashCode() + a.hashCode()) - + b.hashCode(); + + b.hashCode(); } } @@ -166,7 +166,7 @@ public int getPrecedence() { private static class Not extends Expression { - private Expression a; + private final Expression a; Not(Expression a) { this.a = a; @@ -209,7 +209,7 @@ public int hashCode() { private static class Variable extends Expression { - private String name; + private final String name; Variable(String name) { this.name = name; @@ -252,7 +252,7 @@ public int hashCode() { private static class Constant extends Expression { - private int value; + private final int value; Constant(int value) { this.value = value; diff --git a/src/main/java/com/cburch/logisim/analyze/model/Implicant.java b/src/main/java/com/cburch/logisim/analyze/model/Implicant.java index 2564e2e..24442dc 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/Implicant.java +++ b/src/main/java/com/cburch/logisim/analyze/model/Implicant.java @@ -4,7 +4,6 @@ package com.cburch.logisim.analyze.model; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -15,9 +14,9 @@ public class Implicant implements Comparable { static Implicant MINIMAL_IMPLICANT = new Implicant(0, -1); - static List MINIMAL_LIST = Arrays.asList(MINIMAL_IMPLICANT); - private int unknowns; - private int values; + static List MINIMAL_LIST = Collections.singletonList(MINIMAL_IMPLICANT); + private final int unknowns; + private final int values; private Implicant(int unknowns, int values) { this.unknowns = unknowns; @@ -45,7 +44,7 @@ static Expression toExpression(int format, AnalyzerModel model, List } static List computeMinimal(int format, AnalyzerModel model, - String variable) { + String variable) { TruthTable table = model.getTruthTable(); int column = model.getOutputs().indexOf(variable); if (column < 0) { @@ -53,7 +52,7 @@ static List computeMinimal(int format, AnalyzerModel model, } Entry desired = format == AnalyzerModel.FORMAT_SUM_OF_PRODUCTS - ? Entry.ONE : Entry.ZERO; + ? Entry.ONE : Entry.ZERO; Entry undesired = desired == Entry.ONE ? Entry.ZERO : Entry.ONE; // determine the first-cut implicants, as well as the rows @@ -97,7 +96,7 @@ static List computeMinimal(int format, AnalyzerModel model, toRemove.add(imp); toRemove.add(opp); Implicant i = new Implicant(opp.unknowns | j, - opp.values); + opp.values); Entry e; if (oppEntry == Entry.DONT_CARE && detEntry == Entry.DONT_CARE) { e = Entry.DONT_CARE; @@ -289,7 +288,7 @@ private Expression toSum(TruthTable source) { } private static class TermIterator - implements Iterable, Iterator { + implements Iterable, Iterator { Implicant source; int currentMask = 0; diff --git a/src/main/java/com/cburch/logisim/analyze/model/OutputExpressions.java b/src/main/java/com/cburch/logisim/analyze/model/OutputExpressions.java index 0cc5e70..71c1305 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/OutputExpressions.java +++ b/src/main/java/com/cburch/logisim/analyze/model/OutputExpressions.java @@ -11,9 +11,9 @@ public class OutputExpressions { - private AnalyzerModel model; - private HashMap outputData = new HashMap<>(); - private ArrayList listeners = new ArrayList<>(); + private final AnalyzerModel model; + private final HashMap outputData = new HashMap<>(); + private final ArrayList listeners = new ArrayList<>(); private boolean updatingTable = false; public OutputExpressions(AnalyzerModel model) { @@ -35,7 +35,7 @@ private static Entry[] computeColumn(TruthTable table, Expression expression) { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { assignments.put(table.getInputHeader(j), - TruthTable.isInputSet(i, j, columns)); + TruthTable.isInputSet(i, j, columns)); } entries[i] = expression.evaluate(assignments) ? Entry.ONE : Entry.ZERO; } @@ -50,7 +50,7 @@ private static boolean columnsMatch(Entry[] a, Entry[] b) { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { boolean bothDefined = (a[i] == Entry.ZERO || a[i] == Entry.ONE) - && (b[i] == Entry.ZERO || b[i] == Entry.ONE); + && (b[i] == Entry.ZERO || b[i] == Entry.ONE); if (bothDefined) { return false; } @@ -428,6 +428,7 @@ public void cellsChanged(TruthTableEvent event) { invalidate(output, false); } - public void structureChanged(TruthTableEvent event) { } + public void structureChanged(TruthTableEvent event) { + } } } diff --git a/src/main/java/com/cburch/logisim/analyze/model/OutputExpressionsEvent.java b/src/main/java/com/cburch/logisim/analyze/model/OutputExpressionsEvent.java index 1f721e6..55ca4f1 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/OutputExpressionsEvent.java +++ b/src/main/java/com/cburch/logisim/analyze/model/OutputExpressionsEvent.java @@ -9,10 +9,10 @@ public class OutputExpressionsEvent { public static final int OUTPUT_EXPRESSION = 1; public static final int OUTPUT_MINIMAL = 2; - private AnalyzerModel model; - private int type; - private String variable; - private Object data; + private final AnalyzerModel model; + private final int type; + private final String variable; + private final Object data; public OutputExpressionsEvent(AnalyzerModel model, int type, String variable, Object data) { this.model = model; diff --git a/src/main/java/com/cburch/logisim/analyze/model/Parser.java b/src/main/java/com/cburch/logisim/analyze/model/Parser.java index f80c558..008b1c6 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/Parser.java +++ b/src/main/java/com/cburch/logisim/analyze/model/Parser.java @@ -186,7 +186,7 @@ private static ArrayList toTokens(String in, boolean includeWhite) { private static boolean okCharacter(char c) { return Character.isWhitespace(c) || Character.isJavaIdentifierStart(c) - || "()01~^+!&|".indexOf(c) >= 0; + || "()01~^+!&|".indexOf(c) >= 0; } private static Expression parse(ArrayList tokens) throws ParserException { @@ -217,7 +217,7 @@ private static Expression parse(ArrayList tokens) throws ParserException } else if (t.type == TOKEN_NOT) { if (current != null) { push(stack, current, Expression.AND_LEVEL, - new Token(TOKEN_AND, t.offset, Strings.get("implicitAndOperator"))); + new Token(TOKEN_AND, t.offset, Strings.get("implicitAndOperator"))); } push(stack, null, Expression.NOT_LEVEL, t); current = null; @@ -226,7 +226,7 @@ private static Expression parse(ArrayList tokens) throws ParserException } else if (t.type == TOKEN_LPAREN) { if (current != null) { push(stack, current, Expression.AND_LEVEL, - new Token(TOKEN_AND, t.offset, 0, Strings.get("implicitAndOperator"))); + new Token(TOKEN_AND, t.offset, 0, Strings.get("implicitAndOperator"))); } push(stack, null, -2, t); current = null; @@ -271,7 +271,7 @@ private static Expression parse(ArrayList tokens) throws ParserException } private static void push(ArrayList stack, Expression expr, - int level, Token cause) { + int level, Token cause) { stack.add(new Context(expr, level, cause)); } @@ -288,7 +288,7 @@ private static Context pop(ArrayList stack) { } private static Expression popTo(ArrayList stack, int level, - Expression current) throws ParserException { + Expression current) throws ParserException { while (!stack.isEmpty() && peekLevel(stack) >= level) { Context top = pop(stack); if (current == null) { diff --git a/src/main/java/com/cburch/logisim/analyze/model/ParserException.java b/src/main/java/com/cburch/logisim/analyze/model/ParserException.java index ba9f360..2059710 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/ParserException.java +++ b/src/main/java/com/cburch/logisim/analyze/model/ParserException.java @@ -7,9 +7,9 @@ public class ParserException extends Exception { - private StringGetter message; - private int start; - private int length; + private final StringGetter message; + private final int start; + private final int length; public ParserException(StringGetter message, int start, int length) { super(message.get()); @@ -34,4 +34,4 @@ public int getOffset() { public int getEndOffset() { return start + length; } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/analyze/model/Strings.java b/src/main/java/com/cburch/logisim/analyze/model/Strings.java index a6da8e5..6dbe813 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/Strings.java +++ b/src/main/java/com/cburch/logisim/analyze/model/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "analyze"); + private static final LocaleManager source = new LocaleManager("logisim", "analyze"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/analyze/model/TruthTable.java b/src/main/java/com/cburch/logisim/analyze/model/TruthTable.java index 8c4b248..50a372c 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/TruthTable.java +++ b/src/main/java/com/cburch/logisim/analyze/model/TruthTable.java @@ -12,10 +12,10 @@ public class TruthTable { private static final Entry DEFAULT_ENTRY = Entry.DONT_CARE; - private MyListener myListener = new MyListener(); - private List listeners = new ArrayList<>(); - private AnalyzerModel model; - private HashMap outputColumns = new HashMap<>(); + private final MyListener myListener = new MyListener(); + private final List listeners = new ArrayList<>(); + private final AnalyzerModel model; + private final HashMap outputColumns = new HashMap<>(); public TruthTable(AnalyzerModel model) { this.model = model; @@ -259,7 +259,7 @@ private Entry[] moveInput(Entry[] old, int oldIndex, int newIndex) { newIndex = inputs - 1 - newIndex; Entry[] ret = new Entry[old.length]; int sameMask = (old.length - 1) ^ ((1 << (1 + Math.max(oldIndex, newIndex))) - 1) - ^ ((1 << Math.min(oldIndex, newIndex)) - 1); // bits that don't change + ^ ((1 << Math.min(oldIndex, newIndex)) - 1); // bits that don't change int moveMask = 1 << oldIndex; // bit that moves int moveDist = Math.abs(newIndex - oldIndex); boolean moveLeft = newIndex > oldIndex; @@ -268,10 +268,10 @@ private Entry[] moveInput(Entry[] old, int oldIndex, int newIndex) { int j; // new index if (moveLeft) { j = (i & sameMask) | ((i & moveMask) << moveDist) - | ((i & blockMask) >> 1); + | ((i & blockMask) >> 1); } else { j = (i & sameMask) | ((i & moveMask) >> moveDist) - | ((i & blockMask) << 1); + | ((i & blockMask) << 1); } ret[j] = old[i]; } diff --git a/src/main/java/com/cburch/logisim/analyze/model/TruthTableEvent.java b/src/main/java/com/cburch/logisim/analyze/model/TruthTableEvent.java index ce61ccb..f916f3b 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/TruthTableEvent.java +++ b/src/main/java/com/cburch/logisim/analyze/model/TruthTableEvent.java @@ -6,7 +6,7 @@ public class TruthTableEvent { - private TruthTable source; + private final TruthTable source; private int column; private Object data; diff --git a/src/main/java/com/cburch/logisim/analyze/model/VariableList.java b/src/main/java/com/cburch/logisim/analyze/model/VariableList.java index 85f33b5..d068917 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/VariableList.java +++ b/src/main/java/com/cburch/logisim/analyze/model/VariableList.java @@ -10,10 +10,10 @@ public class VariableList { - private ArrayList listeners = new ArrayList<>(); - private int maxSize; - private ArrayList data; - private List dataView; + private final ArrayList listeners = new ArrayList<>(); + private final int maxSize; + private final ArrayList data; + private final List dataView; public VariableList(int maxSize) { this.maxSize = maxSize; @@ -123,11 +123,11 @@ public void move(String name, int delta) { int newIndex = index + delta; if (newIndex < 0) { throw new IllegalArgumentException("cannot move index " + index - + " by " + delta); + + " by " + delta); } if (newIndex > data.size() - 1) { throw new IllegalArgumentException("cannot move index " + index - + " by " + delta + ": size " + data.size()); + + " by " + delta + ": size " + data.size()); } if (index == newIndex) { return; diff --git a/src/main/java/com/cburch/logisim/analyze/model/VariableListEvent.java b/src/main/java/com/cburch/logisim/analyze/model/VariableListEvent.java index 6c83bdc..15e90e9 100644 --- a/src/main/java/com/cburch/logisim/analyze/model/VariableListEvent.java +++ b/src/main/java/com/cburch/logisim/analyze/model/VariableListEvent.java @@ -11,10 +11,10 @@ public class VariableListEvent { public static final int MOVE = 3; public static final int REPLACE = 4; - private VariableList source; - private int type; - private String variable; - private Object data; + private final VariableList source; + private final int type; + private final String variable; + private final Object data; public VariableListEvent(VariableList source, int type, String variable, Object data) { this.source = source; diff --git a/src/main/java/com/cburch/logisim/circuit/Analyze.java b/src/main/java/com/cburch/logisim/circuit/Analyze.java index 20925fd..dff3eb4 100644 --- a/src/main/java/com/cburch/logisim/circuit/Analyze.java +++ b/src/main/java/com/cburch/logisim/circuit/Analyze.java @@ -98,12 +98,12 @@ public int compare(Instance ac, Instance bc) { String defaultList; if (Pin.FACTORY.isInputPin(pin)) { defaultList = Strings.get("defaultInputLabels"); - if (defaultList.indexOf(",") < 0) { + if (!defaultList.contains(",")) { defaultList = "a,b,c,d,e,f,g,h"; } } else { defaultList = Strings.get("defaultOutputLabels"); - if (defaultList.indexOf(",") < 0) { + if (!defaultList.contains(",")) { defaultList = "x,y,z,u,v,w,s,t"; } } @@ -168,7 +168,7 @@ private static String toValidLabel(String label) { } } if (end != null && ret.length() > 0) { - ret.append(end.toString()); + ret.append(end); } if (ret.length() == 0) { return null; @@ -186,7 +186,7 @@ private static String toValidLabel(String label) { * arise. */ public static void computeExpression(AnalyzerModel model, Circuit circuit, - Map pinNames) throws AnalyzeException { + Map pinNames) throws AnalyzeException { ExpressionMap expressionMap = new ExpressionMap(circuit); ArrayList inputNames = new ArrayList<>(); @@ -229,13 +229,13 @@ public static void computeExpression(AnalyzerModel model, Circuit circuit, for (int i = 0; i < outputPins.size(); i++) { Instance pin = outputPins.get(i); model.getOutputExpressions().setExpression(outputNames.get(i), - expressionMap.get(pin.getLocation())); + expressionMap.get(pin.getLocation())); } } // propagates expressions down wires private static void propagateWires(ExpressionMap expressionMap, - HashSet pointsToProcess) throws AnalyzeException { + HashSet pointsToProcess) throws AnalyzeException { expressionMap.currentCause = null; for (Location p : pointsToProcess) { Expression e = expressionMap.get(p); @@ -262,7 +262,7 @@ private static void propagateWires(ExpressionMap expressionMap, // computes outputs of affected components private static HashSet getDirtyComponents(Circuit circuit, - Set pointsToProcess) throws AnalyzeException { + Set pointsToProcess) throws AnalyzeException { HashSet dirtyComponents = new HashSet<>(); for (Location point : pointsToProcess) { for (Component comp : circuit.getNonWires(point)) { @@ -273,10 +273,10 @@ private static HashSet getDirtyComponents(Circuit circuit, } private static void propagateComponents(ExpressionMap expressionMap, - Collection components) throws AnalyzeException { + Collection components) throws AnalyzeException { for (Component comp : components) { ExpressionComputer computer - = (ExpressionComputer) comp.getFeature(ExpressionComputer.class); + = (ExpressionComputer) comp.getFeature(ExpressionComputer.class); if (computer != null) { try { expressionMap.currentCause = comp; @@ -298,7 +298,7 @@ private static void propagateComponents(ExpressionMap expressionMap, * expression map are self-referential; if so, return it. */ private static Expression checkForCircularExpressions(ExpressionMap expressionMap) - throws AnalyzeException { + throws AnalyzeException { for (Location point : expressionMap.dirtyPoints) { Expression expr = expressionMap.get(point); if (expr.isCircular()) { @@ -312,7 +312,7 @@ private static Expression checkForCircularExpressions(ExpressionMap expressionMa * Returns a truth table corresponding to the circuit. */ public static void computeTable(AnalyzerModel model, Project proj, - Circuit circuit, Map pinLabels) { + Circuit circuit, Map pinLabels) { ArrayList inputPins = new ArrayList<>(); ArrayList inputNames = new ArrayList<>(); ArrayList outputPins = new ArrayList<>(); @@ -385,9 +385,9 @@ public static void computeTable(AnalyzerModel model, Project proj, private static class ExpressionMap extends HashMap { - private Circuit circuit; - private Set dirtyPoints = new HashSet<>(); - private Map causes = new HashMap<>(); + private final Circuit circuit; + private final Set dirtyPoints = new HashSet<>(); + private final Map causes = new HashMap<>(); private Component currentCause = null; ExpressionMap(Circuit circuit) { diff --git a/src/main/java/com/cburch/logisim/circuit/Circuit.java b/src/main/java/com/cburch/logisim/circuit/Circuit.java index d6f0499..b0e4f29 100644 --- a/src/main/java/com/cburch/logisim/circuit/Circuit.java +++ b/src/main/java/com/cburch/logisim/circuit/Circuit.java @@ -33,17 +33,17 @@ public class Circuit { private static final PrintStream DEBUG_STREAM = null; + private final MyComponentListener myComponentListener = new MyComponentListener(); + private final EventSourceWeakSupport listeners = new EventSourceWeakSupport<>(); + // wires is package-protected for CircuitState and Analyze only. + private final ArrayList clocks = new ArrayList<>(); + private final CircuitLocker locker; + private final WeakHashMap circuitsUsingThis; + private final CircuitAppearance appearance; + private final AttributeSet staticAttributes; + private final SubcircuitFactory subcircuitFactory; CircuitWires wires = new CircuitWires(); - private MyComponentListener myComponentListener = new MyComponentListener(); - private EventSourceWeakSupport listeners = new EventSourceWeakSupport<>(); private HashSet components = new HashSet<>(); // doesn't include wires - // wires is package-protected for CircuitState and Analyze only. - private ArrayList clocks = new ArrayList<>(); - private CircuitLocker locker; - private WeakHashMap circuitsUsingThis; - private CircuitAppearance appearance; - private AttributeSet staticAttributes; - private SubcircuitFactory subcircuitFactory; public Circuit(String name) { appearance = new CircuitAppearance(this); @@ -436,12 +436,12 @@ public void draw(ComponentDrawContext context, Collection hiddenCompo private class EndChangedTransaction extends CircuitTransaction { - private Component component; - private Map toRemove; - private Map toAdd; + private final Component component; + private final Map toRemove; + private final Map toAdd; EndChangedTransaction(Component component, Map toRemove, - Map toAdd) { + Map toAdd) { this.component = component; this.toRemove = toRemove; this.toAdd = toAdd; diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitAction.java b/src/main/java/com/cburch/logisim/circuit/CircuitAction.java index 61a28eb..6f05b5d 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitAction.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitAction.java @@ -9,8 +9,8 @@ public class CircuitAction extends Action { - private StringGetter name; - private CircuitTransaction forward; + private final StringGetter name; + private final CircuitTransaction forward; private CircuitTransaction reverse; CircuitAction(StringGetter name, CircuitMutation forward) { diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitAttributes.java b/src/main/java/com/cburch/logisim/circuit/CircuitAttributes.java index be252d1..e0f2a91 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitAttributes.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitAttributes.java @@ -22,32 +22,32 @@ public class CircuitAttributes extends AbstractAttributeSet { public static final Attribute NAME_ATTRIBUTE - = Attributes.forString("circuit", Strings.getter("circuitName")); + = Attributes.forString("circuit", Strings.getter("circuitName")); public static final Attribute LABEL_LOCATION_ATTR - = Attributes.forDirection("labelloc", Strings.getter("circuitLabelLocAttr")); + = Attributes.forDirection("labelloc", Strings.getter("circuitLabelLocAttr")); public static final Attribute CIRCUIT_LABEL_ATTR - = Attributes.forString("clabel", Strings.getter("circuitLabelAttr")); + = Attributes.forString("clabel", Strings.getter("circuitLabelAttr")); public static final Attribute CIRCUIT_LABEL_FACING_ATTR - = Attributes.forDirection("clabelup", Strings.getter("circuitLabelDirAttr")); + = Attributes.forDirection("clabelup", Strings.getter("circuitLabelDirAttr")); public static final Attribute CIRCUIT_LABEL_FONT_ATTR - = Attributes.forFont("clabelfont", Strings.getter("circuitLabelFontAttr")); + = Attributes.forFont("clabelfont", Strings.getter("circuitLabelFontAttr")); private static final Attribute[] STATIC_ATTRS = { - NAME_ATTRIBUTE, CIRCUIT_LABEL_ATTR, CIRCUIT_LABEL_FACING_ATTR, CIRCUIT_LABEL_FONT_ATTR, + NAME_ATTRIBUTE, CIRCUIT_LABEL_ATTR, CIRCUIT_LABEL_FACING_ATTR, CIRCUIT_LABEL_FONT_ATTR, }; private static final Object[] STATIC_DEFAULTS = { - "", "", Direction.EAST, StdAttr.DEFAULT_LABEL_FONT, + "", "", Direction.EAST, StdAttr.DEFAULT_LABEL_FONT, }; private static final List> INSTANCE_ATTRS - = Arrays.asList(StdAttr.FACING, StdAttr.LABEL, LABEL_LOCATION_ATTR, - StdAttr.LABEL_FONT, - CircuitAttributes.NAME_ATTRIBUTE, CIRCUIT_LABEL_ATTR, - CIRCUIT_LABEL_FACING_ATTR, CIRCUIT_LABEL_FONT_ATTR); - private Circuit source; + = Arrays.asList(StdAttr.FACING, StdAttr.LABEL, LABEL_LOCATION_ATTR, + StdAttr.LABEL_FONT, + CircuitAttributes.NAME_ATTRIBUTE, CIRCUIT_LABEL_ATTR, + CIRCUIT_LABEL_FACING_ATTR, CIRCUIT_LABEL_FONT_ATTR); + private final Circuit source; private Instance subcircInstance; private Direction facing; private String label; @@ -167,7 +167,7 @@ public void setValue(Attribute attr, E value) { private static class StaticListener implements AttributeListener { - private Circuit source; + private final Circuit source; private StaticListener(Circuit s) { source = s; diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitChange.java b/src/main/java/com/cburch/logisim/circuit/CircuitChange.java index 031c0ee..3cab5d3 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitChange.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitChange.java @@ -19,26 +19,26 @@ class CircuitChange { static final int REPLACE = 5; static final int SET = 6; static final int SET_FOR_CIRCUIT = 7; - private Circuit circuit; - private int type; - private Component comp; + private final Circuit circuit; + private final int type; + private final Component comp; + private final Attribute attr; + private final Object oldValue; + private final Object newValue; private Collection comps; - private Attribute attr; - private Object oldValue; - private Object newValue; private CircuitChange(Circuit circuit, int type, Component comp) { this(circuit, type, comp, null, null, null); } private CircuitChange(Circuit circuit, int type, - Collection comps) { + Collection comps) { this(circuit, type, null, null, null, null); this.comps = comps; } private CircuitChange(Circuit circuit, int type, Component comp, - Attribute attr, Object oldValue, Object newValue) { + Attribute attr, Object oldValue, Object newValue) { this.circuit = circuit; this.type = type; this.comp = comp; @@ -48,7 +48,7 @@ private CircuitChange(Circuit circuit, int type, Component comp, } public static CircuitChange clear(Circuit circuit, - Collection oldComponents) { + Collection oldComponents) { return new CircuitChange(circuit, CLEAR, oldComponents); } @@ -57,7 +57,7 @@ public static CircuitChange add(Circuit circuit, Component comp) { } public static CircuitChange addAll(Circuit circuit, - Collection comps) { + Collection comps) { return new CircuitChange(circuit, ADD_ALL, comps); } @@ -66,34 +66,34 @@ public static CircuitChange remove(Circuit circuit, Component comp) { } public static CircuitChange removeAll(Circuit circuit, - Collection comps) { + Collection comps) { return new CircuitChange(circuit, REMOVE_ALL, comps); } public static CircuitChange replace(Circuit circuit, - ReplacementMap replMap) { + ReplacementMap replMap) { return new CircuitChange(circuit, REPLACE, null, null, null, replMap); } public static CircuitChange set(Circuit circuit, Component comp, - Attribute attr, Object value) { + Attribute attr, Object value) { return new CircuitChange(circuit, SET, comp, attr, null, value); } public static CircuitChange set(Circuit circuit, Component comp, - Attribute attr, Object oldValue, Object newValue) { + Attribute attr, Object oldValue, Object newValue) { return new CircuitChange(circuit, SET, comp, attr, oldValue, newValue); } public static CircuitChange setForCircuit(Circuit circuit, - Attribute attr, Object v) { + Attribute attr, Object v) { return new CircuitChange(circuit, SET_FOR_CIRCUIT, null, attr, null, v); } public static CircuitChange setForCircuit(Circuit circuit, - Attribute attr, Object oldValue, Object newValue) { + Attribute attr, Object oldValue, Object newValue) { return new CircuitChange(circuit, SET_FOR_CIRCUIT, null, attr, oldValue, - newValue); + newValue); } public Circuit getCircuit() { @@ -138,7 +138,7 @@ CircuitChange getReverseChange() { return CircuitChange.setForCircuit(circuit, attr, newValue, oldValue); case REPLACE: return CircuitChange.replace(circuit, - ((ReplacementMap) newValue).getInverseMap()); + ((ReplacementMap) newValue).getInverseMap()); default: throw new IllegalArgumentException("unknown change type " + type); } @@ -214,9 +214,9 @@ boolean concernsSupercircuit() { return false; case SET: return comp.getFactory() instanceof Pin - && (attr == StdAttr.WIDTH || attr == Pin.ATTR_TYPE); + && (attr == StdAttr.WIDTH || attr == Pin.ATTR_TYPE); default: return false; } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitEvent.java b/src/main/java/com/cburch/logisim/circuit/CircuitEvent.java index ce58019..1849119 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitEvent.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitEvent.java @@ -14,9 +14,9 @@ public class CircuitEvent { public final static int ACTION_CLEAR = 5; // entire circuit cleared public final static int TRANSACTION_DONE = 6; - private int action; - private Circuit circuit; - private Object data; + private final int action; + private final Circuit circuit; + private final Object data; CircuitEvent(int action, Circuit circuit, Object data) { this.action = action; diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitLocker.java b/src/main/java/com/cburch/logisim/circuit/CircuitLocker.java index c664ef0..45a36d6 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitLocker.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitLocker.java @@ -3,6 +3,7 @@ package com.cburch.logisim.circuit; +import com.adlerd.logger.Logger; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; @@ -14,10 +15,10 @@ class CircuitLocker { - private static AtomicInteger NEXT_SERIAL_NUMBER = new AtomicInteger(0); + private static final AtomicInteger NEXT_SERIAL_NUMBER = new AtomicInteger(0); - private int serialNumber; - private ReadWriteLock circuitLock; + private final int serialNumber; + private final ReadWriteLock circuitLock; private transient Thread mutatingThread; private CircuitMutatorImpl mutatingMutator; @@ -29,7 +30,7 @@ class CircuitLocker { } static Map acquireLocks(CircuitTransaction xn, - CircuitMutatorImpl mutator) { + CircuitMutatorImpl mutator) { Map requests = xn.getAccessedCircuits(); Map circuitLocks = new HashMap<>(); // Acquire locks in serial-number order to avoid deadlock @@ -39,14 +40,15 @@ static Map acquireLocks(CircuitTransaction xn, for (Circuit circ : lockOrder) { Integer access = requests.get(circ); CircuitLocker locker = circ.getLocker(); - if (access == CircuitTransaction.READ_ONLY) { + if (access.equals(CircuitTransaction.READ_ONLY)) { Lock lock = locker.circuitLock.readLock(); lock.lock(); circuitLocks.put(circ, lock); - } else if (access == CircuitTransaction.READ_WRITE) { + } else if (access.equals(CircuitTransaction.READ_WRITE)) { Thread curThread = Thread.currentThread(); if (locker.mutatingThread == curThread) { // nothing to do - thread already has lock + Logger.debugln("Nothing to do... Thread already has lock"); } else { Lock lock = locker.circuitLock.writeLock(); lock.lock(); @@ -69,9 +71,9 @@ static Map acquireLocks(CircuitTransaction xn, static void releaseLocks(Map locks) { Thread curThread = Thread.currentThread(); for (Map.Entry entry : locks.entrySet()) { - Circuit circ = entry.getKey(); + Circuit circuit = entry.getKey(); Lock lock = entry.getValue(); - CircuitLocker locker = circ.getLocker(); + CircuitLocker locker = circuit.getLocker(); if (locker.mutatingThread == curThread) { locker.mutatingThread = null; locker.mutatingMutator = null; diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitMutation.java b/src/main/java/com/cburch/logisim/circuit/CircuitMutation.java index 30b129c..ca71108 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitMutation.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitMutation.java @@ -16,8 +16,8 @@ public final class CircuitMutation extends CircuitTransaction { - private Circuit primary; - private List changes; + private final Circuit primary; + private final List changes; public CircuitMutation(Circuit circuit) { this.primary = circuit; @@ -88,13 +88,13 @@ protected Map getAccessedCircuits() { HashMap accessMap = new HashMap<>(); HashSet supercircsDone = new HashSet<>(); for (CircuitChange change : changes) { - Circuit circ = change.getCircuit(); - accessMap.put(circ, READ_WRITE); + Circuit circuit = change.getCircuit(); + accessMap.put(circuit, READ_WRITE); if (change.concernsSupercircuit()) { - boolean isFirstForCirc = supercircsDone.add(circ); + boolean isFirstForCirc = supercircsDone.add(circuit); if (isFirstForCirc) { - for (Circuit supercirc : circ.getCircuitsUsingThis()) { + for (Circuit supercirc : circuit.getCircuitsUsingThis()) { accessMap.put(supercirc, READ_WRITE); } } @@ -122,4 +122,4 @@ protected void run(CircuitMutator mutator) { mutator.replace(curCircuit, curReplacements); } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitMutatorImpl.java b/src/main/java/com/cburch/logisim/circuit/CircuitMutatorImpl.java index dc53d48..f5f716e 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitMutatorImpl.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitMutatorImpl.java @@ -14,9 +14,9 @@ class CircuitMutatorImpl implements CircuitMutator { - private ArrayList log; - private HashMap replacements; - private HashSet modified; + private final ArrayList log; + private final HashMap replacements; + private final HashSet modified; public CircuitMutatorImpl() { log = new ArrayList<>(); @@ -87,7 +87,7 @@ public void replace(Circuit circuit, ReplacementMap repl) { } public void set(Circuit circuit, Component comp, Attribute attr, - Object newValue) { + Object newValue) { if (circuit.contains(comp)) { modified.add(circuit); @SuppressWarnings("unchecked") @@ -100,7 +100,7 @@ public void set(Circuit circuit, Component comp, Attribute attr, } public void setForCircuit(Circuit circuit, Attribute attr, - Object newValue) { + Object newValue) { @SuppressWarnings("unchecked") Attribute a = (Attribute) attr; AttributeSet attrs = circuit.getStaticAttributes(); diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitPoints.java b/src/main/java/com/cburch/logisim/circuit/CircuitPoints.java index 4106bb8..fa43f72 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitPoints.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitPoints.java @@ -16,10 +16,8 @@ class CircuitPoints { - private HashMap map - = new HashMap<>(); - private HashMap incompatibilityData - = new HashMap<>(); + private final HashMap map = new HashMap<>(); + private final HashMap incompatibilityData = new HashMap<>(); public CircuitPoints() { } @@ -90,9 +88,9 @@ private Collection find(Location loc, boolean isWire) { ArrayList list = locData.components; int retSize = 0; Component retValue = null; - for (Component o : list) { - if ((o instanceof Wire) == isWire) { - retValue = o; + for (Component component : list) { + if ((component instanceof Wire) == isWire) { + retValue = component; retSize++; } } @@ -123,17 +121,15 @@ Collection getWidthIncompatibilityData() { } boolean hasConflict(Component comp) { - if (comp instanceof Wire) { - return false; - } else { + if (!(comp instanceof Wire)) { for (EndData endData : comp.getEnds()) { if (endData != null && endData.isExclusive() - && getExclusive(endData.getLocation()) != null) { + && getExclusive(endData.getLocation()) != null) { return true; } } - return false; } + return false; } // @@ -141,9 +137,9 @@ && getExclusive(endData.getLocation()) != null) { // void add(Component comp) { if (comp instanceof Wire) { - Wire w = (Wire) comp; - addSub(w.getEnd0(), w, null); - addSub(w.getEnd1(), w, null); + Wire wire = (Wire) comp; + addSub(wire.getEnd0(), wire, null); + addSub(wire.getEnd1(), wire, null); } else { for (EndData endData : comp.getEnds()) { if (endData != null) { @@ -161,9 +157,9 @@ void add(Component comp, EndData endData) { void remove(Component comp) { if (comp instanceof Wire) { - Wire w = (Wire) comp; - removeSub(w.getEnd0(), w); - removeSub(w.getEnd1(), w); + Wire wire = (Wire) comp; + removeSub(wire.getEnd0(), wire); + removeSub(wire.getEnd1(), wire); } else { for (EndData endData : comp.getEnds()) { if (endData != null) { @@ -180,14 +176,14 @@ void remove(Component comp, EndData endData) { } private void addSub(Location loc, Component comp, EndData endData) { - LocationData locData = map.get(loc); - if (locData == null) { - locData = new LocationData(); - map.put(loc, locData); - } - locData.components.add(comp); - locData.ends.add(endData); - computeIncompatibilityData(loc, locData); + LocationData locationData = map.get(loc); + if (locationData == null) { + locationData = new LocationData(); + map.put(loc, locationData); + } + locationData.components.add(comp); + locationData.ends.add(endData); + computeIncompatibilityData(loc, locationData); } private void removeSub(Location loc, Component comp) { diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitState.java b/src/main/java/com/cburch/logisim/circuit/CircuitState.java index 06a8a4a..25e2afd 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitState.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitState.java @@ -29,29 +29,29 @@ public class CircuitState implements InstanceData { private static int lastId = 0; + private final MyCircuitListener myCircuitListener = new MyCircuitListener(); + private final Project project; // project where circuit lies + private final Circuit circuit; // circuit being simulated + private final HashMap componentData = new HashMap<>(); + private final Map values = new HashMap<>(); + private final SmallSet dirtyPoints = new SmallSet<>(); + private final int id = lastId++; HashMap causes = new HashMap<>(); - private MyCircuitListener myCircuitListener = new MyCircuitListener(); private Propagator base = null; // base of tree of CircuitStates - private Project proj; // project where circuit lies - private Circuit circuit; // circuit being simulated private CircuitState parentState = null; // parent in tree of CircuitStates private Component parentComp = null; // subcircuit component containing this state private ArraySet substates = new ArraySet<>(); private CircuitWires.State wireData = null; - private HashMap componentData = new HashMap<>(); - private Map values = new HashMap<>(); private SmallSet dirtyComponents = new SmallSet<>(); - private SmallSet dirtyPoints = new SmallSet<>(); - private int id = lastId++; - public CircuitState(Project proj, Circuit circuit) { - this.proj = proj; + public CircuitState(Project project, Circuit circuit) { + this.project = project; this.circuit = circuit; circuit.addCircuitListener(myCircuitListener); } public Project getProject() { - return proj; + return project; } Component getSubcircuit() { @@ -64,7 +64,7 @@ public CircuitState clone() { } public CircuitState cloneState() { - CircuitState ret = new CircuitState(proj, circuit); + CircuitState ret = new CircuitState(project, circuit); ret.copyFrom(this, new Propagator(ret)); ret.parentComp = null; ret.parentState = null; @@ -78,7 +78,7 @@ private void copyFrom(CircuitState src, Propagator base) { HashMap substateData = new HashMap<>(); this.substates = new ArraySet<>(); for (CircuitState oldSub : src.substates) { - CircuitState newSub = new CircuitState(src.proj, oldSub.circuit); + CircuitState newSub = new CircuitState(src.project, oldSub.circuit); newSub.copyFrom(oldSub, base); newSub.parentState = this; this.substates.add(newSub); @@ -262,9 +262,9 @@ void processDirtyComponents() { } } dirtyComponents.clear(); - for (Object compObj : toProcess) { - if (compObj instanceof Component) { - Component comp = (Component) compObj; + for (Object componentObject : toProcess) { + if (componentObject instanceof Component) { + Component comp = (Component) componentObject; comp.propagate(this); if (comp.getFactory() instanceof Pin && parentState != null) { // should be propagated in superstate @@ -293,6 +293,7 @@ void processDirtyPoints() { try { Thread.sleep(1); } catch (InterruptedException e2) { + e2.printStackTrace(); } if (i == 0) { e.printStackTrace(); @@ -444,33 +445,36 @@ public void circuitChanged(CircuitEvent event) { } } } else { - Component comp = (Component) event.getData(); - markComponentAsDirty(comp); + Component component = (Component) event.getData(); + markComponentAsDirty(component); if (base != null) { - base.checkComponentEnds(CircuitState.this, comp); + base.checkComponentEnds(CircuitState.this, component); } } } else if (action == CircuitEvent.ACTION_INVALIDATE) { - Component comp = (Component) event.getData(); - markComponentAsDirty(comp); - // TODO detemine if this should really be missing if (base != null) base.checkComponentEnds(CircuitState.this, comp); + Component component = (Component) event.getData(); + markComponentAsDirty(component); + // TODO determine if this should really be missing + // if (base != null) { + // base.checkComponentEnds(CircuitState.this, component); + // } } else if (action == CircuitEvent.TRANSACTION_DONE) { ReplacementMap map = event.getResult().getReplacementMap(circuit); if (map != null) { - for (Component comp : map.getReplacedComponents()) { - Object compState = componentData.remove(comp); - if (compState != null) { - Class compFactory = comp.getFactory().getClass(); + for (Component component : map.getReplacedComponents()) { + Object componentState = componentData.remove(component); + if (componentState != null) { + Class compFactory = component.getFactory().getClass(); boolean found = false; - for (Component repl : map.get(comp)) { + for (Component repl : map.get(component)) { if (repl.getFactory().getClass() == compFactory) { found = true; - setData(repl, compState); + setData(repl, componentState); break; } } - if (!found && compState instanceof CircuitState) { - CircuitState sub = (CircuitState) compState; + if (!found && componentState instanceof CircuitState) { + CircuitState sub = (CircuitState) componentState; sub.parentState = null; substates.remove(sub); } diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitTransactionResult.java b/src/main/java/com/cburch/logisim/circuit/CircuitTransactionResult.java index d746420..f08275c 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitTransactionResult.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitTransactionResult.java @@ -7,7 +7,7 @@ public class CircuitTransactionResult { - private CircuitMutatorImpl mutator; + private final CircuitMutatorImpl mutator; CircuitTransactionResult(CircuitMutatorImpl mutator) { this.mutator = mutator; diff --git a/src/main/java/com/cburch/logisim/circuit/CircuitWires.java b/src/main/java/com/cburch/logisim/circuit/CircuitWires.java index cecdb11..9f9a3e7 100644 --- a/src/main/java/com/cburch/logisim/circuit/CircuitWires.java +++ b/src/main/java/com/cburch/logisim/circuit/CircuitWires.java @@ -34,11 +34,11 @@ class CircuitWires { final CircuitPoints points = new CircuitPoints(); // user-given data - private HashSet wires = new HashSet<>(); - private HashSet splitters = new HashSet<>(); - private HashSet tunnels = new HashSet<>(); // of Components with Tunnel factory - private TunnelListener tunnelListener = new TunnelListener(); - private HashSet pulls = new HashSet<>(); // of Components with PullResistor factory + private final HashSet wires = new HashSet<>(); + private final HashSet splitters = new HashSet<>(); + private final HashSet tunnels = new HashSet<>(); // of Components with Tunnel factory + private final TunnelListener tunnelListener = new TunnelListener(); + private final HashSet pulls = new HashSet<>(); // of Components with PullResistor factory // derived data private Bounds bounds = Bounds.EMPTY_BOUNDS; private BundleMap bundleMap = null; @@ -115,7 +115,7 @@ Location getWidthDeterminant(Location q) { Iterator getComponents() { return IteratorUtil.createJoinedIterator(splitters.iterator(), - wires.iterator()); + wires.iterator()); } Set getWires() { @@ -740,7 +740,7 @@ private Bounds recomputeBounds() { } } Bounds bds = Bounds.create(xmin, ymin, - xmax - xmin + 1, ymax - ymin + 1); + xmax - xmin + 1, ymax - ymin + 1); bounds = bds; return bds; } diff --git a/src/main/java/com/cburch/logisim/circuit/PropagationPoints.java b/src/main/java/com/cburch/logisim/circuit/PropagationPoints.java index e131dc9..73e4852 100644 --- a/src/main/java/com/cburch/logisim/circuit/PropagationPoints.java +++ b/src/main/java/com/cburch/logisim/circuit/PropagationPoints.java @@ -14,7 +14,7 @@ class PropagationPoints { - private HashSet data; + private final HashSet data; PropagationPoints() { this.data = new HashSet<>(); @@ -60,7 +60,7 @@ void draw(ComponentDrawContext context) { } private void addSubstates(HashMap map, - CircuitState source, CircuitState value) { + CircuitState source, CircuitState value) { map.put(source, value); for (CircuitState s : source.getSubstates()) { addSubstates(map, s, value); @@ -69,8 +69,8 @@ private void addSubstates(HashMap map, private static class Entry { - private CircuitState state; - private Location loc; + private final CircuitState state; + private final Location loc; private Entry(CircuitState state, Location loc) { this.state = state; diff --git a/src/main/java/com/cburch/logisim/circuit/Propagator.java b/src/main/java/com/cburch/logisim/circuit/Propagator.java index 1deba74..2a87e54 100644 --- a/src/main/java/com/cburch/logisim/circuit/Propagator.java +++ b/src/main/java/com/cburch/logisim/circuit/Propagator.java @@ -19,14 +19,16 @@ public class Propagator { - private static int lastId = 0; - private int id = lastId++; - private CircuitState root; // root of state tree /** * The number of clock cycles to let pass before deciding that the * circuit is oscillating. */ private static final int SIM_LIMIT = 1000; + private static int lastId = 0; + private final int id = lastId++; + private final CircuitState root; // root of state tree + private final PriorityQueue toProcess = new PriorityQueue<>(); + private final Random noiseSource = new Random(); /** * On average, one out of every 2**simRandomShift propagations * through a component is delayed one step more than the component @@ -35,13 +37,11 @@ public class Propagator { * practice). */ private volatile int simulateRandomShift; - private PriorityQueue toProcess = new PriorityQueue<>(); private int clock = 0; private boolean isOscillating = false; private boolean oscillatorAdding = false; private PropagationPoints oscillatorPoints = new PropagationPoints(); private int ticks = 0; - private Random noiseSource = new Random(); private int noiseCount = 0; private int setDataSerialNumber = 0; @@ -174,7 +174,7 @@ private void stepInternal(PropagationPoints changedPoints) { handled.add(new ComponentPoint(data.cause, data.location)); } - // TODO: DEBUGGING - comment out + // TODO: DEBUGGING - comment out // Logger.debugln("(Propagator.class ln:179) -> " + data.time + ": proc " + data.location + " in " + data.state + " to " + data.value + " by " + data.cause); if (changedPoints != null) { @@ -211,7 +211,7 @@ void locationTouched(CircuitState state, Location location) { // package-protected helper methods // void setValue(CircuitState state, Location point, Value value, - Component cause, int delay) { + Component cause, int delay) { if (cause instanceof Wire || cause instanceof Splitter) { return; } @@ -234,7 +234,7 @@ void setValue(CircuitState state, Location point, Value value, } } toProcess.add(new SetData(clock + delay, setDataSerialNumber, - state, point, cause, value)); + state, point, cause, value)); // TODO: DEBUGGING - comment out // Logger.debugln(String.format("(Propagator.class ln:240) -> %d: set %s in %s to %s by %s after %d", clock, point, state, value, cause, delay)); @@ -354,7 +354,7 @@ private SetData addCause(CircuitState state, SetData head, SetData data) { } private SetData removeCause(CircuitState state, SetData head, - Location location, Component cause) { + Location location, Component cause) { HashMap causes = state.causes; if (head != null) { if (head.cause == cause) { @@ -381,16 +381,17 @@ private SetData removeCause(CircuitState state, SetData head, } static class SetData implements Comparable { - private int time; - private int serialNumber; - private CircuitState state; // state of circuit containing component - private Component cause; // component emitting the value - private Location location; // the location at which value is emitted + + private final int time; + private final int serialNumber; + private final CircuitState state; // state of circuit containing component + private final Component cause; // component emitting the value + private final Location location; // the location at which value is emitted private Value value; // value being emitted private SetData next = null; private SetData(int time, int serialNumber, CircuitState state, - Location location, Component cause, Value value) { + Location location, Component cause, Value value) { this.time = time; this.serialNumber = serialNumber; this.state = state; @@ -413,7 +414,7 @@ public SetData cloneFor(CircuitState newState) { Propagator newProp = newState.getPropagator(); int clockTime = newProp.clock - state.getPropagator().clock; SetData setData = new SetData(this.time + clockTime, - newProp.setDataSerialNumber, newState, location, cause, value); + newProp.setDataSerialNumber, newState, location, cause, value); newProp.setDataSerialNumber++; if (this.next != null) { setData.next = this.next.cloneFor(newState); @@ -429,8 +430,8 @@ public String toString() { private static class ComponentPoint { - private Component cause; - private Location location; + private final Component cause; + private final Location location; private ComponentPoint(Component cause, Location location) { this.cause = cause; @@ -454,13 +455,14 @@ public boolean equals(Object object) { private static class Listener implements AttributeListener { - private WeakReference propagators; + private final WeakReference propagators; private Listener(Propagator propagator) { propagators = new WeakReference<>(propagator); } - public void attributeListChanged(AttributeEvent event) { } + public void attributeListChanged(AttributeEvent event) { + } public void attributeValueChanged(AttributeEvent event) { Propagator propagator = propagators.get(); diff --git a/src/main/java/com/cburch/logisim/circuit/RadixOption.java b/src/main/java/com/cburch/logisim/circuit/RadixOption.java index 23c6055..498f526 100644 --- a/src/main/java/com/cburch/logisim/circuit/RadixOption.java +++ b/src/main/java/com/cburch/logisim/circuit/RadixOption.java @@ -19,12 +19,12 @@ public abstract class RadixOption extends AttributeOption { public static final RadixOption RADIX_16 = new Radix16(); public static final RadixOption[] OPTIONS = { - RADIX_2, RADIX_8, RADIX_10_SIGNED, RADIX_10_UNSIGNED, RADIX_16 + RADIX_2, RADIX_8, RADIX_10_SIGNED, RADIX_10_UNSIGNED, RADIX_16 }; public static final Attribute ATTRIBUTE - = Attributes.forOption("radix", Strings.getter("radixAttr"), OPTIONS); - private String saveName; - private StringGetter displayGetter; + = Attributes.forOption("radix", Strings.getter("radixAttr"), OPTIONS); + private final String saveName; + private final StringGetter displayGetter; private RadixOption(String saveName, StringGetter displayGetter) { super(saveName, displayGetter); diff --git a/src/main/java/com/cburch/logisim/circuit/ReplacementMap.java b/src/main/java/com/cburch/logisim/circuit/ReplacementMap.java index a5bcc2a..a90a767 100644 --- a/src/main/java/com/cburch/logisim/circuit/ReplacementMap.java +++ b/src/main/java/com/cburch/logisim/circuit/ReplacementMap.java @@ -13,13 +13,12 @@ public class ReplacementMap { + private final HashMap> map; + private final HashMap> inverse; private boolean frozen; - private HashMap> map; - private HashMap> inverse; public ReplacementMap(Component oldComp, Component newComp) { - this(new HashMap<>(), - new HashMap<>()); + this(new HashMap<>(), new HashMap<>()); HashSet oldSet = new HashSet<>(3); oldSet.add(oldComp); HashSet newSet = new HashSet<>(3); @@ -29,12 +28,10 @@ public ReplacementMap(Component oldComp, Component newComp) { } public ReplacementMap() { - this(new HashMap<>(), - new HashMap<>()); + this(new HashMap<>(), new HashMap<>()); } - private ReplacementMap(HashMap> map, - HashMap> inverse) { + private ReplacementMap(HashMap> map, HashMap> inverse) { this.map = map; this.inverse = inverse; } diff --git a/src/main/java/com/cburch/logisim/circuit/Simulator.java b/src/main/java/com/cburch/logisim/circuit/Simulator.java index ef5b425..d04dbe5 100644 --- a/src/main/java/com/cburch/logisim/circuit/Simulator.java +++ b/src/main/java/com/cburch/logisim/circuit/Simulator.java @@ -8,7 +8,7 @@ import java.util.ArrayList; public class Simulator { - // begin DEBUGGING +// begin DEBUGGING // private static PrintWriter debugLog; // // static { @@ -26,15 +26,15 @@ public class Simulator { // public static void flushLog() { // debugLog.flush(); // } - //end DEBUGGING*/ +//end DEBUGGING + private final PropagationManager manager; + private final SimulatorTicker ticker; + private final ArrayList listeners = new ArrayList<>(); private boolean isRunning = true; private boolean isTicking = false; - private final PropagationManager manager; private boolean isExceptionEncountered = false; private double tickFrequency; - private SimulatorTicker ticker; - private ArrayList listeners = new ArrayList<>(); public Simulator() { manager = new PropagationManager(); @@ -182,11 +182,11 @@ private void fireSimulatorStateChanged() { class PropagationManager extends Thread { + private final PropagationPoints stepPoints = new PropagationPoints(); // These variables apply only if PRINT_TICK_RATE is set int tickRateTicks = 0; long tickRateStart = System.currentTimeMillis(); private Propagator propagator = null; - private PropagationPoints stepPoints = new PropagationPoints(); private volatile int ticksRequested = 0; private volatile int stepsRequested = 0; private volatile boolean isResetRequested = false; @@ -232,8 +232,8 @@ public void run() { while (!complete) { synchronized (this) { while (!complete && !propagateRequested - && !isResetRequested && ticksRequested == 0 - && stepsRequested == 0) { + && !isResetRequested && ticksRequested == 0 + && stepsRequested == 0) { try { wait(); } catch (InterruptedException e) { diff --git a/src/main/java/com/cburch/logisim/circuit/SimulatorEvent.java b/src/main/java/com/cburch/logisim/circuit/SimulatorEvent.java index 115b849..2547be8 100644 --- a/src/main/java/com/cburch/logisim/circuit/SimulatorEvent.java +++ b/src/main/java/com/cburch/logisim/circuit/SimulatorEvent.java @@ -5,7 +5,7 @@ public class SimulatorEvent { - private Simulator source; + private final Simulator source; public SimulatorEvent(Simulator source) { this.source = source; diff --git a/src/main/java/com/cburch/logisim/circuit/SimulatorTicker.java b/src/main/java/com/cburch/logisim/circuit/SimulatorTicker.java index c4ff41a..0dc77a8 100644 --- a/src/main/java/com/cburch/logisim/circuit/SimulatorTicker.java +++ b/src/main/java/com/cburch/logisim/circuit/SimulatorTicker.java @@ -5,7 +5,7 @@ class SimulatorTicker extends Thread { - private Simulator.PropagationManager manager; + private final Simulator.PropagationManager manager; private int ticksPerTickPhase; private int millisPerTickPhase; @@ -57,7 +57,7 @@ public void run() { millis = millisPerTickPhase; ticks = ticksPerTickPhase; while (!curShouldTick && ticksPending == 0 - && !complete) { + && !complete) { wait(); curShouldTick = shouldTick; millis = millisPerTickPhase; @@ -65,6 +65,7 @@ public void run() { } } } catch (InterruptedException e) { + e.printStackTrace(); } if (complete) { @@ -107,6 +108,7 @@ public void run() { } Thread.sleep(wait); } catch (InterruptedException e) { + e.printStackTrace(); } } } diff --git a/src/main/java/com/cburch/logisim/circuit/Splitter.java b/src/main/java/com/cburch/logisim/circuit/Splitter.java index a13a4d2..07d214d 100644 --- a/src/main/java/com/cburch/logisim/circuit/Splitter.java +++ b/src/main/java/com/cburch/logisim/circuit/Splitter.java @@ -25,7 +25,7 @@ import javax.swing.JPopupMenu; public class Splitter extends ManagedComponent - implements WireRepair, ToolTipMaker, MenuExtender, AttributeListener { + implements WireRepair, ToolTipMaker, MenuExtender, AttributeListener { // basic data byte[] bit_thread; // how each bit maps to thread within end @@ -46,7 +46,7 @@ private static void appendBuf(StringBuilder buf, int start, int end) { if (start == end) { buf.append(start); } else { - buf.append(start + "-" + end); + buf.append(start).append("-").append(end); } } @@ -70,10 +70,10 @@ public boolean contains(Location loc) { Direction facing = getAttributeSet().getValue(StdAttr.FACING); if (facing == Direction.EAST || facing == Direction.WEST) { return Math.abs(loc.getX() - myLoc.getX()) > 5 - || loc.manhattanDistanceTo(myLoc) <= 5; + || loc.manhattanDistanceTo(myLoc) <= 5; } else { return Math.abs(loc.getY() - myLoc.getY()) > 5 - || loc.manhattanDistanceTo(myLoc) <= 5; + || loc.manhattanDistanceTo(myLoc) <= 5; } } else { return false; @@ -82,7 +82,7 @@ public boolean contains(Location loc) { private synchronized void configureComponent() { SplitterAttributes attrs = (SplitterAttributes) getAttributeSet(); - SplitterParameters parms = attrs.getParameters(); + SplitterParameters parameters = attrs.getParameters(); int fanout = attrs.fanout; byte[] bit_end = attrs.bit_end; @@ -102,16 +102,16 @@ private synchronized void configureComponent() { // compute end positions Location origin = getLocation(); - int x = origin.getX() + parms.getEnd0X(); - int y = origin.getY() + parms.getEnd0Y(); - int dx = parms.getEndToEndDeltaX(); - int dy = parms.getEndToEndDeltaY(); + int x = origin.getX() + parameters.getEnd0X(); + int y = origin.getY() + parameters.getEnd0Y(); + int dx = parameters.getEndToEndDeltaX(); + int dy = parameters.getEndToEndDeltaY(); EndData[] ends = new EndData[fanout + 1]; ends[0] = new EndData(origin, BitWidth.create(bit_end.length), EndData.INPUT_OUTPUT); for (int i = 0; i < fanout; i++) { ends[i + 1] = new EndData(Location.create(x, y), - BitWidth.create(end_width[i + 1]), EndData.INPUT_OUTPUT); + BitWidth.create(end_width[i + 1]), EndData.INPUT_OUTPUT); x += dx; y += dy; } @@ -223,4 +223,4 @@ public void attributeListChanged(AttributeEvent e) { public void attributeValueChanged(AttributeEvent e) { configureComponent(); } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/circuit/SplitterAttributes.java b/src/main/java/com/cburch/logisim/circuit/SplitterAttributes.java index 238b89c..52a5e71 100644 --- a/src/main/java/com/cburch/logisim/circuit/SplitterAttributes.java +++ b/src/main/java/com/cburch/logisim/circuit/SplitterAttributes.java @@ -10,9 +10,11 @@ import com.cburch.logisim.data.BitWidth; import com.cburch.logisim.data.Direction; import com.cburch.logisim.instance.StdAttr; +import java.awt.Component; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.swing.JComboBox; class SplitterAttributes extends AbstractAttributeSet { @@ -336,9 +338,9 @@ public String toStandardString(Integer value) { } @Override - public java.awt.Component getCellEditor(Integer value) { + public Component getCellEditor(Integer value) { int index = value; - javax.swing.JComboBox combo = new javax.swing.JComboBox(options); + JComboBox combo = new JComboBox<>(options); combo.setSelectedIndex(index); return combo; } diff --git a/src/main/java/com/cburch/logisim/circuit/SplitterDistributeItem.java b/src/main/java/com/cburch/logisim/circuit/SplitterDistributeItem.java index f86b00b..307f142 100644 --- a/src/main/java/com/cburch/logisim/circuit/SplitterDistributeItem.java +++ b/src/main/java/com/cburch/logisim/circuit/SplitterDistributeItem.java @@ -11,9 +11,9 @@ class SplitterDistributeItem extends JMenuItem implements ActionListener { - private Project proj; - private Splitter splitter; - private int order; + private final Project proj; + private final Splitter splitter; + private final int order; public SplitterDistributeItem(Project proj, Splitter splitter, int order) { this.proj = proj; @@ -24,11 +24,12 @@ public SplitterDistributeItem(Project proj, Splitter splitter, int order) { SplitterAttributes attrs = (SplitterAttributes) splitter.getAttributeSet(); byte[] actual = attrs.bit_end; byte[] desired = SplitterAttributes.computeDistribution(attrs.fanout, - actual.length, order); + actual.length, order); boolean same = actual.length == desired.length; for (int i = 0; same && i < desired.length; i++) { if (actual[i] != desired[i]) { same = false; + break; } } setEnabled(!same); @@ -46,15 +47,13 @@ private StringGetter toGetter() { public void actionPerformed(ActionEvent e) { SplitterAttributes attrs = (SplitterAttributes) splitter.getAttributeSet(); byte[] actual = attrs.bit_end; - byte[] desired = SplitterAttributes.computeDistribution(attrs.fanout, - actual.length, order); - CircuitMutation xn = new CircuitMutation(proj.getCircuitState().getCircuit()); + byte[] desired = SplitterAttributes.computeDistribution(attrs.fanout, actual.length, order); + CircuitMutation mutation = new CircuitMutation(proj.getCircuitState().getCircuit()); for (int i = 0, n = Math.min(actual.length, desired.length); i < n; i++) { if (actual[i] != desired[i]) { - xn.set(splitter, attrs.getBitOutAttribute(i), - (int) desired[i]); + mutation.set(splitter, attrs.getBitOutAttribute(i), (int) desired[i]); } } - proj.doAction(xn.toAction(toGetter())); + proj.doAction(mutation.toAction(toGetter())); } } diff --git a/src/main/java/com/cburch/logisim/circuit/SplitterFactory.java b/src/main/java/com/cburch/logisim/circuit/SplitterFactory.java index f976718..7447cc0 100644 --- a/src/main/java/com/cburch/logisim/circuit/SplitterFactory.java +++ b/src/main/java/com/cburch/logisim/circuit/SplitterFactory.java @@ -80,7 +80,7 @@ public Bounds getOffsetBounds(AttributeSet attributes) { Bounds bds = Bounds.create(0, 0, 1, 1); bds = bds.add(xEnd0, yEnd0); bds = bds.add(xEnd0 + (fanout - 1) * parms.getEndToEndDeltaX(), - yEnd0 + (fanout - 1) * parms.getEndToEndDeltaY()); + yEnd0 + (fanout - 1) * parms.getEndToEndDeltaY()); return bds; } @@ -89,7 +89,7 @@ public Bounds getOffsetBounds(AttributeSet attributes) { // @Override public void drawGhost(ComponentDrawContext context, - Color color, int x, int y, AttributeSet attributes) { + Color color, int x, int y, AttributeSet attributes) { SplitterAttributes attrs = (SplitterAttributes) attributes; context.getGraphics().setColor(color); Location loc = Location.create(x, y); @@ -102,7 +102,7 @@ public void drawGhost(ComponentDrawContext context, @Override public void paintIcon(ComponentDrawContext c, - int x, int y, AttributeSet attributes) { + int x, int y, AttributeSet attributes) { Graphics g = c.getGraphics(); if (toolIcon != null) { toolIcon.paintIcon(c.getDestination(), g, x + 2, y + 2); @@ -115,12 +115,12 @@ public Object getFeature(Object key, AttributeSet attributeSet) { return StdAttr.FACING; } else if (key == KeyConfigurator.class) { KeyConfigurator altConfig = ParallelConfigurator.create( - new BitWidthConfigurator(SplitterAttributes.ATTR_WIDTH), - new IntegerConfigurator(SplitterAttributes.ATTR_FANOUT, - 1, 32, InputEvent.ALT_DOWN_MASK)); + new BitWidthConfigurator(SplitterAttributes.ATTR_WIDTH), + new IntegerConfigurator(SplitterAttributes.ATTR_FANOUT, + 1, 32, InputEvent.ALT_DOWN_MASK)); return JoinedConfigurator.create( - new IntegerConfigurator(SplitterAttributes.ATTR_FANOUT, 1, 32, 0), - altConfig); + new IntegerConfigurator(SplitterAttributes.ATTR_FANOUT, 1, 32, 0), + altConfig); } return super.getFeature(key, attributeSet); } diff --git a/src/main/java/com/cburch/logisim/circuit/SplitterPainter.java b/src/main/java/com/cburch/logisim/circuit/SplitterPainter.java index 5089375..17a20e3 100644 --- a/src/main/java/com/cburch/logisim/circuit/SplitterPainter.java +++ b/src/main/java/com/cburch/logisim/circuit/SplitterPainter.java @@ -19,7 +19,7 @@ class SplitterPainter { private static final int SPINE_DOT = Wire.WIDTH + 4; static void drawLines(ComponentDrawContext context, - SplitterAttributes attrs, Location origin) { + SplitterAttributes attrs, Location origin) { boolean showState = context.getShowState(); CircuitState state = showState ? context.getCircuitState() : null; if (state == null) { @@ -93,7 +93,7 @@ static void drawLines(ComponentDrawContext context, } static void drawLabels(ComponentDrawContext context, - SplitterAttributes attrs, Location origin) { + SplitterAttributes attrs, Location origin) { // compute labels String[] ends = new String[attrs.fanout + 1]; int curEnd = -1; @@ -159,7 +159,7 @@ static void drawLabels(ComponentDrawContext context, } static void drawLegacy(ComponentDrawContext context, SplitterAttributes attrs, - Location origin) { + Location origin) { Graphics g = context.getGraphics(); CircuitState state = context.getCircuitState(); Direction facing = attrs.facing; @@ -195,7 +195,7 @@ static void drawLegacy(ComponentDrawContext context, SplitterAttributes attrs, } else { g.setColor(Color.BLACK); g.fillOval(x0 - SPINE_DOT / 2, ySpine - SPINE_DOT / 2, - SPINE_DOT, SPINE_DOT); + SPINE_DOT, SPINE_DOT); } } else { int xSpine = (x0 + x1) / 2; @@ -219,9 +219,9 @@ static void drawLegacy(ComponentDrawContext context, SplitterAttributes attrs, } else { g.setColor(Color.BLACK); g.fillOval(xSpine - SPINE_DOT / 2, y0 - SPINE_DOT / 2, - SPINE_DOT, SPINE_DOT); + SPINE_DOT, SPINE_DOT); } } GraphicsUtil.switchToWidth(g, 1); } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/circuit/SplitterParameters.java b/src/main/java/com/cburch/logisim/circuit/SplitterParameters.java index 308b447..9c31d57 100644 --- a/src/main/java/com/cburch/logisim/circuit/SplitterParameters.java +++ b/src/main/java/com/cburch/logisim/circuit/SplitterParameters.java @@ -8,19 +8,19 @@ class SplitterParameters { - private int dxEnd0; // location of split end 0 relative to origin - private int dyEnd0; - private int ddxEnd; // distance from split end i to split end (i + 1) - private int ddyEnd; - private int dxEndSpine; // distance from split end to spine - private int dyEndSpine; - private int dxSpine0; // distance from origin to far end of spine - private int dySpine0; - private int dxSpine1; // distance from origin to near end of spine - private int dySpine1; - private int textAngle; // angle to rotate text - private int halign; // justification of text - private int valign; + private final int dxEnd0; // location of split end 0 relative to origin + private final int dyEnd0; + private final int ddxEnd; // distance from split end i to split end (i + 1) + private final int ddyEnd; + private final int dxEndSpine; // distance from split end to spine + private final int dyEndSpine; + private final int dxSpine0; // distance from origin to far end of spine + private final int dySpine0; + private final int dxSpine1; // distance from origin to near end of spine + private final int dySpine1; + private final int textAngle; // angle to rotate text + private final int hAlign; // justification of text + private final int vAlign; SplitterParameters(SplitterAttributes attrs) { @@ -52,8 +52,8 @@ class SplitterParameters { dxSpine1 = m * justify * offs; dySpine1 = -m * offs; textAngle = 90; - halign = m > 0 ? GraphicsUtil.H_RIGHT : GraphicsUtil.H_LEFT; - valign = m * justify <= 0 ? GraphicsUtil.V_BASELINE : GraphicsUtil.V_TOP; + hAlign = m > 0 ? GraphicsUtil.H_RIGHT : GraphicsUtil.H_LEFT; + vAlign = m * justify <= 0 ? GraphicsUtil.V_BASELINE : GraphicsUtil.V_TOP; } else { // > or < int m = facing == Direction.WEST ? -1 : 1; dxEnd0 = m * width; @@ -67,8 +67,8 @@ class SplitterParameters { dxSpine1 = m * offs; dySpine1 = m * justify * offs; textAngle = 0; - halign = m > 0 ? GraphicsUtil.H_LEFT : GraphicsUtil.H_RIGHT; - valign = m * justify < 0 ? GraphicsUtil.V_TOP : GraphicsUtil.V_BASELINE; + hAlign = m > 0 ? GraphicsUtil.H_LEFT : GraphicsUtil.H_RIGHT; + vAlign = m * justify < 0 ? GraphicsUtil.V_TOP : GraphicsUtil.V_BASELINE; } } @@ -117,10 +117,10 @@ public int getTextAngle() { } public int getTextHorzAlign() { - return halign; + return hAlign; } public int getTextVertAlign() { - return valign; + return vAlign; } } diff --git a/src/main/java/com/cburch/logisim/circuit/Strings.java b/src/main/java/com/cburch/logisim/circuit/Strings.java index e168b2d..c1c3bcf 100644 --- a/src/main/java/com/cburch/logisim/circuit/Strings.java +++ b/src/main/java/com/cburch/logisim/circuit/Strings.java @@ -9,8 +9,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "circuit"); + private static final LocaleManager source = new LocaleManager("logisim", "circuit"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/circuit/SubcircuitFactory.java b/src/main/java/com/cburch/logisim/circuit/SubcircuitFactory.java index 467f764..d9750b0 100644 --- a/src/main/java/com/cburch/logisim/circuit/SubcircuitFactory.java +++ b/src/main/java/com/cburch/logisim/circuit/SubcircuitFactory.java @@ -38,7 +38,7 @@ public class SubcircuitFactory extends InstanceFactory { - private Circuit source; + private final Circuit source; public SubcircuitFactory(Circuit source) { super("", null); @@ -257,7 +257,7 @@ private void paintBase(InstancePainter painter, Graphics g) { } private void drawCircuitLabel(InstancePainter painter, Bounds bds, - Direction facing, Direction defaultFacing) { + Direction facing, Direction defaultFacing) { AttributeSet staticAttrs = source.getStaticAttributes(); String label = staticAttrs.getValue(CircuitAttributes.CIRCUIT_LABEL_ATTR); if (label != null && !label.equals("")) { @@ -298,7 +298,7 @@ private void drawCircuitLabel(InstancePainter painter, Bounds bds, if (c == 'n') { String line = label.substring(0, back); GraphicsUtil.drawText(g, line, x, y, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); y += height; label = label.substring(back + 2); back = label.indexOf('\\'); @@ -310,7 +310,7 @@ private void drawCircuitLabel(InstancePainter painter, Bounds bds, } } GraphicsUtil.drawText(g, label, x, y, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); } g.dispose(); } @@ -318,7 +318,7 @@ private void drawCircuitLabel(InstancePainter painter, Bounds bds, private class CircuitFeature implements StringGetter, MenuExtender, ActionListener { - private Instance instance; + private final Instance instance; private Project proj; public CircuitFeature(Instance instance) { diff --git a/src/main/java/com/cburch/logisim/circuit/SubcircuitPoker.java b/src/main/java/com/cburch/logisim/circuit/SubcircuitPoker.java index fe6302e..0a2e057 100644 --- a/src/main/java/com/cburch/logisim/circuit/SubcircuitPoker.java +++ b/src/main/java/com/cburch/logisim/circuit/SubcircuitPoker.java @@ -30,7 +30,7 @@ public Bounds getBounds(InstancePainter painter) { @Override public void paint(InstancePainter painter) { if (painter.getDestination() instanceof Canvas - && painter.getData() instanceof CircuitState) { + && painter.getData() instanceof CircuitState) { Bounds bds = painter.getInstance().getBounds(); int cx = bds.getX() + bds.getWidth() / 2; int cy = bds.getY() + bds.getHeight() / 2; @@ -66,7 +66,7 @@ public void mouseReleased(InstanceState state, MouseEvent e) { mouseDown = false; Object sub = state.getData(); if (e.getClickCount() == 2 && isWithin(state, e) - && sub instanceof CircuitState) { + && sub instanceof CircuitState) { state.getProject().setCircuitState((CircuitState) sub); } else { state.getInstance().fireInvalidated(); diff --git a/src/main/java/com/cburch/logisim/circuit/WidthIncompatibilityData.java b/src/main/java/com/cburch/logisim/circuit/WidthIncompatibilityData.java index 0acf563..4975080 100644 --- a/src/main/java/com/cburch/logisim/circuit/WidthIncompatibilityData.java +++ b/src/main/java/com/cburch/logisim/circuit/WidthIncompatibilityData.java @@ -9,8 +9,8 @@ public class WidthIncompatibilityData { - private ArrayList points; - private ArrayList widths; + private final ArrayList points; + private final ArrayList widths; public WidthIncompatibilityData() { points = new ArrayList<>(); diff --git a/src/main/java/com/cburch/logisim/circuit/Wire.java b/src/main/java/com/cburch/logisim/circuit/Wire.java index b5056b2..a9267de 100644 --- a/src/main/java/com/cburch/logisim/circuit/Wire.java +++ b/src/main/java/com/cburch/logisim/circuit/Wire.java @@ -33,14 +33,14 @@ public final class Wire implements Component, AttributeSet, CustomHandles, Itera public static final int WIDTH = 3; public static final AttributeOption VALUE_HORIZONTAL - = new AttributeOption("horz", Strings.getter("wireDirectionHorzOption")); + = new AttributeOption("horz", Strings.getter("wireDirectionHorzOption")); public static final AttributeOption VALUE_VERTICAL - = new AttributeOption("vert", Strings.getter("wireDirectionVertOption")); + = new AttributeOption("vert", Strings.getter("wireDirectionVertOption")); public static final Attribute DIRECTION_ATTRIBUTE - = Attributes.forOption("direction", Strings.getter("wireDirectionAttr"), - new AttributeOption[]{VALUE_HORIZONTAL, VALUE_VERTICAL}); + = Attributes.forOption("direction", Strings.getter("wireDirectionAttr"), + new AttributeOption[]{VALUE_HORIZONTAL, VALUE_VERTICAL}); public static final Attribute LENGTH_ATTRIBUTE - = Attributes.forInteger("length", Strings.getter("wireLengthAttr")); + = Attributes.forInteger("length", Strings.getter("wireLengthAttr")); private static final List> ATTRIBUTES = Arrays.asList(DIRECTION_ATTRIBUTE, LENGTH_ATTRIBUTE); private static final Cache cache = new Cache(); @@ -123,7 +123,7 @@ public Bounds getBounds() { int x0 = start.getX(); int y0 = start.getY(); return Bounds.create(x0 - 2, y0 - 2, - end.getX() - x0 + 5, end.getY() - y0 + 5); + end.getX() - x0 + 5, end.getY() - y0 + 5); } public Bounds getBounds(Graphics g) { @@ -136,11 +136,11 @@ public boolean contains(Location q) { if (isXEqual) { int wx = start.getX(); return qx >= wx - 2 && qx <= wx + 2 - && start.getY() <= qy && qy <= end.getY(); + && start.getY() <= qy && qy <= end.getY(); } else { int wy = start.getY(); return qy >= wy - 2 && qy <= wy + 2 - && start.getX() <= qx && qx <= end.getX(); + && start.getX() <= qx && qx <= end.getX(); } } @@ -158,7 +158,7 @@ public List getEnds() { public EndData getEnd(int index) { Location loc = getEndLocation(index); return new EndData(loc, BitWidth.UNKNOWN, - EndData.INPUT_OUTPUT); + EndData.INPUT_OUTPUT); } public boolean endsAt(Location pt) { @@ -180,7 +180,7 @@ public void expose(ComponentDrawContext context) { int x0 = start.getX(); int y0 = start.getY(); dest.repaint(x0 - 5, y0 - 5, - end.getX() - x0 + 10, end.getY() - y0 + 10); + end.getX() - x0 + 10, end.getY() - y0 + 10); } public void draw(ComponentDrawContext context) { @@ -190,7 +190,7 @@ public void draw(ComponentDrawContext context) { GraphicsUtil.switchToWidth(g, WIDTH); g.setColor(state.getValue(start).getColor()); g.drawLine(start.getX(), start.getY(), - end.getX(), end.getY()); + end.getX(), end.getY()); } public Object getFeature(Object key) { @@ -286,7 +286,7 @@ public Location getOtherEnd(Location loc) { public boolean sharesEnd(Wire other) { return this.start.equals(other.start) || this.end.equals(other.start) - || this.start.equals(other.end) || this.end.equals(other.end); + || this.start.equals(other.end) || this.end.equals(other.end); } public boolean overlaps(Wire other, boolean includeEnds) { diff --git a/src/main/java/com/cburch/logisim/circuit/WireFactory.java b/src/main/java/com/cburch/logisim/circuit/WireFactory.java index 5e10145..9891a56 100644 --- a/src/main/java/com/cburch/logisim/circuit/WireFactory.java +++ b/src/main/java/com/cburch/logisim/circuit/WireFactory.java @@ -65,7 +65,7 @@ public Bounds getOffsetBounds(AttributeSet attributes) { // @Override public void drawGhost(ComponentDrawContext context, - Color color, int x, int y, AttributeSet attributes) { + Color color, int x, int y, AttributeSet attributes) { Graphics g = context.getGraphics(); Object dir = attributes.getValue(Wire.DIRECTION_ATTRIBUTE); int len = attributes.getValue(Wire.LENGTH_ATTRIBUTE); diff --git a/src/main/java/com/cburch/logisim/circuit/WireIterator.java b/src/main/java/com/cburch/logisim/circuit/WireIterator.java index 8f25dc1..fb63a35 100644 --- a/src/main/java/com/cburch/logisim/circuit/WireIterator.java +++ b/src/main/java/com/cburch/logisim/circuit/WireIterator.java @@ -8,12 +8,12 @@ class WireIterator implements Iterator { + private final int deltaX; + private final int deltaY; private int curX; private int curY; private int destX; private int destY; - private int deltaX; - private int deltaY; private boolean destReturned; public WireIterator(Location e0, Location e1) { diff --git a/src/main/java/com/cburch/logisim/circuit/WireRepair.java b/src/main/java/com/cburch/logisim/circuit/WireRepair.java index 67dbecd..2c31fa8 100644 --- a/src/main/java/com/cburch/logisim/circuit/WireRepair.java +++ b/src/main/java/com/cburch/logisim/circuit/WireRepair.java @@ -17,7 +17,7 @@ class WireRepair extends CircuitTransaction { - private Circuit circuit; + private final Circuit circuit; public WireRepair(Circuit circuit) { this.circuit = circuit; @@ -132,7 +132,7 @@ private void doOverlaps(CircuitMutator mutator) { } private void doMergeSet(ArrayList mergeSet, ReplacementMap replacements, - Set splitLocs) { + Set splitLocs) { TreeSet ends = new TreeSet<>(); for (Wire w : mergeSet) { ends.add(w.getEnd0()); diff --git a/src/main/java/com/cburch/logisim/circuit/WireSet.java b/src/main/java/com/cburch/logisim/circuit/WireSet.java index 7103e74..5afadd6 100644 --- a/src/main/java/com/cburch/logisim/circuit/WireSet.java +++ b/src/main/java/com/cburch/logisim/circuit/WireSet.java @@ -13,8 +13,8 @@ public class WireSet { private static final Set NULL_WIRES = Collections.emptySet(); public static final WireSet EMPTY = new WireSet(NULL_WIRES); - private Set wires; - private Set points; + private final Set wires; + private final Set points; WireSet(Set wires) { if (wires.isEmpty()) { diff --git a/src/main/java/com/cburch/logisim/circuit/WireThread.java b/src/main/java/com/cburch/logisim/circuit/WireThread.java index 6a5d3d9..7694849 100644 --- a/src/main/java/com/cburch/logisim/circuit/WireThread.java +++ b/src/main/java/com/cburch/logisim/circuit/WireThread.java @@ -8,8 +8,7 @@ class WireThread { private WireThread parent; - private SmallSet bundles - = new SmallSet<>(); + private final SmallSet bundles = new SmallSet<>(); WireThread() { parent = this; diff --git a/src/main/java/com/cburch/logisim/circuit/WireUtil.java b/src/main/java/com/cburch/logisim/circuit/WireUtil.java index e51d148..b0d3260 100644 --- a/src/main/java/com/cburch/logisim/circuit/WireUtil.java +++ b/src/main/java/com/cburch/logisim/circuit/WireUtil.java @@ -16,8 +16,8 @@ private WireUtil() { static CircuitPoints computeCircuitPoints(Collection components) { CircuitPoints points = new CircuitPoints(); - for (Component comp : components) { - points.add(comp); + for (Component component : components) { + points.add(component); } return points; } @@ -28,12 +28,12 @@ public static Collection mergeExclusive(Collection ret = new HashSet<>(toMerge); + HashSet components = new HashSet<>(toMerge); CircuitPoints points = computeCircuitPoints(toMerge); HashSet wires = new HashSet<>(); - for (Location loc : points.getSplitLocations()) { - Collection at = points.getComponents(loc); + for (Location location : points.getSplitLocations()) { + Collection at = points.getComponents(location); if (at.size() == 2) { Iterator atIt = at.iterator(); Component o0 = atIt.next(); @@ -50,7 +50,7 @@ public static Collection mergeExclusive(Collection it = wires.iterator(); Wire w = it.next(); @@ -73,9 +73,9 @@ public static Collection mergeExclusive(Collection FACING - = Attributes.forDirection("facing", Strings.getter("appearanceFacingAttr")); - static final List> ATTRIBUTES - = UnmodifiableList.create(new Attribute[]{FACING}); + = Attributes.forDirection("facing", Strings.getter("appearanceFacingAttr")); + static final List> ATTRIBUTES = UnmodifiableList.create(new Attribute[]{FACING}); private static final int RADIUS = 3; private static final int INDICATOR_LENGTH = 8; @@ -125,10 +124,10 @@ public boolean contains(Location location, boolean assumeFilled) { Location end = center.translate(facing, RADIUS + INDICATOR_LENGTH); if (facing == Direction.EAST || facing == Direction.WEST) { return Math.abs(location.getY() - center.getY()) < 2 - && (location.getX() < center.getX()) != (location.getX() < end.getX()); + && (location.getX() < center.getX()) != (location.getX() < end.getX()); } else { return Math.abs(location.getX() - center.getX()) < 2 - && (location.getY() < center.getY()) != (location.getY() < end.getY()); + && (location.getY() < center.getY()) != (location.getY() < end.getY()); } } } @@ -138,6 +137,6 @@ public List getHandles(HandleGesture gesture) { Location c = getLocation(); Location end = c.translate(facing, RADIUS + INDICATOR_LENGTH); return UnmodifiableList.create(new Handle[]{new Handle(this, c), - new Handle(this, end)}); + new Handle(this, end)}); } } diff --git a/src/main/java/com/cburch/logisim/circuit/appear/AppearanceElement.java b/src/main/java/com/cburch/logisim/circuit/appear/AppearanceElement.java index 5357e3c..3594e09 100644 --- a/src/main/java/com/cburch/logisim/circuit/appear/AppearanceElement.java +++ b/src/main/java/com/cburch/logisim/circuit/appear/AppearanceElement.java @@ -77,6 +77,6 @@ public Location getRandomPoint(Bounds bounds, Random random) { protected Bounds getBounds(int radius) { return Bounds.create(location.getX() - radius, location.getY() - radius, - 2 * radius, 2 * radius); + 2 * radius, 2 * radius); } } diff --git a/src/main/java/com/cburch/logisim/circuit/appear/AppearancePort.java b/src/main/java/com/cburch/logisim/circuit/appear/AppearancePort.java index b59c927..782ad4d 100644 --- a/src/main/java/com/cburch/logisim/circuit/appear/AppearancePort.java +++ b/src/main/java/com/cburch/logisim/circuit/appear/AppearancePort.java @@ -98,10 +98,10 @@ public List getHandles(HandleGesture gesture) { int r = isInput() ? INPUT_RADIUS : OUTPUT_RADIUS; return UnmodifiableList.create(new Handle[]{ - new Handle(this, loc.translate(-r, -r)), - new Handle(this, loc.translate(r, -r)), - new Handle(this, loc.translate(r, r)), - new Handle(this, loc.translate(-r, r))}); + new Handle(this, loc.translate(-r, -r)), + new Handle(this, loc.translate(r, -r)), + new Handle(this, loc.translate(r, r)), + new Handle(this, loc.translate(-r, r))}); } @Override diff --git a/src/main/java/com/cburch/logisim/circuit/appear/AppearanceSvgReader.java b/src/main/java/com/cburch/logisim/circuit/appear/AppearanceSvgReader.java index 8cd62af..c35f998 100644 --- a/src/main/java/com/cburch/logisim/circuit/appear/AppearanceSvgReader.java +++ b/src/main/java/com/cburch/logisim/circuit/appear/AppearanceSvgReader.java @@ -13,29 +13,29 @@ public class AppearanceSvgReader { - public static AbstractCanvasObject createShape(Element elt, Map pins) { - String name = elt.getTagName(); + public static AbstractCanvasObject createShape(Element element, Map pins) { + String name = element.getTagName(); if (name.equals("circ-anchor") || name.equals("circ-origin")) { - Location loc = getLocation(elt); - AbstractCanvasObject ret = new AppearanceAnchor(loc); - if (elt.hasAttribute("facing")) { - Direction facing = Direction.parse(elt.getAttribute("facing")); - ret.setValue(AppearanceAnchor.FACING, facing); + Location location = getLocation(element); + AbstractCanvasObject canvasObject = new AppearanceAnchor(location); + if (element.hasAttribute("facing")) { + Direction facing = Direction.parse(element.getAttribute("facing")); + canvasObject.setValue(AppearanceAnchor.FACING, facing); } - return ret; + return canvasObject; } else if (name.equals("circ-port")) { - Location loc = getLocation(elt); - String[] pinStr = elt.getAttribute("pin").split(","); - Location pinLoc = Location.create(Integer.parseInt(pinStr[0].trim()), - Integer.parseInt(pinStr[1].trim())); - Instance pin = pins.get(pinLoc); + Location location = getLocation(element); + String[] pinString = element.getAttribute("pin").split(","); + Location pinLocation = Location + .create(Integer.parseInt(pinString[0].trim()), Integer.parseInt(pinString[1].trim())); + Instance pin = pins.get(pinLocation); if (pin == null) { return null; } else { - return new AppearancePort(loc, pin); + return new AppearancePort(location, pin); } } else { - return SvgReader.createShape(elt); + return SvgReader.createShape(element); } } diff --git a/src/main/java/com/cburch/logisim/circuit/appear/CircuitAppearance.java b/src/main/java/com/cburch/logisim/circuit/appear/CircuitAppearance.java index 521d400..a3a47fe 100644 --- a/src/main/java/com/cburch/logisim/circuit/appear/CircuitAppearance.java +++ b/src/main/java/com/cburch/logisim/circuit/appear/CircuitAppearance.java @@ -24,9 +24,9 @@ public class CircuitAppearance extends Drawing { - private Circuit circuit; - private EventSourceWeakSupport listeners; - private CircuitPins circuitPins; + private final Circuit circuit; + private final EventSourceWeakSupport listeners; + private final CircuitPins circuitPins; private boolean isDefault; private boolean suppressRecompute; diff --git a/src/main/java/com/cburch/logisim/circuit/appear/CircuitAppearanceEvent.java b/src/main/java/com/cburch/logisim/circuit/appear/CircuitAppearanceEvent.java index 8aa3a51..92f7378 100644 --- a/src/main/java/com/cburch/logisim/circuit/appear/CircuitAppearanceEvent.java +++ b/src/main/java/com/cburch/logisim/circuit/appear/CircuitAppearanceEvent.java @@ -12,8 +12,8 @@ public class CircuitAppearanceEvent { public static final int PORTS = 4; public static final int ALL_TYPES = 7; - private Circuit circuit; - private int affects; + private final Circuit circuit; + private final int affects; CircuitAppearanceEvent(Circuit circuit, int affects) { this.circuit = circuit; diff --git a/src/main/java/com/cburch/logisim/circuit/appear/CircuitPins.java b/src/main/java/com/cburch/logisim/circuit/appear/CircuitPins.java index 1f3be55..e0ba12b 100644 --- a/src/main/java/com/cburch/logisim/circuit/appear/CircuitPins.java +++ b/src/main/java/com/cburch/logisim/circuit/appear/CircuitPins.java @@ -22,9 +22,9 @@ public class CircuitPins { - private PortManager appearanceManager; - private MyComponentListener myComponentListener; - private Set pins; + private final PortManager appearanceManager; + private final MyComponentListener myComponentListener; + private final Set pins; CircuitPins(PortManager appearanceManager) { this.appearanceManager = appearanceManager; @@ -76,7 +76,7 @@ public Collection getPins() { } private class MyComponentListener - implements ComponentListener, AttributeListener { + implements ComponentListener, AttributeListener { public void endChanged(ComponentEvent e) { appearanceManager.updatePorts(); @@ -91,7 +91,7 @@ public void attributeListChanged(AttributeEvent e) { public void attributeValueChanged(AttributeEvent e) { Attribute attr = e.getAttribute(); if (attr == StdAttr.FACING || attr == StdAttr.LABEL - || attr == Pin.ATTR_TYPE) { + || attr == Pin.ATTR_TYPE) { appearanceManager.updatePorts(); } } diff --git a/src/main/java/com/cburch/logisim/circuit/appear/DefaultAppearance.java b/src/main/java/com/cburch/logisim/circuit/appear/DefaultAppearance.java index fcc8049..22420fe 100644 --- a/src/main/java/com/cburch/logisim/circuit/appear/DefaultAppearance.java +++ b/src/main/java/com/cburch/logisim/circuit/appear/DefaultAppearance.java @@ -106,13 +106,13 @@ public static List build(Collection pins) { ret.add(notch); ret.add(rect); placePins(ret, edge.get(Direction.WEST), - rx, ry + offsWest, 0, 10); + rx, ry + offsWest, 0, 10); placePins(ret, edge.get(Direction.EAST), - rx + width, ry + offsEast, 0, 10); + rx + width, ry + offsEast, 0, 10); placePins(ret, edge.get(Direction.NORTH), - rx + offsNorth, ry, 10, 0); + rx + offsNorth, ry, 10, 0); placePins(ret, edge.get(Direction.SOUTH), - rx + offsSouth, ry + height, 10, 0); + rx + offsSouth, ry + height, 10, 0); ret.add(new AppearanceAnchor(Location.create(rx + ax, ry + ay))); return ret; } @@ -145,7 +145,7 @@ private static int computeOffset(int numFacing, int numOpposite, int maxOthers) } private static void placePins(List dest, List pins, - int x, int y, int dx, int dy) { + int x, int y, int dx, int dy) { for (Instance pin : pins) { dest.add(new AppearancePort(Location.create(x, y), pin)); x += dx; @@ -155,7 +155,7 @@ private static void placePins(List dest, List pins, private static class CompareLocations implements Comparator { - private boolean byX; + private final boolean byX; CompareLocations(boolean byX) { this.byX = byX; diff --git a/src/main/java/com/cburch/logisim/circuit/appear/PortManager.java b/src/main/java/com/cburch/logisim/circuit/appear/PortManager.java index fdb1977..fa80d44 100644 --- a/src/main/java/com/cburch/logisim/circuit/appear/PortManager.java +++ b/src/main/java/com/cburch/logisim/circuit/appear/PortManager.java @@ -20,7 +20,7 @@ class PortManager { - private CircuitAppearance appearance; + private final CircuitAppearance appearance; private boolean doingUpdate; PortManager(CircuitAppearance appearance) { @@ -29,16 +29,16 @@ class PortManager { } private static Location computeDefaultLocation(CircuitAppearance appear, - Instance pin, Map others) { + Instance pin, Map others) { // Determine which locations are being used in canvas, and look for // which instances facing the same way in layout - Set usedLocs = new HashSet<>(); + Set usedLocations = new HashSet<>(); List sameWay = new ArrayList<>(); Direction facing = pin.getAttributeValue(StdAttr.FACING); for (Map.Entry entry : others.entrySet()) { Instance pin2 = entry.getKey(); - Location loc = entry.getValue().getLocation(); - usedLocs.add(loc); + Location location = entry.getValue().getLocation(); + usedLocations.add(location); if (pin2.getAttributeValue(StdAttr.FACING) == facing) { sameWay.add(pin2); } @@ -72,13 +72,13 @@ private static Location computeDefaultLocation(CircuitAppearance appear, Location loc = others.get(neighbor).getLocation(); do { loc = loc.translate(dx, dy); - } while (usedLocs.contains(loc)); + } while (usedLocations.contains(loc)); if (loc.getX() >= 0 && loc.getY() >= 0) { return loc; } do { loc = loc.translate(-dx, -dy); - } while (usedLocs.contains(loc)); + } while (usedLocations.contains(loc)); return loc; } @@ -108,7 +108,7 @@ private static Location computeDefaultLocation(CircuitAppearance appear, x = (x + 9) / 10 * 10; // round coordinates up to ensure they're on grid y = (y + 9) / 10 * 10; Location loc = Location.create(x, y); - while (usedLocs.contains(loc)) { + while (usedLocations.contains(loc)) { loc = loc.translate(dx, dy); } return loc; @@ -119,7 +119,7 @@ void updatePorts() { } void updatePorts(Set adds, Set removes, - Map replaces, Collection allPins) { + Map replaces, Collection allPins) { if (appearance.isDefaultAppearance()) { appearance.recomputePorts(); } else if (!doingUpdate) { @@ -135,7 +135,7 @@ void updatePorts(Set adds, Set removes, } private void performUpdate(Set adds, Set removes, - Map replaces, Collection allPins) { + Map replaces, Collection allPins) { // Find the current objects corresponding to pins Map oldObjects; oldObjects = new HashMap<>(); diff --git a/src/main/java/com/cburch/logisim/circuit/appear/Strings.java b/src/main/java/com/cburch/logisim/circuit/appear/Strings.java index 37094a5..a1d2832 100644 --- a/src/main/java/com/cburch/logisim/circuit/appear/Strings.java +++ b/src/main/java/com/cburch/logisim/circuit/appear/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "circuit"); + private static final LocaleManager source = new LocaleManager("logisim", "circuit"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/comp/ComponentDrawContext.java b/src/main/java/com/cburch/logisim/comp/ComponentDrawContext.java index 176e152..06e08cb 100644 --- a/src/main/java/com/cburch/logisim/comp/ComponentDrawContext.java +++ b/src/main/java/com/cburch/logisim/comp/ComponentDrawContext.java @@ -22,20 +22,20 @@ public class ComponentDrawContext { private static final int PIN_OFFS = 2; private static final int PIN_RAD = 4; - private java.awt.Component dest; - private Circuit circuit; - private CircuitState circuitState; - private Graphics base; + private final java.awt.Component dest; + private final Circuit circuit; + private final CircuitState circuitState; + private final Graphics base; + private final boolean printView; + private final InstancePainter instancePainter; private Graphics g; private boolean showState; private boolean showColor; - private boolean printView; private WireSet highlightedWires; - private InstancePainter instancePainter; public ComponentDrawContext(java.awt.Component dest, - Circuit circuit, CircuitState circuitState, - Graphics base, Graphics g, boolean printView) { + Circuit circuit, CircuitState circuitState, + Graphics base, Graphics g, boolean printView) { this.dest = dest; this.circuit = circuit; this.circuitState = circuitState; @@ -49,8 +49,8 @@ public ComponentDrawContext(java.awt.Component dest, } public ComponentDrawContext(java.awt.Component dest, - Circuit circuit, CircuitState circuitState, - Graphics base, Graphics g) { + Circuit circuit, CircuitState circuitState, + Graphics base, Graphics g) { this(dest, circuit, circuitState, base, g, false); } @@ -118,7 +118,7 @@ public void drawBounds(Component comp) { g.setColor(Color.BLACK); Bounds bds = comp.getBounds(); g.drawRect(bds.getX(), bds.getY(), - bds.getWidth(), bds.getHeight()); + bds.getWidth(), bds.getHeight()); GraphicsUtil.switchToWidth(g, 1); } @@ -129,11 +129,11 @@ public void drawRectangle(Component comp) { public void drawRectangle(Component comp, String label) { Bounds bds = comp.getBounds(g); drawRectangle(bds.getX(), bds.getY(), bds.getWidth(), - bds.getHeight(), label); + bds.getHeight(), label); } public void drawRectangle(int x, int y, - int width, int height, String label) { + int width, int height, String label) { GraphicsUtil.switchToWidth(g, 2); g.drawRect(x, y, width, height); if (label != null && !label.equals("")) { @@ -141,23 +141,23 @@ public void drawRectangle(int x, int y, int lwid = fm.stringWidth(label); if (height > 20) { // centered at top edge g.drawString(label, x + (width - lwid) / 2, - y + 2 + fm.getAscent()); + y + 2 + fm.getAscent()); } else { // centered overall g.drawString(label, x + (width - lwid) / 2, - y + (height + fm.getAscent()) / 2 - 1); + y + (height + fm.getAscent()) / 2 - 1); } } } public void drawRectangle(ComponentFactory source, int x, int y, - AttributeSet attrs, String label) { + AttributeSet attrs, String label) { Bounds bds = source.getOffsetBounds(attrs); drawRectangle(source, x + bds.getX(), y + bds.getY(), bds.getWidth(), - bds.getHeight(), label); + bds.getHeight(), label); } public void drawRectangle(ComponentFactory source, int x, int y, - int width, int height, String label) { + int width, int height, String label) { GraphicsUtil.switchToWidth(g, 2); g.drawRect(x + 1, y + 1, width - 1, height - 1); if (label != null && !label.equals("")) { @@ -165,10 +165,10 @@ public void drawRectangle(ComponentFactory source, int x, int y, int lwid = fm.stringWidth(label); if (height > 20) { // centered at top edge g.drawString(label, x + (width - lwid) / 2, - y + 2 + fm.getAscent()); + y + 2 + fm.getAscent()); } else { // centered overall g.drawString(label, x + (width - lwid) / 2, - y + (height + fm.getAscent()) / 2 - 1); + y + (height + fm.getAscent()) / 2 - 1); } } } @@ -179,7 +179,7 @@ public void drawDongle(int x, int y) { } public void drawPin(Component comp, int i, - String label, Direction dir) { + String label, Direction dir) { Color curColor = g.getColor(); if (i < 0 || i >= comp.getEnds().size()) { return; @@ -198,16 +198,16 @@ public void drawPin(Component comp, int i, g.setColor(curColor); if (dir == Direction.EAST) { GraphicsUtil.drawText(g, label, x + 3, y, - GraphicsUtil.H_LEFT, GraphicsUtil.V_CENTER); + GraphicsUtil.H_LEFT, GraphicsUtil.V_CENTER); } else if (dir == Direction.WEST) { GraphicsUtil.drawText(g, label, x - 3, y, - GraphicsUtil.H_RIGHT, GraphicsUtil.V_CENTER); + GraphicsUtil.H_RIGHT, GraphicsUtil.V_CENTER); } else if (dir == Direction.SOUTH) { GraphicsUtil.drawText(g, label, x, y - 3, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); } else if (dir == Direction.NORTH) { GraphicsUtil.drawText(g, label, x, y + 3, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); } } @@ -241,7 +241,7 @@ public void drawPins(Component comp) { } public void drawClock(Component comp, int i, - Direction dir) { + Direction dir) { Color curColor = g.getColor(); g.setColor(Color.BLACK); GraphicsUtil.switchToWidth(g, 2); diff --git a/src/main/java/com/cburch/logisim/comp/ComponentEvent.java b/src/main/java/com/cburch/logisim/comp/ComponentEvent.java index 55d17da..ea231a1 100644 --- a/src/main/java/com/cburch/logisim/comp/ComponentEvent.java +++ b/src/main/java/com/cburch/logisim/comp/ComponentEvent.java @@ -5,9 +5,9 @@ public class ComponentEvent { - private Component source; - private Object oldData; - private Object newData; + private final Component source; + private final Object oldData; + private final Object newData; public ComponentEvent(Component source) { this(source, null, null); diff --git a/src/main/java/com/cburch/logisim/comp/ComponentUserEvent.java b/src/main/java/com/cburch/logisim/comp/ComponentUserEvent.java index 565d6ee..48eb174 100644 --- a/src/main/java/com/cburch/logisim/comp/ComponentUserEvent.java +++ b/src/main/java/com/cburch/logisim/comp/ComponentUserEvent.java @@ -9,7 +9,7 @@ public class ComponentUserEvent { - private Canvas canvas; + private final Canvas canvas; private int x = 0; private int y = 0; diff --git a/src/main/java/com/cburch/logisim/comp/EndData.java b/src/main/java/com/cburch/logisim/comp/EndData.java index 7cb9c23..fe06365 100644 --- a/src/main/java/com/cburch/logisim/comp/EndData.java +++ b/src/main/java/com/cburch/logisim/comp/EndData.java @@ -12,15 +12,15 @@ public class EndData { public static final int OUTPUT_ONLY = 2; public static final int INPUT_OUTPUT = 3; - private Location loc; - private BitWidth width; - private int i_o; - private boolean exclusive; + private final Location loc; + private final BitWidth width; + private final int io; + private final boolean exclusive; public EndData(Location loc, BitWidth width, int type, boolean exclusive) { this.loc = loc; this.width = width; - this.i_o = type; + this.io = type; this.exclusive = exclusive; } @@ -33,11 +33,11 @@ public boolean isExclusive() { } public boolean isInput() { - return (i_o & INPUT_ONLY) != 0; + return (io & INPUT_ONLY) != 0; } public boolean isOutput() { - return (i_o & OUTPUT_ONLY) != 0; + return (io & OUTPUT_ONLY) != 0; } public Location getLocation() { @@ -49,7 +49,7 @@ public BitWidth getWidth() { } public int getType() { - return i_o; + return io; } @Override @@ -62,6 +62,6 @@ public boolean equals(Object other) { } EndData o = (EndData) other; return o.loc.equals(this.loc) && o.width.equals(this.width) - && o.i_o == this.i_o && o.exclusive == this.exclusive; + && o.io == this.io && o.exclusive == this.exclusive; } } diff --git a/src/main/java/com/cburch/logisim/comp/ManagedComponent.java b/src/main/java/com/cburch/logisim/comp/ManagedComponent.java index cc685e9..22bd694 100644 --- a/src/main/java/com/cburch/logisim/comp/ManagedComponent.java +++ b/src/main/java/com/cburch/logisim/comp/ManagedComponent.java @@ -15,12 +15,11 @@ public abstract class ManagedComponent extends AbstractComponent { - private EventSourceWeakSupport listeners - = new EventSourceWeakSupport<>(); - private Location loc; + private final EventSourceWeakSupport listeners = new EventSourceWeakSupport<>(); + private final Location loc; + private final ArrayList ends; + private final List endsView; private AttributeSet attrs; - private ArrayList ends; - private List endsView; private Bounds bounds = null; public ManagedComponent(Location loc, AttributeSet attrs, int num_ends) { @@ -49,8 +48,8 @@ protected void fireEndChanged(ComponentEvent e) { for (ComponentListener l : listeners) { if (copy == null) { copy = new ComponentEvent(e.getSource(), - Collections.singletonList(e.getOldData()), - Collections.singletonList(e.getData())); + Collections.singletonList(e.getOldData()), + Collections.singletonList(e.getData())); } l.endChanged(copy); } @@ -188,7 +187,7 @@ public void expose(ComponentDrawContext context) { java.awt.Component dest = context.getDestination(); if (bounds != null) { dest.repaint(bounds.getX() - 5, bounds.getY() - 5, - bounds.getWidth() + 10, bounds.getHeight() + 10); + bounds.getWidth() + 10, bounds.getHeight() + 10); } } diff --git a/src/main/java/com/cburch/logisim/comp/TextField.java b/src/main/java/com/cburch/logisim/comp/TextField.java index 58cd709..adf5c79 100644 --- a/src/main/java/com/cburch/logisim/comp/TextField.java +++ b/src/main/java/com/cburch/logisim/comp/TextField.java @@ -28,14 +28,13 @@ public class TextField { private int vAlign; private Font font; private String text = ""; - private LinkedList listeners = new LinkedList<>(); + private final LinkedList listeners = new LinkedList<>(); public TextField(int x, int y, int hAlign, int vAlign) { this(x, y, hAlign, vAlign, null); } - public TextField(int x, int y, int hAlign, int vAlign, - Font font) { + public TextField(int x, int y, int hAlign, int vAlign, Font font) { this.x = x; this.y = y; this.hAlign = hAlign; @@ -55,8 +54,8 @@ public void removeTextFieldListener(TextFieldListener l) { } private void fireTextChanged(TextFieldEvent e) { - for (TextFieldListener l : new ArrayList<>(listeners)) { - l.textChanged(e); + for (TextFieldListener listener : new ArrayList<>(listeners)) { + listener.textChanged(e); } } @@ -141,15 +140,15 @@ public TextFieldCaret getCaret(Graphics g, int x, int y) { public Bounds getBounds(Graphics g) { int x = this.x; int y = this.y; - FontMetrics fm; + FontMetrics metrics; if (font == null) { - fm = g.getFontMetrics(); + metrics = g.getFontMetrics(); } else { - fm = g.getFontMetrics(font); + metrics = g.getFontMetrics(font); } - int width = fm.stringWidth(text); - int ascent = fm.getAscent(); - int descent = fm.getDescent(); + int width = metrics.stringWidth(text); + int ascent = metrics.getAscent(); + int descent = metrics.getDescent(); switch (hAlign) { case TextField.H_CENTER: x -= width / 2; diff --git a/src/main/java/com/cburch/logisim/comp/TextFieldCaret.java b/src/main/java/com/cburch/logisim/comp/TextFieldCaret.java index 85c7b76..c0d76f7 100644 --- a/src/main/java/com/cburch/logisim/comp/TextFieldCaret.java +++ b/src/main/java/com/cburch/logisim/comp/TextFieldCaret.java @@ -19,19 +19,19 @@ class TextFieldCaret implements Caret, TextFieldListener { - private LinkedList listeners = new LinkedList<>(); - private TextField field; - private Graphics g; + private final LinkedList listeners = new LinkedList<>(); + private final TextField field; + private final Graphics g; private String oldText; private String curText; - private int pos; + private int position; - public TextFieldCaret(TextField field, Graphics g, int pos) { + public TextFieldCaret(TextField field, Graphics g, int position) { this.field = field; this.g = g; this.oldText = field.getText(); this.curText = field.getText(); - this.pos = pos; + this.position = position; field.addTextFieldListener(this); } @@ -55,7 +55,7 @@ public String getText() { public void commitText(String text) { curText = text; - pos = curText.length(); + position = curText.length(); field.setText(text); } @@ -65,13 +65,11 @@ public void draw(Graphics g) { } // draw boundary - Bounds bds = getBounds(g); + Bounds bounds = getBounds(g); g.setColor(Color.white); - g.fillRect(bds.getX(), bds.getY(), - bds.getWidth(), bds.getHeight()); + g.fillRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); g.setColor(Color.black); - g.drawRect(bds.getX(), bds.getY(), - bds.getWidth(), bds.getHeight()); + g.drawRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); // draw text int x = field.getX(); @@ -106,8 +104,8 @@ public void draw(Graphics g) { g.drawString(curText, x, y); // draw cursor - if (pos > 0) { - x += fm.stringWidth(curText.substring(0, pos)); + if (position > 0) { + x += fm.stringWidth(curText.substring(0, position)); } g.drawLine(x, y, x, y - ascent); } @@ -149,26 +147,24 @@ public Bounds getBounds(Graphics g) { default: break; } - return Bounds.create(x, y - ascent, width, height) - .add(field.getBounds(g)) - .expand(3); + return Bounds.create(x, y - ascent, width, height).add(field.getBounds(g)).expand(3); } public void cancelEditing() { - CaretEvent e = new CaretEvent(this, oldText, oldText); + CaretEvent event = new CaretEvent(this, oldText, oldText); curText = oldText; - pos = curText.length(); - for (CaretListener l : new ArrayList<>(listeners)) { - l.editingCanceled(e); + position = curText.length(); + for (CaretListener listener : new ArrayList<>(listeners)) { + listener.editingCanceled(event); } field.removeTextFieldListener(this); } public void stopEditing() { - CaretEvent e = new CaretEvent(this, oldText, curText); + CaretEvent event = new CaretEvent(this, oldText, curText); field.setText(curText); - for (CaretListener l : new ArrayList<>(listeners)) { - l.editingStopped(e); + for (CaretListener listener : new ArrayList<>(listeners)) { + listener.editingStopped(event); } field.removeTextFieldListener(this); } @@ -188,29 +184,28 @@ public void mouseReleased(MouseEvent e) { } public void keyPressed(KeyEvent e) { - int ign = InputEvent.ALT_MASK | InputEvent.CTRL_MASK - | InputEvent.META_MASK; - if ((e.getModifiers() & ign) != 0) { + int ign = InputEvent.ALT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK | InputEvent.META_DOWN_MASK; + if ((e.getModifiersEx() & ign) != 0) { return; } switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: - if (pos > 0) { - --pos; + if (position > 0) { + --position; } break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: - if (pos < curText.length()) { - ++pos; + if (position < curText.length()) { + ++position; } break; case KeyEvent.VK_HOME: - pos = 0; + position = 0; break; case KeyEvent.VK_END: - pos = curText.length(); + position = curText.length(); break; case KeyEvent.VK_ESCAPE: case KeyEvent.VK_CANCEL: @@ -218,22 +213,22 @@ public void keyPressed(KeyEvent e) { break; case KeyEvent.VK_CLEAR: curText = ""; - pos = 0; + position = 0; break; case KeyEvent.VK_ENTER: stopEditing(); break; case KeyEvent.VK_BACK_SPACE: - if (pos > 0) { - curText = curText.substring(0, pos - 1) - + curText.substring(pos); - --pos; + if (position > 0) { + curText = curText.substring(0, position - 1) + + curText.substring(position); + --position; } break; case KeyEvent.VK_DELETE: - if (pos < curText.length()) { - curText = curText.substring(0, pos) - + curText.substring(pos + 1); + if (position < curText.length()) { + curText = curText.substring(0, position) + + curText.substring(position + 1); } break; case KeyEvent.VK_INSERT: @@ -251,9 +246,8 @@ public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { - int ign = InputEvent.ALT_MASK | InputEvent.CTRL_MASK - | InputEvent.META_MASK; - if ((e.getModifiers() & ign) != 0) { + int ign = InputEvent.ALT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK | InputEvent.META_DOWN_MASK; + if ((e.getModifiersEx() & ign) != 0) { return; } @@ -261,14 +255,14 @@ public void keyTyped(KeyEvent e) { if (c == '\n') { stopEditing(); } else if (c != KeyEvent.CHAR_UNDEFINED - && !Character.isISOControl(c)) { - if (pos < curText.length()) { - curText = curText.substring(0, pos) + c - + curText.substring(pos); + && !Character.isISOControl(c)) { + if (position < curText.length()) { + curText = curText.substring(0, position) + c + + curText.substring(position); } else { curText += c; } - ++pos; + ++position; } } @@ -280,17 +274,17 @@ private void moveCaret(int x, int y) { for (int i = 0; i < curText.length(); i++) { int cur = fm.stringWidth(curText.substring(0, i + 1)); if (x <= (last + cur) / 2) { - pos = i; + position = i; return; } last = cur; } - pos = curText.length(); + position = curText.length(); } public void textChanged(TextFieldEvent e) { curText = field.getText(); oldText = curText; - pos = curText.length(); + position = curText.length(); } } diff --git a/src/main/java/com/cburch/logisim/comp/TextFieldEvent.java b/src/main/java/com/cburch/logisim/comp/TextFieldEvent.java index ea5d2a8..f2ba9dc 100644 --- a/src/main/java/com/cburch/logisim/comp/TextFieldEvent.java +++ b/src/main/java/com/cburch/logisim/comp/TextFieldEvent.java @@ -5,14 +5,14 @@ public class TextFieldEvent { - private TextField field; - private String oldval; - private String newval; + private final TextField field; + private final String oldValue; + private final String newValue; public TextFieldEvent(TextField field, String old, String val) { this.field = field; - this.oldval = old; - this.newval = val; + this.oldValue = old; + this.newValue = val; } public TextField getTextField() { @@ -20,10 +20,10 @@ public TextField getTextField() { } public String getOldText() { - return oldval; + return oldValue; } public String getText() { - return newval; + return newValue; } } diff --git a/src/main/java/com/cburch/logisim/data/Attribute.java b/src/main/java/com/cburch/logisim/data/Attribute.java index 9abcddb..d43e34c 100644 --- a/src/main/java/com/cburch/logisim/data/Attribute.java +++ b/src/main/java/com/cburch/logisim/data/Attribute.java @@ -9,12 +9,12 @@ public abstract class Attribute { - private String name; - private StringGetter disp; + private final String name; + private final StringGetter display; - public Attribute(String name, StringGetter disp) { + public Attribute(String name, StringGetter display) { this.name = name; - this.disp = disp; + this.display = display; } @Override @@ -27,7 +27,7 @@ public String getName() { } public String getDisplayName() { - return disp.get(); + return display.get(); } public java.awt.Component getCellEditor(Window source, V value) { diff --git a/src/main/java/com/cburch/logisim/data/AttributeEvent.java b/src/main/java/com/cburch/logisim/data/AttributeEvent.java index eec0bdd..0aaf7c7 100644 --- a/src/main/java/com/cburch/logisim/data/AttributeEvent.java +++ b/src/main/java/com/cburch/logisim/data/AttributeEvent.java @@ -5,12 +5,12 @@ public class AttributeEvent { - private AttributeSet source; - private Attribute attr; - private Object value; + private final AttributeSet source; + private final Attribute attr; + private final Object value; public AttributeEvent(AttributeSet source, Attribute attr, - Object value) { + Object value) { this.source = source; this.attr = attr; this.value = value; diff --git a/src/main/java/com/cburch/logisim/data/AttributeOption.java b/src/main/java/com/cburch/logisim/data/AttributeOption.java index 61f3dbf..29aefe0 100644 --- a/src/main/java/com/cburch/logisim/data/AttributeOption.java +++ b/src/main/java/com/cburch/logisim/data/AttributeOption.java @@ -7,20 +7,20 @@ public class AttributeOption implements AttributeOptionInterface { - private Object value; - private String name; - private StringGetter desc; + private final Object value; + private final String name; + private final StringGetter description; - public AttributeOption(Object value, StringGetter desc) { + public AttributeOption(Object value, StringGetter description) { this.value = value; this.name = value.toString(); - this.desc = desc; + this.description = description; } - public AttributeOption(Object value, String name, StringGetter desc) { + public AttributeOption(Object value, String name, StringGetter description) { this.value = value; this.name = name; - this.desc = desc; + this.description = description; } public Object getValue() { @@ -33,6 +33,6 @@ public String toString() { } public String toDisplayString() { - return desc.get(); + return description.get(); } } diff --git a/src/main/java/com/cburch/logisim/data/AttributeSetImpl.java b/src/main/java/com/cburch/logisim/data/AttributeSetImpl.java index ae22d18..06d05cb 100644 --- a/src/main/java/com/cburch/logisim/data/AttributeSetImpl.java +++ b/src/main/java/com/cburch/logisim/data/AttributeSetImpl.java @@ -9,7 +9,7 @@ public class AttributeSetImpl extends AbstractAttributeSet { - private AttrList list = new AttrList(); + private final AttrList list = new AttrList(); private Node head = null; private Node tail = null; private int count = 0; @@ -59,7 +59,7 @@ public void addAttribute(Attribute attr, V value) { } if (findNode(attr) != null) { throw new IllegalArgumentException("Attribute " + attr - + " already created"); + + " already created"); } Node n = new Node(attr, value, false, null); @@ -94,7 +94,7 @@ public void removeAttribute(Attribute attr) { n = n.next; } throw new IllegalArgumentException("Attribute " + attr - + " absent"); + + " absent"); } // @@ -105,7 +105,7 @@ public boolean isReadOnly(Attribute attr) { Node n = findNode(attr); if (n == null) { throw new IllegalArgumentException("Unknown attribute " - + attr); + + attr); } return n.is_read_only; } @@ -115,7 +115,7 @@ public void setReadOnly(Attribute attr, boolean value) { Node n = findNode(attr); if (n == null) { throw new IllegalArgumentException("Unknown attribute " - + attr); + + attr); } n.is_read_only = value; } @@ -128,7 +128,7 @@ public V getValue(Attribute attr) { Node n = findNode(attr); if (n == null) { throw new IllegalArgumentException("Unknown attribute " - + attr); + + attr); } @SuppressWarnings("unchecked") V ret = (V) n.value; @@ -144,11 +144,11 @@ public void setValue(Attribute attr, V value) { Node n = findNode(attr); if (n == null) { throw new IllegalArgumentException("Unknown attribute " - + attr); + + attr); } if (n.is_read_only) { throw new IllegalArgumentException("Attribute " - + attr + " is read-only"); + + attr + " is read-only"); } if (value.equals(n.value)) { // do nothing - why change what's already there? @@ -178,7 +178,7 @@ private static class Node { Node next; Node(Attribute attr, Object value, boolean is_read_only, - Node next) { + Node next) { this.attr = attr; this.value = value; this.is_read_only = is_read_only; @@ -233,7 +233,7 @@ public Attribute get(int i) { } if (remaining != 0 || n == null) { throw new IndexOutOfBoundsException(i + " not in list " - + " [" + count + " elements]"); + + " [" + count + " elements]"); } return n.attr; } diff --git a/src/main/java/com/cburch/logisim/data/Attributes.java b/src/main/java/com/cburch/logisim/data/Attributes.java index bb8bee1..d16601b 100644 --- a/src/main/java/com/cburch/logisim/data/Attributes.java +++ b/src/main/java/com/cburch/logisim/data/Attributes.java @@ -33,7 +33,7 @@ public static Attribute forString(String name) { } public static Attribute forOption(String name, - Object[] vals) { + Object[] vals) { return forOption(name, getter(name), vals); } @@ -46,7 +46,7 @@ public static Attribute forHexInteger(String name) { } public static Attribute forIntegerRange(String name, - int start, int end) { + int start, int end) { return forIntegerRange(name, getter(name), start, end); } @@ -90,7 +90,7 @@ public static Attribute forString(String name, StringGetter disp) { } public static Attribute forOption(String name, StringGetter disp, - V[] vals) { + V[] vals) { return new OptionAttribute<>(name, disp, vals); } @@ -103,7 +103,7 @@ public static Attribute forHexInteger(String name, StringGetter disp) { } public static Attribute forIntegerRange(String name, StringGetter disp, - int start, int end) { + int start, int end) { return new IntegerRangeAttribute(name, disp, start, end); } @@ -141,7 +141,7 @@ public static Attribute forColor(String name, StringGetter disp) { private static class ConstantGetter implements StringGetter { - private String str; + private final String str; public ConstantGetter(String str) { this.str = str; @@ -170,7 +170,7 @@ public String parse(String value) { } private static class OptionComboRenderer - extends BasicComboBoxRenderer { + extends BasicComboBoxRenderer { Attribute attr; @@ -180,10 +180,10 @@ private static class OptionComboRenderer @Override public Component getListCellRendererComponent(JList list, - Object value, int index, boolean isSelected, - boolean cellHasFocus) { + Object value, int index, boolean isSelected, + boolean cellHasFocus) { Component ret = super.getListCellRendererComponent(list, - value, index, isSelected, cellHasFocus); + value, index, isSelected, cellHasFocus); if (ret instanceof JLabel) { @SuppressWarnings("unchecked") V val = (V) value; @@ -195,10 +195,10 @@ public Component getListCellRendererComponent(JList list, private static class OptionAttribute extends Attribute { - private V[] vals; + private final V[] vals; private OptionAttribute(String name, StringGetter disp, - V[] vals) { + V[] vals) { super(name, disp); this.vals = vals; } @@ -214,9 +214,9 @@ public String toDisplayString(V value) { @Override public V parse(String value) { - for (int i = 0; i < vals.length; i++) { - if (value.equals(vals[i].toString())) { - return vals[i]; + for (V val : vals) { + if (value.equals(val.toString())) { + return val; } } throw new NumberFormatException("value not among choices"); @@ -224,7 +224,7 @@ public V parse(String value) { @Override public java.awt.Component getCellEditor(Object value) { - JComboBox combo = new JComboBox(vals); + JComboBox combo = new JComboBox<>(vals); combo.setRenderer(new OptionComboRenderer<>(this)); if (value == null) { combo.setSelectedIndex(-1); @@ -297,7 +297,7 @@ public Double parse(String value) { private static class BooleanAttribute extends OptionAttribute { - private static Boolean[] vals = {Boolean.TRUE, Boolean.FALSE}; + private static final Boolean[] vals = {Boolean.TRUE, Boolean.FALSE}; private BooleanAttribute(String name, StringGetter disp) { super(name, disp, vals); @@ -314,7 +314,7 @@ public String toDisplayString(Boolean value) { @Override public Boolean parse(String value) { - Boolean b = Boolean.valueOf(value); + boolean b = Boolean.parseBoolean(value); return vals[b ? 0 : 1]; } } @@ -354,7 +354,7 @@ public java.awt.Component getCellEditor(Integer value) { options[i - start] = i; } } - JComboBox combo = new JComboBox(options); + JComboBox combo = new JComboBox<>(options); if (value == null) { combo.setSelectedIndex(-1); } else { @@ -367,11 +367,11 @@ public java.awt.Component getCellEditor(Integer value) { private static class DirectionAttribute extends OptionAttribute { - private static Direction[] vals = { - Direction.NORTH, - Direction.SOUTH, - Direction.EAST, - Direction.WEST, + private static final Direction[] vals = { + Direction.NORTH, + Direction.SOUTH, + Direction.EAST, + Direction.WEST, }; public DirectionAttribute(String name, StringGetter disp) { @@ -401,15 +401,15 @@ public String toDisplayString(Font f) { return "???"; } return f.getFamily() - + " " + FontUtil.toStyleDisplayString(f.getStyle()) - + " " + f.getSize(); + + " " + FontUtil.toStyleDisplayString(f.getStyle()) + + " " + f.getSize(); } @Override public String toStandardString(Font f) { return f.getFamily() - + " " + FontUtil.toStyleStandardString(f.getStyle()) - + " " + f.getSize(); + + " " + FontUtil.toStyleStandardString(f.getStyle()) + + " " + f.getSize(); } @Override @@ -424,7 +424,7 @@ public java.awt.Component getCellEditor(Font value) { } private static class FontChooser extends JFontChooser - implements JInputComponent { + implements JInputComponent { FontChooser(Font initial) { super(initial); @@ -497,7 +497,7 @@ public java.awt.Component getCellEditor(Color value) { } private static class ColorChooser extends ColorPicker - implements JInputComponent { + implements JInputComponent { ColorChooser(Color initial) { if (initial != null) { diff --git a/src/main/java/com/cburch/logisim/data/BitWidth.java b/src/main/java/com/cburch/logisim/data/BitWidth.java index fdc5b0f..cbb2625 100644 --- a/src/main/java/com/cburch/logisim/data/BitWidth.java +++ b/src/main/java/com/cburch/logisim/data/BitWidth.java @@ -25,8 +25,7 @@ public static BitWidth create(int width) { if (width == 0) { return UNKNOWN; } else { - throw new IllegalArgumentException("width " + width - + " must be positive"); + throw new IllegalArgumentException("width " + width + " must be positive"); } } else if (width - 1 < prefab.length) { return prefab[width - 1]; @@ -94,7 +93,7 @@ public String toString() { static class Attribute extends com.cburch.logisim.data.Attribute { - private BitWidth[] choices; + private final BitWidth[] choices; public Attribute(String name, StringGetter disp) { super(name, disp); @@ -117,7 +116,7 @@ public BitWidth parse(String value) { @Override public java.awt.Component getCellEditor(BitWidth value) { - JComboBox combo = new JComboBox(choices); + JComboBox combo = new JComboBox<>(choices); if (value != null) { int wid = value.getWidth(); if (wid <= 0 || wid > prefab.length) { diff --git a/src/main/java/com/cburch/logisim/data/Bounds.java b/src/main/java/com/cburch/logisim/data/Bounds.java index f7722a4..be289cd 100644 --- a/src/main/java/com/cburch/logisim/data/Bounds.java +++ b/src/main/java/com/cburch/logisim/data/Bounds.java @@ -13,8 +13,8 @@ */ public class Bounds { - private static final Cache cache = new Cache(); public static final Bounds EMPTY_BOUNDS = new Bounds(0, 0, 0, 0); + private static final Cache cache = new Cache(); private final int x; private final int y; private final int width; @@ -122,7 +122,7 @@ public boolean contains(int pointX, int pointY) { public boolean contains(int pointX, int pointY, int allowedError) { return pointX >= x - allowedError && pointX < x + width + allowedError - && pointY >= y - allowedError && pointY < y + height + allowedError; + && pointY >= y - allowedError && pointY < y + height + allowedError; } public boolean contains(int x1, int y1, int width, int height) { @@ -276,7 +276,7 @@ public Bounds intersect(Bounds bounds) { int y2 = bounds.y; int x3 = x2 + bounds.width; int y3 = y2 + bounds.height; - if (x2 > x0) { + if (x2 > x0) { x0 = x2; } if (y2 > y0) { diff --git a/src/main/java/com/cburch/logisim/data/Direction.java b/src/main/java/com/cburch/logisim/data/Direction.java index e4cfb6d..f9cac63 100644 --- a/src/main/java/com/cburch/logisim/data/Direction.java +++ b/src/main/java/com/cburch/logisim/data/Direction.java @@ -8,18 +8,18 @@ public class Direction implements AttributeOptionInterface { public static final Direction EAST = new Direction("east", Strings.getter("directionEastOption"), - Strings.getter("directionEastVertical"), 0); + Strings.getter("directionEastVertical"), 0); public static final Direction WEST = new Direction("west", Strings.getter("directionWestOption"), - Strings.getter("directionWestVertical"), 1); + Strings.getter("directionWestVertical"), 1); public static final Direction NORTH = new Direction("north", Strings.getter("directionNorthOption"), - Strings.getter("directionNorthVertical"), 2); + Strings.getter("directionNorthVertical"), 2); public static final Direction SOUTH = new Direction("south", Strings.getter("directionSouthOption"), - Strings.getter("directionSouthVertical"), 3); + Strings.getter("directionSouthVertical"), 3); public static final Direction[] cardinals = {NORTH, EAST, SOUTH, WEST}; - private String name; - private StringGetter disp; - private StringGetter vert; - private int id; + private final String name; + private final StringGetter disp; + private final StringGetter vert; + private final int id; private Direction(String name, StringGetter disp, StringGetter vert, int id) { this.name = name; diff --git a/src/main/java/com/cburch/logisim/data/Location.java b/src/main/java/com/cburch/logisim/data/Location.java index 2b0bbca..8b83b11 100644 --- a/src/main/java/com/cburch/logisim/data/Location.java +++ b/src/main/java/com/cburch/logisim/data/Location.java @@ -45,8 +45,7 @@ public static Location parse(String value) { if (value.charAt(0) == '(') { int len = value.length(); if (value.charAt(len - 1) != ')') { - throw new NumberFormatException("invalid point '" - + base + "'"); + throw new NumberFormatException("invalid point '" + base + "'"); } value = value.substring(1, len - 1); } @@ -55,8 +54,7 @@ public static Location parse(String value) { if (comma < 0) { comma = value.indexOf(' '); if (comma < 0) { - throw new NumberFormatException("invalid point '" - + base + "'"); + throw new NumberFormatException("invalid point '" + base + "'"); } } int x = Integer.parseInt(value.substring(0, comma).trim()); diff --git a/src/main/java/com/cburch/logisim/data/Strings.java b/src/main/java/com/cburch/logisim/data/Strings.java index b373a62..eed3ed7 100644 --- a/src/main/java/com/cburch/logisim/data/Strings.java +++ b/src/main/java/com/cburch/logisim/data/Strings.java @@ -8,7 +8,7 @@ class Strings { - private static LocaleManager source = new LocaleManager("logisim", "data"); + private static final LocaleManager source = new LocaleManager("logisim", "data"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/data/Value.java b/src/main/java/com/cburch/logisim/data/Value.java index bc03509..92e7358 100644 --- a/src/main/java/com/cburch/logisim/data/Value.java +++ b/src/main/java/com/cburch/logisim/data/Value.java @@ -48,8 +48,7 @@ public static Value create(Value[] values) { return values[0]; } if (values.length > MAX_WIDTH) { - throw new RuntimeException( - "Cannot have more than " + MAX_WIDTH + " bits in a value"); + throw new RuntimeException("Cannot have more than " + MAX_WIDTH + " bits in a value"); } int width = values.length; @@ -60,14 +59,15 @@ public static Value create(Value[] values) { int mask = 1 << i; if (values[i] == TRUE) { value |= mask; - } else if (values[i] == FALSE) /* do nothing */ { + } else if (values[i] == FALSE) { + /* do nothing */ } else if (values[i] == UNKNOWN) { unknown |= mask; } else if (values[i] == ERROR) { error |= mask; } else { throw new RuntimeException("unrecognized value " - + values[i]); + + values[i]); } } return Value.create(width, error, unknown, value); @@ -109,7 +109,7 @@ private static Value create(int width, int error, int unknown, int value) { if (cached != null) { Value val = (Value) cached; if (val.value == value && val.width == width && val.error == error - && val.unknown == unknown) { + && val.unknown == unknown) { return val; } } @@ -174,9 +174,9 @@ public Value set(int which, Value val) { } else { int mask = ~(1 << which); return Value.create(this.width, - (this.error & mask) | (val.error << which), - (this.unknown & mask) | (val.unknown << which), - (this.value & mask) | (val.value << which)); + (this.error & mask) | (val.error << which), + (this.unknown & mask) | (val.unknown << which), + (this.value & mask) | (val.value << which)); } } @@ -219,9 +219,9 @@ public boolean equals(Object other_obj) { } Value other = (Value) other_obj; boolean ret = this.width == other.width - && this.error == other.error - && this.unknown == other.unknown - && this.value == other.value; + && this.error == other.error + && this.unknown == other.unknown + && this.value == other.value; return ret; } @@ -432,11 +432,11 @@ public Value combine(Value other) { return ERROR; } else { int disagree = (this.value ^ other.value) - & ~(this.unknown | other.unknown); + & ~(this.unknown | other.unknown); return Value.create(Math.max(this.width, other.width), - this.error | other.error | disagree, - this.unknown & other.unknown, - (this.value & ~this.unknown) | (other.value & ~other.unknown)); + this.error | other.error | disagree, + this.unknown & other.unknown, + (this.value & ~this.unknown) | (other.value & ~other.unknown)); } } @@ -457,9 +457,9 @@ public Value and(Value other) { int false1 = ~other.value & ~other.error & ~other.unknown; int falses = false0 | false1; return Value.create(Math.max(this.width, other.width), - (this.error | other.error | this.unknown | other.unknown) & ~falses, - 0, - this.value & other.value); + (this.error | other.error | this.unknown | other.unknown) & ~falses, + 0, + this.value & other.value); } } @@ -480,9 +480,9 @@ public Value or(Value other) { int true1 = other.value & ~other.error & ~other.unknown; int trues = true0 | true1; return Value.create(Math.max(this.width, other.width), - (this.error | other.error | this.unknown | other.unknown) & ~trues, - 0, - this.value | other.value); + (this.error | other.error | this.unknown | other.unknown) & ~trues, + 0, + this.value | other.value); } } @@ -506,9 +506,9 @@ public Value xor(Value other) { return TRUE; } else { return Value.create(Math.max(this.width, other.width), - this.error | other.error | this.unknown | other.unknown, - 0, - this.value ^ other.value); + this.error | other.error | this.unknown | other.unknown, + 0, + this.value ^ other.value); } } @@ -523,9 +523,9 @@ public Value not() { return ERROR; } else { return Value.create(this.width, - this.error | this.unknown, - 0, - ~this.value); + this.error | this.unknown, + 0, + ~this.value); } } diff --git a/src/main/java/com/cburch/logisim/file/FileStatistics.java b/src/main/java/com/cburch/logisim/file/FileStatistics.java index 5276819..2772e43 100644 --- a/src/main/java/com/cburch/logisim/file/FileStatistics.java +++ b/src/main/java/com/cburch/logisim/file/FileStatistics.java @@ -20,9 +20,9 @@ public class FileStatistics { - private List counts; - private Count totalWithout; - private Count totalWith; + private final List counts; + private final Count totalWithout; + private final Count totalWith; private FileStatistics(List counts, Count totalWithout, Count totalWith) { this.counts = Collections.unmodifiableList(counts); @@ -40,7 +40,7 @@ public static FileStatistics compute(LogisimFile file, Circuit circuit) { } private static Map doRecursiveCount(Circuit circuit, Set circuits, - Map> countMap) { + Map> countMap) { if (countMap.containsKey(circuit)) { return countMap.get(circuit); } @@ -85,8 +85,8 @@ private static Map doSimpleCount(Circuit circuit) { return counts; } - private static void doUniqueCounts(Map counts, - Map> circuitCounts) { + private static void doUniqueCounts(Map counts, Map> circuitCounts) { for (Count count : counts.values()) { ComponentFactory factory = count.getFactory(); int unique = 0; @@ -100,8 +100,7 @@ private static void doUniqueCounts(Map counts, } } - private static List sortCounts(Map counts, - LogisimFile file) { + private static List sortCounts(Map counts, LogisimFile file) { List returnCounts = new ArrayList<>(); for (AddTool tool : file.getTools()) { ComponentFactory factory = tool.getFactory(); @@ -158,7 +157,7 @@ public Count getTotalWithSubcircuits() { public static class Count { private Library library; - private ComponentFactory factory; + private final ComponentFactory factory; private int simpleCount; private int uniqueCount; private int recursiveCount; diff --git a/src/main/java/com/cburch/logisim/file/LibraryEvent.java b/src/main/java/com/cburch/logisim/file/LibraryEvent.java index d6749fc..59e10ac 100644 --- a/src/main/java/com/cburch/logisim/file/LibraryEvent.java +++ b/src/main/java/com/cburch/logisim/file/LibraryEvent.java @@ -16,9 +16,9 @@ public class LibraryEvent { public final static int SET_NAME = 6; public static final int DIRTY_STATE = 7; - private Library source; - private int action; - private Object data; + private final Library source; + private final int action; + private final Object data; LibraryEvent(Library source, int action, Object data) { this.source = source; diff --git a/src/main/java/com/cburch/logisim/file/LibraryManager.java b/src/main/java/com/cburch/logisim/file/LibraryManager.java index f98b5a2..45a1b21 100644 --- a/src/main/java/com/cburch/logisim/file/LibraryManager.java +++ b/src/main/java/com/cburch/logisim/file/LibraryManager.java @@ -17,9 +17,9 @@ class LibraryManager { public static final LibraryManager instance = new LibraryManager(); - private static final char DESCRIPTOR_SEPERATOR = '#'; - private HashMap> fileMap; - private WeakHashMap invMap; + private static final char DESCRIPTOR_SEPARATOR = '#'; + private final HashMap> fileMap; + private final WeakHashMap invMap; private LibraryManager() { fileMap = new HashMap<>(); @@ -74,7 +74,7 @@ Collection getLogisimLibraries() { public Library loadLibrary(Loader loader, String descriptor) { // It may already be loaded. // Otherwise we'll have to decode it. - int separator = descriptor.indexOf(DESCRIPTOR_SEPERATOR); + int separator = descriptor.indexOf(DESCRIPTOR_SEPARATOR); if (separator < 0) { loader.showError(StringUtil.format(Strings.get("fileDescriptorError"), descriptor)); return null; @@ -95,7 +95,7 @@ public Library loadLibrary(Loader loader, String descriptor) { return loadLogisimLibrary(loader, fileToRead); } case "jar": { - int separatorLocation = name.lastIndexOf(DESCRIPTOR_SEPERATOR); + int separatorLocation = name.lastIndexOf(DESCRIPTOR_SEPARATOR); String fileName = name.substring(0, separatorLocation); String className = name.substring(separatorLocation + 1); File fileToRead = loader.getFileFor(fileName, Loader.JAR_FILTER); @@ -149,7 +149,7 @@ public void reload(Loader loader, LoadedLibrary loadedLibrary) { LibraryDescriptor descriptor = invMap.get(loadedLibrary); if (descriptor == null) { loader.showError(StringUtil.format(Strings.get("unknownLibraryFileError"), - loadedLibrary.getDisplayName())); + loadedLibrary.getDisplayName())); } else { try { descriptor.setBase(loader, loadedLibrary); @@ -198,14 +198,14 @@ public void fileSaved(Loader loader, File destination, File oldFile, LogisimFile @SuppressWarnings("SuspiciousMethodCalls") public String getDescriptor(Loader loader, Library library) { if (loader.getBuiltin().getLibraries().contains(library)) { - return DESCRIPTOR_SEPERATOR + library.getName(); + return DESCRIPTOR_SEPARATOR + library.getName(); } else { LibraryDescriptor descriptor = invMap.get(library); if (descriptor != null) { return descriptor.toDescriptor(loader); } else { throw new LoaderException(StringUtil.format(Strings.get("fileDescriptorUnknownError"), - library.getDisplayName())); + library.getDisplayName())); } } } @@ -233,12 +233,12 @@ private static abstract class LibraryDescriptor { abstract String toDescriptor(Loader loader); abstract void setBase(Loader loader, LoadedLibrary loadedLibrary) - throws LoadFailedException; + throws LoadFailedException; } private static class LogisimProjectDescriptor extends LibraryDescriptor { - private File file; + private final File file; private LogisimProjectDescriptor(File file) { this.file = file; @@ -276,8 +276,8 @@ public int hashCode() { private static class JarDescriptor extends LibraryDescriptor { - private File file; - private String className; + private final File file; + private final String className; private JarDescriptor(File file, String className) { this.file = file; @@ -291,7 +291,7 @@ boolean concernsFile(File query) { @Override String toDescriptor(Loader loader) { - return "jar#" + toRelative(loader, file) + DESCRIPTOR_SEPERATOR + className; + return "jar#" + toRelative(loader, file) + DESCRIPTOR_SEPARATOR + className; } @Override @@ -313,4 +313,4 @@ public int hashCode() { return file.hashCode() * 31 + className.hashCode(); } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/file/LoadFailedException.java b/src/main/java/com/cburch/logisim/file/LoadFailedException.java index 66d2e02..acc7aa2 100644 --- a/src/main/java/com/cburch/logisim/file/LoadFailedException.java +++ b/src/main/java/com/cburch/logisim/file/LoadFailedException.java @@ -5,7 +5,7 @@ public class LoadFailedException extends Exception { - private boolean shown; + private final boolean shown; LoadFailedException(String desc) { this(desc, false); @@ -19,4 +19,4 @@ public class LoadFailedException extends Exception { public boolean isShown() { return shown; } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/file/LoadedLibrary.java b/src/main/java/com/cburch/logisim/file/LoadedLibrary.java index d7f9899..1b76916 100644 --- a/src/main/java/com/cburch/logisim/file/LoadedLibrary.java +++ b/src/main/java/com/cburch/logisim/file/LoadedLibrary.java @@ -26,8 +26,8 @@ public class LoadedLibrary extends Library implements LibraryEventSource { private Library library; private boolean isDirty; - private MyListener myListener; - private EventSourceWeakSupport listeners; + private final MyListener myListener; + private final EventSourceWeakSupport listeners; LoadedLibrary(Library library) { isDirty = false; @@ -44,7 +44,7 @@ public class LoadedLibrary extends Library implements LibraryEventSource { } private static void replaceAll(Map componentMap, - Map toolMap) { + Map toolMap) { for (Project project : Projects.getOpenProjects()) { Tool oldTool = project.getTool(); Circuit oldCircuit = project.getCurrentCircuit(); @@ -63,9 +63,7 @@ private static void replaceAll(Map component } } - private static void replaceAll(LogisimFile file, - Map compMap, - Map toolMap) { + private static void replaceAll(LogisimFile file, Map compMap, Map toolMap) { file.getOptions().getToolbarData().replaceAll(toolMap); file.getOptions().getMouseMappings().replaceAll(toolMap); for (Circuit circuit : file.getCircuits()) { @@ -73,8 +71,7 @@ private static void replaceAll(LogisimFile file, } } - private static void replaceAll(Circuit circuit, - Map compMap) { + private static void replaceAll(Circuit circuit, Map compMap) { ArrayList toReplace = null; for (Component comp : circuit.getNonWires()) { if (compMap.containsKey(comp.getFactory())) { @@ -194,14 +191,14 @@ private void resolveChanges(Library old) { } HashSet changes = new HashSet<>(old.getLibraries()); - changes.removeAll(library.getLibraries()); + library.getLibraries().forEach(changes::remove); for (Library lib : changes) { fireLibraryEvent(LibraryEvent.REMOVE_LIBRARY, lib); } changes.clear(); changes.addAll(library.getLibraries()); - changes.removeAll(old.getLibraries()); + old.getLibraries().forEach(changes::remove); for (Library lib : changes) { fireLibraryEvent(LibraryEvent.ADD_LIBRARY, lib); } @@ -215,7 +212,7 @@ private void resolveChanges(Library old) { toolMap.put(oldTool, newTool); if (oldTool instanceof AddTool) { ComponentFactory oldFactory = ((AddTool) oldTool).getFactory(); - if (newTool != null && newTool instanceof AddTool) { + if (newTool instanceof AddTool) { ComponentFactory newFactory = ((AddTool) newTool).getFactory(); componentMap.put(oldFactory, newFactory); } else { diff --git a/src/main/java/com/cburch/logisim/file/Loader.java b/src/main/java/com/cburch/logisim/file/Loader.java index 3c627a3..9af2194 100644 --- a/src/main/java/com/cburch/logisim/file/Loader.java +++ b/src/main/java/com/cburch/logisim/file/Loader.java @@ -30,12 +30,12 @@ public class Loader implements LibraryLoader { public static final String LOGISIM_EXTENSION = ".circ"; public static final FileFilter LOGISIM_FILTER = new LogisimFileFilter(); public static final FileFilter JAR_FILTER = new JarFileFilter(); + private final Builtin builtin = new Builtin(); + private final Stack filesOpening = new Stack<>(); // fixed private Component parent; - private Builtin builtin = new Builtin(); // to be cleared with each new file private File mainFile = null; - private Stack filesOpening = new Stack<>(); private Map substitutions = new HashMap<>(); public Loader(Component parent) { @@ -116,7 +116,7 @@ public void clear() { } public LogisimFile openLogisimFile(File file, Map substitutions) - throws LoadFailedException { + throws LoadFailedException { this.substitutions = substitutions; try { return openLogisimFile(file); @@ -172,9 +172,9 @@ public boolean save(LogisimFile file, File destination) { Library referenceLibrary = LibraryManager.instance.findReference(file, destination); if (referenceLibrary != null) { JOptionPane.showMessageDialog(parent, - StringUtil.format(Strings.get("fileCircularError"), referenceLibrary.getDisplayName()), - Strings.get("fileSaveErrorTitle"), - JOptionPane.ERROR_MESSAGE); + StringUtil.format(Strings.get("fileCircularError"), referenceLibrary.getDisplayName()), + Strings.get("fileSaveErrorTitle"), + JOptionPane.ERROR_MESSAGE); return false; } @@ -185,7 +185,8 @@ public boolean save(LogisimFile file, File destination) { try { try { MacCompatibility.setFileCreatorAndType(destination, "LGSM", "circ"); - } catch (IOException ignored) { } + } catch (IOException ignored) { + } outputStream = new FileOutputStream(destination); file.write(outputStream, this); @@ -202,10 +203,10 @@ public boolean save(LogisimFile file, File destination) { destination.delete(); } JOptionPane.showMessageDialog(parent, - StringUtil.format(Strings.get("fileSaveError"), + StringUtil.format(Strings.get("fileSaveError"), ioException.toString()), - Strings.get("fileSaveErrorTitle"), - JOptionPane.ERROR_MESSAGE); + Strings.get("fileSaveErrorTitle"), + JOptionPane.ERROR_MESSAGE); return false; } finally { if (outputStream != null) { @@ -219,10 +220,10 @@ public boolean save(LogisimFile file, File destination) { destination.delete(); } JOptionPane.showMessageDialog(parent, - StringUtil.format(Strings.get("fileSaveCloseError"), + StringUtil.format(Strings.get("fileSaveCloseError"), ioException.toString()), - Strings.get("fileSaveErrorTitle"), - JOptionPane.ERROR_MESSAGE); + Strings.get("fileSaveErrorTitle"), + JOptionPane.ERROR_MESSAGE); } } } @@ -234,9 +235,9 @@ public boolean save(LogisimFile file, File destination) { destination.delete(); } JOptionPane.showMessageDialog(parent, - Strings.get("fileSaveZeroError"), - Strings.get("fileSaveErrorTitle"), - JOptionPane.ERROR_MESSAGE); + Strings.get("fileSaveZeroError"), + Strings.get("fileSaveErrorTitle"), + JOptionPane.ERROR_MESSAGE); return false; } @@ -254,7 +255,7 @@ LogisimFile loadLogisimFile(File requestedFile) throws LoadFailedException { for (File fileOpening : filesOpening) { if (fileOpening.equals(actualFile)) { throw new LoadFailedException(StringUtil.format(Strings.get("logisimCircularError"), - toProjectName(actualFile))); + toProjectName(actualFile))); } } @@ -264,7 +265,7 @@ LogisimFile loadLogisimFile(File requestedFile) throws LoadFailedException { logisimFile = LogisimFile.load(actualFile, this); } catch (IOException e) { throw new LoadFailedException(StringUtil.format(Strings.get("logisimLoadError"), - toProjectName(actualFile), e.toString())); + toProjectName(actualFile), e.toString())); } finally { filesOpening.pop(); } @@ -313,7 +314,9 @@ Library loadJarFile(File requestedFile, String className) throws LoadFailedExcep // instantiate library Library returnLibrary; try { - returnLibrary = (Library) returnClass.newInstance(); + // TODO See if this is proper form +// returnLibrary = (Library) returnClass.newInstance(); + returnLibrary = (Library) returnClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new LoadFailedException(StringUtil.format(Strings.get("jarLibraryNotCreatedError"), className)); } @@ -345,7 +348,7 @@ public void showError(String description) { if (description.contains("\n") || description.length() > 60) { int lines = 1; for (int position = description.indexOf('\n'); position >= 0; - position = description.indexOf('\n', position + 1)) { + position = description.indexOf('\n', position + 1)) { lines++; } lines = Math.max(4, Math.min(lines, 7)); @@ -358,10 +361,10 @@ public void showError(String description) { JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setPreferredSize(new Dimension(350, 150)); JOptionPane.showMessageDialog(parent, scrollPane, - Strings.get("fileErrorTitle"), JOptionPane.ERROR_MESSAGE); + Strings.get("fileErrorTitle"), JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(parent, description, - Strings.get("fileErrorTitle"), JOptionPane.ERROR_MESSAGE); + Strings.get("fileErrorTitle"), JOptionPane.ERROR_MESSAGE); } } @@ -372,10 +375,10 @@ private void showMessages(LogisimFile sourceLogisimFile) { String message = sourceLogisimFile.getMessage(); while (message != null) { JOptionPane.showMessageDialog( - parent, - message, - Strings.get("fileMessageTitle"), - JOptionPane.INFORMATION_MESSAGE); + parent, + message, + Strings.get("fileMessageTitle"), + JOptionPane.INFORMATION_MESSAGE); message = sourceLogisimFile.getMessage(); } } @@ -441,4 +444,4 @@ public String getDescription() { return Strings.get("jarFileFilter"); } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/file/LoaderException.java b/src/main/java/com/cburch/logisim/file/LoaderException.java index f06037e..28a7dad 100644 --- a/src/main/java/com/cburch/logisim/file/LoaderException.java +++ b/src/main/java/com/cburch/logisim/file/LoaderException.java @@ -5,7 +5,7 @@ public class LoaderException extends RuntimeException { - private boolean shown; + private final boolean shown; LoaderException(String desc) { this(desc, false); @@ -19,4 +19,4 @@ public class LoaderException extends RuntimeException { public boolean isShown() { return shown; } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/file/LogisimFile.java b/src/main/java/com/cburch/logisim/file/LogisimFile.java index 864ced5..7f90acf 100644 --- a/src/main/java/com/cburch/logisim/file/LogisimFile.java +++ b/src/main/java/com/cburch/logisim/file/LogisimFile.java @@ -35,12 +35,12 @@ public class LogisimFile extends Library implements LibraryEventSource { - private EventSourceWeakSupport listeners = new EventSourceWeakSupport<>(); + private final EventSourceWeakSupport listeners = new EventSourceWeakSupport<>(); + private final LinkedList messages = new LinkedList<>(); + private final Options options = new Options(); + private final LinkedList tools = new LinkedList<>(); + private final LinkedList libraries = new LinkedList<>(); private Loader loader; - private LinkedList messages = new LinkedList<>(); - private Options options = new Options(); - private LinkedList tools = new LinkedList<>(); - private LinkedList libraries = new LinkedList<>(); private Circuit main = null; private String name; private boolean isDirty = false; @@ -105,18 +105,18 @@ public static LogisimFile load(File file, Loader loader) throws IOException { } public static LogisimFile load(InputStream in, Loader loader) - throws IOException { + throws IOException { try { return loadSub(in, loader); } catch (SAXException e) { loader.showError(StringUtil.format( - Strings.get("xmlFormatError"), e.toString())); + Strings.get("xmlFormatError"), e.toString())); return null; } } private static LogisimFile loadSub(InputStream in, Loader loader) - throws IOException, SAXException { + throws IOException, SAXException { // fetch first line and then reset BufferedInputStream inBuffered = new BufferedInputStream(in); String firstLine = getFirstLine(inBuffered); @@ -136,7 +136,7 @@ private static LogisimFile loadSub(InputStream in, Loader loader) } private static String getFirstLine(BufferedInputStream in) - throws IOException { + throws IOException { byte[] first = new byte[512]; in.mark(first.length - 1); in.read(first); @@ -354,7 +354,7 @@ public String getUnloadLibraryMessage(Library lib) { for (Component comp : circuit.getNonWires()) { if (factories.contains(comp.getFactory())) { return StringUtil.format(Strings.get("unloadUsedError"), - circuit.getName()); + circuit.getName()); } } } @@ -400,7 +400,7 @@ public LogisimFile cloneLogisimFile(Loader newloader) { reader.connect(writer); } catch (IOException e) { newloader.showError(StringUtil.format( - Strings.get("fileDuplicateError"), e.toString())); + Strings.get("fileDuplicateError"), e.toString())); return null; } new WritingThread(writer, this).start(); @@ -408,7 +408,7 @@ public LogisimFile cloneLogisimFile(Loader newloader) { return LogisimFile.load(reader, newloader); } catch (IOException e) { newloader.showError(StringUtil.format( - Strings.get("fileDuplicateError"), e.toString())); + Strings.get("fileDuplicateError"), e.toString())); return null; } } @@ -448,13 +448,13 @@ public void run() { file.write(out, file.loader); } catch (IOException e) { file.loader.showError(StringUtil.format( - Strings.get("fileDuplicateError"), e.toString())); + Strings.get("fileDuplicateError"), e.toString())); } try { out.close(); } catch (IOException e) { file.loader.showError(StringUtil.format( - Strings.get("fileDuplicateError"), e.toString())); + Strings.get("fileDuplicateError"), e.toString())); } } } diff --git a/src/main/java/com/cburch/logisim/file/LogisimFileActions.java b/src/main/java/com/cburch/logisim/file/LogisimFileActions.java index 521d9bd..efce77c 100644 --- a/src/main/java/com/cburch/logisim/file/LogisimFileActions.java +++ b/src/main/java/com/cburch/logisim/file/LogisimFileActions.java @@ -58,7 +58,7 @@ public static Action revertDefaults() { private static class AddCircuit extends Action { - private Circuit circuit; + private final Circuit circuit; AddCircuit(Circuit circuit) { this.circuit = circuit; @@ -82,7 +82,7 @@ public void undo(Project proj) { private static class RemoveCircuit extends Action { - private Circuit circuit; + private final Circuit circuit; private int index; RemoveCircuit(Circuit circuit) { @@ -108,9 +108,9 @@ public void undo(Project proj) { private static class MoveCircuit extends Action { - private AddTool tool; + private final AddTool tool; private int fromIndex; - private int toIndex; + private final int toIndex; MoveCircuit(AddTool tool, int toIndex) { this.tool = tool; @@ -136,7 +136,7 @@ public void undo(Project proj) { @Override public boolean shouldAppendTo(Action other) { return other instanceof MoveCircuit - && ((MoveCircuit) other).tool == this.tool; + && ((MoveCircuit) other).tool == this.tool; } @Override @@ -149,7 +149,7 @@ public Action append(Action other) { private static class LoadLibraries extends Action { - private Library[] libs; + private final Library[] libs; LoadLibraries(Library[] libs) { this.libs = libs; @@ -181,7 +181,7 @@ public void undo(Project proj) { private static class UnloadLibraries extends Action { - private Library[] libs; + private final Library[] libs; UnloadLibraries(Library[] libs) { this.libs = libs; @@ -214,7 +214,7 @@ public void undo(Project proj) { private static class SetMainCircuit extends Action { private Circuit oldval; - private Circuit newval; + private final Circuit newval; SetMainCircuit(Circuit circuit) { newval = circuit; @@ -239,9 +239,9 @@ public void undo(Project proj) { private static class RevertAttributeValue { - private AttributeSet attrs; - private Attribute attr; - private Object value; + private final AttributeSet attrs; + private final Attribute attr; + private final Object value; RevertAttributeValue(AttributeSet attrs, Attribute attr, Object value) { this.attrs = attrs; @@ -254,7 +254,7 @@ private static class RevertDefaults extends Action { private Options oldOpts; private ArrayList libraries = null; - private ArrayList attrValues; + private final ArrayList attrValues; RevertDefaults() { libraries = null; diff --git a/src/main/java/com/cburch/logisim/file/MouseMappings.java b/src/main/java/com/cburch/logisim/file/MouseMappings.java index 965bb68..608dbad 100644 --- a/src/main/java/com/cburch/logisim/file/MouseMappings.java +++ b/src/main/java/com/cburch/logisim/file/MouseMappings.java @@ -16,8 +16,8 @@ public class MouseMappings { - private ArrayList listeners; - private HashMap map; + private final ArrayList listeners; + private final HashMap map; private int cache_mods; private Tool cache_tool; @@ -113,7 +113,7 @@ public void copyFrom(MouseMappings other, LogisimFile file) { if (dstTool != null) { dstTool = dstTool.cloneTool(); AttributeSets.copy(srcTool.getAttributeSet(), - dstTool.getAttributeSet()); + dstTool.getAttributeSet()); this.map.put(mods, dstTool); } } @@ -178,7 +178,7 @@ void replaceAll(Map toolMap) { } else { Tool clone = newTool.cloneTool(); LoadedLibrary.copyAttributes(clone.getAttributeSet(), - tool.getAttributeSet()); + tool.getAttributeSet()); map.put(key, clone); } } @@ -191,7 +191,7 @@ void replaceAll(Map toolMap) { } else { Tool clone = newTool.cloneTool(); LoadedLibrary.copyAttributes(clone.getAttributeSet(), - tool.getAttributeSet()); + tool.getAttributeSet()); map.put(key, clone); } } diff --git a/src/main/java/com/cburch/logisim/file/Options.java b/src/main/java/com/cburch/logisim/file/Options.java index f441340..2f38e29 100644 --- a/src/main/java/com/cburch/logisim/file/Options.java +++ b/src/main/java/com/cburch/logisim/file/Options.java @@ -12,25 +12,25 @@ public class Options { public static final AttributeOption GATE_UNDEFINED_IGNORE - = new AttributeOption("ignore", Strings.getter("gateUndefinedIgnore")); + = new AttributeOption("ignore", Strings.getter("gateUndefinedIgnore")); public static final AttributeOption GATE_UNDEFINED_ERROR - = new AttributeOption("error", Strings.getter("gateUndefinedError")); + = new AttributeOption("error", Strings.getter("gateUndefinedError")); public static final Attribute SIMULATOR_LIMIT_ATTRIBUTE - = Attributes.forInteger("simlimit", Strings.getter("simLimitOption")); + = Attributes.forInteger("simlimit", Strings.getter("simLimitOption")); public static final Attribute SIMULATOR_RANDOM_ATTRIBUTE - = Attributes.forInteger("simrand", Strings.getter("simRandomOption")); + = Attributes.forInteger("simrand", Strings.getter("simRandomOption")); public static final Attribute ATTR_GATE_UNDEFINED - = Attributes.forOption("gateUndefined", Strings.getter("gateUndefinedOption"), - new AttributeOption[]{GATE_UNDEFINED_IGNORE, GATE_UNDEFINED_ERROR}); + = Attributes.forOption("gateUndefined", Strings.getter("gateUndefinedOption"), + new AttributeOption[]{GATE_UNDEFINED_IGNORE, GATE_UNDEFINED_ERROR}); public static final Integer SIMULATOR_RANDOM_DEFAULT = 32; private static final Attribute[] ATTRIBUTES = { - ATTR_GATE_UNDEFINED, SIMULATOR_LIMIT_ATTRIBUTE, SIMULATOR_RANDOM_ATTRIBUTE + ATTR_GATE_UNDEFINED, SIMULATOR_LIMIT_ATTRIBUTE, SIMULATOR_RANDOM_ATTRIBUTE }; - private static final Object[] DEFAULTS = { GATE_UNDEFINED_IGNORE, 1000, 0}; + private static final Object[] DEFAULTS = {GATE_UNDEFINED_IGNORE, 1000, 0}; - private AttributeSet attributeSet; - private MouseMappings mouseMappings; - private ToolbarData toolbarData; + private final AttributeSet attributeSet; + private final MouseMappings mouseMappings; + private final ToolbarData toolbarData; public Options() { attributeSet = AttributeSets.fixedSet(ATTRIBUTES, DEFAULTS); diff --git a/src/main/java/com/cburch/logisim/file/ProjectsDirty.java b/src/main/java/com/cburch/logisim/file/ProjectsDirty.java index c5cb5e1..ded86d9 100644 --- a/src/main/java/com/cburch/logisim/file/ProjectsDirty.java +++ b/src/main/java/com/cburch/logisim/file/ProjectsDirty.java @@ -12,8 +12,8 @@ class ProjectsDirty { - private static ProjectListListener projectListListener = new ProjectListListener(); - private static ArrayList listeners = new ArrayList<>(); + private static final ProjectListListener projectListListener = new ProjectListListener(); + private static final ArrayList listeners = new ArrayList<>(); private ProjectsDirty() { } diff --git a/src/main/java/com/cburch/logisim/file/ReaderInputStream.java b/src/main/java/com/cburch/logisim/file/ReaderInputStream.java index 9439226..c4f4dae 100644 --- a/src/main/java/com/cburch/logisim/file/ReaderInputStream.java +++ b/src/main/java/com/cburch/logisim/file/ReaderInputStream.java @@ -109,7 +109,7 @@ public synchronized int read() throws IOException { */ @Override public synchronized int read(byte[] bytes, int offset, int length) - throws IOException { + throws IOException { if (in == null) { throw new IOException("Stream Closed"); } @@ -210,4 +210,4 @@ public synchronized void close() throws IOException { in = null; } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/file/Strings.java b/src/main/java/com/cburch/logisim/file/Strings.java index a77d22d..548c338 100644 --- a/src/main/java/com/cburch/logisim/file/Strings.java +++ b/src/main/java/com/cburch/logisim/file/Strings.java @@ -9,8 +9,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "file"); + private static final LocaleManager source = new LocaleManager("logisim", "file"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/file/ToolbarData.java b/src/main/java/com/cburch/logisim/file/ToolbarData.java index 6ff66f5..cf5d8c2 100644 --- a/src/main/java/com/cburch/logisim/file/ToolbarData.java +++ b/src/main/java/com/cburch/logisim/file/ToolbarData.java @@ -16,9 +16,9 @@ public class ToolbarData { - private EventSourceWeakSupport listeners; - private EventSourceWeakSupport toolListeners; - private ArrayList contents; + private final EventSourceWeakSupport listeners; + private final EventSourceWeakSupport toolListeners; + private final ArrayList contents; public ToolbarData() { listeners = new EventSourceWeakSupport<>(); @@ -62,26 +62,26 @@ public void removeToolAttributeListener(AttributeListener l) { } private void addAttributeListeners(Tool tool) { - for (AttributeListener l : toolListeners) { + for (AttributeListener listener : toolListeners) { AttributeSet attrs = tool.getAttributeSet(); if (attrs != null) { - attrs.addAttributeListener(l); + attrs.addAttributeListener(listener); } } } private void removeAttributeListeners(Tool tool) { - for (AttributeListener l : toolListeners) { + for (AttributeListener listener : toolListeners) { AttributeSet attrs = tool.getAttributeSet(); if (attrs != null) { - attrs.removeAttributeListener(l); + attrs.removeAttributeListener(listener); } } } public void fireToolbarChanged() { - for (ToolbarListener l : listeners) { - l.toolbarChanged(); + for (ToolbarListener listener : listeners) { + listener.toolbarChanged(); } } @@ -130,7 +130,7 @@ public void copyFrom(ToolbarData other, LogisimFile file) { if (toolCopy != null) { Tool dstTool = toolCopy.cloneTool(); AttributeSets.copy(srcTool.getAttributeSet(), - dstTool.getAttributeSet()); + dstTool.getAttributeSet()); this.addTool(dstTool); addAttributeListeners(toolCopy); } @@ -169,9 +169,9 @@ public Object move(int from, int to) { } public Object remove(int pos) { - Object ret = contents.remove(pos); - if (ret instanceof Tool) { - removeAttributeListeners((Tool) ret); + Tool ret = contents.remove(pos); + if (ret != null) { + removeAttributeListeners(ret); } fireToolbarChanged(); return ret; @@ -192,18 +192,17 @@ boolean usesToolFromSource(Tool query) { void replaceAll(Map toolMap) { boolean changed = false; for (ListIterator it = contents.listIterator(); it.hasNext(); ) { - Object old = it.next(); + Tool old = it.next(); if (toolMap.containsKey(old)) { changed = true; - removeAttributeListeners((Tool) old); + removeAttributeListeners(old); Tool newTool = toolMap.get(old); if (newTool == null) { it.remove(); } else { Tool addedTool = newTool.cloneTool(); addAttributeListeners(addedTool); - LoadedLibrary.copyAttributes(addedTool.getAttributeSet(), - ((Tool) old).getAttributeSet()); + LoadedLibrary.copyAttributes(addedTool.getAttributeSet(), old.getAttributeSet()); it.set(addedTool); } } diff --git a/src/main/java/com/cburch/logisim/file/XmlCircuitReader.java b/src/main/java/com/cburch/logisim/file/XmlCircuitReader.java index 8abcb99..6269066 100644 --- a/src/main/java/com/cburch/logisim/file/XmlCircuitReader.java +++ b/src/main/java/com/cburch/logisim/file/XmlCircuitReader.java @@ -23,17 +23,17 @@ public class XmlCircuitReader extends CircuitTransaction { - private XmlReader.ReadContext reader; - private List circuitsData; + private final XmlReader.ReadContext reader; + private final List circuitsData; public XmlCircuitReader(XmlReader.ReadContext reader, - List circDatas) { + List circDatas) { this.reader = reader; this.circuitsData = circDatas; } static Component getComponent(Element elt, XmlReader.ReadContext reader) - throws XmlReaderException { + throws XmlReaderException { // Determine the factory that creates this element String name = elt.getAttribute("name"); if (name == null || name.equals("")) { @@ -47,7 +47,7 @@ static Component getComponent(Element elt, XmlReader.ReadContext reader) } Tool tool = lib.getTool(name); - if (tool == null || !(tool instanceof AddTool)) { + if (!(tool instanceof AddTool)) { if (libName == null || libName.equals("")) { throw new XmlReaderException(Strings.get("compUnknownError", name)); } else { @@ -70,7 +70,7 @@ static Component getComponent(Element elt, XmlReader.ReadContext reader) return source.createComponent(loc, attrs); } catch (NumberFormatException e) { throw new XmlReaderException(Strings.get("compLocInvalidError", - source.getName(), loc_str)); + source.getName(), loc_str)); } } } @@ -92,19 +92,19 @@ protected void run(CircuitMutator mutator) { } private void buildCircuit(XmlReader.CircuitData circData, CircuitMutator mutator) { - Element elt = circData.circuitElement; - Circuit dest = circData.circuit; + Element element = circData.circuitElement; + Circuit destination = circData.circuit; Map knownComponents = circData.knownComponents; if (knownComponents == null) { knownComponents = Collections.emptyMap(); } try { - reader.initAttributeSet(circData.circuitElement, dest.getStaticAttributes(), null); + reader.initAttributeSet(circData.circuitElement, destination.getStaticAttributes(), null); } catch (XmlReaderException e) { reader.addErrors(e, circData.circuit.getName() + ".static"); } - for (Element sub_elt : XmlIterator.forChildElements(elt)) { + for (Element sub_elt : XmlIterator.forChildElements(element)) { String sub_elt_name = sub_elt.getTagName(); if (sub_elt_name.equals("comp")) { try { @@ -112,13 +112,13 @@ private void buildCircuit(XmlReader.CircuitData circData, CircuitMutator mutator if (comp == null) { comp = getComponent(sub_elt, reader); } - mutator.add(dest, comp); + mutator.add(destination, comp); } catch (XmlReaderException e) { reader.addErrors(e, circData.circuit.getName() + "." + toComponentString(sub_elt)); } } else if (sub_elt_name.equals("wire")) { try { - addWire(dest, mutator, sub_elt); + addWire(destination, mutator, sub_elt); } catch (XmlReaderException e) { reader.addErrors(e, circData.circuit.getName() + "." + toWireString(sub_elt)); } @@ -127,15 +127,15 @@ private void buildCircuit(XmlReader.CircuitData circData, CircuitMutator mutator List appearance = circData.appearance; if (appearance != null && !appearance.isEmpty()) { - dest.getAppearance().setObjectsForce(appearance); - dest.getAppearance().setDefaultAppearance(false); + destination.getAppearance().setObjectsForce(appearance); + destination.getAppearance().setDefaultAppearance(false); } } private String toComponentString(Element elt) { String name = elt.getAttribute("name"); - String loc = elt.getAttribute("loc"); - return name + "(" + loc + ")"; + String location = elt.getAttribute("loc"); + return name + "(" + location + ")"; } private String toWireString(Element elt) { @@ -145,7 +145,7 @@ private String toWireString(Element elt) { } void addWire(Circuit dest, CircuitMutator mutator, Element elt) - throws XmlReaderException { + throws XmlReaderException { Location pt0; try { String str = elt.getAttribute("from"); diff --git a/src/main/java/com/cburch/logisim/file/XmlIterator.java b/src/main/java/com/cburch/logisim/file/XmlIterator.java index 7941dfa..58257ce 100644 --- a/src/main/java/com/cburch/logisim/file/XmlIterator.java +++ b/src/main/java/com/cburch/logisim/file/XmlIterator.java @@ -12,7 +12,7 @@ public class XmlIterator implements Iterable, Iterator, Cloneable { - private NodeList list; + private final NodeList list; private int index; public XmlIterator(NodeList nodes) { diff --git a/src/main/java/com/cburch/logisim/file/XmlReader.java b/src/main/java/com/cburch/logisim/file/XmlReader.java index 43afd1f..a17e636 100644 --- a/src/main/java/com/cburch/logisim/file/XmlReader.java +++ b/src/main/java/com/cburch/logisim/file/XmlReader.java @@ -34,14 +34,14 @@ class XmlReader { - private LibraryLoader loader; + private final LibraryLoader loader; XmlReader(Loader loader) { this.loader = loader; } private static void findLibraryUses(ArrayList destinations, String label, - Iterable candidates) { + Iterable candidates) { for (Element elements : candidates) { String lib = elements.getAttribute("lib"); if (lib.equals(label)) { @@ -201,9 +201,9 @@ private void repairForWiringLibrary(Document document, Element root) { HashMap labelMap = new HashMap<>(); addToLabelMap(labelMap, oldBaseLabel, newBaseLabel, "Poke Tool;" - + "Edit Tool;Select Tool;Wiring Tool;Text Tool;Menu Tool;Text"); + + "Edit Tool;Select Tool;Wiring Tool;Text Tool;Menu Tool;Text"); addToLabelMap(labelMap, oldBaseLabel, wiringLabel, "Splitter;Pin;" - + "Probe;Tunnel;Clock;Pull Resistor;Bit Extender"); + + "Probe;Tunnel;Clock;Pull Resistor;Bit Extender"); addToLabelMap(labelMap, gatesLabel, wiringLabel, "Constant"); relocateTools(oldBaseElement, newBaseElement, labelMap); relocateTools(oldBaseElement, wiringElement, labelMap); @@ -213,7 +213,7 @@ private void repairForWiringLibrary(Document document, Element root) { } private void addToLabelMap(HashMap labelMap, String sourceLabel, - String destinationLabel, String toolNames) { + String destinationLabel, String toolNames) { if (sourceLabel != null && destinationLabel != null) { for (String tool : toolNames.split(";")) { labelMap.put(sourceLabel + ":" + tool, destinationLabel); @@ -275,16 +275,16 @@ private void repairForLegacyLibrary(Document document, Element root) { ArrayList elementsToRemove = new ArrayList<>(); findLibraryUses(elementsToRemove, legacyLabel, - XmlIterator.forDescendantElements(root, "comp")); + XmlIterator.forDescendantElements(root, "comp")); boolean componentsRemoved = !elementsToRemove.isEmpty(); findLibraryUses(elementsToRemove, legacyLabel, - XmlIterator.forDescendantElements(root, "tool")); + XmlIterator.forDescendantElements(root, "tool")); for (Element elt : elementsToRemove) { elt.getParentNode().removeChild(elt); } if (componentsRemoved) { String error = "Some components have been deleted;" - + " the Legacy library is no longer supported."; + + " the Legacy library is no longer supported."; Element element = document.createElement("message"); element.setAttribute("value", error); root.appendChild(element); @@ -307,10 +307,10 @@ public CircuitData(Element circuitElement, Circuit circuit) { class ReadContext { - private LogisimFile file; + private final LogisimFile file; private LogisimVersion sourceVersion; - private HashMap libraries = new HashMap<>(); - private ArrayList messages; + private final HashMap libraries = new HashMap<>(); + private final ArrayList messages; private ReadContext(LogisimFile file) { this.file = file; @@ -448,7 +448,7 @@ private Map loadKnownComponents(Element elt) { } private void loadAppearance(Element appearElt, CircuitData circData, - String context) { + String context) { Map pins = new HashMap<>(); for (Component comp : circData.knownComponents.values()) { if (comp.getFactory() == Pin.FACTORY) { @@ -463,13 +463,13 @@ private void loadAppearance(Element appearElt, CircuitData circData, AbstractCanvasObject m = AppearanceSvgReader.createShape(sub, pins); if (m == null) { addError(Strings.get("fileAppearanceNotFound", sub.getTagName()), - context + "." + sub.getTagName()); + context + "." + sub.getTagName()); } else { shapes.add(m); } } catch (RuntimeException e) { addError(Strings.get("fileAppearanceError", sub.getTagName()), - context + "." + sub.getTagName()); + context + "." + sub.getTagName()); } } if (!shapes.isEmpty()) { @@ -502,7 +502,7 @@ private void initMouseMappings(Element elt) { mods = InputEventUtil.fromString(mods_str); } catch (NumberFormatException e) { loader.showError(StringUtil.format( - Strings.get("mappingBadError"), mods_str)); + Strings.get("mappingBadError"), mods_str)); continue; } @@ -557,7 +557,7 @@ private Tool toTool(Element elt) throws XmlReaderException { } void initAttributeSet(Element parentElt, AttributeSet attrs, - AttributeDefaultProvider defaults) throws XmlReaderException { + AttributeDefaultProvider defaults) throws XmlReaderException { ArrayList messages = null; HashMap attrsDefined = new HashMap<>(); @@ -585,7 +585,7 @@ void initAttributeSet(Element parentElt, AttributeSet attrs, LogisimVersion ver = sourceVersion; boolean setDefaults = defaults != null - && !defaults.isAllDefaultValues(attrs, ver); + && !defaults.isAllDefaultValues(attrs, ver); // We need to process this in order, and we have to refetch the // attribute list each time because it may change as we iterate // (as it will for a splitter). @@ -614,8 +614,8 @@ void initAttributeSet(Element parentElt, AttributeSet attrs, messages = new ArrayList<>(); } messages.add(StringUtil.format( - Strings.get("attrValueInvalidError"), - attrVal, attrName)); + Strings.get("attrValueInvalidError"), + attrVal, attrName)); } } } @@ -632,7 +632,7 @@ Library findLibrary(String lib_name) throws XmlReaderException { Library ret = libraries.get(lib_name); if (ret == null) { throw new XmlReaderException(StringUtil.format( - Strings.get("libMissingError"), lib_name)); + Strings.get("libMissingError"), lib_name)); } else { return ret; } diff --git a/src/main/java/com/cburch/logisim/file/XmlReaderException.java b/src/main/java/com/cburch/logisim/file/XmlReaderException.java index ccd84ab..eab3296 100644 --- a/src/main/java/com/cburch/logisim/file/XmlReaderException.java +++ b/src/main/java/com/cburch/logisim/file/XmlReaderException.java @@ -8,7 +8,7 @@ class XmlReaderException extends Exception { - private List messages; + private final List messages; public XmlReaderException(String message) { this(Collections.singletonList(message)); diff --git a/src/main/java/com/cburch/logisim/file/XmlWriter.java b/src/main/java/com/cburch/logisim/file/XmlWriter.java index f4b86ce..d2f4fe5 100644 --- a/src/main/java/com/cburch/logisim/file/XmlWriter.java +++ b/src/main/java/com/cburch/logisim/file/XmlWriter.java @@ -36,10 +36,10 @@ class XmlWriter { - private LogisimFile file; - private Document document; - private LibraryLoader libraryLoader; - private HashMap libraries = new HashMap<>(); + private final LogisimFile file; + private final Document document; + private final LibraryLoader libraryLoader; + private final HashMap libraries = new HashMap<>(); private XmlWriter(LogisimFile file, Document document, LibraryLoader libraryLoader) { this.file = file; @@ -48,8 +48,8 @@ private XmlWriter(LogisimFile file, Document document, LibraryLoader libraryLoad } static void write(LogisimFile file, OutputStream outputStream, LibraryLoader libraryLoader) - throws ParserConfigurationException, - TransformerException { + throws ParserConfigurationException, + TransformerException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); @@ -80,7 +80,8 @@ static void write(LogisimFile file, OutputStream outputStream, LibraryLoader lib private Element fromLogisimFile() { Element element = document.createElement("project"); document.appendChild(element); - element.appendChild(document.createTextNode("\nThis file is intended to be loaded by Logisim (http://www.cburch.com/logisim/).\n")); + element.appendChild( + document.createTextNode("\nThis file is intended to be loaded by Logisim (http://www.cburch.com/logisim/).\n")); element.setAttribute("version", "1.0"); element.setAttribute("source", Main.VERSION_NAME); @@ -115,8 +116,7 @@ Element fromLibrary(Library lib) { String name = "" + libraries.size(); String desc = libraryLoader.getDescriptor(lib); if (desc == null) { - libraryLoader.showError("library location unknown: " - + lib.getName()); + libraryLoader.showError("library location unknown: " + lib.getName()); return null; } libraries.put(lib, name); @@ -175,7 +175,7 @@ private Element fromTool(Tool tool) { String libraryName; if (library == null) { libraryLoader.showError(StringUtil.format("tool `%s' not found", - tool.getDisplayName())); + tool.getDisplayName())); return null; } else if (library == file) { libraryName = null; @@ -259,7 +259,7 @@ private Element fromWire(Wire wire) { } private void addAttributeSetContent(Element element, AttributeSet attributes, - AttributeDefaultProvider source) { + AttributeDefaultProvider source) { if (attributes == null) { return; } diff --git a/src/main/java/com/cburch/logisim/gui/appear/AppearanceCanvas.java b/src/main/java/com/cburch/logisim/gui/appear/AppearanceCanvas.java index 24258fc..d925614 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/AppearanceCanvas.java +++ b/src/main/java/com/cburch/logisim/gui/appear/AppearanceCanvas.java @@ -34,17 +34,17 @@ import javax.swing.JPopupMenu; public class AppearanceCanvas extends Canvas - implements CanvasPaneContents, ActionDispatcher { + implements CanvasPaneContents, ActionDispatcher { private static final int BOUNDS_BUFFER = 70; // pixels shown in canvas beyond outermost boundaries private static final int THRESH_SIZE_UPDATE = 10; // don't bother to update the size if it hasn't changed more than this - private CanvasTool selectTool; + private final CanvasTool selectTool; + private final Listener listener; + private final GridPainter grid; private Project proj; private CircuitState circuitState; - private Listener listener; - private GridPainter grid; private CanvasPane canvasPane; private Bounds oldPreferredSize; private LayoutPopupManager popupManager; @@ -176,7 +176,7 @@ public void doAction(Action canvasAction) { int max = getMaxIndex(getModel()); if (cur > max) { canvasAction = new ModelAddAction(getModel(), - addAction.getObjects(), max + 1); + addAction.getObjects(), max + 1); } } @@ -297,8 +297,8 @@ private void computeSize(boolean immediate) { if (!immediate) { Bounds old = oldPreferredSize; if (old != null - && Math.abs(old.getWidth() - dim.width) < THRESH_SIZE_UPDATE - && Math.abs(old.getHeight() - dim.height) < THRESH_SIZE_UPDATE) { + && Math.abs(old.getWidth() - dim.width) < THRESH_SIZE_UPDATE + && Math.abs(old.getHeight() - dim.height) < THRESH_SIZE_UPDATE) { return; } } @@ -326,7 +326,7 @@ public Dimension getPreferredScrollableViewportSize() { } public int getScrollableBlockIncrement(Rectangle visibleRect, - int orientation, int direction) { + int orientation, int direction) { return canvasPane.supportScrollableBlockIncrement(visibleRect, orientation, direction); } @@ -339,12 +339,12 @@ public boolean getScrollableTracksViewportWidth() { } public int getScrollableUnitIncrement(Rectangle visibleRect, - int orientation, int direction) { + int orientation, int direction) { return canvasPane.supportScrollableUnitIncrement(visibleRect, orientation, direction); } private class Listener - implements CanvasModelListener, PropertyChangeListener { + implements CanvasModelListener, PropertyChangeListener { public void modelChanged(CanvasModelEvent event) { computeSize(false); diff --git a/src/main/java/com/cburch/logisim/gui/appear/AppearanceEditHandler.java b/src/main/java/com/cburch/logisim/gui/appear/AppearanceEditHandler.java index 7e28c9d..7a60cc0 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/AppearanceEditHandler.java +++ b/src/main/java/com/cburch/logisim/gui/appear/AppearanceEditHandler.java @@ -32,10 +32,10 @@ import java.util.List; import java.util.Map; -public class AppearanceEditHandler extends EditHandler - implements SelectionListener, PropertyChangeListener, CanvasModelListener { +public class AppearanceEditHandler extends EditHandler implements SelectionListener, PropertyChangeListener, + CanvasModelListener { - private AppearanceCanvas canvas; + private final AppearanceCanvas canvas; AppearanceEditHandler(AppearanceCanvas canvas) { this.canvas = canvas; @@ -65,7 +65,7 @@ public void computeEnabled() { boolean canLower; if (!selEmpty && canChange) { Map zs = ZOrder.getZIndex(sel.getSelected(), - canvas.getModel()); + canvas.getModel()); int zmin = Integer.MAX_VALUE; int zmax = Integer.MIN_VALUE; int count = 0; @@ -173,8 +173,8 @@ public void paste() { } canvas.getProject().doAction(new SelectionAction(canvas, - Strings.getter("pasteClipboardAction"), null, add, add, - anchorLocation, clip.getAnchorFacing())); + Strings.getter("pasteClipboardAction"), null, add, add, + anchorLocation, clip.getAnchorFacing())); } @Override @@ -200,8 +200,8 @@ public void delete() { if (!remove.isEmpty()) { canvas.getProject().doAction(new SelectionAction(canvas, - Strings.getter("deleteSelectionAction"), remove, null, select, - anchorLocation, anchorFacing)); + Strings.getter("deleteSelectionAction"), remove, null, select, + anchorLocation, anchorFacing)); } } @@ -224,8 +224,8 @@ public void duplicate() { if (!clones.isEmpty()) { canvas.getProject().doAction(new SelectionAction(canvas, - Strings.getter("duplicateSelectionAction"), null, clones, select, - null, null)); + Strings.getter("duplicateSelectionAction"), null, clones, select, + null, null)); } } @@ -239,7 +239,7 @@ public void selectAll() { @Override public void raise() { ModelReorderAction act = ModelReorderAction.createRaise(canvas.getModel(), - canvas.getSelection().getSelected()); + canvas.getSelection().getSelected()); if (act != null) { canvas.doAction(act); } @@ -248,7 +248,7 @@ public void raise() { @Override public void lower() { ModelReorderAction act = ModelReorderAction.createLower(canvas.getModel(), - canvas.getSelection().getSelected()); + canvas.getSelection().getSelected()); if (act != null) { canvas.doAction(act); } @@ -257,7 +257,7 @@ public void lower() { @Override public void raiseTop() { ModelReorderAction act = ModelReorderAction.createRaiseTop(canvas.getModel(), - canvas.getSelection().getSelected()); + canvas.getSelection().getSelected()); if (act != null) { canvas.doAction(act); } @@ -266,7 +266,7 @@ public void raiseTop() { @Override public void lowerBottom() { ModelReorderAction act = ModelReorderAction.createLowerBottom(canvas.getModel(), - canvas.getSelection().getSelected()); + canvas.getSelection().getSelected()); if (act != null) { canvas.doAction(act); } diff --git a/src/main/java/com/cburch/logisim/gui/appear/AppearanceEditPopup.java b/src/main/java/com/cburch/logisim/gui/appear/AppearanceEditPopup.java index b098633..ea104a9 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/AppearanceEditPopup.java +++ b/src/main/java/com/cburch/logisim/gui/appear/AppearanceEditPopup.java @@ -12,9 +12,9 @@ public class AppearanceEditPopup extends EditPopup implements EditHandler.Listener { - private AppearanceCanvas canvas; - private EditHandler handler; - private Map enabled; + private final AppearanceCanvas canvas; + private final EditHandler handler; + private final Map enabled; public AppearanceEditPopup(AppearanceCanvas canvas) { super(true); @@ -27,7 +27,7 @@ public AppearanceEditPopup(AppearanceCanvas canvas) { } public void enableChanged(EditHandler handler, LogisimMenuItem action, - boolean value) { + boolean value) { enabled.put(action, value); } diff --git a/src/main/java/com/cburch/logisim/gui/appear/AppearanceToolbarModel.java b/src/main/java/com/cburch/logisim/gui/appear/AppearanceToolbarModel.java index 01750c9..0d526ea 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/AppearanceToolbarModel.java +++ b/src/main/java/com/cburch/logisim/gui/appear/AppearanceToolbarModel.java @@ -23,25 +23,25 @@ import java.util.List; class AppearanceToolbarModel extends AbstractToolbarModel - implements PropertyChangeListener { + implements PropertyChangeListener { - private Canvas canvas; - private List items; + private final Canvas canvas; + private final List items; public AppearanceToolbarModel(AbstractTool selectTool, Canvas canvas, - DrawingAttributeSet attrs) { + DrawingAttributeSet attrs) { this.canvas = canvas; AbstractTool[] tools = { - selectTool, - new TextTool(attrs), - new LineTool(attrs), - new CurveTool(attrs), - new PolyTool(false, attrs), - new RectangleTool(attrs), - new RoundRectangleTool(attrs), - new OvalTool(attrs), - new PolyTool(true, attrs), + selectTool, + new TextTool(attrs), + new LineTool(attrs), + new CurveTool(attrs), + new PolyTool(false, attrs), + new RectangleTool(attrs), + new RoundRectangleTool(attrs), + new OvalTool(attrs), + new PolyTool(true, attrs), }; ArrayList rawItems = new ArrayList<>(); diff --git a/src/main/java/com/cburch/logisim/gui/appear/AppearanceView.java b/src/main/java/com/cburch/logisim/gui/appear/AppearanceView.java index 7c3981f..53adbdf 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/AppearanceView.java +++ b/src/main/java/com/cburch/logisim/gui/appear/AppearanceView.java @@ -22,13 +22,13 @@ public class AppearanceView { private static final double[] ZOOM_OPTIONS = {100, 150, 200, 300, 400, 600, 800}; - private DrawingAttributeSet attrs; - private AppearanceCanvas canvas; - private CanvasPane canvasPane; - private AppearanceToolbarModel toolbarModel; + private final DrawingAttributeSet attrs; + private final AppearanceCanvas canvas; + private final CanvasPane canvasPane; + private final AppearanceToolbarModel toolbarModel; private AttrTableDrawManager attrTableManager; - private ZoomModel zoomModel; - private AppearanceEditHandler editHandler; + private final ZoomModel zoomModel; + private final AppearanceEditHandler editHandler; public AppearanceView() { attrs = new DrawingAttributeSet(); @@ -36,7 +36,7 @@ public AppearanceView() { canvas = new AppearanceCanvas(selectTool); toolbarModel = new AppearanceToolbarModel(selectTool, canvas, attrs); zoomModel = new BasicZoomModel(AppPreferences.APPEARANCE_SHOW_GRID, - AppPreferences.APPEARANCE_ZOOM, ZOOM_OPTIONS); + AppPreferences.APPEARANCE_ZOOM, ZOOM_OPTIONS); canvas.getGridPainter().setZoomModel(zoomModel); attrTableManager = null; canvasPane = new CanvasPane(canvas); diff --git a/src/main/java/com/cburch/logisim/gui/appear/CanvasActionAdapter.java b/src/main/java/com/cburch/logisim/gui/appear/CanvasActionAdapter.java index dea1400..1ea86b7 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/CanvasActionAdapter.java +++ b/src/main/java/com/cburch/logisim/gui/appear/CanvasActionAdapter.java @@ -16,8 +16,8 @@ public class CanvasActionAdapter extends com.cburch.logisim.proj.Action { - private Circuit circuit; - private Action canvasAction; + private final Circuit circuit; + private final Action canvasAction; private boolean wasDefault; public CanvasActionAdapter(Circuit circuit, Action action) { @@ -65,7 +65,7 @@ private boolean affectsPorts() { private class ActionTransaction extends CircuitTransaction { - private boolean forward; + private final boolean forward; private ActionTransaction(boolean forward) { this.forward = forward; diff --git a/src/main/java/com/cburch/logisim/gui/appear/Clipboard.java b/src/main/java/com/cburch/logisim/gui/appear/Clipboard.java index 7718154..51168fe 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/Clipboard.java +++ b/src/main/java/com/cburch/logisim/gui/appear/Clipboard.java @@ -10,8 +10,7 @@ class Clipboard { public static final String contentsProperty = "appearance"; private static ClipboardContents current = ClipboardContents.EMPTY; - private static PropertyChangeWeakSupport propertySupport - = new PropertyChangeWeakSupport(Clipboard.class); + private static final PropertyChangeWeakSupport propertySupport = new PropertyChangeWeakSupport(Clipboard.class); private Clipboard() { } diff --git a/src/main/java/com/cburch/logisim/gui/appear/ClipboardActions.java b/src/main/java/com/cburch/logisim/gui/appear/ClipboardActions.java index daf99bd..195ee66 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/ClipboardActions.java +++ b/src/main/java/com/cburch/logisim/gui/appear/ClipboardActions.java @@ -16,12 +16,12 @@ public class ClipboardActions extends Action { - private boolean remove; - private AppearanceCanvas canvas; - private CanvasModel canvasModel; + private final boolean remove; + private final AppearanceCanvas canvas; + private final CanvasModel canvasModel; + private final Map affected; + private final ClipboardContents newClipboard; private ClipboardContents oldClipboard; - private Map affected; - private ClipboardContents newClipboard; private ClipboardActions(boolean remove, AppearanceCanvas canvas) { this.remove = remove; diff --git a/src/main/java/com/cburch/logisim/gui/appear/ClipboardContents.java b/src/main/java/com/cburch/logisim/gui/appear/ClipboardContents.java index 4e7387c..7a610cd 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/ClipboardContents.java +++ b/src/main/java/com/cburch/logisim/gui/appear/ClipboardContents.java @@ -12,15 +12,14 @@ class ClipboardContents { - static final ClipboardContents EMPTY - = new ClipboardContents(Collections.emptySet(), null, null); + static final ClipboardContents EMPTY = new ClipboardContents(Collections.emptySet(), null, null); - private Collection onClipboard; - private Location anchorLocation; - private Direction anchorFacing; + private final Collection onClipboard; + private final Location anchorLocation; + private final Direction anchorFacing; public ClipboardContents(Collection onClipboard, - Location anchorLocation, Direction anchorFacing) { + Location anchorLocation, Direction anchorFacing) { this.onClipboard = Collections.unmodifiableList(new ArrayList<>(onClipboard)); this.anchorLocation = anchorLocation; this.anchorFacing = anchorFacing; diff --git a/src/main/java/com/cburch/logisim/gui/appear/LayoutPopupManager.java b/src/main/java/com/cburch/logisim/gui/appear/LayoutPopupManager.java index 467a69f..c580b66 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/LayoutPopupManager.java +++ b/src/main/java/com/cburch/logisim/gui/appear/LayoutPopupManager.java @@ -26,8 +26,8 @@ class LayoutPopupManager implements SelectionListener, MouseListener, MouseMotionListener { - private CanvasPane canvasPane; - private AppearanceCanvas canvas; + private final CanvasPane canvasPane; + private final AppearanceCanvas canvas; private Popup curPopup; private long curPopupTime; private Location dragStart; diff --git a/src/main/java/com/cburch/logisim/gui/appear/LayoutThumbnail.java b/src/main/java/com/cburch/logisim/gui/appear/LayoutThumbnail.java index d32c21f..6471682 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/LayoutThumbnail.java +++ b/src/main/java/com/cburch/logisim/gui/appear/LayoutThumbnail.java @@ -34,7 +34,7 @@ public LayoutThumbnail() { } public void setCircuit(CircuitState circuitState, - Collection ports) { + Collection ports) { this.circuitState = circuitState; this.ports = ports; repaint(); @@ -60,7 +60,7 @@ protected void paintComponent(Graphics g) { gCopy.translate(-bds.getX(), -bds.getY()); ComponentDrawContext context = new ComponentDrawContext(this, circuit, - circuitState, g, gCopy); + circuitState, g, gCopy); context.setShowState(false); context.setShowColor(false); circuit.draw(context, Collections.emptySet()); diff --git a/src/main/java/com/cburch/logisim/gui/appear/RevertAppearanceAction.java b/src/main/java/com/cburch/logisim/gui/appear/RevertAppearanceAction.java index e429431..38c2b58 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/RevertAppearanceAction.java +++ b/src/main/java/com/cburch/logisim/gui/appear/RevertAppearanceAction.java @@ -12,7 +12,7 @@ public class RevertAppearanceAction extends Action { - private Circuit circuit; + private final Circuit circuit; private ArrayList old; private boolean wasDefault; diff --git a/src/main/java/com/cburch/logisim/gui/appear/SelectionAction.java b/src/main/java/com/cburch/logisim/gui/appear/SelectionAction.java index 65c85db..d4680dc 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/SelectionAction.java +++ b/src/main/java/com/cburch/logisim/gui/appear/SelectionAction.java @@ -19,22 +19,22 @@ class SelectionAction extends Action { - private StringGetter displayName; - private AppearanceCanvas canvas; - private CanvasModel canvasModel; - private Map toRemove; - private Collection toAdd; - private Collection oldSelection; - private Collection newSelection; - private Location anchorNewLocation; - private Direction anchorNewFacing; + private final StringGetter displayName; + private final AppearanceCanvas canvas; + private final CanvasModel canvasModel; + private final Map toRemove; + private final Collection toAdd; + private final Collection oldSelection; + private final Collection newSelection; + private final Location anchorNewLocation; + private final Direction anchorNewFacing; private Location anchorOldLocation; private Direction anchorOldFacing; public SelectionAction(AppearanceCanvas canvas, StringGetter displayName, - Collection toRemove, Collection toAdd, - Collection newSelection, Location anchorLocation, - Direction anchorFacing) { + Collection toRemove, Collection toAdd, + Collection newSelection, Location anchorLocation, + Direction anchorFacing) { this.canvas = canvas; this.canvasModel = canvas.getModel(); this.displayName = displayName; @@ -67,7 +67,7 @@ public void doIt(Project proj) { if (anchor != null && anchorNewLocation != null) { anchorOldLocation = anchor.getLocation(); anchor.translate(anchorNewLocation.getX() - anchorOldLocation.getX(), - anchorNewLocation.getY() - anchorOldLocation.getY()); + anchorNewLocation.getY() - anchorOldLocation.getY()); } if (anchor != null && anchorNewFacing != null) { anchorOldFacing = anchor.getFacing(); @@ -91,7 +91,7 @@ public void undo(Project proj) { AppearanceAnchor anchor = findAnchor(canvasModel); if (anchor != null && anchorOldLocation != null) { anchor.translate(anchorOldLocation.getX() - anchorNewLocation.getX(), - anchorOldLocation.getY() - anchorNewLocation.getY()); + anchorOldLocation.getY() - anchorNewLocation.getY()); } if (anchor != null && anchorOldFacing != null) { anchor.setValue(AppearanceAnchor.FACING, anchorOldFacing); diff --git a/src/main/java/com/cburch/logisim/gui/appear/Strings.java b/src/main/java/com/cburch/logisim/gui/appear/Strings.java index 1dbeb7d..6bafdd2 100644 --- a/src/main/java/com/cburch/logisim/gui/appear/Strings.java +++ b/src/main/java/com/cburch/logisim/gui/appear/Strings.java @@ -10,8 +10,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "gui"); + private static final LocaleManager source = new LocaleManager("logisim", "gui"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/gui/generic/AttrTable.java b/src/main/java/com/cburch/logisim/gui/generic/AttrTable.java index fdfe139..52b7373 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/AttrTable.java +++ b/src/main/java/com/cburch/logisim/gui/generic/AttrTable.java @@ -42,12 +42,12 @@ public class AttrTable extends JPanel implements LocaleListener { private static final AttrTableModel NULL_ATTR_MODEL = new NullAttrModel(); - private Window parent; + private final Window parent; + private final JLabel title; + private final JTable table; + private final TableModelAdapter tableModel; + private final CellEditor editor = new CellEditor(); private boolean titleEnabled; - private JLabel title; - private JTable table; - private TableModelAdapter tableModel; - private CellEditor editor = new CellEditor(); public AttrTable(Window parent) { super(new BorderLayout()); @@ -191,7 +191,7 @@ public Object getValue() { } private class TableModelAdapter - implements TableModel, AttrTableModelListener { + implements TableModel, AttrTableModelListener { Window parent; LinkedList listeners; @@ -264,14 +264,14 @@ public boolean isCellEditable(int rowIndex, int columnIndex) { } public void setValueAt(Object value, int rowIndex, - int columnIndex) { + int columnIndex) { if (columnIndex > 0) { try { attrModel.getRow(rowIndex).setValue(value); } catch (AttrTableSetException e) { JOptionPane.showMessageDialog(parent, e.getMessage(), - Strings.get("attributeChangeInvalidTitle"), - JOptionPane.WARNING_MESSAGE); + Strings.get("attributeChangeInvalidTitle"), + JOptionPane.WARNING_MESSAGE); } } } @@ -307,7 +307,7 @@ public void attrValueChanged(AttrTableModelEvent e) { int row = e.getRowIndex(); TableCellEditor ed = table.getCellEditor(); if (row >= 0 && ed instanceof CellEditor - && attrModel.getRow(row) == ((CellEditor) ed).currentRow) { + && attrModel.getRow(row) == ((CellEditor) ed).currentRow) { ed.cancelCellEditing(); } fireTableChanged(); @@ -315,7 +315,7 @@ public void attrValueChanged(AttrTableModelEvent e) { } private class CellEditor - implements TableCellEditor, FocusListener, ActionListener { + implements TableCellEditor, FocusListener, ActionListener { LinkedList listeners = new LinkedList<>(); AttrTableModelRow currentRow; @@ -389,7 +389,7 @@ public boolean shouldSelectCell(EventObject anEvent) { } public Component getTableCellEditorComponent(JTable table, Object value, - boolean isSelected, int rowIndex, int columnIndex) { + boolean isSelected, int rowIndex, int columnIndex) { AttrTableModel attrModel = tableModel.attrModel; AttrTableModelRow row = attrModel.getRow(rowIndex); @@ -419,8 +419,8 @@ public Component getTableCellEditorComponent(JTable table, Object value, row.setValue(retval); } catch (AttrTableSetException e) { JOptionPane.showMessageDialog(parent, e.getMessage(), - Strings.get("attributeChangeInvalidTitle"), - JOptionPane.WARNING_MESSAGE); + Strings.get("attributeChangeInvalidTitle"), + JOptionPane.WARNING_MESSAGE); } editor = new JLabel(row.getValue()); } else { diff --git a/src/main/java/com/cburch/logisim/gui/generic/AttrTableModelEvent.java b/src/main/java/com/cburch/logisim/gui/generic/AttrTableModelEvent.java index 9ab2222..a0390f0 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/AttrTableModelEvent.java +++ b/src/main/java/com/cburch/logisim/gui/generic/AttrTableModelEvent.java @@ -5,8 +5,8 @@ public class AttrTableModelEvent { - private AttrTableModel model; - private int index; + private final AttrTableModel model; + private final int index; public AttrTableModelEvent(AttrTableModel model) { this(model, -1); diff --git a/src/main/java/com/cburch/logisim/gui/generic/AttributeSetTableModel.java b/src/main/java/com/cburch/logisim/gui/generic/AttributeSetTableModel.java index dcb5faf..532d2f0 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/AttributeSetTableModel.java +++ b/src/main/java/com/cburch/logisim/gui/generic/AttributeSetTableModel.java @@ -14,12 +14,11 @@ import java.util.HashSet; import java.util.Objects; -public abstract class AttributeSetTableModel - implements AttrTableModel, AttributeListener { +public abstract class AttributeSetTableModel implements AttrTableModel, AttributeListener { - private ArrayList listeners; + private final ArrayList listeners; + private final HashMap, AttrRow> rowMap; private AttributeSet attributes; - private HashMap, AttrRow> rowMap; private ArrayList rows; public AttributeSetTableModel(AttributeSet attributes) { @@ -99,7 +98,7 @@ public AttrTableModelRow getRow(int rowIndex) { } protected abstract void setValueRequested(Attribute attribute, Object value) - throws AttrTableSetException; + throws AttrTableSetException; // // AttributeListener methods @@ -154,7 +153,7 @@ public void attributeValueChanged(AttributeEvent event) { private class AttrRow implements AttrTableModelRow { - private Attribute attribute; + private final Attribute attribute; private AttrRow(Attribute attribute) { @SuppressWarnings("unchecked") diff --git a/src/main/java/com/cburch/logisim/gui/generic/BasicZoomModel.java b/src/main/java/com/cburch/logisim/gui/generic/BasicZoomModel.java index 651e87d..996128a 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/BasicZoomModel.java +++ b/src/main/java/com/cburch/logisim/gui/generic/BasicZoomModel.java @@ -9,14 +9,13 @@ public class BasicZoomModel implements ZoomModel { - private double[] zoomOptions; + private final double[] zoomOptions; - private PropertyChangeSupport support; + private final PropertyChangeSupport support; private double zoomFactor; private boolean showGrid; - public BasicZoomModel(PrefMonitor gridPref, - PrefMonitor zoomPref, double[] zoomOpts) { + public BasicZoomModel(PrefMonitor gridPref, PrefMonitor zoomPref, double[] zoomOpts) { zoomOptions = zoomOpts; support = new PropertyChangeSupport(this); zoomFactor = 1.0; @@ -31,7 +30,7 @@ public void addPropertyChangeListener(String prop, PropertyChangeListener l) { } public void removePropertyChangeListener(String prop, - PropertyChangeListener l) { + PropertyChangeListener l) { support.removePropertyChangeListener(prop, l); } @@ -54,8 +53,7 @@ public void setZoomFactor(double value) { double oldValue = zoomFactor; if (value != oldValue) { zoomFactor = value; - support.firePropertyChange(ZoomModel.ZOOM, oldValue, - value); + support.firePropertyChange(ZoomModel.ZOOM, oldValue, value); } } diff --git a/src/main/java/com/cburch/logisim/gui/generic/CanvasPane.java b/src/main/java/com/cburch/logisim/gui/generic/CanvasPane.java index cfa6e17..1e017f1 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/CanvasPane.java +++ b/src/main/java/com/cburch/logisim/gui/generic/CanvasPane.java @@ -16,8 +16,8 @@ public class CanvasPane extends JScrollPane { - private CanvasPaneContents contents; - private Listener listener; + private final CanvasPaneContents contents; + private final Listener listener; private ZoomModel zoomModel; public CanvasPane(CanvasPaneContents contents) { @@ -57,9 +57,9 @@ public Dimension getViewportSize() { } public int supportScrollableBlockIncrement(Rectangle visibleRect, - int orientation, int direction) { + int orientation, int direction) { int unit = supportScrollableUnitIncrement(visibleRect, orientation, - direction); + direction); if (direction == SwingConstants.VERTICAL) { return visibleRect.height / unit * unit; } else { @@ -68,7 +68,7 @@ public int supportScrollableBlockIncrement(Rectangle visibleRect, } public int supportScrollableUnitIncrement(Rectangle visibleRect, - int orientation, int direction) { + int orientation, int direction) { double zoom = getZoomFactor(); return (int) Math.round(10 * zoom); } diff --git a/src/main/java/com/cburch/logisim/gui/generic/CardPanel.java b/src/main/java/com/cburch/logisim/gui/generic/CardPanel.java index 7661a5a..4138736 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/CardPanel.java +++ b/src/main/java/com/cburch/logisim/gui/generic/CardPanel.java @@ -12,7 +12,7 @@ public class CardPanel extends JPanel { - private ArrayList listeners; + private final ArrayList listeners; private String current; public CardPanel() { diff --git a/src/main/java/com/cburch/logisim/gui/generic/GridPainter.java b/src/main/java/com/cburch/logisim/gui/generic/GridPainter.java index 927a7f6..30f1ce8 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/GridPainter.java +++ b/src/main/java/com/cburch/logisim/gui/generic/GridPainter.java @@ -23,12 +23,12 @@ public class GridPainter { private static final int GRID_DOT_ZOOMED_COLOR = 0xFFCCCCCC; private static final Color GRID_ZOOMED_OUT_COLOR = new Color(210, 210, 210); - private Component destination; - private PropertyChangeSupport support; + private final Component destination; + private final PropertyChangeSupport support; + private final int gridSize; private Listener listener; private ZoomModel zoomModel; private boolean showGrid; - private int gridSize; private double zoomFactor; private Image gridImage; private int gridImageWidth; diff --git a/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorer.java b/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorer.java index 77ec3e8..c146a34 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorer.java +++ b/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorer.java @@ -46,10 +46,10 @@ public class ProjectExplorer extends JTree implements LocaleListener { public static final Color MAGNIFYING_INTERIOR = new Color(200, 200, 255, 64); private static final String DIRTY_MARKER = "*"; - private Project proj; - private MyListener myListener = new MyListener(); - private MyCellRenderer renderer = new MyCellRenderer(); - private DeleteAction deleteAction = new DeleteAction(); + private final Project proj; + private final MyListener myListener = new MyListener(); + private final MyCellRenderer renderer = new MyCellRenderer(); + private final DeleteAction deleteAction = new DeleteAction(); private ProjectExplorerListener listener = null; private Tool haloedTool = null; @@ -110,6 +110,70 @@ public void localeChanged() { model.fireStructureChanged(); } + private static class MySelectionModel extends DefaultTreeSelectionModel { + + @Override + public void addSelectionPath(TreePath path) { + if (isPathValid(path)) { + super.addSelectionPath(path); + } + } + + @Override + public void setSelectionPath(TreePath path) { + if (isPathValid(path)) { + super.setSelectionPath(path); + } + } + + @Override + public void addSelectionPaths(TreePath[] paths) { + paths = getValidPaths(paths); + if (paths != null) { + super.addSelectionPaths(paths); + } + } + + @Override + public void setSelectionPaths(TreePath[] paths) { + paths = getValidPaths(paths); + if (paths != null) { + super.setSelectionPaths(paths); + } + } + + private TreePath[] getValidPaths(TreePath[] paths) { + int count = 0; + for (TreePath path : paths) { + if (isPathValid(path)) { + ++count; + } + } + if (count == 0) { + return null; + } else if (count == paths.length) { + return paths; + } else { + TreePath[] ret = new TreePath[count]; + int j = 0; + for (TreePath path : paths) { + if (isPathValid(path)) { + ret[j++] = path; + } + } + return ret; + } + } + + private boolean isPathValid(TreePath path) { + if (path == null || path.getPathCount() > 3) { + return false; + } + Object last = path.getLastPathComponent(); + return last instanceof ProjectExplorerToolNode; + } + } + private class ToolIcon implements Icon { Tool tool; @@ -134,7 +198,7 @@ public int getIconWidth() { } public void paintIcon(java.awt.Component c, Graphics g, - int x, int y) { + int x, int y) { // draw halo if appropriate if (tool == haloedTool && AppPreferences.ATTRIBUTE_HALO.getBoolean()) { g.setColor(Canvas.HALO_COLOR); @@ -167,12 +231,12 @@ private class MyCellRenderer extends DefaultTreeCellRenderer { @Override public java.awt.Component getTreeCellRendererComponent( - JTree tree, Object value, boolean selected, - boolean expanded, boolean leaf, int row, - boolean hasFocus) { + JTree tree, Object value, boolean selected, + boolean expanded, boolean leaf, int row, + boolean hasFocus) { java.awt.Component ret; ret = super.getTreeCellRendererComponent(tree, value, - selected, expanded, leaf, row, hasFocus); + selected, expanded, leaf, row, hasFocus); if (ret instanceof JComponent) { JComponent comp = (JComponent) ret; @@ -188,10 +252,10 @@ public java.awt.Component getTreeCellRendererComponent( } } else if (value instanceof ProjectExplorerLibraryNode) { ProjectExplorerLibraryNode libNode = (ProjectExplorerLibraryNode) value; - Library lib = libNode.getValue(); + Library library = libNode.getValue(); if (ret instanceof JLabel) { - String text = lib.getDisplayName(); - if (lib.isDirty()) { + String text = library.getDisplayName(); + if (library.isDirty()) { text += DIRTY_MARKER; } ((JLabel) ret).setText(text); @@ -201,70 +265,6 @@ public java.awt.Component getTreeCellRendererComponent( } } - private class MySelectionModel extends DefaultTreeSelectionModel { - - @Override - public void addSelectionPath(TreePath path) { - if (isPathValid(path)) { - super.addSelectionPath(path); - } - } - - @Override - public void setSelectionPath(TreePath path) { - if (isPathValid(path)) { - super.setSelectionPath(path); - } - } - - @Override - public void addSelectionPaths(TreePath[] paths) { - paths = getValidPaths(paths); - if (paths != null) { - super.addSelectionPaths(paths); - } - } - - @Override - public void setSelectionPaths(TreePath[] paths) { - paths = getValidPaths(paths); - if (paths != null) { - super.setSelectionPaths(paths); - } - } - - private TreePath[] getValidPaths(TreePath[] paths) { - int count = 0; - for (int i = 0; i < paths.length; i++) { - if (isPathValid(paths[i])) { - ++count; - } - } - if (count == 0) { - return null; - } else if (count == paths.length) { - return paths; - } else { - TreePath[] ret = new TreePath[count]; - int j = 0; - for (int i = 0; i < paths.length; i++) { - if (isPathValid(paths[i])) { - ret[j++] = paths[i]; - } - } - return ret; - } - } - - private boolean isPathValid(TreePath path) { - if (path == null || path.getPathCount() > 3) { - return false; - } - Object last = path.getLastPathComponent(); - return last instanceof ProjectExplorerToolNode; - } - } - private class DeleteAction extends AbstractAction { public void actionPerformed(ActionEvent event) { @@ -276,9 +276,7 @@ public void actionPerformed(ActionEvent event) { } } - private class MyListener - implements MouseListener, TreeSelectionListener, - ProjectListener, PropertyChangeListener { + private class MyListener implements MouseListener, TreeSelectionListener, ProjectListener, PropertyChangeListener { // // MouseListener methods diff --git a/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerEvent.java b/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerEvent.java index 310314a..4e65348 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerEvent.java +++ b/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerEvent.java @@ -7,7 +7,7 @@ public class ProjectExplorerEvent { - private TreePath path; + private final TreePath path; public ProjectExplorerEvent(TreePath path) { this.path = path; diff --git a/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerLibraryNode.java b/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerLibraryNode.java index 2a3c433..0092baa 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerLibraryNode.java +++ b/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerLibraryNode.java @@ -13,8 +13,7 @@ import java.util.List; import java.util.Map; -public class ProjectExplorerLibraryNode extends ProjectExplorerModel.Node - implements LibraryListener { +public class ProjectExplorerLibraryNode extends ProjectExplorerModel.Node implements LibraryListener { private LogisimFile file; @@ -54,7 +53,7 @@ private void buildChildren() { } private void buildChildren(ProjectExplorerModel.Node factory, List items, - int startIndex) { + int startIndex) { // go through previously built children Map> nodeMap = new HashMap<>(); List> nodeList = new ArrayList<>(); diff --git a/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerToolNode.java b/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerToolNode.java index a1fb0b1..390e446 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerToolNode.java +++ b/src/main/java/com/cburch/logisim/gui/generic/ProjectExplorerToolNode.java @@ -10,8 +10,7 @@ import com.cburch.logisim.tools.AddTool; import com.cburch.logisim.tools.Tool; -public class ProjectExplorerToolNode extends ProjectExplorerModel.Node - implements CircuitListener { +public class ProjectExplorerToolNode extends ProjectExplorerModel.Node implements CircuitListener { private Circuit circuit; diff --git a/src/main/java/com/cburch/logisim/gui/generic/Strings.java b/src/main/java/com/cburch/logisim/gui/generic/Strings.java index f184295..f87361a 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/Strings.java +++ b/src/main/java/com/cburch/logisim/gui/generic/Strings.java @@ -9,8 +9,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "gui"); + private static final LocaleManager source = new LocaleManager("logisim", "gui"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/gui/generic/ZoomControl.java b/src/main/java/com/cburch/logisim/gui/generic/ZoomControl.java index 3434d51..0f28a4d 100644 --- a/src/main/java/com/cburch/logisim/gui/generic/ZoomControl.java +++ b/src/main/java/com/cburch/logisim/gui/generic/ZoomControl.java @@ -19,10 +19,10 @@ public class ZoomControl extends JPanel { + private final JSpinner spinner; + private final GridIcon grid; private ZoomModel model; - private JSpinner spinner; private SpinnerModel spinnerModel; - private GridIcon grid; public ZoomControl(ZoomModel model) { super(new BorderLayout()); @@ -60,7 +60,7 @@ public void setZoomModel(ZoomModel value) { } private class SpinnerModel extends AbstractSpinnerModel - implements PropertyChangeListener { + implements PropertyChangeListener { public Object getNextValue() { double zoom = model.getZoomFactor(); @@ -123,7 +123,7 @@ public void propertyChange(PropertyChangeEvent evt) { } private class GridIcon extends JComponent - implements MouseListener, PropertyChangeListener { + implements MouseListener, PropertyChangeListener { boolean state = true; diff --git a/src/main/java/com/cburch/logisim/gui/hex/Clip.java b/src/main/java/com/cburch/logisim/gui/hex/Clip.java index a5e0212..a25c816 100644 --- a/src/main/java/com/cburch/logisim/gui/hex/Clip.java +++ b/src/main/java/com/cburch/logisim/gui/hex/Clip.java @@ -18,7 +18,7 @@ class Clip implements ClipboardOwner { private static final DataFlavor binaryFlavor = new DataFlavor(int[].class, "Binary data"); - private HexEditor editor; + private final HexEditor editor; Clip(HexEditor editor) { this.editor = editor; @@ -61,18 +61,14 @@ public void paste() { if (xfer.isDataFlavorSupported(binaryFlavor)) { try { data = (int[]) xfer.getTransferData(binaryFlavor); - } catch (UnsupportedFlavorException e) { - return; - } catch (IOException e) { + } catch (UnsupportedFlavorException | IOException e) { return; } } else if (xfer.isDataFlavorSupported(DataFlavor.stringFlavor)) { String buf; try { buf = (String) xfer.getTransferData(DataFlavor.stringFlavor); - } catch (UnsupportedFlavorException e) { - return; - } catch (IOException e) { + } catch (UnsupportedFlavorException | IOException e) { return; } @@ -80,17 +76,17 @@ public void paste() { data = HexFile.parse(new StringReader(buf)); } catch (IOException e) { JOptionPane.showMessageDialog(editor.getRootPane(), - e.getMessage(), - // Strings.get("hexPasteSupportedError"), - Strings.get("hexPasteErrorTitle"), - JOptionPane.ERROR_MESSAGE); + e.getMessage(), + // Strings.get("hexPasteSupportedError"), + Strings.get("hexPasteErrorTitle"), + JOptionPane.ERROR_MESSAGE); return; } } else { JOptionPane.showMessageDialog(editor.getRootPane(), - Strings.get("hexPasteSupportedError"), - Strings.get("hexPasteErrorTitle"), - JOptionPane.ERROR_MESSAGE); + Strings.get("hexPasteSupportedError"), + Strings.get("hexPasteErrorTitle"), + JOptionPane.ERROR_MESSAGE); return; } @@ -103,9 +99,9 @@ public void paste() { model.set(p0, data); } else { JOptionPane.showMessageDialog(editor.getRootPane(), - Strings.get("hexPasteEndError"), - Strings.get("hexPasteErrorTitle"), - JOptionPane.ERROR_MESSAGE); + Strings.get("hexPasteEndError"), + Strings.get("hexPasteErrorTitle"), + JOptionPane.ERROR_MESSAGE); } } else { if (p0 < 0 || p1 < 0) { @@ -123,9 +119,9 @@ public void paste() { model.set(p0, data); } else { JOptionPane.showMessageDialog(editor.getRootPane(), - Strings.get("hexPasteSizeError"), - Strings.get("hexPasteErrorTitle"), - JOptionPane.ERROR_MESSAGE); + Strings.get("hexPasteSizeError"), + Strings.get("hexPasteErrorTitle"), + JOptionPane.ERROR_MESSAGE); } } } @@ -135,7 +131,7 @@ public void lostOwnership(Clipboard clip, Transferable transfer) { private static class Data implements Transferable { - private int[] data; + private final int[] data; Data(int[] data) { this.data = data; @@ -149,13 +145,13 @@ public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor == binaryFlavor || flavor == DataFlavor.stringFlavor; } - public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { + public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (flavor == binaryFlavor) { return data; } else if (flavor == DataFlavor.stringFlavor) { int bits = 1; - for (int i = 0; i < data.length; i++) { - int k = data[i] >> bits; + for (int datum : data) { + int k = datum >> bits; while (k != 0 && bits < 32) { bits++; k >>= 1; @@ -168,9 +164,9 @@ public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorExcepti if (i > 0) { buf.append(i % 8 == 0 ? '\n' : ' '); } - String s = Integer.toHexString(data[i]); + StringBuilder s = new StringBuilder(Integer.toHexString(data[i])); while (s.length() < chars) { - s = "0" + s; + s.insert(0, "0"); } buf.append(s); } diff --git a/src/main/java/com/cburch/logisim/gui/hex/HexFile.java b/src/main/java/com/cburch/logisim/gui/hex/HexFile.java index aed2f72..a089a36 100644 --- a/src/main/java/com/cburch/logisim/gui/hex/HexFile.java +++ b/src/main/java/com/cburch/logisim/gui/hex/HexFile.java @@ -144,15 +144,16 @@ public static void save(File dst, HexModel src) throws IOException { try { out.close(); } catch (IOException e) { - throw new IOException(Strings.get("hexFileWriteError")); +// throw new IOException(Strings.get("hexFileWriteError")); + Strings.get("hexFileWriteError"); } } } private static class HexReader { - private BufferedReader in; - private int[] data; + private final BufferedReader in; + private final int[] data; private StringTokenizer curLine; private long leftCount; private long leftValue; diff --git a/src/main/java/com/cburch/logisim/gui/hex/HexFrame.java b/src/main/java/com/cburch/logisim/gui/hex/HexFrame.java index 6ae3e52..e0f2597 100644 --- a/src/main/java/com/cburch/logisim/gui/hex/HexFrame.java +++ b/src/main/java/com/cburch/logisim/gui/hex/HexFrame.java @@ -31,14 +31,14 @@ public class HexFrame extends LFrame { - private WindowMenuManager windowManager = new WindowMenuManager(); - private EditListener editListener = new EditListener(); - private MyListener myListener = new MyListener(); - private HexModel model; - private HexEditor editor; - private JButton open = new JButton(); - private JButton save = new JButton(); - private JButton close = new JButton(); + private final WindowMenuManager windowManager = new WindowMenuManager(); + private final EditListener editListener = new EditListener(); + private final MyListener myListener = new MyListener(); + private final HexModel model; + private final HexEditor editor; + private final JButton open = new JButton(); + private final JButton save = new JButton(); + private final JButton close = new JButton(); public HexFrame(Project proj, HexModel model) { setDefaultCloseOperation(HIDE_ON_CLOSE); @@ -59,8 +59,8 @@ public HexFrame(Project proj, HexModel model) { Dimension pref = editor.getPreferredSize(); JScrollPane scroll = new JScrollPane(editor, - JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, - JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, + JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); pref.height = Math.min(pref.height, pref.width * 3 / 2); scroll.setPreferredSize(pref); scroll.getViewport().setBackground(editor.getBackground()); @@ -95,7 +95,7 @@ public void setVisible(boolean value) { } private class WindowMenuManager extends WindowMenuItemManager - implements LocaleListener { + implements LocaleListener { WindowMenuManager() { super(Strings.get("hexFrameMenuItem"), false); @@ -113,7 +113,7 @@ public void localeChanged() { } private class MyListener - implements ActionListener, LocaleListener { + implements ActionListener, LocaleListener { private File lastFile = null; @@ -130,7 +130,7 @@ public void actionPerformed(ActionEvent event) { lastFile = f; } catch (IOException e) { JOptionPane.showMessageDialog(HexFrame.this, e.getMessage(), - Strings.get("hexOpenErrorTitle"), JOptionPane.ERROR_MESSAGE); + Strings.get("hexOpenErrorTitle"), JOptionPane.ERROR_MESSAGE); } } } else if (src == save) { @@ -144,12 +144,12 @@ public void actionPerformed(ActionEvent event) { lastFile = f; } catch (IOException e) { JOptionPane.showMessageDialog(HexFrame.this, e.getMessage(), - Strings.get("hexSaveErrorTitle"), JOptionPane.ERROR_MESSAGE); + Strings.get("hexSaveErrorTitle"), JOptionPane.ERROR_MESSAGE); } } } else if (src == close) { WindowEvent e = new WindowEvent(HexFrame.this, - WindowEvent.WINDOW_CLOSING); + WindowEvent.WINDOW_CLOSING); HexFrame.this.processWindowEvent(e); } } diff --git a/src/main/java/com/cburch/logisim/gui/hex/Strings.java b/src/main/java/com/cburch/logisim/gui/hex/Strings.java index 9617897..c0ce0bc 100644 --- a/src/main/java/com/cburch/logisim/gui/hex/Strings.java +++ b/src/main/java/com/cburch/logisim/gui/hex/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "hex"); + private static final LocaleManager source = new LocaleManager("logisim", "hex"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/gui/log/ComponentIcon.java b/src/main/java/com/cburch/logisim/gui/log/ComponentIcon.java index 688b70b..b5e210a 100644 --- a/src/main/java/com/cburch/logisim/gui/log/ComponentIcon.java +++ b/src/main/java/com/cburch/logisim/gui/log/ComponentIcon.java @@ -15,7 +15,7 @@ class ComponentIcon implements Icon { public static final int TRIANGLE_CLOSED = 1; public static final int TRIANGLE_OPEN = 2; - private Component comp; + private final Component comp; private int triangleState = TRIANGLE_NONE; ComponentIcon(Component comp) { @@ -35,7 +35,7 @@ public int getIconWidth() { } public void paintIcon(java.awt.Component c, Graphics g, - int x, int y) { + int x, int y) { // draw tool icon Graphics gIcon = g.create(); ComponentDrawContext context = new ComponentDrawContext(c, null, null, g, gIcon); diff --git a/src/main/java/com/cburch/logisim/gui/log/ComponentSelector.java b/src/main/java/com/cburch/logisim/gui/log/ComponentSelector.java index eb96ece..c4829da 100644 --- a/src/main/java/com/cburch/logisim/gui/log/ComponentSelector.java +++ b/src/main/java/com/cburch/logisim/gui/log/ComponentSelector.java @@ -54,14 +54,13 @@ public void setLogModel(Model value) { } public List getSelectedItems() { - TreePath[] sel = getSelectionPaths(); - if (sel == null || sel.length == 0) { + TreePath[] paths = getSelectionPaths(); + if (paths == null || paths.length == 0) { return Collections.emptyList(); } ArrayList ret = new ArrayList<>(); - for (int i = 0; i < sel.length; i++) { - TreePath path = sel[i]; + for (TreePath path : paths) { Object last = path.getLastPathComponent(); ComponentNode n = null; Object opt = null; @@ -93,13 +92,13 @@ public List getSelectedItems() { } public boolean hasSelectedItems() { - TreePath[] sel = getSelectionPaths(); - if (sel == null || sel.length == 0) { + TreePath[] paths = getSelectionPaths(); + if (paths == null || paths.length == 0) { return false; } - for (int i = 0; i < sel.length; i++) { - Object last = sel[i].getLastPathComponent(); + for (TreePath treePath : paths) { + Object last = treePath.getLastPathComponent(); if (last instanceof OptionNode) { return true; } else if (last instanceof ComponentNode) { @@ -123,15 +122,15 @@ public int compare(Object a, Object b) { } private class CircuitNode implements TreeNode, CircuitListener, - Comparator { + Comparator { - private CircuitNode parent; - private CircuitState circuitState; - private Component subcircComp; + private final CircuitNode parent; + private final CircuitState circuitState; + private final Component subcircComp; private ArrayList children; public CircuitNode(CircuitNode parent, CircuitState circuitState, - Component subcircComp) { + Component subcircComp) { this.parent = parent; this.circuitState = circuitState; this.subcircComp = subcircComp; @@ -214,24 +213,24 @@ public void circuitChanged(CircuitEvent event) { private boolean computeChildren() { ArrayList newChildren = new ArrayList<>(); ArrayList subcircs = new ArrayList<>(); - for (Component comp : circuitState.getCircuit().getNonWires()) { - if (comp.getFactory() instanceof SubcircuitFactory) { - subcircs.add(comp); + for (Component component : circuitState.getCircuit().getNonWires()) { + if (component.getFactory() instanceof SubcircuitFactory) { + subcircs.add(component); } else { - Object o = comp.getFeature(Loggable.class); + Object o = component.getFeature(Loggable.class); if (o != null) { ComponentNode toAdd = null; - for (TreeNode o2 : children) { - if (o2 instanceof ComponentNode) { - ComponentNode n = (ComponentNode) o2; - if (n.comp == comp) { - toAdd = n; + for (TreeNode child : children) { + if (child instanceof ComponentNode) { + ComponentNode node = (ComponentNode) child; + if (node.comp == component) { + toAdd = node; break; } } } if (toAdd == null) { - toAdd = new ComponentNode(this, comp); + toAdd = new ComponentNode(this, component); } newChildren.add(toAdd); } @@ -239,21 +238,21 @@ private boolean computeChildren() { } newChildren.sort(new CompareByName()); subcircs.sort(this); - for (Component comp : subcircs) { - SubcircuitFactory factory = (SubcircuitFactory) comp.getFactory(); - CircuitState state = factory.getSubstate(circuitState, comp); + for (Component component : subcircs) { + SubcircuitFactory factory = (SubcircuitFactory) component.getFactory(); + CircuitState state = factory.getSubstate(circuitState, component); CircuitNode toAdd = null; - for (TreeNode o : children) { - if (o instanceof CircuitNode) { - CircuitNode n = (CircuitNode) o; - if (n.circuitState == state) { - toAdd = n; + for (TreeNode child : children) { + if (child instanceof CircuitNode) { + CircuitNode node = (CircuitNode) child; + if (node.circuitState == state) { + toAdd = node; break; } } } if (toAdd == null) { - toAdd = new CircuitNode(this, state, comp); + toAdd = new CircuitNode(this, state, component); } newChildren.add(toAdd); } @@ -281,8 +280,8 @@ public int compare(Component a, Component b) { private class ComponentNode implements TreeNode { - private CircuitNode parent; - private Component comp; + private final CircuitNode parent; + private final Component comp; private OptionNode[] opts; public ComponentNode(CircuitNode parent, Component comp) { @@ -292,11 +291,11 @@ public ComponentNode(CircuitNode parent, Component comp) { Loggable log = (Loggable) comp.getFeature(Loggable.class); if (log != null) { - Object[] opts = log.getLogOptions(parent.circuitState); - if (opts != null && opts.length > 0) { - this.opts = new OptionNode[opts.length]; - for (int i = 0; i < opts.length; i++) { - this.opts[i] = new OptionNode(this, opts[i]); + Object[] options = log.getLogOptions(parent.circuitState); + if (options != null && options.length > 0) { + this.opts = new OptionNode[options.length]; + for (int i = 0; i < options.length; i++) { + this.opts[i] = new OptionNode(this, options[i]); } } } @@ -306,9 +305,9 @@ public ComponentNode(CircuitNode parent, Component comp) { public String toString() { Loggable log = (Loggable) comp.getFeature(Loggable.class); if (log != null) { - String ret = log.getLogName(null); - if (ret != null && !ret.equals("")) { - return ret; + String logName = log.getLogName(null); + if (logName != null && !logName.equals("")) { + return logName; } } return comp.getFactory().getDisplayName() + " " + comp.getLocation(); @@ -350,8 +349,8 @@ public Enumeration children() { private class OptionNode implements TreeNode { - private ComponentNode parent; - private Object option; + private final ComponentNode parent; + private final Object option; public OptionNode(ComponentNode parent, Object option) { this.parent = parent; @@ -396,16 +395,16 @@ private class MyCellRenderer extends DefaultTreeCellRenderer { @Override public java.awt.Component getTreeCellRendererComponent(JTree tree, - Object value, boolean selected, boolean expanded, - boolean leaf, int row, boolean hasFocus) { + Object value, boolean selected, boolean expanded, + boolean leaf, int row, boolean hasFocus) { java.awt.Component ret = super.getTreeCellRendererComponent(tree, - value, selected, expanded, leaf, row, hasFocus); + value, selected, expanded, leaf, row, hasFocus); if (ret instanceof JLabel && value instanceof ComponentNode) { ComponentNode node = (ComponentNode) value; ComponentIcon icon = new ComponentIcon(node.comp); if (node.getChildCount() > 0) { icon.setTriangleState(expanded - ? ComponentIcon.TRIANGLE_OPEN : ComponentIcon.TRIANGLE_CLOSED); + ? ComponentIcon.TRIANGLE_OPEN : ComponentIcon.TRIANGLE_CLOSED); } ((JLabel) ret).setIcon(icon); } diff --git a/src/main/java/com/cburch/logisim/gui/log/FilePanel.java b/src/main/java/com/cburch/logisim/gui/log/FilePanel.java index 91acbca..4c44b23 100644 --- a/src/main/java/com/cburch/logisim/gui/log/FilePanel.java +++ b/src/main/java/com/cburch/logisim/gui/log/FilePanel.java @@ -24,14 +24,14 @@ class FilePanel extends LogPanel { - private Listener listener = new Listener(); - private JLabel enableLabel = new JLabel(); - private JButton enableButton = new JButton(); - private JLabel fileLabel = new JLabel(); - private JTextField fileField = new JTextField(); - private JButton selectButton = new JButton(); - private JCheckBox headerCheckBox = new JCheckBox(); - private JFileChooser chooser = JFileChoosers.create(); + private final Listener listener = new Listener(); + private final JLabel enableLabel = new JLabel(); + private final JButton enableButton = new JButton(); + private final JLabel fileLabel = new JLabel(); + private final JTextField fileField = new JTextField(); + private final JButton selectButton = new JButton(); + private final JCheckBox headerCheckBox = new JCheckBox(); + private final JFileChooser chooser = JFileChoosers.create(); public FilePanel(LogFrame frame) { super(frame); @@ -166,30 +166,32 @@ public void actionPerformed(ActionEvent event) { File file = chooser.getSelectedFile(); if (file.exists() && (!file.canWrite() || file.isDirectory())) { JOptionPane.showMessageDialog(getLogFrame(), - StringUtil.format(Strings.get("fileCannotWriteMessage"), file.getName()), - Strings.get("fileCannotWriteTitle"), - JOptionPane.OK_OPTION); + StringUtil.format(Strings.get("fileCannotWriteMessage"), file.getName()), + Strings.get("fileCannotWriteTitle"), + JOptionPane.OK_OPTION); return; } if (file.exists() && file.length() > 0) { String[] options = { - Strings.get("fileOverwriteOption"), - Strings.get("fileAppendOption"), - Strings.get("fileCancelOption"), + Strings.get("fileOverwriteOption"), + Strings.get("fileAppendOption"), + Strings.get("fileCancelOption"), }; int option = JOptionPane.showOptionDialog(getLogFrame(), - StringUtil.format(Strings.get("fileExistsMessage"), file.getName()), - Strings.get("fileExistsTitle"), - 0, JOptionPane.QUESTION_MESSAGE, null, - options, options[0]); + StringUtil.format(Strings.get("fileExistsMessage"), file.getName()), + Strings.get("fileExistsTitle"), + 0, JOptionPane.QUESTION_MESSAGE, null, + options, options[0]); if (option == 0) { try { FileWriter delete = new FileWriter(file); delete.close(); } catch (IOException e) { + e.printStackTrace(); } } else if (option == 1) { // do nothing + System.err.println("WARNING: No option for 1!"); } else { return; } diff --git a/src/main/java/com/cburch/logisim/gui/log/LogFrame.java b/src/main/java/com/cburch/logisim/gui/log/LogFrame.java index 7c35907..71dc68f 100644 --- a/src/main/java/com/cburch/logisim/gui/log/LogFrame.java +++ b/src/main/java/com/cburch/logisim/gui/log/LogFrame.java @@ -33,15 +33,15 @@ public class LogFrame extends LFrame { - private Project project; + private final Project project; + private final Map modelMap = new HashMap<>(); + private final MyListener myListener = new MyListener(); + private final WindowMenuManager windowManager; + private final LogPanel[] panels; + private final JTabbedPane tabbedPane; + private final JButton close = new JButton(); private Simulator curSimulator = null; private Model curModel; - private Map modelMap = new HashMap<>(); - private MyListener myListener = new MyListener(); - private WindowMenuManager windowManager; - private LogPanel[] panels; - private JTabbedPane tabbedPane; - private JButton close = new JButton(); public LogFrame(Project project) { this.project = project; @@ -53,13 +53,12 @@ public LogFrame(Project project) { setSimulator(project.getSimulator(), project.getCircuitState()); panels = new LogPanel[]{ - new SelectionPanel(this), - new ScrollPanel(this), - new FilePanel(this), + new SelectionPanel(this), + new ScrollPanel(this), + new FilePanel(this), }; tabbedPane = new JTabbedPane(); - for (int index = 0; index < panels.length; index++) { - LogPanel panel = panels[index]; + for (LogPanel panel : panels) { tabbedPane.addTab(panel.getTitle(), null, panel, panel.getToolTipText()); } @@ -80,7 +79,7 @@ public LogFrame(Project project) { private static String computeTitle(Model data, Project proj) { String name = data == null ? "???" : data.getCircuitState().getCircuit().getName(); return StringUtil.format(Strings.get("logFrameTitle"), name, - proj.getLogisimFile().getDisplayName()); + proj.getLogisimFile().getDisplayName()); } public Project getProject() { @@ -128,8 +127,8 @@ private void setSimulator(Simulator value, CircuitState state) { } setTitle(computeTitle(curModel, project)); if (panels != null) { - for (int i = 0; i < panels.length; i++) { - panels[i].modelChanged(oldModel, curModel); + for (LogPanel panel : panels) { + panel.modelChanged(oldModel, curModel); } } } @@ -149,7 +148,7 @@ LogPanel[] getPrefPanels() { // TODO should automatically repaint icons when component attr change // TODO ? moving a component using Select tool removes it from selection private class WindowMenuManager extends WindowMenuItemManager - implements LocaleListener, ProjectListener, LibraryListener { + implements LocaleListener, ProjectListener, LibraryListener { WindowMenuManager() { super(Strings.get("logFrameMenuItem"), false); @@ -181,14 +180,14 @@ public void libraryChanged(LibraryEvent event) { } private class MyListener - implements ActionListener, ProjectListener, LibraryListener, - SimulatorListener, LocaleListener { + implements ActionListener, ProjectListener, LibraryListener, + SimulatorListener, LocaleListener { public void actionPerformed(ActionEvent event) { Object src = event.getSource(); if (src == close) { WindowEvent e = new WindowEvent(LogFrame.this, - WindowEvent.WINDOW_CLOSING); + WindowEvent.WINDOW_CLOSING); LogFrame.this.processWindowEvent(e); } } @@ -197,7 +196,7 @@ public void projectChanged(ProjectEvent event) { int action = event.getAction(); if (action == ProjectEvent.ACTION_SET_STATE) { setSimulator(event.getProject().getSimulator(), - event.getProject().getCircuitState()); + event.getProject().getCircuitState()); } else if (action == ProjectEvent.ACTION_SET_FILE) { setTitle(computeTitle(curModel, project)); } diff --git a/src/main/java/com/cburch/logisim/gui/log/LogPanel.java b/src/main/java/com/cburch/logisim/gui/log/LogPanel.java index af24d20..9bd838e 100644 --- a/src/main/java/com/cburch/logisim/gui/log/LogPanel.java +++ b/src/main/java/com/cburch/logisim/gui/log/LogPanel.java @@ -9,7 +9,7 @@ abstract class LogPanel extends JPanel { - private LogFrame logFrame; + private final LogFrame logFrame; public LogPanel(LogFrame frame) { super(); diff --git a/src/main/java/com/cburch/logisim/gui/log/LogThread.java b/src/main/java/com/cburch/logisim/gui/log/LogThread.java index 16b0b3d..3ed8911 100644 --- a/src/main/java/com/cburch/logisim/gui/log/LogThread.java +++ b/src/main/java/com/cburch/logisim/gui/log/LogThread.java @@ -16,9 +16,9 @@ class LogThread extends Thread implements ModelListener { // file will be closed after waiting this many milliseconds between writes private static final int IDLE_UNTIL_CLOSE = 10000; - private Model model; + private final Model model; + private final Object lock = new Object(); private boolean canceled = false; - private Object lock = new Object(); private PrintWriter writer = null; private boolean headerDirty = true; private long lastWrite = 0; @@ -44,6 +44,7 @@ public void run() { try { Thread.sleep(FLUSH_FREQUENCY); } catch (InterruptedException e) { + e.printStackTrace(); } } synchronized (lock) { @@ -103,8 +104,7 @@ public void filePropertyChanged(ModelEvent event) { } private boolean isFileEnabled() { - return !canceled && model.isSelected() && model.isFileEnabled() - && model.getFile() != null; + return !canceled && model.isSelected() && model.isFileEnabled() && model.getFile() != null; } // Should hold lock and have verified that isFileEnabled() before @@ -118,17 +118,17 @@ private void addEntry(Value[] values) { return; } } - Selection sel = model.getSelection(); + Selection selection = model.getSelection(); if (headerDirty) { if (model.getFileHeader()) { StringBuilder buf = new StringBuilder(); - for (int i = 0; i < sel.size(); i++) { + for (int i = 0; i < selection.size(); i++) { if (i > 0) { buf.append("\t"); } - buf.append(sel.get(i).toString()); + buf.append(selection.get(i).toString()); } - writer.println(buf.toString()); + writer.println(buf); } headerDirty = false; } @@ -138,11 +138,11 @@ private void addEntry(Value[] values) { buf.append("\t"); } if (values[i] != null) { - int radix = sel.get(i).getRadix(); + int radix = selection.get(i).getRadix(); buf.append(values[i].toDisplayString(radix)); } } - writer.println(buf.toString()); + writer.println(buf); lastWrite = System.currentTimeMillis(); } } diff --git a/src/main/java/com/cburch/logisim/gui/log/Model.java b/src/main/java/com/cburch/logisim/gui/log/Model.java index 0a8fe29..3bc7a9f 100644 --- a/src/main/java/com/cburch/logisim/gui/log/Model.java +++ b/src/main/java/com/cburch/logisim/gui/log/Model.java @@ -12,9 +12,9 @@ class Model { - private EventSourceWeakSupport listeners; - private Selection selection; - private HashMap log; + private final EventSourceWeakSupport listeners; + private final Selection selection; + private final HashMap log; private boolean fileEnabled = false; private File file = null; private boolean fileHeader = true; @@ -48,12 +48,12 @@ public Selection getSelection() { } public ValueLog getValueLog(SelectionItem item) { - ValueLog ret = log.get(item); - if (ret == null && selection.indexOf(item) >= 0) { - ret = new ValueLog(); - log.put(item, ret); + ValueLog valueLog = log.get(item); + if (valueLog == null && selection.indexOf(item) >= 0) { + valueLog = new ValueLog(); + log.put(item, valueLog); } - return ret; + return valueLog; } public boolean isFileEnabled() { @@ -95,22 +95,22 @@ public void setFileHeader(boolean value) { public void propagationCompleted() { CircuitState circuitState = getCircuitState(); - Value[] vals = new Value[selection.size()]; + Value[] values = new Value[selection.size()]; boolean changed = false; for (int i = selection.size() - 1; i >= 0; i--) { SelectionItem item = selection.get(i); - vals[i] = item.fetchValue(circuitState); + values[i] = item.fetchValue(circuitState); if (!changed) { Value v = getValueLog(item).getLast(); - changed = v == null ? vals[i] != null : !v.equals(vals[i]); + changed = v == null ? values[i] != null : !v.equals(values[i]); } } if (changed) { for (int i = selection.size() - 1; i >= 0; i--) { SelectionItem item = selection.get(i); - getValueLog(item).append(vals[i]); + getValueLog(item).append(values[i]); } - fireEntryAdded(new ModelEvent(), vals); + fireEntryAdded(new ModelEvent(), values); } } diff --git a/src/main/java/com/cburch/logisim/gui/log/ScrollPanel.java b/src/main/java/com/cburch/logisim/gui/log/ScrollPanel.java index 72ca2d3..30741d7 100644 --- a/src/main/java/com/cburch/logisim/gui/log/ScrollPanel.java +++ b/src/main/java/com/cburch/logisim/gui/log/ScrollPanel.java @@ -8,14 +8,14 @@ class ScrollPanel extends LogPanel { - private TablePanel table; + private final TablePanel table; public ScrollPanel(LogFrame frame) { super(frame); this.table = new TablePanel(frame); JScrollPane pane = new JScrollPane(table, - JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); pane.setVerticalScrollBar(table.getVerticalScrollBar()); setLayout(new BorderLayout()); add(pane); diff --git a/src/main/java/com/cburch/logisim/gui/log/Selection.java b/src/main/java/com/cburch/logisim/gui/log/Selection.java index 05576a5..be12c65 100644 --- a/src/main/java/com/cburch/logisim/gui/log/Selection.java +++ b/src/main/java/com/cburch/logisim/gui/log/Selection.java @@ -8,9 +8,9 @@ class Selection { - private CircuitState root; - private Model model; - private ArrayList components; + private final CircuitState root; + private final Model model; + private final ArrayList components; public Selection(CircuitState root, Model model) { this.root = root; diff --git a/src/main/java/com/cburch/logisim/gui/log/SelectionItem.java b/src/main/java/com/cburch/logisim/gui/log/SelectionItem.java index 93a2d14..5f8ed45 100644 --- a/src/main/java/com/cburch/logisim/gui/log/SelectionItem.java +++ b/src/main/java/com/cburch/logisim/gui/log/SelectionItem.java @@ -16,10 +16,10 @@ class SelectionItem implements AttributeListener, CircuitListener { - private Model model; - private Component[] path; - private Component comp; - private Object option; + private final Model model; + private final Component[] path; + private final Component component; + private final Object option; private int radix = 2; private String shortDescriptor; private String longDescriptor; @@ -27,16 +27,16 @@ class SelectionItem implements AttributeListener, CircuitListener { public SelectionItem(Model model, Component[] path, Component comp, Object option) { this.model = model; this.path = path; - this.comp = comp; + this.component = comp; this.option = option; computeDescriptors(); if (path != null) { model.getCircuitState().getCircuit().addCircuitListener(this); - for (int i = 0; i < path.length; i++) { - path[i].getAttributeSet().addAttributeListener(this); - SubcircuitFactory circFact = (SubcircuitFactory) path[i].getFactory(); - circFact.getSubcircuit().addCircuitListener(this); + for (Component component : path) { + component.getAttributeSet().addAttributeListener(this); + SubcircuitFactory subcircuitFactory = (SubcircuitFactory) component.getFactory(); + subcircuitFactory.getSubcircuit().addCircuitListener(this); } } comp.getAttributeSet().addAttributeListener(this); @@ -45,13 +45,12 @@ public SelectionItem(Model model, Component[] path, Component comp, Object optio private boolean computeDescriptors() { boolean changed = false; - Loggable log = (Loggable) comp.getFeature(Loggable.class); + Loggable log = (Loggable) component.getFeature(Loggable.class); String newShort = log.getLogName(option); if (newShort == null || newShort.equals("")) { - newShort = comp.getFactory().getDisplayName() - + comp.getLocation().toString(); + newShort = component.getFactory().getDisplayName() + component.getLocation().toString(); if (option != null) { - newShort += "." + option.toString(); + newShort += "." + option; } } if (!newShort.equals(shortDescriptor)) { @@ -88,7 +87,7 @@ public Component[] getPath() { } public Component getComponent() { - return comp; + return component; } public Object getOption() { @@ -114,13 +113,13 @@ public String toString() { } public Value fetchValue(CircuitState root) { - CircuitState cur = root; - for (int i = 0; i < path.length; i++) { - SubcircuitFactory circFact = (SubcircuitFactory) path[i].getFactory(); - cur = circFact.getSubstate(cur, path[i]); + CircuitState circuitState = root; + for (Component value : path) { + SubcircuitFactory subcircuitFactory = (SubcircuitFactory) value.getFactory(); + circuitState = subcircuitFactory.getSubstate(circuitState, value); } - Loggable log = (Loggable) comp.getFeature(Loggable.class); - return log == null ? Value.NIL : log.getLogValue(cur, option); + Loggable log = (Loggable) component.getFeature(Loggable.class); + return log == null ? Value.NIL : log.getLogValue(circuitState, option); } public void attributeListChanged(AttributeEvent e) { @@ -135,25 +134,25 @@ public void attributeValueChanged(AttributeEvent e) { public void circuitChanged(CircuitEvent event) { int action = event.getAction(); if (action == CircuitEvent.ACTION_CLEAR - || action == CircuitEvent.ACTION_REMOVE) { - Circuit circ = event.getCircuit(); - Component circComp = null; - if (circ == model.getCircuitState().getCircuit()) { - circComp = path != null && path.length > 0 ? path[0] : comp; + || action == CircuitEvent.ACTION_REMOVE) { + Circuit circuit = event.getCircuit(); + Component component = null; + if (circuit == model.getCircuitState().getCircuit()) { + component = path != null && path.length > 0 ? path[0] : this.component; } else if (path != null) { for (int i = 0; i < path.length; i++) { SubcircuitFactory circFact = (SubcircuitFactory) path[i].getFactory(); - if (circ == circFact.getSubcircuit()) { - circComp = i + 1 < path.length ? path[i + 1] : comp; + if (circuit == circFact.getSubcircuit()) { + component = i + 1 < path.length ? path[i + 1] : this.component; } } } - if (circComp == null) { + if (component == null) { return; } if (action == CircuitEvent.ACTION_REMOVE - && event.getData() != circComp) { + && event.getData() != component) { return; } diff --git a/src/main/java/com/cburch/logisim/gui/log/SelectionList.java b/src/main/java/com/cburch/logisim/gui/log/SelectionList.java index 15cbfe3..0f0a206 100644 --- a/src/main/java/com/cburch/logisim/gui/log/SelectionList.java +++ b/src/main/java/com/cburch/logisim/gui/log/SelectionList.java @@ -11,7 +11,7 @@ import javax.swing.JList; import javax.swing.ListSelectionModel; -class SelectionList extends JList { +class SelectionList extends JList { private Selection selection; @@ -40,8 +40,24 @@ public void localeChanged() { repaint(); } - private class Model extends AbstractListModel - implements ModelListener { + private static class MyCellRenderer extends DefaultListCellRenderer { + + @Override + public java.awt.Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, + boolean hasFocus) { + java.awt.Component component = super.getListCellRendererComponent(list, value, index, isSelected, hasFocus); + if (component instanceof JLabel && value instanceof SelectionItem) { + JLabel label = (JLabel) component; + SelectionItem item = (SelectionItem) value; + Component comp = item.getComponent(); + label.setIcon(new ComponentIcon(comp)); + label.setText(item + " - " + item.getRadix()); + } + return component; + } + } + + private class Model extends AbstractListModel implements ModelListener { public int getSize() { return selection == null ? 0 : selection.size(); @@ -61,22 +77,4 @@ public void entryAdded(ModelEvent event, Value[] values) { public void filePropertyChanged(ModelEvent event) { } } - - private class MyCellRenderer extends DefaultListCellRenderer { - - @Override - public java.awt.Component getListCellRendererComponent(JList list, - Object value, int index, boolean isSelected, boolean hasFocus) { - java.awt.Component ret = super.getListCellRendererComponent(list, - value, index, isSelected, hasFocus); - if (ret instanceof JLabel && value instanceof SelectionItem) { - JLabel label = (JLabel) ret; - SelectionItem item = (SelectionItem) value; - Component comp = item.getComponent(); - label.setIcon(new ComponentIcon(comp)); - label.setText(item.toString() + " - " + item.getRadix()); - } - return ret; - } - } } diff --git a/src/main/java/com/cburch/logisim/gui/log/SelectionPanel.java b/src/main/java/com/cburch/logisim/gui/log/SelectionPanel.java index 59e5b50..28f697e 100644 --- a/src/main/java/com/cburch/logisim/gui/log/SelectionPanel.java +++ b/src/main/java/com/cburch/logisim/gui/log/SelectionPanel.java @@ -23,14 +23,14 @@ class SelectionPanel extends LogPanel { - private Listener listener = new Listener(); - private ComponentSelector selector; - private JButton addToolButton; - private JButton changeBaseButton; - private JButton moveUpButton; - private JButton moveDownButton; - private JButton removeButton; - private SelectionList list; + private final Listener listener = new Listener(); + private final ComponentSelector selector; + private final JButton addToolButton; + private final JButton changeBaseButton; + private final JButton moveUpButton; + private final JButton moveDownButton; + private final JButton removeButton; + private final SelectionList list; public SelectionPanel(LogFrame window) { super(window); @@ -64,11 +64,11 @@ public SelectionPanel(LogFrame window) { GridBagConstraints constraints = new GridBagConstraints(); setLayout(layout); JScrollPane explorerPane = new JScrollPane(selector, - ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); JScrollPane listPane = new JScrollPane(list, - ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); constraints.fill = GridBagConstraints.BOTH; constraints.weightx = 1.0; constraints.weighty = 1.0; @@ -119,8 +119,8 @@ public void modelChanged(Model oldModel, Model newModel) { } private class Listener extends MouseAdapter - implements ActionListener, TreeSelectionListener, - ListSelectionListener { + implements ActionListener, TreeSelectionListener, + ListSelectionListener { @Override public void mouseClicked(MouseEvent mouseEvent) { @@ -157,8 +157,9 @@ public void actionPerformed(ActionEvent event) { doMove(1); } else if (source.equals(removeButton)) { Selection selection = getSelection(); - @SuppressWarnings("deprecation") - Object[] objectsToRemove = list.getSelectedValues(); +// @SuppressWarnings("deprecation") +// Object[] objectsToRemove = list.getSelectedValues(); + Object[] objectsToRemove = list.getSelectedValuesList().toArray(); boolean changed = false; for (Object object : objectsToRemove) { int index = selection.indexOf((SelectionItem) object); diff --git a/src/main/java/com/cburch/logisim/gui/log/Strings.java b/src/main/java/com/cburch/logisim/gui/log/Strings.java index 208190b..c7a7ea5 100644 --- a/src/main/java/com/cburch/logisim/gui/log/Strings.java +++ b/src/main/java/com/cburch/logisim/gui/log/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "log"); + private static final LocaleManager source = new LocaleManager("logisim", "log"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/gui/log/TablePanel.java b/src/main/java/com/cburch/logisim/gui/log/TablePanel.java index 7fef077..080cbb8 100644 --- a/src/main/java/com/cburch/logisim/gui/log/TablePanel.java +++ b/src/main/java/com/cburch/logisim/gui/log/TablePanel.java @@ -22,17 +22,17 @@ class TablePanel extends LogPanel { private static final Font BODY_FONT = new Font("Serif", Font.PLAIN, 14); private static final int COLUMN_SEP = 8; private static final int HEADER_SEP = 4; - private MyListener myListener = new MyListener(); + private final MyListener myListener = new MyListener(); private int cellWidth = 25; // reasonable start values private int cellHeight = 15; private int rowCount = 0; private int tableWidth; private int tableHeight; - private VerticalScrollBar vsb; + private final VerticalScrollBar scrollBar; public TablePanel(LogFrame frame) { super(frame); - vsb = new VerticalScrollBar(); + scrollBar = new VerticalScrollBar(); modelChanged(null, getModel()); } @@ -131,7 +131,7 @@ public void paintComponent(Graphics g) { String label = val.toDisplayString(radix); int width = bodyMetric.stringWidth(label); g.drawString(label, x + (cellWidth - width) / 2, - y + bodyMetric.getAscent()); + y + bodyMetric.getAscent()); y += cellHeight; } x += cellWidth + COLUMN_SEP; @@ -139,7 +139,7 @@ public void paintComponent(Graphics g) { } private int paintHeader(String header, int x, int y, - Graphics g, FontMetrics fm) { + Graphics g, FontMetrics fm) { int width = fm.stringWidth(header); g.drawString(header, x + (cellWidth - width) / 2, y); return x + cellWidth + COLUMN_SEP; @@ -176,7 +176,7 @@ private void computePreferredSize() { } JScrollBar getVerticalScrollBar() { - return vsb; + return scrollBar; } private class MyListener implements ModelListener { @@ -189,10 +189,10 @@ public void entryAdded(ModelEvent event, Value[] values) { int oldCount = rowCount; computeRowCount(); if (oldCount == rowCount) { - int value = vsb.getValue(); - if (value > vsb.getMinimum() - && value < vsb.getMaximum() - vsb.getVisibleAmount()) { - vsb.setValue(vsb.getValue() - vsb.getUnitIncrement(-1)); + int value = scrollBar.getValue(); + if (value > scrollBar.getMinimum() + && value < scrollBar.getMaximum() - scrollBar.getVisibleAmount()) { + scrollBar.setValue(scrollBar.getValue() - scrollBar.getUnitIncrement(-1)); } else { repaint(); } @@ -220,7 +220,7 @@ private void computeRowCount() { } private class VerticalScrollBar extends JScrollBar - implements ChangeListener { + implements ChangeListener { private int oldMaximum = -1; private int oldExtent = -1; @@ -236,7 +236,7 @@ public int getUnitIncrement(int direction) { return curY > 0 ? cellHeight : cellHeight + HEADER_SEP; } else { return curY > cellHeight + HEADER_SEP ? cellHeight - : cellHeight + HEADER_SEP; + : cellHeight + HEADER_SEP; } } @@ -250,12 +250,12 @@ public int getBlockIncrement(int direction) { } if (direction > 0) { return curY > 0 - ? numCells * cellHeight - : numCells * cellHeight + HEADER_SEP; + ? numCells * cellHeight + : numCells * cellHeight + HEADER_SEP; } else { return curY > cellHeight + HEADER_SEP - ? numCells * cellHeight - : numCells * cellHeight + HEADER_SEP; + ? numCells * cellHeight + : numCells * cellHeight + HEADER_SEP; } } diff --git a/src/main/java/com/cburch/logisim/gui/log/ValueLog.java b/src/main/java/com/cburch/logisim/gui/log/ValueLog.java index b7992ba..e423b17 100644 --- a/src/main/java/com/cburch/logisim/gui/log/ValueLog.java +++ b/src/main/java/com/cburch/logisim/gui/log/ValueLog.java @@ -9,7 +9,7 @@ class ValueLog { private static final int LOG_SIZE = 400; - private Value[] log; + private final Value[] log; private short curSize; private short firstIndex; @@ -33,7 +33,7 @@ public Value get(int index) { public Value getLast() { return curSize < LOG_SIZE ? (curSize == 0 ? null : log[curSize - 1]) - : (firstIndex == 0 ? log[curSize - 1] : log[firstIndex - 1]); + : (firstIndex == 0 ? log[curSize - 1] : log[firstIndex - 1]); } public void append(Value val) { diff --git a/src/main/java/com/cburch/logisim/gui/main/AttrTableCircuitModel.java b/src/main/java/com/cburch/logisim/gui/main/AttrTableCircuitModel.java index 5ac53d1..2b25078 100644 --- a/src/main/java/com/cburch/logisim/gui/main/AttrTableCircuitModel.java +++ b/src/main/java/com/cburch/logisim/gui/main/AttrTableCircuitModel.java @@ -12,30 +12,30 @@ public class AttrTableCircuitModel extends AttributeSetTableModel { - private Project proj; - private Circuit circ; + private final Project project; + private final Circuit circuit; - public AttrTableCircuitModel(Project proj, Circuit circ) { - super(circ.getStaticAttributes()); - this.proj = proj; - this.circ = circ; + public AttrTableCircuitModel(Project project, Circuit circuit) { + super(circuit.getStaticAttributes()); + this.project = project; + this.circuit = circuit; } @Override public String getTitle() { - return Strings.get("circuitAttrTitle", circ.getName()); + return Strings.get("circuitAttrTitle", circuit.getName()); } @Override public void setValueRequested(Attribute attribute, Object value) - throws AttrTableSetException { - if (!proj.getLogisimFile().contains(circ)) { + throws AttrTableSetException { + if (!project.getLogisimFile().contains(circuit)) { String msg = Strings.get("cannotModifyCircuitError"); throw new AttrTableSetException(msg); } else { - CircuitMutation xn = new CircuitMutation(circ); + CircuitMutation xn = new CircuitMutation(circuit); xn.setForCircuit(attribute, value); - proj.doAction(xn.toAction(Strings.getter("changeCircuitAttrAction"))); + project.doAction(xn.toAction(Strings.getter("changeCircuitAttrAction"))); } } } diff --git a/src/main/java/com/cburch/logisim/gui/main/AttrTableComponentModel.java b/src/main/java/com/cburch/logisim/gui/main/AttrTableComponentModel.java index 3095cf9..c2944dc 100644 --- a/src/main/java/com/cburch/logisim/gui/main/AttrTableComponentModel.java +++ b/src/main/java/com/cburch/logisim/gui/main/AttrTableComponentModel.java @@ -13,41 +13,41 @@ class AttrTableComponentModel extends AttributeSetTableModel { - Project proj; - Circuit circ; - Component comp; - - AttrTableComponentModel(Project proj, Circuit circ, Component comp) { - super(comp.getAttributeSet()); - this.proj = proj; - this.circ = circ; - this.comp = comp; + Project project; + Circuit circuit; + Component component; + + AttrTableComponentModel(Project project, Circuit circuit, Component component) { + super(component.getAttributeSet()); + this.project = project; + this.circuit = circuit; + this.component = component; } public Circuit getCircuit() { - return circ; + return circuit; } public Component getComponent() { - return comp; + return component; } @Override public String getTitle() { - return comp.getFactory().getDisplayName(); + return component.getFactory().getDisplayName(); } @Override public void setValueRequested(Attribute attribute, Object value) - throws AttrTableSetException { - if (!proj.getLogisimFile().contains(circ)) { + throws AttrTableSetException { + if (!project.getLogisimFile().contains(circuit)) { String msg = Strings.get("cannotModifyCircuitError"); throw new AttrTableSetException(msg); } else { - SetAttributeAction act = new SetAttributeAction(circ, - Strings.getter("changeAttributeAction")); - act.set(comp, attribute, value); - proj.doAction(act); + SetAttributeAction act = new SetAttributeAction(circuit, + Strings.getter("changeAttributeAction")); + act.set(component, attribute, value); + project.doAction(act); } } } diff --git a/src/main/java/com/cburch/logisim/gui/main/AttrTableSelectionModel.java b/src/main/java/com/cburch/logisim/gui/main/AttrTableSelectionModel.java index 060bc0a..556eae9 100644 --- a/src/main/java/com/cburch/logisim/gui/main/AttrTableSelectionModel.java +++ b/src/main/java/com/cburch/logisim/gui/main/AttrTableSelectionModel.java @@ -14,11 +14,10 @@ import com.cburch.logisim.proj.Project; import com.cburch.logisim.tools.SetAttributeAction; -class AttrTableSelectionModel extends AttributeSetTableModel - implements Selection.Listener { +class AttrTableSelectionModel extends AttributeSetTableModel implements Selection.Listener { - private Project project; - private Frame frame; + private final Project project; + private final Frame frame; public AttrTableSelectionModel(Project project, Frame frame) { super(frame.getCanvas().getSelection().getAttributeSet()); @@ -63,19 +62,18 @@ public String getTitle() { if (variousFound) { return Strings.get("selectionVarious", "" + totalCount); } else if (factoryCount == 0) { - String circName = frame.getCanvas().getCircuit().getName(); - return Strings.get("circuitAttrTitle", circName); + String circuitName = frame.getCanvas().getCircuit().getName(); + return Strings.get("circuitAttrTitle", circuitName); } else if (factoryCount == 1) { return Strings.get("selectionOne", factory.getDisplayName()); } else { - return Strings.get("selectionMultiple", factory.getDisplayName(), - "" + factoryCount); + return Strings.get("selectionMultiple", factory.getDisplayName(), "" + factoryCount); } } @Override public void setValueRequested(Attribute attribute, Object value) - throws AttrTableSetException { + throws AttrTableSetException { Selection selection = frame.getCanvas().getSelection(); Circuit circuit = frame.getCanvas().getCircuit(); if (selection.isEmpty() && circuit != null) { @@ -83,7 +81,7 @@ public void setValueRequested(Attribute attribute, Object value) circuitModel.setValueRequested(attribute, value); } else { SetAttributeAction act = new SetAttributeAction(circuit, - Strings.getter("selectionAttributeAction")); + Strings.getter("selectionAttributeAction")); for (Component comp : selection.getComponents()) { if (!(comp instanceof Wire)) { act.set(comp, attribute, value); diff --git a/src/main/java/com/cburch/logisim/gui/main/AttrTableToolModel.java b/src/main/java/com/cburch/logisim/gui/main/AttrTableToolModel.java index 38c27a2..9a0d12b 100644 --- a/src/main/java/com/cburch/logisim/gui/main/AttrTableToolModel.java +++ b/src/main/java/com/cburch/logisim/gui/main/AttrTableToolModel.java @@ -10,12 +10,12 @@ public class AttrTableToolModel extends AttributeSetTableModel { - Project proj; + Project project; Tool tool; - public AttrTableToolModel(Project proj, Tool tool) { + public AttrTableToolModel(Project project, Tool tool) { super(tool.getAttributeSet()); - this.proj = proj; + this.project = project; this.tool = tool; } @@ -30,6 +30,6 @@ public Tool getTool() { @Override public void setValueRequested(Attribute attribute, Object value) { - proj.doAction(ToolAttributeAction.create(tool, attribute, value)); + project.doAction(ToolAttributeAction.create(tool, attribute, value)); } } diff --git a/src/main/java/com/cburch/logisim/gui/main/Canvas.java b/src/main/java/com/cburch/logisim/gui/main/Canvas.java index 08d4187..e30598f 100644 --- a/src/main/java/com/cburch/logisim/gui/main/Canvas.java +++ b/src/main/java/com/cburch/logisim/gui/main/Canvas.java @@ -65,8 +65,7 @@ import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; -public class Canvas extends JPanel - implements LocaleListener, CanvasPaneContents { +public class Canvas extends JPanel implements LocaleListener, CanvasPaneContents { public static final Color HALO_COLOR = new Color(192, 255, 255); // don't bother to update the size if it hasn't changed more than this @@ -75,26 +74,26 @@ public class Canvas extends JPanel // pixels shown in canvas beyond outermost boundaries private static final int THRESH_SIZE_UPDATE = 10; private static final int BUTTONS_MASK = InputEvent.BUTTON1_DOWN_MASK - | InputEvent.BUTTON2_DOWN_MASK | InputEvent.BUTTON3_DOWN_MASK; + | InputEvent.BUTTON2_DOWN_MASK | InputEvent.BUTTON3_DOWN_MASK; private static final Color DEFAULT_ERROR_COLOR = new Color(192, 0, 0); private static final Color TICK_RATE_COLOR = new Color(0, 0, 92, 92); private static final Font TICK_RATE_FONT = new Font("serif", Font.BOLD, 12); - private Project proj; + private final Project proj; + private final Selection selection; + private final MyListener myListener = new MyListener(); + private final MyViewport viewport = new MyViewport(); + private final MyProjectListener myProjectListener = new MyProjectListener(); + private final TickCounter tickCounter; + private final CanvasPaintThread paintThread; + private final CanvasPainter painter; + private final Object repaintLock = new Object(); // for waitForRepaintDone private Tool drag_tool; - private Selection selection; private MouseMappings mappings; private CanvasPane canvasPane; private Bounds oldPreferredSize; - private MyListener myListener = new MyListener(); - private MyViewport viewport = new MyViewport(); - private MyProjectListener myProjectListener = new MyProjectListener(); - private TickCounter tickCounter; - private CanvasPaintThread paintThread; - private CanvasPainter painter; private boolean paintDirty = false; // only for within paintComponent private boolean inPaint = false; // only for within paintComponent - private Object repaintLock = new Object(); // for waitForRepaintDone public Canvas(Project proj) { this.proj = proj; @@ -269,8 +268,8 @@ public void computeSize(boolean immediate) { if (!immediate) { Bounds old = oldPreferredSize; if (old != null - && Math.abs(old.getWidth() - dim.width) < THRESH_SIZE_UPDATE - && Math.abs(old.getHeight() - dim.height) < THRESH_SIZE_UPDATE) { + && Math.abs(old.getWidth() - dim.width) < THRESH_SIZE_UPDATE + && Math.abs(old.getHeight() - dim.height) < THRESH_SIZE_UPDATE) { return; } } @@ -338,13 +337,13 @@ private void computeViewportContents() { viewable = viewableBase; } else { viewable = new Rectangle((int) (viewableBase.x / zoom), - (int) (viewableBase.y / zoom), - (int) (viewableBase.width / zoom), - (int) (viewableBase.height / zoom)); + (int) (viewableBase.y / zoom), + (int) (viewableBase.width / zoom), + (int) (viewableBase.height / zoom)); } viewport.setWidthMessage(Strings.get("canvasWidthError") - + (exceptions.size() == 1 ? "" : " (" + exceptions.size() + ")")); + + (exceptions.size() == 1 ? "" : " (" + exceptions.size() + ")")); for (WidthIncompatibilityData ex : exceptions) { // See whether any of the points are on the canvas. boolean isWithin = false; @@ -353,7 +352,7 @@ private void computeViewportContents() { int x = p.getX(); int y = p.getY(); if (x >= viewable.x && x < viewable.x + viewable.width - && y >= viewable.y && y < viewable.y + viewable.height) { + && y >= viewable.y && y < viewable.y + viewable.height) { isWithin = true; break; } @@ -504,7 +503,7 @@ public Dimension getPreferredScrollableViewportSize() { } public int getScrollableBlockIncrement(Rectangle visibleRect, - int orientation, int direction) { + int orientation, int direction) { return canvasPane.supportScrollableBlockIncrement(visibleRect, orientation, direction); } @@ -517,7 +516,7 @@ public boolean getScrollableTracksViewportWidth() { } public int getScrollableUnitIncrement(Rectangle visibleRect, - int orientation, int direction) { + int orientation, int direction) { return canvasPane.supportScrollableUnitIncrement(visibleRect, orientation, direction); } @@ -526,8 +525,8 @@ public void localeChanged() { } private class MyListener - implements MouseInputListener, KeyListener, PopupMenuListener, - PropertyChangeListener { + implements MouseInputListener, KeyListener, PopupMenuListener, + PropertyChangeListener { boolean menu_on = false; @@ -660,7 +659,7 @@ public void popupMenuWillBecomeVisible(PopupMenuEvent e) { public void propertyChange(PropertyChangeEvent event) { if (AppPreferences.GATE_SHAPE.isSource(event) - || AppPreferences.SHOW_TICK_RATE.isSource(event)) { + || AppPreferences.SHOW_TICK_RATE.isSource(event)) { paintThread.requestRepaint(); } else if (AppPreferences.COMPONENT_TIPS.isSource(event)) { boolean showTips = AppPreferences.COMPONENT_TIPS.getBoolean(); @@ -670,8 +669,8 @@ public void propertyChange(PropertyChangeEvent event) { } private class MyProjectListener - implements ProjectListener, LibraryListener, CircuitListener, - AttributeListener, SimulatorListener, Selection.Listener { + implements ProjectListener, LibraryListener, CircuitListener, + AttributeListener, SimulatorListener, Selection.Listener { public void projectChanged(ProjectEvent event) { int act = event.getAction(); @@ -714,8 +713,8 @@ public void projectChanged(ProjectEvent event) { } if (act != ProjectEvent.ACTION_SELECTION - && act != ProjectEvent.ACTION_START - && act != ProjectEvent.UNDO_START) { + && act != ProjectEvent.ACTION_START + && act != ProjectEvent.UNDO_START) { completeAction(); } } @@ -737,7 +736,7 @@ public void libraryChanged(LibraryEvent event) { if (proj.getTool() == event.getData()) { Tool next = findTool(proj.getLogisimFile().getOptions() - .getToolbarData().getContents()); + .getToolbarData().getContents()); if (next == null) { for (Library lib : proj.getLogisimFile().getLibraries()) { next = findTool(lib.getTools()); @@ -962,35 +961,35 @@ void paintContents(Graphics g) { GraphicsUtil.switchToWidth(g, 3); if (isNorth) { GraphicsUtil.drawArrow(g, sz.width / 2, 20, - sz.width / 2, 2, 10, 30); + sz.width / 2, 2, 10, 30); } if (isSouth) { GraphicsUtil.drawArrow(g, sz.width / 2, sz.height - 20, - sz.width / 2, sz.height - 2, 10, 30); + sz.width / 2, sz.height - 2, 10, 30); } if (isEast) { GraphicsUtil.drawArrow(g, sz.width - 20, sz.height / 2, - sz.width - 2, sz.height / 2, 10, 30); + sz.width - 2, sz.height / 2, 10, 30); } if (isWest) { GraphicsUtil.drawArrow(g, 20, sz.height / 2, - 2, sz.height / 2, 10, 30); + 2, sz.height / 2, 10, 30); } if (isNortheast) { GraphicsUtil.drawArrow(g, sz.width - 14, 14, - sz.width - 2, 2, 10, 30); + sz.width - 2, 2, 10, 30); } if (isNorthwest) { GraphicsUtil.drawArrow(g, 14, 14, - 2, 2, 10, 30); + 2, 2, 10, 30); } if (isSoutheast) { GraphicsUtil.drawArrow(g, sz.width - 14, sz.height - 14, - sz.width - 2, sz.height - 2, 10, 30); + sz.width - 2, sz.height - 2, 10, 30); } if (isSouthwest) { GraphicsUtil.drawArrow(g, 14, sz.height - 14, - 2, sz.height - 2, 10, 30); + 2, sz.height - 2, 10, 30); } if (AppPreferences.SHOW_TICK_RATE.getBoolean()) { diff --git a/src/main/java/com/cburch/logisim/gui/main/CanvasPaintThread.java b/src/main/java/com/cburch/logisim/gui/main/CanvasPaintThread.java index d46fbc2..535e149 100644 --- a/src/main/java/com/cburch/logisim/gui/main/CanvasPaintThread.java +++ b/src/main/java/com/cburch/logisim/gui/main/CanvasPaintThread.java @@ -9,8 +9,8 @@ class CanvasPaintThread extends Thread { private static final int REPAINT_TIMESPAN = 50; // 50 ms between repaints - private Canvas canvas; - private Object lock; + private final Canvas canvas; + private final Object lock; private boolean repaintRequested; private long nextRepaint; private boolean alive; @@ -69,6 +69,7 @@ public void run() { lock.wait(); } } catch (InterruptedException e) { + e.printStackTrace(); } now = System.currentTimeMillis(); wait = nextRepaint - now; diff --git a/src/main/java/com/cburch/logisim/gui/main/CanvasPainter.java b/src/main/java/com/cburch/logisim/gui/main/CanvasPainter.java index 18c65b2..c8d3615 100644 --- a/src/main/java/com/cburch/logisim/gui/main/CanvasPainter.java +++ b/src/main/java/com/cburch/logisim/gui/main/CanvasPainter.java @@ -33,8 +33,8 @@ class CanvasPainter implements PropertyChangeListener { private static final Set NO_COMPONENTS = Collections.emptySet(); - private Canvas canvas; - private GridPainter grid; + private final Canvas canvas; + private final GridPainter grid; private Component haloedComponent = null; private Circuit haloedCircuit = null; private WireSet highlightedWires = WireSet.EMPTY; @@ -87,13 +87,13 @@ private void exposeHaloedComponent(Graphics g) { double a = Canvas.SQRT_2 * w; double b = Canvas.SQRT_2 * h; canvas.repaint((int) Math.round(bds.getX() + w / 2.0 - a / 2.0), - (int) Math.round(bds.getY() + h / 2.0 - b / 2.0), - (int) Math.round(a), (int) Math.round(b)); + (int) Math.round(bds.getY() + h / 2.0 - b / 2.0), + (int) Math.round(a), (int) Math.round(b)); } public void propertyChange(PropertyChangeEvent event) { if (AppPreferences.PRINTER_VIEW.isSource(event) - || AppPreferences.ATTRIBUTE_HALO.isSource(event)) { + || AppPreferences.ATTRIBUTE_HALO.isSource(event)) { canvas.repaint(); } } @@ -125,7 +125,7 @@ void paintContents(Graphics g, Project proj) { CircuitState circState = proj.getCircuitState(); ComponentDrawContext ptContext = new ComponentDrawContext(canvas, - circ, circState, g, gScaled); + circ, circState, g, gScaled); ptContext.setHighlightedWires(highlightedWires); gScaled.setColor(Color.RED); circState.drawOscillatingPoints(ptContext); @@ -151,7 +151,7 @@ private void drawWithUserState(Graphics base, Graphics g, Project proj) { // draw halo around component whose attributes we are viewing boolean showHalo = AppPreferences.ATTRIBUTE_HALO.getBoolean(); if (showHalo && haloedComponent != null && haloedCircuit == circ - && !hidden.contains(haloedComponent)) { + && !hidden.contains(haloedComponent)) { GraphicsUtil.switchToWidth(g, 3); g.setColor(Canvas.HALO_COLOR); Bounds bds = haloedComponent.getBounds(g).expand(5); @@ -160,8 +160,8 @@ private void drawWithUserState(Graphics base, Graphics g, Project proj) { double a = Canvas.SQRT_2 * w; double b = Canvas.SQRT_2 * h; g.drawOval((int) Math.round(bds.getX() + w / 2.0 - a / 2.0), - (int) Math.round(bds.getY() + h / 2.0 - b / 2.0), - (int) Math.round(a), (int) Math.round(b)); + (int) Math.round(bds.getY() + h / 2.0 - b / 2.0), + (int) Math.round(a), (int) Math.round(b)); GraphicsUtil.switchToWidth(g, 1); g.setColor(Color.BLACK); } @@ -170,7 +170,7 @@ private void drawWithUserState(Graphics base, Graphics g, Project proj) { CircuitState circState = proj.getCircuitState(); boolean printerView = AppPreferences.PRINTER_VIEW.getBoolean(); ComponentDrawContext context = new ComponentDrawContext(canvas, - circ, circState, base, g, printerView); + circ, circState, base, g, printerView); context.setHighlightedWires(highlightedWires); circ.draw(context, hidden); sel.draw(context, hidden); diff --git a/src/main/java/com/cburch/logisim/gui/main/CircuitJList.java b/src/main/java/com/cburch/logisim/gui/main/CircuitJList.java index 895061e..13f570d 100644 --- a/src/main/java/com/cburch/logisim/gui/main/CircuitJList.java +++ b/src/main/java/com/cburch/logisim/gui/main/CircuitJList.java @@ -13,19 +13,19 @@ import java.util.Vector; import javax.swing.JList; -class CircuitJList extends JList { +class CircuitJList extends JList { - public CircuitJList(Project proj, boolean includeEmpty) { - LogisimFile file = proj.getLogisimFile(); - Circuit current = proj.getCurrentCircuit(); + public CircuitJList(Project project, boolean includeEmpty) { + LogisimFile file = project.getLogisimFile(); + Circuit current = project.getCurrentCircuit(); Vector options = new Vector<>(); boolean currentFound = false; - for (Circuit circ : file.getCircuits()) { - if (!includeEmpty || circ.getBounds() != Bounds.EMPTY_BOUNDS) { - if (circ == current) { + for (Circuit circuit : file.getCircuits()) { + if (!includeEmpty || circuit.getBounds() != Bounds.EMPTY_BOUNDS) { + if (circuit == current) { currentFound = true; } - options.add(circ); + options.add(circuit); } } @@ -37,15 +37,15 @@ public CircuitJList(Project proj, boolean includeEmpty) { } public List getSelectedCircuits() { - Object[] selected = getSelectedValues(); - if (selected != null && selected.length > 0) { - ArrayList ret = new ArrayList<>(selected.length); - for (Object sel : selected) { - if (sel instanceof Circuit) { - ret.add((Circuit) sel); + List selected = getSelectedValuesList(); + if (selected != null && selected.size() > 0) { + ArrayList circuits = new ArrayList<>(selected.size()); + for (Circuit circuit : selected) { + if (circuit != null) { + circuits.add(circuit); } } - return ret; + return circuits; } else { return Collections.emptyList(); } diff --git a/src/main/java/com/cburch/logisim/gui/main/Clipboard.java b/src/main/java/com/cburch/logisim/gui/main/Clipboard.java index 6e781f0..33bed97 100644 --- a/src/main/java/com/cburch/logisim/gui/main/Clipboard.java +++ b/src/main/java/com/cburch/logisim/gui/main/Clipboard.java @@ -13,25 +13,24 @@ class Clipboard { public static final String contentsProperty = "contents"; - + private static final PropertyChangeWeakSupport propertySupport = new PropertyChangeWeakSupport(Clipboard.class); private static Clipboard current = null; - private static PropertyChangeWeakSupport propertySupport = new PropertyChangeWeakSupport(Clipboard.class); // // instance variables and methods // - private HashSet components; + private final HashSet components; private AttributeSet oldAttrs; private AttributeSet newAttrs; - private Clipboard(Selection sel, AttributeSet viewAttrs) { + private Clipboard(Selection selection, AttributeSet viewAttrs) { components = new HashSet<>(); oldAttrs = null; newAttrs = null; - for (Component base : sel.getComponents()) { + for (Component base : selection.getComponents()) { AttributeSet baseAttrs = base.getAttributeSet(); AttributeSet copyAttrs = (AttributeSet) baseAttrs.clone(); Component copy = base.getFactory().createComponent(base.getLocation(), - copyAttrs); + copyAttrs); components.add(copy); if (baseAttrs == viewAttrs) { oldAttrs = baseAttrs; diff --git a/src/main/java/com/cburch/logisim/gui/main/ExplorerToolbarModel.java b/src/main/java/com/cburch/logisim/gui/main/ExplorerToolbarModel.java index b846e04..bb8ea4e 100644 --- a/src/main/java/com/cburch/logisim/gui/main/ExplorerToolbarModel.java +++ b/src/main/java/com/cburch/logisim/gui/main/ExplorerToolbarModel.java @@ -10,34 +10,33 @@ import com.cburch.logisim.util.UnmodifiableList; import java.util.List; -class ExplorerToolbarModel extends AbstractToolbarModel - implements MenuListener.EnabledListener { +class ExplorerToolbarModel extends AbstractToolbarModel implements MenuListener.EnabledListener { - private Frame frame; - private LogisimToolbarItem itemToolbox; - private LogisimToolbarItem itemSimulation; - private LogisimToolbarItem itemLayout; - private LogisimToolbarItem itemAppearance; - private List items; + private final Frame frame; + private final LogisimToolbarItem itemToolbox; + private final LogisimToolbarItem itemSimulation; + private final LogisimToolbarItem itemLayout; + private final LogisimToolbarItem itemAppearance; + private final List items; public ExplorerToolbarModel(Frame frame, MenuListener menu) { this.frame = frame; itemToolbox = new LogisimToolbarItem(menu, "projtool.gif", - LogisimMenuBar.VIEW_TOOLBOX, Strings.getter("projectViewToolboxTip")); + LogisimMenuBar.VIEW_TOOLBOX, Strings.getter("projectViewToolboxTip")); itemSimulation = new LogisimToolbarItem(menu, "projsim.gif", - LogisimMenuBar.VIEW_SIMULATION, Strings.getter("projectViewSimulationTip")); + LogisimMenuBar.VIEW_SIMULATION, Strings.getter("projectViewSimulationTip")); itemLayout = new LogisimToolbarItem(menu, "projlayo.gif", - LogisimMenuBar.EDIT_LAYOUT, Strings.getter("projectEditLayoutTip")); + LogisimMenuBar.EDIT_LAYOUT, Strings.getter("projectEditLayoutTip")); itemAppearance = new LogisimToolbarItem(menu, "projapp.gif", - LogisimMenuBar.EDIT_APPEARANCE, Strings.getter("projectEditAppearanceTip")); + LogisimMenuBar.EDIT_APPEARANCE, Strings.getter("projectEditAppearanceTip")); items = UnmodifiableList.create(new ToolbarItem[]{ - itemToolbox, - itemSimulation, - new ToolbarSeparator(4), - itemLayout, - itemAppearance, + itemToolbox, + itemSimulation, + new ToolbarSeparator(4), + itemLayout, + itemAppearance, }); menu.addEnabledListener(this); diff --git a/src/main/java/com/cburch/logisim/gui/main/ExportImage.java b/src/main/java/com/cburch/logisim/gui/main/ExportImage.java index 89a7afa..be4410f 100644 --- a/src/main/java/com/cburch/logisim/gui/main/ExportImage.java +++ b/src/main/java/com/cburch/logisim/gui/main/ExportImage.java @@ -60,16 +60,16 @@ static void doExport(Project proj) { CircuitJList list = new CircuitJList(proj, true); if (list.getModel().getSize() == 0) { JOptionPane.showMessageDialog(proj.getFrame(), - Strings.get("exportEmptyCircuitsMessage"), - Strings.get("exportEmptyCircuitsTitle"), - JOptionPane.YES_NO_OPTION); + Strings.get("exportEmptyCircuitsMessage"), + Strings.get("exportEmptyCircuitsTitle"), + JOptionPane.YES_NO_OPTION); return; } OptionsPanel options = new OptionsPanel(list); int action = JOptionPane.showConfirmDialog(frame, - options, Strings.get("exportImageSelect"), - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE); + options, Strings.get("exportImageSelect"), + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); if (action != JOptionPane.OK_OPTION) { return; } @@ -85,15 +85,15 @@ static void doExport(Project proj) { switch (options.getImageFormat()) { case FORMAT_GIF: filter = new ImageFileFilter(fmt, Strings.getter("exportGifFilter"), - new String[]{"gif"}); + new String[]{"gif"}); break; case FORMAT_PNG: filter = new ImageFileFilter(fmt, Strings.getter("exportPngFilter"), - new String[]{"png"}); + new String[]{"png"}); break; case FORMAT_JPG: filter = new ImageFileFilter(fmt, Strings.getter("exportJpgFilter"), - new String[]{"jpg", "jpeg", "jpe", "jfi", "jfif", "jfi"}); + new String[]{"jpg", "jpeg", "jpe", "jfi", "jfif", "jfi"}); break; default: System.err.println("unexpected format; aborted"); //OK @@ -121,9 +121,9 @@ static void doExport(Project proj) { if (dest.exists()) { if (!dest.isDirectory()) { int confirm = JOptionPane.showConfirmDialog(proj.getFrame(), - Strings.get("confirmOverwriteMessage"), - Strings.get("confirmOverwriteTitle"), - JOptionPane.YES_NO_OPTION); + Strings.get("confirmOverwriteMessage"), + Strings.get("confirmOverwriteTitle"), + JOptionPane.YES_NO_OPTION); if (confirm != JOptionPane.YES_OPTION) { return; } @@ -133,9 +133,9 @@ static void doExport(Project proj) { boolean created = dest.mkdir(); if (!created) { JOptionPane.showMessageDialog(proj.getFrame(), - Strings.get("exportNewDirectoryErrorMessage"), - Strings.get("exportNewDirectoryErrorTitle"), - JOptionPane.YES_NO_OPTION); + Strings.get("exportNewDirectoryErrorMessage"), + Strings.get("exportNewDirectoryErrorTitle"), + JOptionPane.YES_NO_OPTION); return; } } @@ -143,9 +143,9 @@ static void doExport(Project proj) { // Create the progress monitor ProgressMonitor monitor = new ProgressMonitor(frame, - Strings.get("exportImageProgress"), - null, - 0, 10000); + Strings.get("exportImageProgress"), + null, + 0, 10000); monitor.setMillisToDecideToPopup(100); monitor.setMillisToPopup(200); monitor.setProgress(0); @@ -154,7 +154,7 @@ static void doExport(Project proj) { // (This is run in a thread so that Swing will update the // monitor.) new ExportThread(frame, frame.getCanvas(), dest, filter, - circuits, scale, printerView, monitor).start(); + circuits, scale, printerView, monitor).start(); } @@ -182,7 +182,7 @@ private static class OptionsPanel extends JPanel implements ChangeListener { formatPng.setSelected(true); slider = new JSlider(JSlider.HORIZONTAL, - -3 * SLIDER_DIVISIONS, 3 * SLIDER_DIVISIONS, 0); + -3 * SLIDER_DIVISIONS, 3 * SLIDER_DIVISIONS, 0); slider.setMajorTickSpacing(10); slider.addChangeListener(this); curScale = new JLabel("222%"); @@ -190,7 +190,7 @@ private static class OptionsPanel extends JPanel implements ChangeListener { curScale.setVerticalAlignment(SwingConstants.CENTER); curScaleDim = new Dimension(curScale.getPreferredSize()); curScaleDim.height = Math.max(curScaleDim.height, - slider.getPreferredSize().height); + slider.getPreferredSize().height); stateChanged(null); printerView = new JCheckBox(); @@ -264,9 +264,9 @@ public void stateChanged(ChangeEvent e) { private static class ImageFileFilter extends FileFilter { - private int type; - private String[] extensions; - private StringGetter desc; + private final int type; + private final String[] extensions; + private final StringGetter desc; private ImageFileFilter(int type, StringGetter desc, String[] exts) { this.type = type; @@ -306,8 +306,8 @@ private static class ExportThread extends Thread { ProgressMonitor monitor; ExportThread(Frame frame, Canvas canvas, File dest, ImageFileFilter f, - List circuits, double scale, boolean printerView, - ProgressMonitor monitor) { + List circuits, double scale, boolean printerView, + ProgressMonitor monitor) { this.frame = frame; this.canvas = canvas; this.dest = dest; @@ -327,11 +327,11 @@ public void run() { private void export(Circuit circuit) { Bounds bds = circuit.getBounds(canvas.getGraphics()) - .expand(BORDER_SIZE); + .expand(BORDER_SIZE); int width = (int) Math.round(bds.getWidth() * scale); int height = (int) Math.round(bds.getHeight() * scale); BufferedImage img = new BufferedImage(width, height, - BufferedImage.TYPE_INT_RGB); + BufferedImage.TYPE_INT_RGB); Graphics base = img.getGraphics(); Graphics g = base.create(); g.setColor(Color.white); @@ -342,13 +342,13 @@ private void export(Circuit circuit) { g.translate(-bds.getX(), -bds.getY()); } else { JOptionPane.showMessageDialog(frame, - Strings.get("couldNotCreateImage")); + Strings.get("couldNotCreateImage")); monitor.close(); } CircuitState circuitState = canvas.getProject().getCircuitState(circuit); ComponentDrawContext context = new ComponentDrawContext(canvas, - circuit, circuitState, base, g, printerView); + circuit, circuitState, base, g, printerView); circuit.draw(context, null); File where; @@ -374,7 +374,7 @@ private void export(Circuit circuit) { } } catch (Exception e) { JOptionPane.showMessageDialog(frame, - Strings.get("couldNotCreateFile")); + Strings.get("couldNotCreateFile")); monitor.close(); return; } diff --git a/src/main/java/com/cburch/logisim/gui/main/Frame.java b/src/main/java/com/cburch/logisim/gui/main/Frame.java index 341c879..9da7f86 100644 --- a/src/main/java/com/cburch/logisim/gui/main/Frame.java +++ b/src/main/java/com/cburch/logisim/gui/main/Frame.java @@ -69,24 +69,24 @@ public class Frame extends LFrame implements LocaleListener { public static final String VIEW_SIMULATION = "simulation"; private static final double[] ZOOM_OPTIONS = {25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400}; - private Project project; - private MyProjectListener myProjectListener = new MyProjectListener(); - private MenuListener menuListener; - private Toolbar toolbar; - private HorizontalSplitPane leftRegion; - private VerticalSplitPane mainRegion; - private JPanel mainPanelSuper; - private CardPanel mainPanel; - private CardPanel explorerPane; - private Toolbox toolbox; - private AttrTable attributeTable; - private ZoomControl zoom; + private final Project project; + private final MyProjectListener myProjectListener = new MyProjectListener(); + private final MenuListener menuListener; + private final Toolbar toolbar; + private final HorizontalSplitPane leftRegion; + private final VerticalSplitPane mainRegion; + private final JPanel mainPanelSuper; + private final CardPanel mainPanel; + private final CardPanel explorerPane; + private final Toolbox toolbox; + private final AttrTable attributeTable; + private final ZoomControl zoom; // for the Layout view - private LayoutToolbarModel layoutToolbarModel; - private Canvas layoutCanvas; - private ZoomModel layoutZoomModel; - private LayoutEditHandler layoutEditHandler; - private AttrTableSelectionModel attributeTableSelectionModel; + private final LayoutToolbarModel layoutToolbarModel; + private final Canvas layoutCanvas; + private final ZoomModel layoutZoomModel; + private final LayoutEditHandler layoutEditHandler; + private final AttrTableSelectionModel attributeTableSelectionModel; // for the Appearance view private AppearanceView appearance; @@ -211,10 +211,8 @@ private static Point getInitialLocation() { int size = inter.width * inter.height; if (size > gcBestSize) { gcBestSize = size; - int x2 = Math.max(gcBounds.x, Math.min(inter.x, - inter.x + inter.width - 50)); - int y2 = Math.max(gcBounds.y, Math.min(inter.y, - inter.y + inter.height - 50)); + int x2 = Math.max(gcBounds.x, Math.min(inter.x, inter.x + inter.width - 50)); + int y2 = Math.max(gcBounds.y, Math.min(inter.y, inter.y + inter.height - 50)); gcBestPoint = new Point(x2, y2); } } @@ -363,7 +361,7 @@ private void computeTitle() { String name = project.getLogisimFile().getName(); if (circuit != null) { str = StringUtil.format(Strings.get("titleCircFileKnown"), - circuit.getName(), name); + circuit.getName(), name); } else { str = StringUtil.format(Strings.get("titleFileKnown"), name); } @@ -404,7 +402,7 @@ private void viewAttributes(Tool oldTool, Tool newTool, boolean force) { if (newAttributes == null) { AttrTableModel oldModel = attributeTable.getAttrTableModel(); boolean same = oldModel instanceof AttrTableToolModel - && ((AttrTableToolModel) oldModel).getTool() == oldTool; + && ((AttrTableToolModel) oldModel).getTool() == oldTool; if (!force && !same && !(oldModel instanceof AttrTableCircuitModel)) { return; } @@ -462,7 +460,7 @@ public boolean confirmClose() { // returns true if user is OK with proceeding public boolean confirmClose(String title) { String message = StringUtil.format(Strings.get("confirmDiscardMessage"), - project.getLogisimFile().getName()); + project.getLogisimFile().getName()); if (!project.isFileDirty()) { return true; @@ -470,8 +468,8 @@ public boolean confirmClose(String title) { toFront(); String[] options = {Strings.get("saveOption"), Strings.get("discardOption"), Strings.get("cancelOption")}; int result = JOptionPane.showOptionDialog(this, - message, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, - options, options[0]); + message, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, + options, options[0]); boolean ret; if (result == 0) { ret = ProjectActions.doSave(project); @@ -485,8 +483,8 @@ public boolean confirmClose(String title) { } class MyProjectListener - implements ProjectListener, LibraryListener, CircuitListener, - PropertyChangeListener, ChangeListener { + implements ProjectListener, LibraryListener, CircuitListener, + PropertyChangeListener, ChangeListener { public void projectChanged(ProjectEvent event) { int action = event.getAction(); @@ -534,7 +532,8 @@ private void enableSave() { getRootPane().putClientProperty("windowModified", isDirty); } - public void attributeListChanged() { } + public void attributeListChanged() { + } public void propertyChange(PropertyChangeEvent event) { if (AppPreferences.TOOLBAR_PLACEMENT.isSource(event)) { diff --git a/src/main/java/com/cburch/logisim/gui/main/KeyboardToolSelection.java b/src/main/java/com/cburch/logisim/gui/main/KeyboardToolSelection.java index abd3788..16120c2 100644 --- a/src/main/java/com/cburch/logisim/gui/main/KeyboardToolSelection.java +++ b/src/main/java/com/cburch/logisim/gui/main/KeyboardToolSelection.java @@ -15,8 +15,8 @@ public class KeyboardToolSelection extends AbstractAction { - private Toolbar toolbar; - private int index; + private final Toolbar toolbar; + private final int index; public KeyboardToolSelection(Toolbar toolbar, int index) { this.toolbar = toolbar; @@ -24,15 +24,15 @@ public KeyboardToolSelection(Toolbar toolbar, int index) { } public static void register(Toolbar toolbar) { - ActionMap amap = toolbar.getActionMap(); + ActionMap actionMap = toolbar.getActionMap(); InputMap imap = toolbar.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); - int mask = toolbar.getToolkit().getMenuShortcutKeyMask(); + int mask = toolbar.getToolkit().getMenuShortcutKeyMaskEx(); for (int i = 0; i < 10; i++) { KeyStroke keyStroke = KeyStroke.getKeyStroke((char) ('0' + i), mask); int j = (i == 0 ? 10 : i - 1); KeyboardToolSelection action = new KeyboardToolSelection(toolbar, j); String key = "ToolSelect" + i; - amap.put(key, action); + actionMap.put(key, action); imap.put(keyStroke, key); } } diff --git a/src/main/java/com/cburch/logisim/gui/main/LayoutEditHandler.java b/src/main/java/com/cburch/logisim/gui/main/LayoutEditHandler.java index acdaab0..1ff60c5 100644 --- a/src/main/java/com/cburch/logisim/gui/main/LayoutEditHandler.java +++ b/src/main/java/com/cburch/logisim/gui/main/LayoutEditHandler.java @@ -18,9 +18,9 @@ import java.beans.PropertyChangeListener; public class LayoutEditHandler extends EditHandler - implements ProjectListener, LibraryListener, PropertyChangeListener { + implements ProjectListener, LibraryListener, PropertyChangeListener { - private Frame frame; + private final Frame frame; LayoutEditHandler(Frame frame) { this.frame = frame; @@ -47,8 +47,7 @@ public void computeEnabled() { setEnabled(LogisimMenuBar.CUT, !selEmpty && selectAvailable && canChange); setEnabled(LogisimMenuBar.COPY, !selEmpty && selectAvailable); - setEnabled(LogisimMenuBar.PASTE, selectAvailable && canChange - && !Clipboard.isEmpty()); + setEnabled(LogisimMenuBar.PASTE, selectAvailable && canChange && !Clipboard.isEmpty()); setEnabled(LogisimMenuBar.DELETE, !selEmpty && selectAvailable && canChange); setEnabled(LogisimMenuBar.DUPLICATE, !selEmpty && selectAvailable && canChange); setEnabled(LogisimMenuBar.SELECT_ALL, selectAvailable); diff --git a/src/main/java/com/cburch/logisim/gui/main/LayoutToolbarModel.java b/src/main/java/com/cburch/logisim/gui/main/LayoutToolbarModel.java index 4fb4cd4..8ee141e 100644 --- a/src/main/java/com/cburch/logisim/gui/main/LayoutToolbarModel.java +++ b/src/main/java/com/cburch/logisim/gui/main/LayoutToolbarModel.java @@ -29,9 +29,9 @@ class LayoutToolbarModel extends AbstractToolbarModel { - private Frame frame; - private Project proj; - private MyListener myListener; + private final Frame frame; + private final Project proj; + private final MyListener myListener; private List items; private Tool haloedTool; @@ -116,7 +116,7 @@ private void buildContents() { private class ToolItem implements ToolbarItem { - private Tool tool; + private final Tool tool; ToolItem(Tool tool) { this.tool = tool; @@ -136,8 +136,7 @@ public void paintIcon(Component destination, Graphics graphics) { // draw tool icon graphics.setColor(Color.BLACK); Graphics g_copy = graphics.create(); - ComponentDrawContext c = new ComponentDrawContext(destination, - null, null, graphics, g_copy); + ComponentDrawContext c = new ComponentDrawContext(destination, null, null, graphics, g_copy); tool.paintIcon(c, 2, 2); g_copy.dispose(); } @@ -157,9 +156,8 @@ public String getToolTip() { if (index == 10) { index = 0; } - int mask = frame.getToolkit().getMenuShortcutKeyMask(); - ret += " (" + InputEventUtil.toKeyDisplayString(mask) - + "-" + index + ")"; + int mask = frame.getToolkit().getMenuShortcutKeyMaskEx(); + ret += " (" + InputEventUtil.toKeyDisplayString(mask) + "-" + index + ")"; } return ret; } @@ -170,7 +168,7 @@ public Dimension getDimension(Object orientation) { } private class MyListener implements ProjectListener, AttributeListener, - ToolbarData.ToolbarListener, PropertyChangeListener { + ToolbarData.ToolbarListener, PropertyChangeListener { // // ProjectListener methods diff --git a/src/main/java/com/cburch/logisim/gui/main/LogisimToolbarItem.java b/src/main/java/com/cburch/logisim/gui/main/LogisimToolbarItem.java index f783f06..6261b9a 100644 --- a/src/main/java/com/cburch/logisim/gui/main/LogisimToolbarItem.java +++ b/src/main/java/com/cburch/logisim/gui/main/LogisimToolbarItem.java @@ -18,13 +18,13 @@ class LogisimToolbarItem implements ToolbarItem { - private MenuListener menu; + private final MenuListener menu; + private final LogisimMenuItem action; private Icon icon; - private LogisimMenuItem action; private StringGetter toolTip; public LogisimToolbarItem(MenuListener menu, String iconName, - LogisimMenuItem action, StringGetter toolTip) { + LogisimMenuItem action, StringGetter toolTip) { this.menu = menu; this.icon = Icons.getIcon(iconName); this.action = action; diff --git a/src/main/java/com/cburch/logisim/gui/main/MenuListener.java b/src/main/java/com/cburch/logisim/gui/main/MenuListener.java index 531649b..af622ae 100644 --- a/src/main/java/com/cburch/logisim/gui/main/MenuListener.java +++ b/src/main/java/com/cburch/logisim/gui/main/MenuListener.java @@ -29,13 +29,13 @@ class MenuListener { - private Frame frame; - private LogisimMenuBar menubar; - private ArrayList listeners; - private FileListener fileListener = new FileListener(); - private EditListener editListener = new EditListener(); - private ProjectMenuListener projectListener = new ProjectMenuListener(); - private SimulateMenuListener simulateListener = new SimulateMenuListener(); + private final Frame frame; + private final LogisimMenuBar menubar; + private final ArrayList listeners; + private final FileListener fileListener = new FileListener(); + private final EditListener editListener = new EditListener(); + private final ProjectMenuListener projectListener = new ProjectMenuListener(); + private final SimulateMenuListener simulateListener = new SimulateMenuListener(); public MenuListener(Frame frame, LogisimMenuBar menubar) { this.frame = frame; @@ -186,7 +186,7 @@ public void actionPerformed(ActionEvent e) { } public void enableChanged(EditHandler handler, LogisimMenuItem action, - boolean value) { + boolean value) { if (handler == this.handler) { menubar.setEnabled(action, value); fireEnableChanged(); @@ -195,7 +195,7 @@ public void enableChanged(EditHandler handler, LogisimMenuItem action, } class ProjectMenuListener implements ProjectListener, LibraryListener, - ActionListener, PropertyChangeListener, CanvasModelListener { + ActionListener, PropertyChangeListener, CanvasModelListener { void register() { Project proj = frame.getProject(); @@ -309,7 +309,7 @@ private void computeEnabled() { canMoveDown = curIndex < tools.size() - 1; canRemove = tools.size() > 1; canRevert = viewAppearance - && !cur.getAppearance().isDefaultAppearance(); + && !cur.getAppearance().isDefaultAppearance(); } menubar.setEnabled(LogisimMenuBar.ADD_CIRCUIT, true); @@ -335,7 +335,7 @@ private void computeRevertEnabled() { boolean isProjectCircuit = file.contains(cur); boolean viewAppearance = frame.getEditorView().equals(Frame.EDIT_APPEARANCE); boolean canRevert = isProjectCircuit && viewAppearance - && !cur.getAppearance().isDefaultAppearance(); + && !cur.getAppearance().isDefaultAppearance(); boolean oldValue = menubar.isEnabled(LogisimMenuBar.REVERT_APPEARANCE); if (canRevert != oldValue) { menubar.setEnabled(LogisimMenuBar.REVERT_APPEARANCE, canRevert); @@ -360,7 +360,7 @@ void register() { public void projectChanged(ProjectEvent event) { if (event.getAction() == ProjectEvent.ACTION_SET_STATE) { menubar.setCircuitState(frame.getProject().getSimulator(), - frame.getProject().getCircuitState()); + frame.getProject().getCircuitState()); } } diff --git a/src/main/java/com/cburch/logisim/gui/main/Print.java b/src/main/java/com/cburch/logisim/gui/main/Print.java index b6ef5e0..4aee320 100644 --- a/src/main/java/com/cburch/logisim/gui/main/Print.java +++ b/src/main/java/com/cburch/logisim/gui/main/Print.java @@ -27,7 +27,6 @@ import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; -import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; @@ -43,16 +42,16 @@ public static void doPrint(Project proj) { Frame frame = proj.getFrame(); if (list.getModel().getSize() == 0) { JOptionPane.showMessageDialog(proj.getFrame(), - Strings.get("printEmptyCircuitsMessage"), - Strings.get("printEmptyCircuitsTitle"), - JOptionPane.YES_NO_OPTION); + Strings.get("printEmptyCircuitsMessage"), + Strings.get("printEmptyCircuitsTitle"), + JOptionPane.YES_NO_OPTION); return; } ParmsPanel parmsPanel = new ParmsPanel(list); int action = JOptionPane.showConfirmDialog(frame, - parmsPanel, Strings.get("printParmsTitle"), - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE); + parmsPanel, Strings.get("printParmsTitle"), + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); if (action != JOptionPane.OK_OPTION) { return; } @@ -63,27 +62,27 @@ public static void doPrint(Project proj) { PageFormat format = new PageFormat(); Printable print = new MyPrintable(proj, circuits, - parmsPanel.getHeader(), - parmsPanel.getRotateToFit(), - parmsPanel.getPrinterView()); + parmsPanel.getHeader(), + parmsPanel.getRotateToFit(), + parmsPanel.getPrinterView()); PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(print, format); - if (job.printDialog() == false) { + if (!job.printDialog()) { return; } try { job.print(); } catch (PrinterException e) { JOptionPane.showMessageDialog(proj.getFrame(), - StringUtil.format(Strings.get("printError"), e.toString()), - Strings.get("printErrorTitle"), - JOptionPane.ERROR_MESSAGE); + StringUtil.format(Strings.get("printError"), e.toString()), + Strings.get("printErrorTitle"), + JOptionPane.ERROR_MESSAGE); } } private static String format(String header, int index, int max, - String circName) { + String circuitName) { int mark = header.indexOf('%'); if (mark < 0) { return header; @@ -91,17 +90,17 @@ private static String format(String header, int index, int max, StringBuilder ret = new StringBuilder(); int start = 0; for (; mark >= 0 && mark + 1 < header.length(); - start = mark + 2, mark = header.indexOf('%', start)) { + start = mark + 2, mark = header.indexOf('%', start)) { ret.append(header, start, mark); switch (header.charAt(mark + 1)) { case 'n': - ret.append(circName); + ret.append(circuitName); break; case 'p': - ret.append("" + index); + ret.append(index); break; case 'P': - ret.append("" + max); + ret.append(max); break; case '%': ret.append("%"); @@ -124,7 +123,7 @@ private static class ParmsPanel extends JPanel { GridBagLayout gridbag; GridBagConstraints gbc; - ParmsPanel(JList list) { + ParmsPanel(CircuitJList list) { // set up components rotateToFit = new JCheckBox(); rotateToFit.setSelected(true); @@ -182,15 +181,15 @@ String getHeader() { private static class MyPrintable implements Printable { - Project proj; + Project project; List circuits; String header; boolean rotateToFit; boolean printerView; - MyPrintable(Project proj, List circuits, String header, - boolean rotateToFit, boolean printerView) { - this.proj = proj; + MyPrintable(Project project, List circuits, String header, + boolean rotateToFit, boolean printerView) { + this.project = project; this.circuits = circuits; this.header = header; this.rotateToFit = rotateToFit; @@ -202,15 +201,15 @@ public int print(Graphics base, PageFormat format, int pageIndex) { return Printable.NO_SUCH_PAGE; } - Circuit circ = circuits.get(pageIndex); - CircuitState circState = proj.getCircuitState(circ); + Circuit circuit = circuits.get(pageIndex); + CircuitState circuitState = project.getCircuitState(circuit); Graphics g = base.create(); - Graphics2D g2 = g instanceof Graphics2D ? (Graphics2D) g : null; + Graphics2D g2d = g instanceof Graphics2D ? (Graphics2D) g : null; FontMetrics fm = g.getFontMetrics(); String head = (header != null && !header.equals("")) - ? format(header, pageIndex + 1, circuits.size(), - circ.getName()) - : null; + ? format(header, pageIndex + 1, circuits.size(), + circuit.getName()) + : null; int headHeight = (head == null ? 0 : fm.getHeight()); // Compute image size @@ -219,22 +218,22 @@ public int print(Graphics base, PageFormat format, int pageIndex) { // Correct coordinate system for page, including // translation and possible rotation. - Bounds bds = circ.getBounds(g).expand(4); + Bounds bds = circuit.getBounds(g).expand(4); double scale = Math.min(imWidth / bds.getWidth(), - (imHeight - headHeight) / bds.getHeight()); - if (g2 != null) { - g2.translate(format.getImageableX(), format.getImageableY()); + (imHeight - headHeight) / bds.getHeight()); + if (g2d != null) { + g2d.translate(format.getImageableX(), format.getImageableY()); if (rotateToFit && scale < 1.0 / 1.1) { double scale2 = Math.min(imHeight / bds.getWidth(), - (imWidth - headHeight) / bds.getHeight()); + (imWidth - headHeight) / bds.getHeight()); if (scale2 >= scale * 1.1) { // will rotate scale = scale2; if (imHeight > imWidth) { // portrait -> landscape - g2.translate(0, imHeight); - g2.rotate(-Math.PI / 2); + g2d.translate(0, imHeight); + g2d.rotate(-Math.PI / 2); } else { // landscape -> portrait - g2.translate(imWidth, 0); - g2.rotate(Math.PI / 2); + g2d.translate(imWidth, 0); + g2d.rotate(Math.PI / 2); } double t = imHeight; imHeight = imWidth; @@ -246,39 +245,39 @@ public int print(Graphics base, PageFormat format, int pageIndex) { // Draw the header line if appropriate if (head != null) { g.drawString(head, - (int) Math.round((imWidth - fm.stringWidth(head)) / 2), - fm.getAscent()); - if (g2 != null) { + (int) Math.round((imWidth - fm.stringWidth(head)) / 2), + fm.getAscent()); + if (g2d != null) { imHeight -= headHeight; - g2.translate(0, headHeight); + g2d.translate(0, headHeight); } } // Now change coordinate system for circuit, including // translation and possible scaling - if (g2 != null) { + if (g2d != null) { if (scale < 1.0) { - g2.scale(scale, scale); + g2d.scale(scale, scale); imWidth /= scale; imHeight /= scale; } double dx = Math.max(0.0, (imWidth - bds.getWidth()) / 2); - g2.translate(-bds.getX() + dx, -bds.getY()); + g2d.translate(-bds.getX() + dx, -bds.getY()); } // Ensure that the circuit is eligible to be drawn Rectangle clip = g.getClipBounds(); clip.add(bds.getX(), bds.getY()); clip.add(bds.getX() + bds.getWidth(), - bds.getY() + bds.getHeight()); + bds.getY() + bds.getHeight()); g.setClip(clip); // And finally draw the circuit onto the page ComponentDrawContext context = new ComponentDrawContext( - proj.getFrame().getCanvas(), circ, circState, - base, g, printerView); + project.getFrame().getCanvas(), circuit, circuitState, + base, g, printerView); Collection noComps = Collections.emptySet(); - circ.draw(context, noComps); + circuit.draw(context, noComps); g.dispose(); return Printable.PAGE_EXISTS; } diff --git a/src/main/java/com/cburch/logisim/gui/main/ProjectToolbarModel.java b/src/main/java/com/cburch/logisim/gui/main/ProjectToolbarModel.java index 6f275b6..8c149d9 100644 --- a/src/main/java/com/cburch/logisim/gui/main/ProjectToolbarModel.java +++ b/src/main/java/com/cburch/logisim/gui/main/ProjectToolbarModel.java @@ -11,41 +11,41 @@ import java.util.List; class ProjectToolbarModel extends AbstractToolbarModel - implements MenuListener.EnabledListener { + implements MenuListener.EnabledListener { - private Frame frame; - private LogisimToolbarItem itemAdd; - private LogisimToolbarItem itemUp; - private LogisimToolbarItem itemDown; - private LogisimToolbarItem itemDelete; - private LogisimToolbarItem itemLayout; - private LogisimToolbarItem itemAppearance; - private List items; + private final Frame frame; + private final LogisimToolbarItem itemAdd; + private final LogisimToolbarItem itemUp; + private final LogisimToolbarItem itemDown; + private final LogisimToolbarItem itemDelete; + private final LogisimToolbarItem itemLayout; + private final LogisimToolbarItem itemAppearance; + private final List items; public ProjectToolbarModel(Frame frame, MenuListener menu) { this.frame = frame; itemAdd = new LogisimToolbarItem(menu, "projadd.gif", LogisimMenuBar.ADD_CIRCUIT, - Strings.getter("projectAddCircuitTip")); + Strings.getter("projectAddCircuitTip")); itemUp = new LogisimToolbarItem(menu, "projup.gif", LogisimMenuBar.MOVE_CIRCUIT_UP, - Strings.getter("projectMoveCircuitUpTip")); + Strings.getter("projectMoveCircuitUpTip")); itemDown = new LogisimToolbarItem(menu, "projdown.gif", LogisimMenuBar.MOVE_CIRCUIT_DOWN, - Strings.getter("projectMoveCircuitDownTip")); + Strings.getter("projectMoveCircuitDownTip")); itemDelete = new LogisimToolbarItem(menu, "projdel.gif", LogisimMenuBar.REMOVE_CIRCUIT, - Strings.getter("projectRemoveCircuitTip")); + Strings.getter("projectRemoveCircuitTip")); itemLayout = new LogisimToolbarItem(menu, "projlayo.gif", LogisimMenuBar.EDIT_LAYOUT, - Strings.getter("projectEditLayoutTip")); + Strings.getter("projectEditLayoutTip")); itemAppearance = new LogisimToolbarItem(menu, "projapp.gif", LogisimMenuBar.EDIT_APPEARANCE, - Strings.getter("projectEditAppearanceTip")); + Strings.getter("projectEditAppearanceTip")); items = UnmodifiableList.create(new ToolbarItem[]{ - itemAdd, - itemUp, - itemDown, - itemDelete, - new ToolbarSeparator(4), - itemLayout, - itemAppearance, + itemAdd, + itemUp, + itemDown, + itemDelete, + new ToolbarSeparator(4), + itemLayout, + itemAppearance, }); menu.addEnabledListener(this); diff --git a/src/main/java/com/cburch/logisim/gui/main/Selection.java b/src/main/java/com/cburch/logisim/gui/main/Selection.java index 29a20a4..bb5bcbe 100644 --- a/src/main/java/com/cburch/logisim/gui/main/Selection.java +++ b/src/main/java/com/cburch/logisim/gui/main/Selection.java @@ -27,9 +27,9 @@ public class Selection extends SelectionBase { - private MyListener myListener; - private boolean isVisible = true; - private SelectionAttributes attrs; + private final MyListener myListener; + private final boolean isVisible = true; + private final SelectionAttributes attrs; public Selection(Project proj, Canvas canvas) { super(proj); @@ -58,7 +58,7 @@ public boolean equals(Object other) { } Selection otherSelection = (Selection) other; return this.selected.equals(otherSelection.selected) - && this.lifted.equals(otherSelection.lifted); + && this.lifted.equals(otherSelection.lifted); } public Set getComponents() { @@ -130,7 +130,7 @@ public void draw(ComponentDrawContext context, Set hidden) { Graphics g_new = g.create(); context.setGraphics(g_new); c.getFactory().drawGhost(context, Color.GRAY, - loc.getX(), loc.getY(), c.getAttributeSet()); + loc.getX(), loc.getY(), c.getAttributeSet()); g_new.dispose(); } } @@ -140,7 +140,7 @@ public void draw(ComponentDrawContext context, Set hidden) { Graphics g_new = g.create(); context.setGraphics(g_new); CustomHandles handler - = (CustomHandles) comp.getFeature(CustomHandles.class); + = (CustomHandles) comp.getFeature(CustomHandles.class); if (handler == null) { context.drawHandles(comp); } else { @@ -154,7 +154,7 @@ public void draw(ComponentDrawContext context, Set hidden) { } public void drawGhostsShifted(ComponentDrawContext context, - int dx, int dy) { + int dx, int dy) { if (shouldSnap()) { dx = Canvas.snapXToGrid(dx); dy = Canvas.snapYToGrid(dy); @@ -198,7 +198,7 @@ public Object getSource() { private class MyListener implements ProjectListener, CircuitListener { - private WeakHashMap savedSelections; + private final WeakHashMap savedSelections; MyListener() { savedSelections = new WeakHashMap<>(); diff --git a/src/main/java/com/cburch/logisim/gui/main/SelectionActions.java b/src/main/java/com/cburch/logisim/gui/main/SelectionActions.java index 8db7236..d10bc99 100644 --- a/src/main/java/com/cburch/logisim/gui/main/SelectionActions.java +++ b/src/main/java/com/cburch/logisim/gui/main/SelectionActions.java @@ -132,13 +132,13 @@ private static HashMap getReplacementMap(Project proj) { dropped.add(compFactory.getDisplayName()); } else { String msg = Strings.get("pasteCloneQuery", - compFactory.getName()); + compFactory.getName()); Object[] opts = {Strings.get("pasteCloneReplace"), - Strings.get("pasteCloneIgnore"), - Strings.get("pasteCloneCancel")}; + Strings.get("pasteCloneIgnore"), + Strings.get("pasteCloneCancel")}; int select = JOptionPane.showOptionDialog(proj.getFrame(), - msg, Strings.get("pasteCloneTitle"), 0, - JOptionPane.QUESTION_MESSAGE, null, opts, opts[0]); + msg, Strings.get("pasteCloneTitle"), 0, + JOptionPane.QUESTION_MESSAGE, null, opts, opts[0]); if (select == 0) { copyFactory = candidate; } else if (select == 1) { @@ -191,15 +191,15 @@ private static HashMap getReplacementMap(Project proj) { area.setCaretPosition(0); JScrollPane areaPane = new JScrollPane(area); JOptionPane.showMessageDialog(proj.getFrame(), areaPane, - Strings.get("pasteDropTitle"), - JOptionPane.WARNING_MESSAGE); + Strings.get("pasteDropTitle"), + JOptionPane.WARNING_MESSAGE); } return replMap; } private static ComponentFactory findComponentFactory(ComponentFactory factory, - ArrayList libs, boolean acceptNameMatch) { + ArrayList libs, boolean acceptNameMatch) { String name = factory.getName(); for (Library lib : libs) { for (Tool tool : lib.getTools()) { @@ -212,7 +212,7 @@ private static ComponentFactory findComponentFactory(ComponentFactory factory, } else if (fact == factory) { return fact; } else if (fact.getClass() == factory.getClass() - && !(fact instanceof SubcircuitFactory)) { + && !(fact instanceof SubcircuitFactory)) { return fact; } } @@ -224,10 +224,10 @@ private static ComponentFactory findComponentFactory(ComponentFactory factory, private static class Drop extends Action { - private Selection sel; - private Component[] drops; - private int numDrops; - private SelectionSave before; + private final Selection sel; + private final Component[] drops; + private final int numDrops; + private final SelectionSave before; private CircuitTransaction xnReverse; Drop(Selection sel, Collection toDrop, int numDrops) { @@ -241,7 +241,7 @@ private static class Drop extends Action { @Override public String getName() { return numDrops == 1 ? Strings.get("dropComponentAction") - : Strings.get("dropComponentsAction"); + : Strings.get("dropComponentsAction"); } @Override @@ -281,9 +281,9 @@ public boolean shouldAppendTo(Action other) { private static class Anchor extends Action { - private Selection sel; - private int numAnchor; - private SelectionSave before; + private final Selection sel; + private final int numAnchor; + private final SelectionSave before; private CircuitTransaction xnReverse; Anchor(Selection sel, int numAnchor) { @@ -295,7 +295,7 @@ private static class Anchor extends Action { @Override public String getName() { return numAnchor == 1 ? Strings.get("dropComponentAction") - : Strings.get("dropComponentsAction"); + : Strings.get("dropComponentsAction"); } @Override @@ -333,7 +333,7 @@ public boolean shouldAppendTo(Action other) { private static class Delete extends Action { - private Selection sel; + private final Selection sel; private CircuitTransaction xnReverse; Delete(Selection sel) { @@ -362,7 +362,7 @@ public void undo(Project proj) { private static class Duplicate extends Action { - private Selection sel; + private final Selection sel; private CircuitTransaction xnReverse; private SelectionSave after; @@ -394,8 +394,8 @@ public void undo(Project proj) { private static class Cut extends Action { - private Action first; - private Action second; + private final Action first; + private final Action second; Cut(Selection sel) { first = new Copy(sel); @@ -422,7 +422,7 @@ public void undo(Project proj) { private static class Copy extends Action { - private Selection sel; + private final Selection sel; private Clipboard oldClip; Copy(Selection sel) { @@ -453,10 +453,10 @@ public void undo(Project proj) { private static class Paste extends Action { - private Selection sel; + private final Selection sel; private CircuitTransaction xnReverse; private SelectionSave after; - private HashMap componentReplacements; + private final HashMap componentReplacements; Paste(Selection sel, HashMap replacements) { this.sel = sel; @@ -512,11 +512,11 @@ public void undo(Project proj) { private static class Translate extends Action { - private Selection sel; - private int dx; - private int dy; - private ReplacementMap replacements; - private SelectionSave before; + private final Selection sel; + private final int dx; + private final int dy; + private final ReplacementMap replacements; + private final SelectionSave before; private CircuitTransaction xnReverse; Translate(Selection sel, int dx, int dy, ReplacementMap replacements) { diff --git a/src/main/java/com/cburch/logisim/gui/main/SelectionAttributes.java b/src/main/java/com/cburch/logisim/gui/main/SelectionAttributes.java index 8b0d351..ae0afc0 100644 --- a/src/main/java/com/cburch/logisim/gui/main/SelectionAttributes.java +++ b/src/main/java/com/cburch/logisim/gui/main/SelectionAttributes.java @@ -26,9 +26,9 @@ class SelectionAttributes extends AbstractAttributeSet { private static final Attribute[] EMPTY_ATTRIBUTES = new Attribute[0]; private static final Object[] EMPTY_VALUES = new Object[0]; - private Canvas canvas; - private Selection selection; - private Listener listener; + private final Canvas canvas; + private final Selection selection; + private final Listener listener; private boolean listening; private Set selected; private Attribute[] attrs; @@ -121,7 +121,7 @@ private static LinkedHashMap, Object> computeAttributes(Collec } private static boolean isSame(LinkedHashMap, Object> attrMap, - Attribute[] oldAttrs, Object[] oldValues) { + Attribute[] oldAttrs, Object[] oldValues) { if (oldAttrs.length != attrMap.size()) { return false; } else { @@ -236,7 +236,7 @@ private void updateList(boolean ignoreIfSelectionSame) { Object oldVal = oldValues[i]; Object newVal = newValues[i]; boolean sameVals = oldVal == null ? newVal == null - : oldVal.equals(newVal); + : oldVal.equals(newVal); if (!sameVals) { @SuppressWarnings("unchecked") Attribute attr = (Attribute) oldAttrs[i]; diff --git a/src/main/java/com/cburch/logisim/gui/main/SelectionBase.java b/src/main/java/com/cburch/logisim/gui/main/SelectionBase.java index 07849a0..87577ea 100644 --- a/src/main/java/com/cburch/logisim/gui/main/SelectionBase.java +++ b/src/main/java/com/cburch/logisim/gui/main/SelectionBase.java @@ -31,13 +31,13 @@ class SelectionBase { final HashSet lifted = new HashSet<>(); // of selected Components removed final HashSet suppressHandles = new HashSet<>(); // of Components final Set unionSet = CollectionUtil.createUnmodifiableSetUnion(selected, lifted); - Project proj; - private ArrayList listeners = new ArrayList<>(); + private final ArrayList listeners = new ArrayList<>(); + Project project; private Bounds bounds = Bounds.EMPTY_BOUNDS; private boolean shouldSnap = false; - public SelectionBase(Project proj) { - this.proj = proj; + public SelectionBase(Project project) { + this.project = project; } private static boolean shouldSnapComponent(Component comp) { @@ -238,8 +238,8 @@ private void computeShouldSnap() { } private boolean hasConflictTranslated(Collection components, - int dx, int dy, boolean selfConflicts) { - Circuit circuit = proj.getCurrentCircuit(); + int dx, int dy, boolean selfConflicts) { + Circuit circuit = project.getCurrentCircuit(); if (circuit == null) { return false; } @@ -309,14 +309,14 @@ private HashMap copyComponents(Collection compo } if (bds.getX() + dx >= 0 && bds.getY() + dy >= 0 - && !hasConflictTranslated(components, dx, dy, true)) { + && !hasConflictTranslated(components, dx, dy, true)) { return copyComponents(components, dx, dy); } } } private HashMap copyComponents(Collection components, - int dx, int dy) { + int dx, int dy) { HashMap ret = new HashMap<>(); for (Component comp : components) { Location oldLoc = comp.getLocation(); @@ -343,14 +343,14 @@ public void print() { boolean hasPrinted = false; for (Component comp : selected) { System.err.println((hasPrinted ? " " : " select: ") //OK - + comp + " [" + comp.hashCode() + "]"); + + comp + " [" + comp.hashCode() + "]"); hasPrinted = true; } hasPrinted = false; for (Component comp : lifted) { System.err.println((hasPrinted ? " " : " lifted: ") //OK - + comp + " [" + comp.hashCode() + "]"); + + comp + " [" + comp.hashCode() + "]"); hasPrinted = true; } } diff --git a/src/main/java/com/cburch/logisim/gui/main/SelectionSave.java b/src/main/java/com/cburch/logisim/gui/main/SelectionSave.java index 3135422..dbb8e86 100644 --- a/src/main/java/com/cburch/logisim/gui/main/SelectionSave.java +++ b/src/main/java/com/cburch/logisim/gui/main/SelectionSave.java @@ -4,6 +4,7 @@ package com.cburch.logisim.gui.main; import com.cburch.logisim.comp.Component; +import java.util.Arrays; import java.util.Collection; import java.util.HashSet; @@ -53,9 +54,10 @@ private static boolean isSame(Component[] a, Component[] b) { private static HashSet toSet(Component[] comps) { HashSet ret = new HashSet<>(comps.length); - for (Component c : comps) { - ret.add(c); - } +// for (Component c : comps) { +// ret.add(c); +// } + ret.addAll(Arrays.asList(comps)); return ret; } @@ -68,8 +70,7 @@ public Component[] getAnchoredComponents() { } public boolean isSame(Selection sel) { - return isSame(floating, sel.getFloatingComponents()) - && isSame(anchored, sel.getAnchoredComponents()); + return isSame(floating, sel.getFloatingComponents()) && isSame(anchored, sel.getAnchoredComponents()); } @Override @@ -77,7 +78,7 @@ public boolean equals(Object other) { if (other instanceof SelectionSave) { SelectionSave o = (SelectionSave) other; return isSame(this.floating, o.floating) - && isSame(this.anchored, o.anchored); + && isSame(this.anchored, o.anchored); } else { return false; } diff --git a/src/main/java/com/cburch/logisim/gui/main/SimulationExplorer.java b/src/main/java/com/cburch/logisim/gui/main/SimulationExplorer.java index 13efce6..d9434c4 100644 --- a/src/main/java/com/cburch/logisim/gui/main/SimulationExplorer.java +++ b/src/main/java/com/cburch/logisim/gui/main/SimulationExplorer.java @@ -17,29 +17,28 @@ import javax.swing.JTree; import javax.swing.tree.TreePath; -class SimulationExplorer extends JPanel - implements ProjectListener, MouseListener { +class SimulationExplorer extends JPanel implements ProjectListener, MouseListener { - private Project project; + private final Project project; + private final JTree tree; private SimulationTreeModel model; - private JTree tree; - SimulationExplorer(Project proj, MenuListener menu) { + SimulationExplorer(Project project, MenuListener menu) { super(new BorderLayout()); - this.project = proj; + this.project = project; - SimulationToolbarModel toolbarModel = new SimulationToolbarModel(proj, menu); + SimulationToolbarModel toolbarModel = new SimulationToolbarModel(project, menu); Toolbar toolbar = new Toolbar(toolbarModel); add(toolbar, BorderLayout.NORTH); - model = new SimulationTreeModel(proj.getSimulator().getCircuitState()); - model.setCurrentView(project.getCircuitState()); + model = new SimulationTreeModel(project.getSimulator().getCircuitState()); + model.setCurrentView(this.project.getCircuitState()); tree = new JTree(model); tree.setCellRenderer(new SimulationTreeRenderer()); tree.addMouseListener(this); tree.setToggleClickCount(3); add(new JScrollPane(tree), BorderLayout.CENTER); - proj.addProjectListener(this); + project.addProjectListener(this); } // @@ -48,8 +47,8 @@ class SimulationExplorer extends JPanel public void projectChanged(ProjectEvent event) { int action = event.getAction(); if (action == ProjectEvent.ACTION_SET_STATE) { - Simulator sim = project.getSimulator(); - CircuitState root = sim.getCircuitState(); + Simulator simulator = project.getSimulator(); + CircuitState root = simulator.getCircuitState(); if (model.getRootState() != root) { model = new SimulationTreeModel(root); tree.setModel(model); diff --git a/src/main/java/com/cburch/logisim/gui/main/SimulationToolbarModel.java b/src/main/java/com/cburch/logisim/gui/main/SimulationToolbarModel.java index e34e1a2..b4c5a38 100644 --- a/src/main/java/com/cburch/logisim/gui/main/SimulationToolbarModel.java +++ b/src/main/java/com/cburch/logisim/gui/main/SimulationToolbarModel.java @@ -14,32 +14,32 @@ import javax.swing.event.ChangeListener; class SimulationToolbarModel extends AbstractToolbarModel - implements ChangeListener { + implements ChangeListener { - private Project project; - private LogisimToolbarItem simEnable; - private LogisimToolbarItem simStep; - private LogisimToolbarItem tickEnable; - private LogisimToolbarItem tickStep; - private List items; + private final Project project; + private final LogisimToolbarItem simEnable; + private final LogisimToolbarItem simStep; + private final LogisimToolbarItem tickEnable; + private final LogisimToolbarItem tickStep; + private final List items; public SimulationToolbarModel(Project project, MenuListener menu) { this.project = project; simEnable = new LogisimToolbarItem(menu, "simplay.png", LogisimMenuBar.SIMULATE_ENABLE, - Strings.getter("simulateEnableStepsTip")); + Strings.getter("simulateEnableStepsTip")); simStep = new LogisimToolbarItem(menu, "simstep.png", LogisimMenuBar.SIMULATE_STEP, - Strings.getter("simulateStepTip")); + Strings.getter("simulateStepTip")); tickEnable = new LogisimToolbarItem(menu, "simtplay.png", LogisimMenuBar.TICK_ENABLE, - Strings.getter("simulateEnableTicksTip")); + Strings.getter("simulateEnableTicksTip")); tickStep = new LogisimToolbarItem(menu, "simtstep.png", LogisimMenuBar.TICK_STEP, - Strings.getter("simulateTickTip")); + Strings.getter("simulateTickTip")); items = UnmodifiableList.create(new ToolbarItem[]{ - simEnable, - simStep, - tickEnable, - tickStep, + simEnable, + simStep, + tickEnable, + tickStep, }); menu.getMenuBar().addEnableListener(this); @@ -72,10 +72,10 @@ public void stateChanged(ChangeEvent e) { boolean ticking = sim != null && sim.isTicking(); simEnable.setIcon(running ? "simstop.png" : "simplay.png"); simEnable.setToolTip(running ? Strings.getter("simulateDisableStepsTip") - : Strings.getter("simulateEnableStepsTip")); + : Strings.getter("simulateEnableStepsTip")); tickEnable.setIcon(ticking ? "simtstop.png" : "simtplay.png"); tickEnable.setToolTip(ticking ? Strings.getter("simulateDisableTicksTip") - : Strings.getter("simulateEnableTicksTip")); + : Strings.getter("simulateEnableTicksTip")); fireToolbarAppearanceChanged(); } } diff --git a/src/main/java/com/cburch/logisim/gui/main/SimulationTreeCircuitNode.java b/src/main/java/com/cburch/logisim/gui/main/SimulationTreeCircuitNode.java index f493fcd..9cdbb8b 100644 --- a/src/main/java/com/cburch/logisim/gui/main/SimulationTreeCircuitNode.java +++ b/src/main/java/com/cburch/logisim/gui/main/SimulationTreeCircuitNode.java @@ -20,25 +20,25 @@ import javax.swing.tree.TreeNode; class SimulationTreeCircuitNode extends SimulationTreeNode - implements CircuitListener, AttributeListener, Comparator { + implements CircuitListener, AttributeListener, Comparator { - private SimulationTreeModel model; - private SimulationTreeCircuitNode parent; - private CircuitState circuitState; - private Component subcircComp; + private final SimulationTreeModel model; + private final SimulationTreeCircuitNode parent; + private final CircuitState circuitState; + private final Component subcircuitComp; private ArrayList children; public SimulationTreeCircuitNode(SimulationTreeModel model, - SimulationTreeCircuitNode parent, CircuitState circuitState, - Component subcircComp) { + SimulationTreeCircuitNode parent, CircuitState circuitState, + Component subcircuitComp) { this.model = model; this.parent = parent; this.circuitState = circuitState; - this.subcircComp = subcircComp; + this.subcircuitComp = subcircuitComp; this.children = new ArrayList<>(); circuitState.getCircuit().addCircuitListener(this); - if (subcircComp != null) { - subcircComp.getAttributeSet().addAttributeListener(this); + if (subcircuitComp != null) { + subcircuitComp.getAttributeSet().addAttributeListener(this); } else { circuitState.getCircuit().getStaticAttributes().addAttributeListener(this); } @@ -61,15 +61,15 @@ public boolean isCurrentView(SimulationTreeModel model) { @Override public String toString() { - if (subcircComp != null) { - String label = subcircComp.getAttributeSet().getValue(StdAttr.LABEL); + if (subcircuitComp != null) { + String label = subcircuitComp.getAttributeSet().getValue(StdAttr.LABEL); if (label != null && !label.equals("")) { return label; } } String ret = circuitState.getCircuit().getName(); - if (subcircComp != null) { - ret += subcircComp.getLocation(); + if (subcircuitComp != null) { + ret += subcircuitComp.getLocation(); } return ret; } @@ -136,21 +136,21 @@ private boolean computeChildren() { } newChildren.sort(new CompareByName()); subcircs.sort(this); - for (Component comp : subcircs) { - SubcircuitFactory factory = (SubcircuitFactory) comp.getFactory(); - CircuitState state = factory.getSubstate(circuitState, comp); + for (Component component : subcircs) { + SubcircuitFactory factory = (SubcircuitFactory) component.getFactory(); + CircuitState state = factory.getSubstate(circuitState, component); SimulationTreeCircuitNode toAdd = null; - for (TreeNode o : children) { - if (o instanceof SimulationTreeCircuitNode) { - SimulationTreeCircuitNode n = (SimulationTreeCircuitNode) o; - if (n.circuitState == state) { - toAdd = n; + for (TreeNode child : children) { + if (child instanceof SimulationTreeCircuitNode) { + SimulationTreeCircuitNode node = (SimulationTreeCircuitNode) child; + if (node.circuitState == state) { + toAdd = node; break; } } } if (toAdd == null) { - toAdd = new SimulationTreeCircuitNode(model, this, state, comp); + toAdd = new SimulationTreeCircuitNode(model, this, state, component); } newChildren.add(toAdd); } diff --git a/src/main/java/com/cburch/logisim/gui/main/SimulationTreeModel.java b/src/main/java/com/cburch/logisim/gui/main/SimulationTreeModel.java index 80fd3b6..dd9e53c 100644 --- a/src/main/java/com/cburch/logisim/gui/main/SimulationTreeModel.java +++ b/src/main/java/com/cburch/logisim/gui/main/SimulationTreeModel.java @@ -14,14 +14,14 @@ public class SimulationTreeModel implements TreeModel { - private ArrayList listeners; - private SimulationTreeCircuitNode root; + private final ArrayList listeners; + private final SimulationTreeCircuitNode root; private CircuitState currentView; public SimulationTreeModel(CircuitState rootState) { this.listeners = new ArrayList<>(); this.root = new SimulationTreeCircuitNode(this, null, - rootState, null); + rootState, null); this.currentView = null; } diff --git a/src/main/java/com/cburch/logisim/gui/main/SimulationTreeRenderer.java b/src/main/java/com/cburch/logisim/gui/main/SimulationTreeRenderer.java index 4cb2a3b..dfe5865 100644 --- a/src/main/java/com/cburch/logisim/gui/main/SimulationTreeRenderer.java +++ b/src/main/java/com/cburch/logisim/gui/main/SimulationTreeRenderer.java @@ -17,11 +17,10 @@ public class SimulationTreeRenderer extends DefaultTreeCellRenderer { @Override - public Component getTreeCellRendererComponent(JTree tree, Object value, - boolean selected, boolean expanded, boolean leaf, int row, - boolean hasFocus) { + public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, + int row, boolean hasFocus) { Component ret = super.getTreeCellRendererComponent(tree, value, - selected, expanded, leaf, row, hasFocus); + selected, expanded, leaf, row, hasFocus); SimulationTreeModel model = (SimulationTreeModel) tree.getModel(); if (ret instanceof JLabel) { JLabel label = (JLabel) ret; @@ -38,8 +37,8 @@ public Component getTreeCellRendererComponent(JTree tree, Object value, private static class RendererIcon implements Icon { - private ComponentFactory factory; - private boolean isCurrentView; + private final ComponentFactory factory; + private final boolean isCurrentView; RendererIcon(ComponentFactory factory, boolean isCurrentView) { this.factory = factory; @@ -56,7 +55,7 @@ public int getIconWidth() { public void paintIcon(Component c, Graphics g, int x, int y) { ComponentDrawContext context = new ComponentDrawContext(c, - null, null, g, g); + null, null, g, g); factory.paintIcon(context, x, y, factory.createAttributeSet()); // draw magnifying glass if appropriate diff --git a/src/main/java/com/cburch/logisim/gui/main/StatisticsDialog.java b/src/main/java/com/cburch/logisim/gui/main/StatisticsDialog.java index 0dc9c24..0016bf6 100644 --- a/src/main/java/com/cburch/logisim/gui/main/StatisticsDialog.java +++ b/src/main/java/com/cburch/logisim/gui/main/StatisticsDialog.java @@ -27,7 +27,7 @@ public class StatisticsDialog extends JDialog implements ActionListener { private StatisticsDialog(JFrame parent, String circuitName, - StatisticsTableModel model) { + StatisticsTableModel model) { super(parent, true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setTitle(Strings.get("statsDialogTitle", circuitName)); @@ -35,7 +35,7 @@ private StatisticsDialog(JFrame parent, String circuitName, JTable table = new StatisticsTable(); TableSorter mySorter = new TableSorter(model, table.getTableHeader()); Comparator comp = new CompareString("", - Strings.get("statsTotalWithout"), Strings.get("statsTotalWith")); + Strings.get("statsTotalWithout"), Strings.get("statsTotalWith")); mySorter.setColumnComparator(String.class, comp); table.setModel(mySorter); JScrollPane tablePane = new JScrollPane(table); @@ -66,7 +66,7 @@ private StatisticsDialog(JFrame parent, String circuitName, public static void show(JFrame parent, LogisimFile file, Circuit circuit) { FileStatistics stats = FileStatistics.compute(file, circuit); StatisticsDialog dlog = new StatisticsDialog(parent, - circuit.getName(), new StatisticsTableModel(stats)); + circuit.getName(), new StatisticsTableModel(stats)); dlog.setVisible(true); } @@ -76,7 +76,7 @@ public void actionPerformed(ActionEvent e) { private static class StatisticsTableModel extends AbstractTableModel { - private FileStatistics stats; + private final FileStatistics stats; StatisticsTableModel(FileStatistics stats) { this.stats = stats; @@ -157,7 +157,7 @@ public Object getValueAt(int row, int column) { private static class CompareString implements Comparator { - private String[] fixedAtBottom; + private final String[] fixedAtBottom; public CompareString(String... fixedAtBottom) { this.fixedAtBottom = fixedAtBottom; diff --git a/src/main/java/com/cburch/logisim/gui/main/Strings.java b/src/main/java/com/cburch/logisim/gui/main/Strings.java index 44e75bf..251a9bb 100644 --- a/src/main/java/com/cburch/logisim/gui/main/Strings.java +++ b/src/main/java/com/cburch/logisim/gui/main/Strings.java @@ -9,8 +9,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "gui"); + private static final LocaleManager source = new LocaleManager("logisim", "gui"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/gui/main/TickCounter.java b/src/main/java/com/cburch/logisim/gui/main/TickCounter.java index 416923f..b9fbae9 100644 --- a/src/main/java/com/cburch/logisim/gui/main/TickCounter.java +++ b/src/main/java/com/cburch/logisim/gui/main/TickCounter.java @@ -11,8 +11,8 @@ class TickCounter implements SimulatorListener { private static final int QUEUE_LENGTH = 1000; - private long[] queueTimes; - private double[] queueRates; + private final long[] queueTimes; + private final double[] queueRates; private int queueStart; private int queueSize; private double tickFrequency; @@ -135,7 +135,7 @@ public String getTickRate() { if (min >= 1000.0) { return Strings.get("tickRateKHz", - roundString(rate / 1000.0, min / 1000.0)); + roundString(rate / 1000.0, min / 1000.0)); } else { return Strings.get("tickRateHz", roundString(rate, min)); } diff --git a/src/main/java/com/cburch/logisim/gui/main/ToolAttributeAction.java b/src/main/java/com/cburch/logisim/gui/main/ToolAttributeAction.java index 1230407..8117615 100644 --- a/src/main/java/com/cburch/logisim/gui/main/ToolAttributeAction.java +++ b/src/main/java/com/cburch/logisim/gui/main/ToolAttributeAction.java @@ -15,7 +15,7 @@ public class ToolAttributeAction extends Action { - private KeyConfigurationResult config; + private final KeyConfigurationResult config; private Map, Object> oldValues; private ToolAttributeAction(KeyConfigurationResult config) { diff --git a/src/main/java/com/cburch/logisim/gui/main/Toolbox.java b/src/main/java/com/cburch/logisim/gui/main/Toolbox.java index 455a2b5..6d3a0ba 100644 --- a/src/main/java/com/cburch/logisim/gui/main/Toolbox.java +++ b/src/main/java/com/cburch/logisim/gui/main/Toolbox.java @@ -13,7 +13,7 @@ class Toolbox extends JPanel { - private ProjectExplorer toolbox; + private final ProjectExplorer toolbox; Toolbox(Project proj, MenuListener menu) { super(new BorderLayout()); diff --git a/src/main/java/com/cburch/logisim/gui/main/ToolboxManip.java b/src/main/java/com/cburch/logisim/gui/main/ToolboxManip.java index 92399ae..e2942f2 100644 --- a/src/main/java/com/cburch/logisim/gui/main/ToolboxManip.java +++ b/src/main/java/com/cburch/logisim/gui/main/ToolboxManip.java @@ -33,16 +33,16 @@ class ToolboxManip implements ProjectExplorerListener { - private Project proj; - private ProjectExplorer explorer; - private MyListener myListener = new MyListener(); + private final Project project; + private final ProjectExplorer explorer; + private final MyListener myListener = new MyListener(); private Tool lastSelected = null; - ToolboxManip(Project proj, ProjectExplorer explorer) { - this.proj = proj; + ToolboxManip(Project project, ProjectExplorer explorer) { + this.project = project; this.explorer = explorer; - proj.addProjectListener(myListener); - myListener.setFile(null, proj.getLogisimFile()); + project.addProjectListener(myListener); + myListener.setFile(null, project.getLogisimFile()); } public void selectionChanged(ProjectExplorerEvent event) { @@ -55,17 +55,17 @@ public void selectionChanged(ProjectExplorerEvent event) { if (source instanceof SubcircuitFactory) { SubcircuitFactory circFact = (SubcircuitFactory) source; Circuit circ = circFact.getSubcircuit(); - if (proj.getCurrentCircuit() == circ) { - AttrTableModel m = new AttrTableCircuitModel(proj, circ); - proj.getFrame().setAttrTableModel(m); + if (project.getCurrentCircuit() == circ) { + AttrTableModel m = new AttrTableCircuitModel(project, circ); + project.getFrame().setAttrTableModel(m); return; } } } - lastSelected = proj.getTool(); - proj.setTool(tool); - proj.getFrame().viewAttributes(tool); + lastSelected = project.getTool(); + project.setTool(tool); + project.getFrame().viewAttributes(tool); } } @@ -78,10 +78,10 @@ public void doubleClicked(ProjectExplorerEvent event) { ComponentFactory source = tool.getFactory(); if (source instanceof SubcircuitFactory) { SubcircuitFactory circFact = (SubcircuitFactory) source; - proj.setCurrentCircuit(circFact.getSubcircuit()); - proj.getFrame().setEditorView(Frame.EDIT_LAYOUT); + project.setCurrentCircuit(circFact.getSubcircuit()); + project.getFrame().setEditorView(Frame.EDIT_LAYOUT); if (lastSelected != null) { - proj.setTool(lastSelected); + project.setTool(lastSelected); } } } @@ -89,27 +89,27 @@ public void doubleClicked(ProjectExplorerEvent event) { } public void moveRequested(ProjectExplorerEvent event, AddTool dragged, AddTool target) { - LogisimFile file = proj.getLogisimFile(); + LogisimFile file = project.getLogisimFile(); int draggedIndex = file.getTools().indexOf(dragged); int targetIndex = file.getTools().indexOf(target); if (targetIndex > draggedIndex) { targetIndex++; } - proj.doAction(LogisimFileActions.moveCircuit(dragged, targetIndex)); + project.doAction(LogisimFileActions.moveCircuit(dragged, targetIndex)); } public void deleteRequested(ProjectExplorerEvent event) { Object request = event.getTarget(); if (request instanceof ProjectExplorerLibraryNode) { Library lib = ((ProjectExplorerLibraryNode) request).getValue(); - ProjectLibraryActions.doUnloadLibrary(proj, lib); + ProjectLibraryActions.doUnloadLibrary(project, lib); } else if (request instanceof ProjectExplorerToolNode) { Tool tool = ((ProjectExplorerToolNode) request).getValue(); if (tool instanceof AddTool) { ComponentFactory factory = ((AddTool) tool).getFactory(); if (factory instanceof SubcircuitFactory) { SubcircuitFactory circFact = (SubcircuitFactory) factory; - ProjectCircuitActions.doRemoveCircuit(proj, circFact.getSubcircuit()); + ProjectCircuitActions.doRemoveCircuit(project, circFact.getSubcircuit()); } } } @@ -124,7 +124,7 @@ public JPopupMenu menuRequested(ProjectExplorerEvent event) { ComponentFactory source = tool.getFactory(); if (source instanceof SubcircuitFactory) { Circuit circ = ((SubcircuitFactory) source).getSubcircuit(); - return Popups.forCircuit(proj, tool, circ); + return Popups.forCircuit(project, tool, circ); } else { return null; } @@ -133,11 +133,11 @@ public JPopupMenu menuRequested(ProjectExplorerEvent event) { } } else if (clicked instanceof ProjectExplorerLibraryNode) { Library lib = ((ProjectExplorerLibraryNode) clicked).getValue(); - if (lib == proj.getLogisimFile()) { - return Popups.forProject(proj); + if (lib == project.getLogisimFile()) { + return Popups.forProject(project); } else { boolean is_top = event.getTreePath().getPathCount() <= 2; - return Popups.forLibrary(proj, lib, is_top); + return Popups.forLibrary(project, lib, is_top); } } else { return null; @@ -145,7 +145,7 @@ public JPopupMenu menuRequested(ProjectExplorerEvent event) { } private class MyListener - implements ProjectListener, LibraryListener, AttributeListener { + implements ProjectListener, LibraryListener, AttributeListener { private LogisimFile curFile = null; @@ -153,7 +153,7 @@ public void projectChanged(ProjectEvent event) { int action = event.getAction(); if (action == ProjectEvent.ACTION_SET_FILE) { setFile((LogisimFile) event.getOldData(), - (LogisimFile) event.getData()); + (LogisimFile) event.getData()); explorer.repaint(); } } diff --git a/src/main/java/com/cburch/logisim/gui/main/ToolboxToolbarModel.java b/src/main/java/com/cburch/logisim/gui/main/ToolboxToolbarModel.java index 1503971..2841027 100644 --- a/src/main/java/com/cburch/logisim/gui/main/ToolboxToolbarModel.java +++ b/src/main/java/com/cburch/logisim/gui/main/ToolboxToolbarModel.java @@ -10,29 +10,29 @@ import java.util.List; class ToolboxToolbarModel extends AbstractToolbarModel - implements MenuListener.EnabledListener { + implements MenuListener.EnabledListener { - private LogisimToolbarItem itemAdd; - private LogisimToolbarItem itemUp; - private LogisimToolbarItem itemDown; - private LogisimToolbarItem itemDelete; - private List items; + private final LogisimToolbarItem itemAdd; + private final LogisimToolbarItem itemUp; + private final LogisimToolbarItem itemDown; + private final LogisimToolbarItem itemDelete; + private final List items; public ToolboxToolbarModel(MenuListener menu) { itemAdd = new LogisimToolbarItem(menu, "projadd.gif", LogisimMenuBar.ADD_CIRCUIT, - Strings.getter("projectAddCircuitTip")); + Strings.getter("projectAddCircuitTip")); itemUp = new LogisimToolbarItem(menu, "projup.gif", LogisimMenuBar.MOVE_CIRCUIT_UP, - Strings.getter("projectMoveCircuitUpTip")); + Strings.getter("projectMoveCircuitUpTip")); itemDown = new LogisimToolbarItem(menu, "projdown.gif", LogisimMenuBar.MOVE_CIRCUIT_DOWN, - Strings.getter("projectMoveCircuitDownTip")); + Strings.getter("projectMoveCircuitDownTip")); itemDelete = new LogisimToolbarItem(menu, "projdel.gif", LogisimMenuBar.REMOVE_CIRCUIT, - Strings.getter("projectRemoveCircuitTip")); + Strings.getter("projectRemoveCircuitTip")); items = UnmodifiableList.create(new ToolbarItem[]{ - itemAdd, - itemUp, - itemDown, - itemDelete, + itemAdd, + itemUp, + itemDown, + itemDelete, }); menu.addEnabledListener(this); diff --git a/src/main/java/com/cburch/logisim/gui/menu/EditPopup.java b/src/main/java/com/cburch/logisim/gui/menu/EditPopup.java index 61590fd..15d1885 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/EditPopup.java +++ b/src/main/java/com/cburch/logisim/gui/menu/EditPopup.java @@ -12,8 +12,8 @@ public abstract class EditPopup extends JPopupMenu { - private Listener listener; - private Map items; + private final Listener listener; + private final Map items; public EditPopup() { this(false); diff --git a/src/main/java/com/cburch/logisim/gui/menu/LogisimMenuBar.java b/src/main/java/com/cburch/logisim/gui/menu/LogisimMenuBar.java index f95c5a8..93781ae 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/LogisimMenuBar.java +++ b/src/main/java/com/cburch/logisim/gui/menu/LogisimMenuBar.java @@ -52,52 +52,51 @@ public class LogisimMenuBar extends JMenuBar { public static final LogisimMenuItem SIMULATE_STEP = new LogisimMenuItem("SimulateStep"); public static final LogisimMenuItem TICK_ENABLE = new LogisimMenuItem("TickEnable"); public static final LogisimMenuItem TICK_STEP = new LogisimMenuItem("TickStep"); - private JFrame parent; - private MyListener listener; - private Project proj; + private final JFrame parent; + private final MyListener listener; + private final Project project; + private final HashMap menuItems = new HashMap<>(); + private final ArrayList enableListeners; + private final MenuFile menuFile; + private final MenuEdit menuEdit; + private final MenuProject menuProject; + private final MenuSimulate menuSimulate; + private final MenuHelp menuHelp; private SimulateListener simulateListener = null; - private HashMap menuItems - = new HashMap<>(); - private ArrayList enableListeners; - private MenuFile file; - private MenuEdit edit; - private MenuProject project; - private MenuSimulate simulate; - private MenuHelp help; - - public LogisimMenuBar(JFrame parent, Project proj) { + + public LogisimMenuBar(JFrame parent, Project project) { this.parent = parent; this.listener = new MyListener(); - this.proj = proj; + this.project = project; this.enableListeners = new ArrayList<>(); - add(file = new MenuFile(this)); - add(edit = new MenuEdit(this)); - add(project = new MenuProject(this)); - add(simulate = new MenuSimulate(this)); + add(menuFile = new MenuFile(this)); + add(menuEdit = new MenuEdit(this)); + add(menuProject = new MenuProject(this)); + add(menuSimulate = new MenuSimulate(this)); add(new WindowMenu(parent)); - add(help = new MenuHelp(this)); + add(menuHelp = new MenuHelp(this)); LocaleManager.addLocaleListener(listener); listener.localeChanged(); } - public void setEnabled(LogisimMenuItem which, boolean value) { - MenuItem item = menuItems.get(which); + public void setEnabled(LogisimMenuItem logisimMenuItem, boolean value) { + MenuItem item = menuItems.get(logisimMenuItem); if (item != null) { item.setEnabled(value); } } - public void addActionListener(LogisimMenuItem which, ActionListener l) { - MenuItem item = menuItems.get(which); + public void addActionListener(LogisimMenuItem logisimMenuItem, ActionListener l) { + MenuItem item = menuItems.get(logisimMenuItem); if (item != null) { item.addActionListener(l); } } - public void removeActionListener(LogisimMenuItem which, ActionListener l) { - MenuItem item = menuItems.get(which); + public void removeActionListener(LogisimMenuItem logisimMenuItem, ActionListener l) { + MenuItem item = menuItems.get(logisimMenuItem); if (item != null) { item.removeActionListener(l); } @@ -112,9 +111,9 @@ public void removeEnableListener(ChangeListener l) { } void fireEnableChanged() { - ChangeEvent e = new ChangeEvent(this); + ChangeEvent event = new ChangeEvent(this); for (ChangeListener listener : enableListeners) { - listener.stateChanged(e); + listener.stateChanged(event); } } @@ -122,47 +121,46 @@ public void setSimulateListener(SimulateListener l) { simulateListener = l; } - public void setCircuitState(Simulator sim, CircuitState state) { - simulate.setCurrentState(sim, state); + public void setCircuitState(Simulator simulator, CircuitState state) { + menuSimulate.setCurrentState(simulator, state); } - public Project getProject() { - return proj; + public Project getMenuProject() { + return project; } JFrame getParentWindow() { return parent; } - void registerItem(LogisimMenuItem which, MenuItem item) { - menuItems.put(which, item); + void registerItem(LogisimMenuItem logisimMenuItem, MenuItem menuItem) { + menuItems.put(logisimMenuItem, menuItem); } - void fireStateChanged(Simulator sim, CircuitState state) { + void fireStateChanged(Simulator simulator, CircuitState state) { if (simulateListener != null) { - simulateListener.stateChangeRequested(sim, state); + simulateListener.stateChangeRequested(simulator, state); } } - public void doAction(LogisimMenuItem which) { - MenuItem item = menuItems.get(which); - item.actionPerformed(new ActionEvent(item, ActionEvent.ACTION_PERFORMED, - which.toString())); + public void doAction(LogisimMenuItem logisimMenuItem) { + MenuItem menuItem = menuItems.get(logisimMenuItem); + menuItem.actionPerformed(new ActionEvent(menuItem, ActionEvent.ACTION_PERFORMED, logisimMenuItem.toString())); } - public boolean isEnabled(LogisimMenuItem item) { - MenuItem menuItem = menuItems.get(item); + public boolean isEnabled(LogisimMenuItem logisimMenuItem) { + MenuItem menuItem = menuItems.get(logisimMenuItem); return menuItem != null && menuItem.isEnabled(); } private class MyListener implements LocaleListener { public void localeChanged() { - file.localeChanged(); - edit.localeChanged(); - project.localeChanged(); - simulate.localeChanged(); - help.localeChanged(); + menuFile.localeChanged(); + menuEdit.localeChanged(); + menuProject.localeChanged(); + menuSimulate.localeChanged(); + menuHelp.localeChanged(); } } } diff --git a/src/main/java/com/cburch/logisim/gui/menu/LogisimMenuItem.java b/src/main/java/com/cburch/logisim/gui/menu/LogisimMenuItem.java index ed782cf..d143f66 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/LogisimMenuItem.java +++ b/src/main/java/com/cburch/logisim/gui/menu/LogisimMenuItem.java @@ -5,7 +5,7 @@ public class LogisimMenuItem { - private String name; + private final String name; LogisimMenuItem(String name) { this.name = name; diff --git a/src/main/java/com/cburch/logisim/gui/menu/MenuEdit.java b/src/main/java/com/cburch/logisim/gui/menu/MenuEdit.java index 0e00f7f..c2c9588 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/MenuEdit.java +++ b/src/main/java/com/cburch/logisim/gui/menu/MenuEdit.java @@ -16,48 +16,48 @@ class MenuEdit extends Menu { - private LogisimMenuBar menubar; - private JMenuItem undo = new JMenuItem(); - private MenuItemImpl cut = new MenuItemImpl(this, LogisimMenuBar.CUT); - private MenuItemImpl copy = new MenuItemImpl(this, LogisimMenuBar.COPY); - private MenuItemImpl paste = new MenuItemImpl(this, LogisimMenuBar.PASTE); - private MenuItemImpl delete = new MenuItemImpl(this, LogisimMenuBar.DELETE); - private MenuItemImpl dup = new MenuItemImpl(this, LogisimMenuBar.DUPLICATE); - private MenuItemImpl selall = new MenuItemImpl(this, LogisimMenuBar.SELECT_ALL); - private MenuItemImpl raise = new MenuItemImpl(this, LogisimMenuBar.RAISE); - private MenuItemImpl lower = new MenuItemImpl(this, LogisimMenuBar.LOWER); - private MenuItemImpl raiseTop = new MenuItemImpl(this, LogisimMenuBar.RAISE_TOP); - private MenuItemImpl lowerBottom = new MenuItemImpl(this, LogisimMenuBar.LOWER_BOTTOM); - private MenuItemImpl addCtrl = new MenuItemImpl(this, LogisimMenuBar.ADD_CONTROL); - private MenuItemImpl remCtrl = new MenuItemImpl(this, LogisimMenuBar.REMOVE_CONTROL); - private MyListener myListener = new MyListener(); + private final LogisimMenuBar menubar; + private final JMenuItem undo = new JMenuItem(); + private final MenuItemImpl cut = new MenuItemImpl(this, LogisimMenuBar.CUT); + private final MenuItemImpl copy = new MenuItemImpl(this, LogisimMenuBar.COPY); + private final MenuItemImpl paste = new MenuItemImpl(this, LogisimMenuBar.PASTE); + private final MenuItemImpl delete = new MenuItemImpl(this, LogisimMenuBar.DELETE); + private final MenuItemImpl dup = new MenuItemImpl(this, LogisimMenuBar.DUPLICATE); + private final MenuItemImpl selall = new MenuItemImpl(this, LogisimMenuBar.SELECT_ALL); + private final MenuItemImpl raise = new MenuItemImpl(this, LogisimMenuBar.RAISE); + private final MenuItemImpl lower = new MenuItemImpl(this, LogisimMenuBar.LOWER); + private final MenuItemImpl raiseTop = new MenuItemImpl(this, LogisimMenuBar.RAISE_TOP); + private final MenuItemImpl lowerBottom = new MenuItemImpl(this, LogisimMenuBar.LOWER_BOTTOM); + private final MenuItemImpl addCtrl = new MenuItemImpl(this, LogisimMenuBar.ADD_CONTROL); + private final MenuItemImpl remCtrl = new MenuItemImpl(this, LogisimMenuBar.REMOVE_CONTROL); + private final MyListener myListener = new MyListener(); public MenuEdit(LogisimMenuBar menubar) { this.menubar = menubar; - int menuMask = getToolkit().getMenuShortcutKeyMask(); + int menuMask = getToolkit().getMenuShortcutKeyMaskEx(); undo.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_Z, menuMask)); + KeyEvent.VK_Z, menuMask)); cut.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_X, menuMask)); + KeyEvent.VK_X, menuMask)); copy.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_C, menuMask)); + KeyEvent.VK_C, menuMask)); paste.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_V, menuMask)); + KeyEvent.VK_V, menuMask)); delete.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_DELETE, 0)); + KeyEvent.VK_DELETE, 0)); dup.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_D, menuMask)); + KeyEvent.VK_D, menuMask)); selall.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_A, menuMask)); + KeyEvent.VK_A, menuMask)); raise.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_UP, menuMask)); + KeyEvent.VK_UP, menuMask)); lower.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_DOWN, menuMask)); + KeyEvent.VK_DOWN, menuMask)); raiseTop.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_UP, menuMask | KeyEvent.SHIFT_DOWN_MASK)); + KeyEvent.VK_UP, menuMask | KeyEvent.SHIFT_DOWN_MASK)); lowerBottom.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_DOWN, menuMask | KeyEvent.SHIFT_DOWN_MASK)); + KeyEvent.VK_DOWN, menuMask | KeyEvent.SHIFT_DOWN_MASK)); add(undo); addSeparator(); @@ -77,7 +77,7 @@ public MenuEdit(LogisimMenuBar menubar) { add(addCtrl); add(remCtrl); - Project proj = menubar.getProject(); + Project proj = menubar.getMenuProject(); if (proj != null) { proj.addProjectListener(myListener); undo.addActionListener(myListener); @@ -118,39 +118,39 @@ public void localeChanged() { @Override void computeEnabled() { - setEnabled(menubar.getProject() != null - || cut.hasListeners() - || copy.hasListeners() - || paste.hasListeners() - || delete.hasListeners() - || dup.hasListeners() - || selall.hasListeners() - || raise.hasListeners() - || lower.hasListeners() - || raiseTop.hasListeners() - || lowerBottom.hasListeners() - || addCtrl.hasListeners() - || remCtrl.hasListeners()); + setEnabled(menubar.getMenuProject() != null + || cut.hasListeners() + || copy.hasListeners() + || paste.hasListeners() + || delete.hasListeners() + || dup.hasListeners() + || selall.hasListeners() + || raise.hasListeners() + || lower.hasListeners() + || raiseTop.hasListeners() + || lowerBottom.hasListeners() + || addCtrl.hasListeners() + || remCtrl.hasListeners()); } private class MyListener implements ProjectListener, ActionListener { public void projectChanged(ProjectEvent e) { - Project proj = menubar.getProject(); + Project proj = menubar.getMenuProject(); Action last = proj == null ? null : proj.getLastAction(); if (last == null) { undo.setText(Strings.get("editCantUndoItem")); undo.setEnabled(false); } else { undo.setText(StringUtil.format(Strings.get("editUndoItem"), - last.getName())); + last.getName())); undo.setEnabled(true); } } public void actionPerformed(ActionEvent e) { Object src = e.getSource(); - Project proj = menubar.getProject(); + Project proj = menubar.getMenuProject(); if (src == undo) { if (proj != null) { proj.undoAction(); diff --git a/src/main/java/com/cburch/logisim/gui/menu/MenuFile.java b/src/main/java/com/cburch/logisim/gui/menu/MenuFile.java index c441f3a..39798cb 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/MenuFile.java +++ b/src/main/java/com/cburch/logisim/gui/menu/MenuFile.java @@ -18,38 +18,38 @@ class MenuFile extends Menu implements ActionListener { - private LogisimMenuBar menubar; - private JMenuItem newi = new JMenuItem(); - private JMenuItem open = new JMenuItem(); - private OpenRecent openRecent; - private JMenuItem close = new JMenuItem(); - private JMenuItem save = new JMenuItem(); - private JMenuItem saveAs = new JMenuItem(); - private MenuItemImpl print = new MenuItemImpl(this, LogisimMenuBar.PRINT); - private MenuItemImpl exportImage = new MenuItemImpl(this, LogisimMenuBar.EXPORT_IMAGE); - private JMenuItem prefs = new JMenuItem(); - private JMenuItem quit = new JMenuItem(); + private final LogisimMenuBar menubar; + private final JMenuItem newi = new JMenuItem(); + private final JMenuItem open = new JMenuItem(); + private final OpenRecent openRecent; + private final JMenuItem close = new JMenuItem(); + private final JMenuItem save = new JMenuItem(); + private final JMenuItem saveAs = new JMenuItem(); + private final MenuItemImpl print = new MenuItemImpl(this, LogisimMenuBar.PRINT); + private final MenuItemImpl exportImage = new MenuItemImpl(this, LogisimMenuBar.EXPORT_IMAGE); + private final JMenuItem prefs = new JMenuItem(); + private final JMenuItem quit = new JMenuItem(); public MenuFile(LogisimMenuBar menubar) { this.menubar = menubar; openRecent = new OpenRecent(menubar); - int menuMask = getToolkit().getMenuShortcutKeyMask(); + int menuMask = getToolkit().getMenuShortcutKeyMaskEx(); newi.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_N, menuMask)); + KeyEvent.VK_N, menuMask)); open.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_O, menuMask)); + KeyEvent.VK_O, menuMask)); close.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_W, menuMask | InputEvent.SHIFT_MASK)); + KeyEvent.VK_W, menuMask | InputEvent.SHIFT_DOWN_MASK)); save.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_S, menuMask)); + KeyEvent.VK_S, menuMask)); saveAs.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_S, menuMask | InputEvent.SHIFT_MASK)); + KeyEvent.VK_S, menuMask | InputEvent.SHIFT_DOWN_MASK)); print.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_P, menuMask)); + KeyEvent.VK_P, menuMask)); quit.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_Q, menuMask)); + KeyEvent.VK_Q, menuMask)); add(newi); add(open); @@ -70,7 +70,7 @@ public MenuFile(LogisimMenuBar menubar) { add(quit); } - Project proj = menubar.getProject(); + Project proj = menubar.getMenuProject(); newi.addActionListener(this); open.addActionListener(this); if (proj == null) { @@ -110,7 +110,7 @@ void computeEnabled() { public void actionPerformed(ActionEvent event) { Object eventSource = event.getSource(); - Project project = menubar.getProject(); + Project project = menubar.getMenuProject(); if (eventSource == newi) { ProjectActions.doNew(project); } else if (eventSource == open) { diff --git a/src/main/java/com/cburch/logisim/gui/menu/MenuHelp.java b/src/main/java/com/cburch/logisim/gui/menu/MenuHelp.java index fdc8fc9..ef5dfae 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/MenuHelp.java +++ b/src/main/java/com/cburch/logisim/gui/menu/MenuHelp.java @@ -17,12 +17,12 @@ class MenuHelp extends JMenu implements ActionListener { - private LogisimMenuBar menubar; - private JMenuItem tutorial = new JMenuItem(); - private JMenuItem guide = new JMenuItem(); - private JMenuItem library = new JMenuItem(); - private JMenuItem about = new JMenuItem(); private static final String HELP_URL = "https://github.com/dadler64/Logisim/wiki"; + private final LogisimMenuBar menubar; + private final JMenuItem tutorial = new JMenuItem(); + private final JMenuItem guide = new JMenuItem(); + private final JMenuItem library = new JMenuItem(); + private final JMenuItem about = new JMenuItem(); public MenuHelp(LogisimMenuBar menubar) { this.menubar = menubar; diff --git a/src/main/java/com/cburch/logisim/gui/menu/MenuItemCheckImpl.java b/src/main/java/com/cburch/logisim/gui/menu/MenuItemCheckImpl.java index e00567d..d09a2a9 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/MenuItemCheckImpl.java +++ b/src/main/java/com/cburch/logisim/gui/menu/MenuItemCheckImpl.java @@ -9,7 +9,7 @@ class MenuItemCheckImpl extends JCheckBoxMenuItem implements MenuItem { - private MenuItemHelper helper; + private final MenuItemHelper helper; public MenuItemCheckImpl(Menu menu, LogisimMenuItem menuItem) { helper = new MenuItemHelper(this, menu, menuItem); diff --git a/src/main/java/com/cburch/logisim/gui/menu/MenuItemHelper.java b/src/main/java/com/cburch/logisim/gui/menu/MenuItemHelper.java index e4645e1..91489a0 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/MenuItemHelper.java +++ b/src/main/java/com/cburch/logisim/gui/menu/MenuItemHelper.java @@ -10,12 +10,12 @@ class MenuItemHelper implements ActionListener { - private JMenuItem source; - private LogisimMenuItem menuItem; - private Menu menu; + private final JMenuItem source; + private final LogisimMenuItem menuItem; + private final Menu menu; + private final ArrayList listeners; private boolean enabled; private boolean inActionListener; - private ArrayList listeners; public MenuItemHelper(JMenuItem source, Menu menu, LogisimMenuItem menuItem) { this.source = source; @@ -59,8 +59,8 @@ private void computeEnabled() { public void actionPerformed(ActionEvent event) { if (!listeners.isEmpty()) { ActionEvent e = new ActionEvent(menuItem, event.getID(), - event.getActionCommand(), event.getWhen(), - event.getModifiers()); + event.getActionCommand(), event.getWhen(), + event.getModifiers()); for (ActionListener l : listeners) { l.actionPerformed(e); } diff --git a/src/main/java/com/cburch/logisim/gui/menu/MenuItemImpl.java b/src/main/java/com/cburch/logisim/gui/menu/MenuItemImpl.java index 4a99abe..045be86 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/MenuItemImpl.java +++ b/src/main/java/com/cburch/logisim/gui/menu/MenuItemImpl.java @@ -9,7 +9,7 @@ class MenuItemImpl extends JMenuItem implements MenuItem { - private MenuItemHelper helper; + private final MenuItemHelper helper; public MenuItemImpl(Menu menu, LogisimMenuItem menuItem) { helper = new MenuItemHelper(this, menu, menuItem); diff --git a/src/main/java/com/cburch/logisim/gui/menu/MenuProject.java b/src/main/java/com/cburch/logisim/gui/menu/MenuProject.java index ea60094..9126f83 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/MenuProject.java +++ b/src/main/java/com/cburch/logisim/gui/menu/MenuProject.java @@ -12,26 +12,26 @@ class MenuProject extends Menu { - private LogisimMenuBar menubar; - private MyListener myListener = new MyListener(); - private MenuItemImpl addCircuit = new MenuItemImpl(this, LogisimMenuBar.ADD_CIRCUIT); - private JMenu loadLibrary = new JMenu(); - private JMenuItem loadBuiltin = new JMenuItem(); - private JMenuItem loadLogisim = new JMenuItem(); - private JMenuItem loadJar = new JMenuItem(); - private JMenuItem unload = new JMenuItem(); - private MenuItemImpl moveUp = new MenuItemImpl(this, LogisimMenuBar.MOVE_CIRCUIT_UP); - private MenuItemImpl moveDown = new MenuItemImpl(this, LogisimMenuBar.MOVE_CIRCUIT_DOWN); - private MenuItemImpl remove = new MenuItemImpl(this, LogisimMenuBar.REMOVE_CIRCUIT); - private MenuItemImpl setAsMain = new MenuItemImpl(this, LogisimMenuBar.SET_MAIN_CIRCUIT); - private MenuItemImpl revertAppearance = new MenuItemImpl(this, LogisimMenuBar.REVERT_APPEARANCE); - private MenuItemImpl layout = new MenuItemImpl(this, LogisimMenuBar.EDIT_LAYOUT); - private MenuItemImpl appearance = new MenuItemImpl(this, LogisimMenuBar.EDIT_APPEARANCE); - private MenuItemImpl viewToolbox = new MenuItemImpl(this, LogisimMenuBar.VIEW_TOOLBOX); - private MenuItemImpl viewSimulation = new MenuItemImpl(this, LogisimMenuBar.VIEW_SIMULATION); - private MenuItemImpl analyze = new MenuItemImpl(this, LogisimMenuBar.ANALYZE_CIRCUIT); - private MenuItemImpl stats = new MenuItemImpl(this, LogisimMenuBar.CIRCUIT_STATS); - private JMenuItem options = new JMenuItem(); + private final LogisimMenuBar menubar; + private final MyListener myListener = new MyListener(); + private final MenuItemImpl addCircuit = new MenuItemImpl(this, LogisimMenuBar.ADD_CIRCUIT); + private final JMenu loadLibrary = new JMenu(); + private final JMenuItem loadBuiltin = new JMenuItem(); + private final JMenuItem loadLogisim = new JMenuItem(); + private final JMenuItem loadJar = new JMenuItem(); + private final JMenuItem unload = new JMenuItem(); + private final MenuItemImpl moveUp = new MenuItemImpl(this, LogisimMenuBar.MOVE_CIRCUIT_UP); + private final MenuItemImpl moveDown = new MenuItemImpl(this, LogisimMenuBar.MOVE_CIRCUIT_DOWN); + private final MenuItemImpl remove = new MenuItemImpl(this, LogisimMenuBar.REMOVE_CIRCUIT); + private final MenuItemImpl setAsMain = new MenuItemImpl(this, LogisimMenuBar.SET_MAIN_CIRCUIT); + private final MenuItemImpl revertAppearance = new MenuItemImpl(this, LogisimMenuBar.REVERT_APPEARANCE); + private final MenuItemImpl layout = new MenuItemImpl(this, LogisimMenuBar.EDIT_LAYOUT); + private final MenuItemImpl appearance = new MenuItemImpl(this, LogisimMenuBar.EDIT_APPEARANCE); + private final MenuItemImpl viewToolbox = new MenuItemImpl(this, LogisimMenuBar.VIEW_TOOLBOX); + private final MenuItemImpl viewSimulation = new MenuItemImpl(this, LogisimMenuBar.VIEW_SIMULATION); + private final MenuItemImpl analyze = new MenuItemImpl(this, LogisimMenuBar.ANALYZE_CIRCUIT); + private final MenuItemImpl stats = new MenuItemImpl(this, LogisimMenuBar.CIRCUIT_STATS); + private final JMenuItem options = new JMenuItem(); MenuProject(LogisimMenuBar menubar) { this.menubar = menubar; @@ -78,7 +78,7 @@ class MenuProject extends Menu { addSeparator(); add(options); - boolean known = menubar.getProject() != null; + boolean known = menubar.getMenuProject() != null; loadLibrary.setEnabled(known); loadBuiltin.setEnabled(known); loadLogisim.setEnabled(known); @@ -112,28 +112,28 @@ public void localeChanged() { @Override void computeEnabled() { - setEnabled(menubar.getProject() != null - || addCircuit.hasListeners() - || moveUp.hasListeners() - || moveDown.hasListeners() - || setAsMain.hasListeners() - || remove.hasListeners() - || layout.hasListeners() - || revertAppearance.hasListeners() - || appearance.hasListeners() - || viewToolbox.hasListeners() - || viewSimulation.hasListeners() - || analyze.hasListeners() - || stats.hasListeners()); + setEnabled(menubar.getMenuProject() != null + || addCircuit.hasListeners() + || moveUp.hasListeners() + || moveDown.hasListeners() + || setAsMain.hasListeners() + || remove.hasListeners() + || layout.hasListeners() + || revertAppearance.hasListeners() + || appearance.hasListeners() + || viewToolbox.hasListeners() + || viewSimulation.hasListeners() + || analyze.hasListeners() + || stats.hasListeners()); menubar.fireEnableChanged(); } private class MyListener - implements ActionListener { + implements ActionListener { public void actionPerformed(ActionEvent event) { Object src = event.getSource(); - Project proj = menubar.getProject(); + Project proj = menubar.getMenuProject(); if (src == loadBuiltin) { ProjectLibraryActions.doLoadBuiltinLibrary(proj); } else if (src == loadLogisim) { diff --git a/src/main/java/com/cburch/logisim/gui/menu/MenuSimulate.java b/src/main/java/com/cburch/logisim/gui/menu/MenuSimulate.java index 0344dbe..49d2881 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/MenuSimulate.java +++ b/src/main/java/com/cburch/logisim/gui/menu/MenuSimulate.java @@ -27,39 +27,39 @@ class MenuSimulate extends Menu { - private LogisimMenuBar menubar; - private MyListener myListener = new MyListener(); + private final LogisimMenuBar menubar; + private final MyListener myListener = new MyListener(); + private final MenuItemCheckImpl run; + private final JMenuItem reset = new JMenuItem(); + private final MenuItemImpl step; + private final MenuItemCheckImpl ticksEnabled; + private final MenuItemImpl tickOnce; + private final JMenu tickFreq = new JMenu(); + private final TickFrequencyChoice[] tickFrequencies = { + new TickFrequencyChoice(4096), + new TickFrequencyChoice(2048), + new TickFrequencyChoice(1024), + new TickFrequencyChoice(512), + new TickFrequencyChoice(256), + new TickFrequencyChoice(128), + new TickFrequencyChoice(64), + new TickFrequencyChoice(32), + new TickFrequencyChoice(16), + new TickFrequencyChoice(8), + new TickFrequencyChoice(4), + new TickFrequencyChoice(2), + new TickFrequencyChoice(1), + new TickFrequencyChoice(0.5), + new TickFrequencyChoice(0.25), + }; + private final JMenu downStateMenu = new JMenu(); + private final ArrayList downStateItems = new ArrayList<>(); + private final JMenu upStateMenu = new JMenu(); + private final ArrayList upStateItems = new ArrayList<>(); + private final JMenuItem log = new JMenuItem(); private CircuitState currentState = null; private CircuitState bottomState = null; private Simulator currentSim = null; - private MenuItemCheckImpl run; - private JMenuItem reset = new JMenuItem(); - private MenuItemImpl step; - private MenuItemCheckImpl ticksEnabled; - private MenuItemImpl tickOnce; - private JMenu tickFreq = new JMenu(); - private TickFrequencyChoice[] tickFrequencies = { - new TickFrequencyChoice(4096), - new TickFrequencyChoice(2048), - new TickFrequencyChoice(1024), - new TickFrequencyChoice(512), - new TickFrequencyChoice(256), - new TickFrequencyChoice(128), - new TickFrequencyChoice(64), - new TickFrequencyChoice(32), - new TickFrequencyChoice(16), - new TickFrequencyChoice(8), - new TickFrequencyChoice(4), - new TickFrequencyChoice(2), - new TickFrequencyChoice(1), - new TickFrequencyChoice(0.5), - new TickFrequencyChoice(0.25), - }; - private JMenu downStateMenu = new JMenu(); - private ArrayList downStateItems = new ArrayList<>(); - private JMenu upStateMenu = new JMenu(); - private ArrayList upStateItems = new ArrayList<>(); - private JMenuItem log = new JMenuItem(); public MenuSimulate(LogisimMenuBar menubar) { this.menubar = menubar; @@ -74,17 +74,17 @@ public MenuSimulate(LogisimMenuBar menubar) { menubar.registerItem(LogisimMenuBar.TICK_ENABLE, ticksEnabled); menubar.registerItem(LogisimMenuBar.TICK_STEP, tickOnce); - int menuMask = getToolkit().getMenuShortcutKeyMask(); + int menuMask = getToolkit().getMenuShortcutKeyMaskEx(); run.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_E, menuMask)); + KeyEvent.VK_E, menuMask)); reset.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_R, menuMask)); + KeyEvent.VK_R, menuMask)); step.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_I, menuMask)); + KeyEvent.VK_I, menuMask)); tickOnce.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_T, menuMask)); + KeyEvent.VK_T, menuMask)); ticksEnabled.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_K, menuMask)); + KeyEvent.VK_K, menuMask)); ButtonGroup buttonGroup = new ButtonGroup(); for (TickFrequencyChoice tickFrequency : tickFrequencies) { @@ -222,7 +222,7 @@ private void recreateStateMenu(JMenu menu, ArrayList items menu.removeAll(); menu.setEnabled(items.size() > 0); boolean first = true; - int mask = getToolkit().getMenuShortcutKeyMask(); + int mask = getToolkit().getMenuShortcutKeyMaskEx(); for (int i = items.size() - 1; i >= 0; i--) { JMenuItem item = items.get(i); menu.add(item); @@ -253,9 +253,9 @@ void computeEnabled() { } private class TickFrequencyChoice extends JRadioButtonMenuItem - implements ActionListener { + implements ActionListener { - private double frequency; + private final double frequency; private TickFrequencyChoice(double value) { frequency = value; @@ -293,7 +293,7 @@ public void localeChanged() { private class CircuitStateMenuItem extends JMenuItem implements CircuitListener, ActionListener { - private CircuitState circuitState; + private final CircuitState circuitState; private CircuitStateMenuItem(CircuitState circuitState) { this.circuitState = circuitState; @@ -324,7 +324,7 @@ private class MyListener implements ActionListener, SimulatorListener, ChangeLis public void actionPerformed(ActionEvent event) { Object source = event.getSource(); - Project project = menubar.getProject(); + Project project = menubar.getMenuProject(); Simulator simulator = project == null ? null : project.getSimulator(); if (source.equals(run) || source.equals(LogisimMenuBar.SIMULATE_ENABLE)) { if (simulator != null) { @@ -348,15 +348,17 @@ public void actionPerformed(ActionEvent event) { simulator.setIsTicking(!simulator.isTicking()); } } else if (source.equals(log)) { - assert menubar.getProject() != null; - LogFrame frame = menubar.getProject().getLogFrame(true); + assert menubar.getMenuProject() != null; + LogFrame frame = menubar.getMenuProject().getLogFrame(true); frame.setVisible(true); } } - public void propagationCompleted(SimulatorEvent event) { } + public void propagationCompleted(SimulatorEvent event) { + } - public void tickCompleted(SimulatorEvent event) { } + public void tickCompleted(SimulatorEvent event) { + } public void simulatorStateChanged(SimulatorEvent event) { Simulator simulator = event.getSource(); diff --git a/src/main/java/com/cburch/logisim/gui/menu/MenuTheme.java b/src/main/java/com/cburch/logisim/gui/menu/MenuTheme.java index 4592e47..4c1e1f2 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/MenuTheme.java +++ b/src/main/java/com/cburch/logisim/gui/menu/MenuTheme.java @@ -1,149 +1,147 @@ -//package com.cburch.logisim.gui.menu; -// -//import com.adlerd.logger.Logger; -//import com.cburch.logisim.gui.start.About; -//import com.cburch.logisim.util.MacCompatibility; -//import java.awt.Component; -//import java.awt.Desktop; -//import java.awt.event.ActionEvent; -//import java.io.IOException; -//import java.net.URISyntaxException; -//import java.net.URL; -//import javax.swing.AbstractAction; -//import javax.swing.Action; -//import javax.swing.ButtonGroup; -//import javax.swing.JMenu; -//import javax.swing.JMenuItem; -//import javax.swing.JPopupMenu; -//import javax.swing.JRadioButtonMenuItem; -//import javax.swing.JRootPane; -//import javax.swing.SwingUtilities; -//import javax.swing.UIManager; -// -//public class MenuTheme extends Menu { -// -// -// /** -// * Create menu items for the Look & Feel menu -// */ -// private JMenu createLAFMenu() -// { -// ButtonGroup buttonGroup = new ButtonGroup(); -// -// JMenu themeMenu = new JMenu("UI Theme"); -// themeMenu.setMnemonic('L'); -// -// String themeId = UIManager.getLookAndFeel().getID(); -// UIManager.LookAndFeelInfo[] themes = UIManager.getInstalledLookAndFeels(); -// -// for (UIManager.LookAndFeelInfo theme : themes) { -// String lookAndFeelClass = theme.getClassName(); -// String name = theme.getName(); -// -// Action action = new ChangeLookAndFeelAction(lookAndFeelClass, name); -// JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(action); -// themeMenu.add(menuItem); -// buttonGroup.add(menuItem); -// -// if (name.equals(themeId)) { -// menuItem.setSelected(true); -// } -// } -// -// return themeMenu; -// } -// -// private LogisimMenuBar menubar; -// private JMenuItem tutorial = new JMenuItem(); -// private JMenuItem guide = new JMenuItem(); -// private JMenuItem library = new JMenuItem(); -// private JMenuItem about = new JMenuItem(); -// private static final String HELP_URL = "https://github.com/dadler64/Logisim/wiki"; -// -// public MenuTheme(LogisimMenuBar menubar) { -// this.menubar = menubar; -// -// add(tutorial); -// add(guide); -// add(library); -// if (!MacCompatibility.isAboutAutomaticallyPresent()) { -// addSeparator(); -// add(about); -// } -// } -// -// public void localeChanged() { -// this.setText(Strings.get("helpMenu")); -// tutorial.setText(Strings.get("helpTutorialItem")); -// guide.setText(Strings.get("helpGuideItem")); -// library.setText(Strings.get("helpLibraryItem")); -// about.setText(Strings.get("helpAboutItem")); -// } -// -// public void actionPerformed(ActionEvent event) { -// Object source = event.getSource(); -// String extension = ""; -// if (source == tutorial) { -// // TODO: Add url extension to get to the Tutorial Page -// extension = ""; -// } else if (source == guide) { -// // TODO: Add url extension to get to the User Guide page -// extension = ""; -// } else if (source == library) { -// // TODO: Add url extension to get to the Library Reference Page -// extension = ""; -// } else if (source == about) { -// About.showAboutDialog(menubar.getParentWindow()); -// } -// -// try { -// Desktop.getDesktop().browse(new URL(HELP_URL + extension).toURI()); -// } catch (IOException e) { -// Logger.errorln("Could not open link"); -// Logger.errorln(Strings.get("linkOpenFail")); -// e.printStackTrace(); -// } catch (URISyntaxException e) { -// Logger.errorln(Strings.get("badUri")); -// e.printStackTrace(); -// } -// } -// -// /* -// * Change the LAF and recreate the UIManagerDefaults so that the properties -// * of the new LAF are correctly displayed. -// */ -// static class ChangeLookAndFeelAction extends AbstractAction -// { -// private String laf; -// -// private ChangeLookAndFeelAction(String laf, String name) -// { -// this.laf = laf; -// putValue(Action.NAME, name); -// putValue(Action.SHORT_DESCRIPTION, getValue(Action.NAME)); -// } -// -// public void actionPerformed(ActionEvent e) -// { -// try -// { -// JMenuItem mi = (JMenuItem)e.getSource(); -// JPopupMenu popup = (JPopupMenu)mi.getParent(); -// JRootPane rootPane = SwingUtilities.getRootPane(popup.getInvoker()); -// Component c = rootPane.getContentPane().getComponent(0); -// rootPane.getContentPane().remove(c); -// -// UIManager.setLookAndFeel(laf); -// rootPane.getContentPane().add( bindings.getContentPane() ); -// SwingUtilities.updateComponentTreeUI( rootPane ); -// rootPane.requestFocusInWindow(); -// } -// catch (Exception ex) -// { -// System.out.println("Failed loading L&F: " + laf); -// System.out.println(ex); -// } -// } -// } -// -//} +package com.cburch.logisim.gui.menu; + +import com.adlerd.logger.Logger; +import com.cburch.logisim.gui.start.About; +import com.cburch.logisim.util.MacCompatibility; +import java.awt.Component; +import java.awt.Desktop; +import java.awt.event.ActionEvent; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.ButtonGroup; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JRootPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +public class MenuTheme extends Menu { + + private static final String HELP_URL = "https://github.com/dadler64/Logisim/wiki"; + private final LogisimMenuBar menubar; + private final JMenuItem tutorial = new JMenuItem(); + private final JMenuItem guide = new JMenuItem(); + private final JMenuItem library = new JMenuItem(); + private final JMenuItem about = new JMenuItem(); + + public MenuTheme(LogisimMenuBar menubar) { + this.menubar = menubar; + + add(tutorial); + add(guide); + add(library); + if (!MacCompatibility.isAboutAutomaticallyPresent()) { + addSeparator(); + add(about); + } + } + + /** + * Create menu items for the Look & Feel menu + */ + private JMenu createLAFMenu() { + ButtonGroup buttonGroup = new ButtonGroup(); + + JMenu themeMenu = new JMenu("UI Theme"); + themeMenu.setMnemonic('L'); + + String themeId = UIManager.getLookAndFeel().getID(); + UIManager.LookAndFeelInfo[] themes = UIManager.getInstalledLookAndFeels(); + + for (UIManager.LookAndFeelInfo theme : themes) { + String lookAndFeelClass = theme.getClassName(); + String name = theme.getName(); + + Action action = new ChangeLookAndFeelAction(lookAndFeelClass, name); + JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(action); + themeMenu.add(menuItem); + buttonGroup.add(menuItem); + + if (name.equals(themeId)) { + menuItem.setSelected(true); + } + } + + return themeMenu; + } + + public void localeChanged() { + this.setText(Strings.get("helpMenu")); + tutorial.setText(Strings.get("helpTutorialItem")); + guide.setText(Strings.get("helpGuideItem")); + library.setText(Strings.get("helpLibraryItem")); + about.setText(Strings.get("helpAboutItem")); + } + + public void actionPerformed(ActionEvent event) { + Object source = event.getSource(); + String extension = ""; + if (source == tutorial) { + // TODO: Add url extension to get to the Tutorial Page + extension = ""; + } else if (source == guide) { + // TODO: Add url extension to get to the User Guide page + extension = ""; + } else if (source == library) { + // TODO: Add url extension to get to the Library Reference Page + extension = ""; + } else if (source == about) { + About.showAboutDialog(menubar.getParentWindow()); + } + + try { + Desktop.getDesktop().browse(new URL(HELP_URL + extension).toURI()); + } catch (IOException e) { + Logger.errorln("Could not open link"); + Logger.errorln(Strings.get("linkOpenFail")); + e.printStackTrace(); + } catch (URISyntaxException e) { + Logger.errorln(Strings.get("badUri")); + e.printStackTrace(); + } + } + + @Override + void computeEnabled() { + + } + + /* + * Change the LAF and recreate the UIManagerDefaults so that the properties + * of the new LAF are correctly displayed. + */ + static class ChangeLookAndFeelAction extends AbstractAction { + + private final String laf; + + private ChangeLookAndFeelAction(String laf, String name) { + this.laf = laf; + putValue(Action.NAME, name); + putValue(Action.SHORT_DESCRIPTION, getValue(Action.NAME)); + } + + public void actionPerformed(ActionEvent e) { + try { + JMenuItem mi = (JMenuItem) e.getSource(); + JPopupMenu popup = (JPopupMenu) mi.getParent(); + JRootPane rootPane = SwingUtilities.getRootPane(popup.getInvoker()); + Component c = rootPane.getContentPane().getComponent(0); + rootPane.getContentPane().remove(c); + + UIManager.setLookAndFeel(laf); +// rootPane.getContentPane().add(bindings.getContentPane()); + SwingUtilities.updateComponentTreeUI(rootPane); + rootPane.requestFocusInWindow(); + } catch (Exception ex) { + System.out.println("Failed loading L&F: " + laf); + System.out.println(ex); + } + } + } + +} diff --git a/src/main/java/com/cburch/logisim/gui/menu/OpenRecent.java b/src/main/java/com/cburch/logisim/gui/menu/OpenRecent.java index 7456bb5..54ada04 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/OpenRecent.java +++ b/src/main/java/com/cburch/logisim/gui/menu/OpenRecent.java @@ -21,8 +21,8 @@ class OpenRecent extends JMenu implements PropertyChangeListener { private static final int MAX_ITEM_LENGTH = 50; - private LogisimMenuBar menubar; - private List recentItems; + private final LogisimMenuBar menubar; + private final List recentItems; OpenRecent(LogisimMenuBar menubar) { this.menubar = menubar; @@ -92,7 +92,7 @@ public void propertyChange(PropertyChangeEvent event) { private class RecentItem extends JMenuItem implements ActionListener { - private File file; + private final File file; RecentItem(File file) { super(getFileText(file)); @@ -102,7 +102,7 @@ private class RecentItem extends JMenuItem implements ActionListener { } public void actionPerformed(ActionEvent event) { - Project proj = menubar.getProject(); + Project proj = menubar.getMenuProject(); Component par = proj == null ? null : proj.getFrame().getCanvas(); ProjectActions.doOpen(par, proj, file); } diff --git a/src/main/java/com/cburch/logisim/gui/menu/Popups.java b/src/main/java/com/cburch/logisim/gui/menu/Popups.java index a976c9c..258a3db 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/Popups.java +++ b/src/main/java/com/cburch/logisim/gui/menu/Popups.java @@ -41,12 +41,12 @@ public static JPopupMenu forLibrary(Project project, Library library, boolean is private static class ProjectPopup extends JPopupMenu implements ActionListener { - private Project project; - private JMenuItem addItem = new JMenuItem(Strings.get("projectAddCircuitItem")); - private JMenu loadItem = new JMenu(Strings.get("projectLoadLibraryItem")); - private JMenuItem loadBuiltinItem = new JMenuItem(Strings.get("projectLoadBuiltinItem")); - private JMenuItem loadLogisimItem = new JMenuItem(Strings.get("projectLoadLogisimItem")); - private JMenuItem loadJarItem = new JMenuItem(Strings.get("projectLoadJarItem")); + private final Project project; + private final JMenuItem addItem = new JMenuItem(Strings.get("projectAddCircuitItem")); + private final JMenu loadItem = new JMenu(Strings.get("projectLoadLibraryItem")); + private final JMenuItem loadBuiltinItem = new JMenuItem(Strings.get("projectLoadBuiltinItem")); + private final JMenuItem loadLogisimItem = new JMenuItem(Strings.get("projectLoadLogisimItem")); + private final JMenuItem loadJarItem = new JMenuItem(Strings.get("projectLoadJarItem")); private ProjectPopup(Project project) { super(Strings.get("projMenu")); @@ -80,10 +80,10 @@ public void actionPerformed(ActionEvent event) { private static class LibraryPopup extends JPopupMenu implements ActionListener { - private Project project; - private Library library; - private JMenuItem unloadItem = new JMenuItem(Strings.get("projectUnloadLibraryItem")); - private JMenuItem reloadItem = new JMenuItem(Strings.get("projectReloadLibraryItem")); + private final Project project; + private final Library library; + private final JMenuItem unloadItem = new JMenuItem(Strings.get("projectUnloadLibraryItem")); + private final JMenuItem reloadItem = new JMenuItem(Strings.get("projectReloadLibraryItem")); private LibraryPopup(Project project, Library library, boolean isTop) { super(Strings.get("libMenu")); @@ -111,15 +111,15 @@ public void actionPerformed(ActionEvent event) { private static class CircuitPopup extends JPopupMenu implements ActionListener { - private Project project; - private Tool tool; - private Circuit circuit; - private JMenuItem analyzeItem = new JMenuItem(Strings.get("projectAnalyzeCircuitItem")); - private JMenuItem statsItem = new JMenuItem(Strings.get("projectGetCircuitStatisticsItem")); - private JMenuItem mainItem = new JMenuItem(Strings.get("projectSetAsMainItem")); - private JMenuItem removeItem = new JMenuItem(Strings.get("projectRemoveCircuitItem")); - private JMenuItem editLayoutItem = new JMenuItem(Strings.get("projectEditCircuitLayoutItem")); - private JMenuItem editAppearanceItem = new JMenuItem(Strings.get("projectEditCircuitAppearanceItem")); + private final Project project; + private final Tool tool; + private final Circuit circuit; + private final JMenuItem analyzeItem = new JMenuItem(Strings.get("projectAnalyzeCircuitItem")); + private final JMenuItem statsItem = new JMenuItem(Strings.get("projectGetCircuitStatisticsItem")); + private final JMenuItem mainItem = new JMenuItem(Strings.get("projectSetAsMainItem")); + private final JMenuItem removeItem = new JMenuItem(Strings.get("projectRemoveCircuitItem")); + private final JMenuItem editLayoutItem = new JMenuItem(Strings.get("projectEditCircuitLayoutItem")); + private final JMenuItem editAppearanceItem = new JMenuItem(Strings.get("projectEditCircuitAppearanceItem")); private CircuitPopup(Project project, Tool tool, Circuit circuit) { super(Strings.get("circuitMenu")); @@ -152,7 +152,7 @@ private CircuitPopup(Project project, Tool tool, Circuit circuit) { } mainItem.setEnabled(canChange && file.getMainCircuit() != circuit); removeItem.setEnabled(canChange && file.getCircuitCount() > 1 - && project.getDependencies().canRemove(circuit)); + && project.getDependencies().canRemove(circuit)); } public void actionPerformed(ActionEvent event) { diff --git a/src/main/java/com/cburch/logisim/gui/menu/ProjectCircuitActions.java b/src/main/java/com/cburch/logisim/gui/menu/ProjectCircuitActions.java index 44e1dc5..5a1e90b 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/ProjectCircuitActions.java +++ b/src/main/java/com/cburch/logisim/gui/menu/ProjectCircuitActions.java @@ -45,8 +45,7 @@ public static void doAddCircuit(Project proj) { } } - private static String promptForCircuitName(JFrame frame, - Library lib, String initialValue) { + private static String promptForCircuitName(JFrame frame, Library lib, String initialValue) { JLabel label = new JLabel(Strings.get("circuitNamePrompt")); final JTextField field = new JTextField(15); field.setText(initialValue); @@ -70,7 +69,7 @@ private static String promptForCircuitName(JFrame frame, gb.setConstraints(strut, gc); panel.add(strut); JOptionPane pane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, - JOptionPane.OK_CANCEL_OPTION); + JOptionPane.OK_CANCEL_OPTION); pane.setInitialValue(field); JDialog dlog = pane.createDialog(frame, Strings.get("circuitNameDialogTitle")); dlog.addWindowFocusListener(new WindowFocusListener() { @@ -88,8 +87,7 @@ public void windowLostFocus(WindowEvent arg0) { dlog.setVisible(true); field.requestFocusInWindow(); Object action = pane.getValue(); - if (action == null || !(action instanceof Integer) - || (Integer) action != JOptionPane.OK_OPTION) { + if (action == null || !(action instanceof Integer) || (Integer) action != JOptionPane.OK_OPTION) { return null; } @@ -125,14 +123,14 @@ public static void doSetAsMainCircuit(Project proj, Circuit circuit) { public static void doRemoveCircuit(Project proj, Circuit circuit) { if (proj.getLogisimFile().getTools().size() == 1) { JOptionPane.showMessageDialog(proj.getFrame(), - Strings.get("circuitRemoveLastError"), - Strings.get("circuitRemoveErrorTitle"), - JOptionPane.ERROR_MESSAGE); + Strings.get("circuitRemoveLastError"), + Strings.get("circuitRemoveErrorTitle"), + JOptionPane.ERROR_MESSAGE); } else if (!proj.getDependencies().canRemove(circuit)) { JOptionPane.showMessageDialog(proj.getFrame(), - Strings.get("circuitRemoveUsedError"), - Strings.get("circuitRemoveErrorTitle"), - JOptionPane.ERROR_MESSAGE); + Strings.get("circuitRemoveUsedError"), + Strings.get("circuitRemoveErrorTitle"), + JOptionPane.ERROR_MESSAGE); } else { proj.doAction(LogisimFileActions.removeCircuit(circuit)); } @@ -160,13 +158,11 @@ public static void doAnalyze(Project proj, Circuit circuit) { } } if (inputNames.size() > AnalyzerModel.MAX_INPUTS) { - analyzeError(proj, StringUtil.format(Strings.get("analyzeTooManyInputsError"), - "" + AnalyzerModel.MAX_INPUTS)); + analyzeError(proj, StringUtil.format(Strings.get("analyzeTooManyInputsError"), "" + AnalyzerModel.MAX_INPUTS)); return; } if (outputNames.size() > AnalyzerModel.MAX_OUTPUTS) { - analyzeError(proj, StringUtil.format(Strings.get("analyzeTooManyOutputsError"), - "" + AnalyzerModel.MAX_OUTPUTS)); + analyzeError(proj, StringUtil.format(Strings.get("analyzeTooManyOutputsError"), "" + AnalyzerModel.MAX_OUTPUTS)); return; } @@ -178,8 +174,8 @@ public static void doAnalyze(Project proj, Circuit circuit) { } private static void configureAnalyzer(Project proj, Circuit circuit, - Analyzer analyzer, Map pinNames, - ArrayList inputNames, ArrayList outputNames) { + Analyzer analyzer, Map pinNames, + ArrayList inputNames, ArrayList outputNames) { analyzer.getModel().setVariables(inputNames, outputNames); // If there are no inputs, we stop with that tab selected @@ -201,8 +197,8 @@ private static void configureAnalyzer(Project proj, Circuit circuit, return; } catch (AnalyzeException ex) { JOptionPane.showMessageDialog(proj.getFrame(), ex.getMessage(), - Strings.get("analyzeNoExpressionTitle"), - JOptionPane.INFORMATION_MESSAGE); + Strings.get("analyzeNoExpressionTitle"), + JOptionPane.INFORMATION_MESSAGE); } // As a backup measure, we compute a truth table. @@ -212,8 +208,7 @@ private static void configureAnalyzer(Project proj, Circuit circuit, private static void analyzeError(Project proj, String message) { JOptionPane.showMessageDialog(proj.getFrame(), message, - Strings.get("analyzeErrorTitle"), - JOptionPane.ERROR_MESSAGE); - return; + Strings.get("analyzeErrorTitle"), + JOptionPane.ERROR_MESSAGE); } } diff --git a/src/main/java/com/cburch/logisim/gui/menu/ProjectLibraryActions.java b/src/main/java/com/cburch/logisim/gui/menu/ProjectLibraryActions.java index 23d62f7..facb4c6 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/ProjectLibraryActions.java +++ b/src/main/java/com/cburch/logisim/gui/menu/ProjectLibraryActions.java @@ -31,16 +31,15 @@ public static void doLoadBuiltinLibrary(Project proj) { builtins.removeAll(file.getLibraries()); if (builtins.isEmpty()) { JOptionPane.showMessageDialog(proj.getFrame(), - Strings.get("loadBuiltinNoneError"), - Strings.get("loadBuiltinErrorTitle"), - JOptionPane.INFORMATION_MESSAGE); + Strings.get("loadBuiltinNoneError"), + Strings.get("loadBuiltinErrorTitle"), + JOptionPane.INFORMATION_MESSAGE); return; } LibraryJList list = new LibraryJList(builtins); JScrollPane listPane = new JScrollPane(list); - int action = JOptionPane.showConfirmDialog(proj.getFrame(), listPane, - Strings.get("loadBuiltinDialogTitle"), JOptionPane.OK_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE); + int action = JOptionPane.showConfirmDialog(proj.getFrame(), listPane, Strings.get("loadBuiltinDialogTitle"), + JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (action == JOptionPane.OK_OPTION) { Library[] libs = list.getSelectedLibraries(); if (libs != null) { @@ -84,11 +83,14 @@ public static void doLoadJarLibrary(Project proj) { className = manifest.getMainAttributes().getValue("Library-Class"); } catch (IOException e) { // if opening the JAR file failed, do nothing + System.err.println("ERROR: Failed to load library -> " + jarFile.getName()); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { + System.err.println("ERROR: ProjectLibraryAssociations.class"); + e.printStackTrace(); } } } @@ -96,9 +98,9 @@ public static void doLoadJarLibrary(Project proj) { // if the class name was not found, go back to the good old dialog if (className == null) { className = JOptionPane.showInputDialog(proj.getFrame(), - Strings.get("jarClassNamePrompt"), - Strings.get("jarClassNameTitle"), - JOptionPane.QUESTION_MESSAGE); + Strings.get("jarClassNamePrompt"), + Strings.get("jarClassNameTitle"), + JOptionPane.QUESTION_MESSAGE); // if user canceled selection, abort if (className == null) { return; @@ -123,16 +125,16 @@ public static void doUnloadLibraries(Project proj) { } if (canUnload.isEmpty()) { JOptionPane.showMessageDialog(proj.getFrame(), - Strings.get("unloadNoneError"), - Strings.get("unloadErrorTitle"), - JOptionPane.INFORMATION_MESSAGE); + Strings.get("unloadNoneError"), + Strings.get("unloadErrorTitle"), + JOptionPane.INFORMATION_MESSAGE); return; } LibraryJList list = new LibraryJList(canUnload); JScrollPane listPane = new JScrollPane(list); int action = JOptionPane.showConfirmDialog(proj.getFrame(), listPane, - Strings.get("unloadLibrariesDialogTitle"), JOptionPane.OK_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE); + Strings.get("unloadLibrariesDialogTitle"), JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); if (action == JOptionPane.OK_OPTION) { Library[] libs = list.getSelectedLibraries(); if (libs != null) { @@ -145,7 +147,7 @@ public static void doUnloadLibrary(Project proj, Library lib) { String message = proj.getLogisimFile().getUnloadLibraryMessage(lib); if (message != null) { JOptionPane.showMessageDialog(proj.getFrame(), message, - Strings.get("unloadErrorTitle"), JOptionPane.ERROR_MESSAGE); + Strings.get("unloadErrorTitle"), JOptionPane.ERROR_MESSAGE); } else { proj.doAction(LogisimFileActions.unloadLibrary(lib)); } @@ -165,18 +167,18 @@ public String toString() { } } - private static class LibraryJList extends JList { + private static class LibraryJList extends JList { LibraryJList(List libraries) { ArrayList options = new ArrayList<>(); for (Library lib : libraries) { options.add(new BuiltinOption(lib)); } - setListData(options.toArray()); + setListData((BuiltinOption[]) options.toArray()); } Library[] getSelectedLibraries() { - Object[] selected = getSelectedValues(); + Object[] selected = getSelectedValuesList().toArray(); if (selected != null && selected.length > 0) { Library[] libs = new Library[selected.length]; for (int i = 0; i < selected.length; i++) { diff --git a/src/main/java/com/cburch/logisim/gui/menu/Strings.java b/src/main/java/com/cburch/logisim/gui/menu/Strings.java index c94fdba..159ce9c 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/Strings.java +++ b/src/main/java/com/cburch/logisim/gui/menu/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "menu"); + private static final LocaleManager source = new LocaleManager("logisim", "menu"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/gui/menu/WindowManagers.java b/src/main/java/com/cburch/logisim/gui/menu/WindowManagers.java index f4ba650..9d0d26d 100644 --- a/src/main/java/com/cburch/logisim/gui/menu/WindowManagers.java +++ b/src/main/java/com/cburch/logisim/gui/menu/WindowManagers.java @@ -23,10 +23,9 @@ public class WindowManagers { + private static final MyListener myListener = new MyListener(); + private static final HashMap projectMap = new LinkedHashMap<>(); private static boolean initialized = false; - private static MyListener myListener = new MyListener(); - private static HashMap projectMap - = new LinkedHashMap<>(); private WindowManagers() { } @@ -68,9 +67,9 @@ public void propertyChange(PropertyChangeEvent event) { } private static class ProjectManager extends WindowMenuItemManager - implements ProjectListener, LibraryListener { + implements ProjectListener, LibraryListener { - private Project proj; + private final Project proj; ProjectManager(Project proj) { super(proj.getLogisimFile().getName(), false); diff --git a/src/main/java/com/cburch/logisim/gui/opts/ComboOption.java b/src/main/java/com/cburch/logisim/gui/opts/ComboOption.java index 2bb85b8..55de900 100644 --- a/src/main/java/com/cburch/logisim/gui/opts/ComboOption.java +++ b/src/main/java/com/cburch/logisim/gui/opts/ComboOption.java @@ -9,8 +9,8 @@ class ComboOption { - private Object value; - private StringGetter getter; + private final Object value; + private final StringGetter getter; ComboOption(String value, StringGetter getter) { this.value = value; @@ -22,7 +22,7 @@ class ComboOption { this.getter = null; } - static void setSelected(JComboBox combo, Object value) { + static void setSelected(JComboBox combo, Object value) { for (int i = combo.getItemCount() - 1; i >= 0; i--) { ComboOption opt = (ComboOption) combo.getItemAt(i); if (opt.getValue().equals(value)) { diff --git a/src/main/java/com/cburch/logisim/gui/opts/MouseOptions.java b/src/main/java/com/cburch/logisim/gui/opts/MouseOptions.java index 9b55620..3edb94a 100644 --- a/src/main/java/com/cburch/logisim/gui/opts/MouseOptions.java +++ b/src/main/java/com/cburch/logisim/gui/opts/MouseOptions.java @@ -43,14 +43,14 @@ class MouseOptions extends OptionsPanel { - private MyListener listener = new MyListener(); + private final MyListener listener = new MyListener(); + private final MappingsModel model; + private final ProjectExplorer explorer; + private final JPanel addArea = new AddArea(); + private final JTable mappings = new JTable(); + private final AttrTable attrTable; + private final JButton remove = new JButton(); private Tool curTool = null; - private MappingsModel model; - private ProjectExplorer explorer; - private JPanel addArea = new AddArea(); - private JTable mappings = new JTable(); - private AttrTable attrTable; - private JButton remove = new JButton(); public MouseOptions(OptionsFrame window) { super(window, new GridLayout(1, 3)); @@ -87,8 +87,8 @@ public MouseOptions(OptionsFrame window) { gbc.gridheight = 4; gbc.fill = GridBagConstraints.BOTH; JScrollPane explorerPane = new JScrollPane(explorer, - ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); gridbag.setConstraints(explorerPane, gbc); add(explorerPane); gbc.weightx = 0.0; @@ -156,8 +156,8 @@ public AddArea() { setPreferredSize(new Dimension(75, 60)); setMinimumSize(new Dimension(75, 60)); setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createEmptyBorder(10, 10, 10, 10), - BorderFactory.createEtchedBorder())); + BorderFactory.createEmptyBorder(10, 10, 10, 10), + BorderFactory.createEtchedBorder())); } @Override @@ -175,7 +175,7 @@ public void paintComponent(Graphics g) { g.setColor(Color.BLACK); label1 = Strings.get("mouseMapText"); label2 = StringUtil.format(Strings.get("mouseMapText2"), - curTool.getDisplayName()); + curTool.getDisplayName()); } FontMetrics fm = g.getFontMetrics(); int x1 = (sz.width - fm.stringWidth(label1)) / 2; @@ -193,8 +193,8 @@ public void paintComponent(Graphics g) { } private class MyListener - implements ActionListener, MouseListener, ListSelectionListener, - MouseMappings.MouseMappingsListener, ProjectExplorerListener { + implements ActionListener, MouseListener, ListSelectionListener, + MouseMappings.MouseMappingsListener, ProjectExplorerListener { // // ActionListener method @@ -204,7 +204,7 @@ public void actionPerformed(ActionEvent e) { if (src == remove) { int row = mappings.getSelectedRow(); getProject().doAction(OptionsActions.removeMapping(getOptions().getMouseMappings(), - model.getKey(row))); + model.getKey(row))); row = Math.min(row, model.getRowCount() - 1); if (row >= 0) { setSelectedRow(row); diff --git a/src/main/java/com/cburch/logisim/gui/opts/OptionsActions.java b/src/main/java/com/cburch/logisim/gui/opts/OptionsActions.java index c35d5b8..6827d03 100644 --- a/src/main/java/com/cburch/logisim/gui/opts/OptionsActions.java +++ b/src/main/java/com/cburch/logisim/gui/opts/OptionsActions.java @@ -26,7 +26,7 @@ public static Action setAttribute(AttributeSet attrs, Attribute attr, Object } public static Action setMapping(MouseMappings mm, Integer mods, - Tool tool) { + Tool tool) { return new SetMapping(mm, mods, tool); } @@ -36,35 +36,35 @@ public static Action removeMapping(MouseMappings mm, Integer mods) { private static class SetAction extends Action { - private AttributeSet attrs; - private Attribute attr; - private Object newval; - private Object oldval; + private final AttributeSet attrs; + private final Attribute attr; + private final Object newVal; + private Object oldVal; SetAction(AttributeSet attrs, Attribute attr, - Object value) { + Object value) { @SuppressWarnings("unchecked") Attribute a = (Attribute) attr; this.attrs = attrs; this.attr = a; - this.newval = value; + this.newVal = value; } @Override public String getName() { return StringUtil.format(Strings.get("setOptionAction"), - attr.getDisplayName()); + attr.getDisplayName()); } @Override public void doIt(Project proj) { - oldval = attrs.getValue(attr); - attrs.setValue(attr, newval); + oldVal = attrs.getValue(attr); + attrs.setValue(attr, newVal); } @Override public void undo(Project proj) { - attrs.setValue(attr, oldval); + attrs.setValue(attr, oldVal); } } diff --git a/src/main/java/com/cburch/logisim/gui/opts/OptionsFrame.java b/src/main/java/com/cburch/logisim/gui/opts/OptionsFrame.java index 20c6f80..0ffaabc 100644 --- a/src/main/java/com/cburch/logisim/gui/opts/OptionsFrame.java +++ b/src/main/java/com/cburch/logisim/gui/opts/OptionsFrame.java @@ -28,14 +28,14 @@ public class OptionsFrame extends LFrame { - private Project project; - private LogisimFile file; - private MyListener myListener = new MyListener(); - private WindowMenuManager windowManager = new WindowMenuManager(); - private OptionsPanel[] panels; - private JTabbedPane tabbedPane; - private JButton revert = new JButton(); - private JButton close = new JButton(); + private final Project project; + private final LogisimFile file; + private final MyListener myListener = new MyListener(); + private final WindowMenuManager windowManager = new WindowMenuManager(); + private final OptionsPanel[] panels; + private final JTabbedPane tabbedPane; + private final JButton revert = new JButton(); + private final JButton close = new JButton(); public OptionsFrame(Project project) { this.project = project; @@ -45,13 +45,12 @@ public OptionsFrame(Project project) { setJMenuBar(new LogisimMenuBar(this, project)); panels = new OptionsPanel[]{ - new SimulateOptions(this), - new ToolbarOptions(this), - new MouseOptions(this), + new SimulateOptions(this), + new ToolbarOptions(this), + new MouseOptions(this), }; tabbedPane = new JTabbedPane(); - for (int index = 0; index < panels.length; index++) { - OptionsPanel panel = panels[index]; + for (OptionsPanel panel : panels) { tabbedPane.addTab(panel.getTitle(), null, panel, panel.getToolTipText()); } @@ -100,8 +99,7 @@ OptionsPanel[] getPrefPanels() { return panels; } - private class WindowMenuManager extends WindowMenuItemManager - implements LocaleListener { + private class WindowMenuManager extends WindowMenuItemManager implements LocaleListener { WindowMenuManager() { super(Strings.get("optionsFrameMenuItem"), false); @@ -119,7 +117,7 @@ public void localeChanged() { } private class MyListener - implements ActionListener, LibraryListener, LocaleListener { + implements ActionListener, LibraryListener, LocaleListener { public void actionPerformed(ActionEvent event) { Object src = event.getSource(); @@ -127,7 +125,7 @@ public void actionPerformed(ActionEvent event) { getProject().doAction(LogisimFileActions.revertDefaults()); } else if (src == close) { WindowEvent e = new WindowEvent(OptionsFrame.this, - WindowEvent.WINDOW_CLOSING); + WindowEvent.WINDOW_CLOSING); OptionsFrame.this.processWindowEvent(e); } } diff --git a/src/main/java/com/cburch/logisim/gui/opts/OptionsPanel.java b/src/main/java/com/cburch/logisim/gui/opts/OptionsPanel.java index 99ffc66..2653b0e 100644 --- a/src/main/java/com/cburch/logisim/gui/opts/OptionsPanel.java +++ b/src/main/java/com/cburch/logisim/gui/opts/OptionsPanel.java @@ -11,7 +11,7 @@ abstract class OptionsPanel extends JPanel { - private OptionsFrame optionsFrame; + private final OptionsFrame optionsFrame; public OptionsPanel(OptionsFrame frame) { super(); diff --git a/src/main/java/com/cburch/logisim/gui/opts/SimulateOptions.java b/src/main/java/com/cburch/logisim/gui/opts/SimulateOptions.java index 70c7290..527b0c2 100644 --- a/src/main/java/com/cburch/logisim/gui/opts/SimulateOptions.java +++ b/src/main/java/com/cburch/logisim/gui/opts/SimulateOptions.java @@ -19,23 +19,23 @@ class SimulateOptions extends OptionsPanel { - private MyListener myListener = new MyListener(); - private JLabel simLimitLabel = new JLabel(); - private JComboBox simLimit = new JComboBox(new Integer[]{ - 200, - 500, - 1000, - 2000, - 5000, - 10000, - 20000, - 50000, + private final MyListener myListener = new MyListener(); + private final JLabel simLimitLabel = new JLabel(); + private final JComboBox simLimit = new JComboBox<>(new Integer[]{ + 200, + 500, + 1000, + 2000, + 5000, + 10000, + 20000, + 50000, }); - private JCheckBox simRandomness = new JCheckBox(); - private JLabel gateUndefinedLabel = new JLabel(); - private JComboBox gateUndefined = new JComboBox(new Object[]{ - new ComboOption(Options.GATE_UNDEFINED_IGNORE), - new ComboOption(Options.GATE_UNDEFINED_ERROR) + private final JCheckBox simRandomness = new JCheckBox(); + private final JLabel gateUndefinedLabel = new JLabel(); + private final JComboBox gateUndefined = new JComboBox<>(new Object[]{ + new ComboOption(Options.GATE_UNDEFINED_IGNORE), + new ComboOption(Options.GATE_UNDEFINED_ERROR) }); public SimulateOptions(OptionsFrame window) { @@ -91,20 +91,20 @@ public void actionPerformed(ActionEvent event) { if (opt != null) { AttributeSet attrs = getOptions().getAttributeSet(); getProject().doAction(OptionsActions.setAttribute(attrs, - Options.SIMULATOR_LIMIT_ATTRIBUTE, opt)); + Options.SIMULATOR_LIMIT_ATTRIBUTE, opt)); } } else if (source == simRandomness) { AttributeSet attrs = getOptions().getAttributeSet(); Object val = simRandomness.isSelected() ? Options.SIMULATOR_RANDOM_DEFAULT - : Integer.valueOf(0); + : Integer.valueOf(0); getProject().doAction(OptionsActions.setAttribute(attrs, - Options.SIMULATOR_RANDOM_ATTRIBUTE, val)); + Options.SIMULATOR_RANDOM_ATTRIBUTE, val)); } else if (source == gateUndefined) { ComboOption opt = (ComboOption) gateUndefined.getSelectedItem(); if (opt != null) { AttributeSet attrs = getOptions().getAttributeSet(); getProject().doAction(OptionsActions.setAttribute(attrs, - Options.ATTR_GATE_UNDEFINED, opt.getValue())); + Options.ATTR_GATE_UNDEFINED, opt.getValue())); } } } @@ -124,9 +124,9 @@ public void attributeValueChanged(AttributeEvent e) { private void loadSimLimit(Integer val) { int value = val; - ComboBoxModel model = simLimit.getModel(); + ComboBoxModel model = simLimit.getModel(); for (int i = 0; i < model.getSize(); i++) { - Integer opt = (Integer) model.getElementAt(i); + Integer opt = model.getElementAt(i); if (opt == value) { simLimit.setSelectedItem(opt); } diff --git a/src/main/java/com/cburch/logisim/gui/opts/Strings.java b/src/main/java/com/cburch/logisim/gui/opts/Strings.java index f76ac13..d6279db 100644 --- a/src/main/java/com/cburch/logisim/gui/opts/Strings.java +++ b/src/main/java/com/cburch/logisim/gui/opts/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "opts"); + private static final LocaleManager source = new LocaleManager("logisim", "opts"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/gui/opts/ToolbarActions.java b/src/main/java/com/cburch/logisim/gui/opts/ToolbarActions.java index 13b0a86..fb9af37 100644 --- a/src/main/java/com/cburch/logisim/gui/opts/ToolbarActions.java +++ b/src/main/java/com/cburch/logisim/gui/opts/ToolbarActions.java @@ -21,13 +21,11 @@ public static Action removeTool(ToolbarData toolbar, int pos) { return new RemoveTool(toolbar, pos); } - public static Action moveTool(ToolbarData toolbar, - int src, int dest) { + public static Action moveTool(ToolbarData toolbar, int src, int dest) { return new MoveTool(toolbar, src, dest); } - public static Action addSeparator(ToolbarData toolbar, - int pos) { + public static Action addSeparator(ToolbarData toolbar, int pos) { return new AddSeparator(toolbar, pos); } @@ -126,7 +124,7 @@ public boolean shouldAppendTo(Action other) { if (other instanceof MoveTool) { MoveTool o = (MoveTool) other; return this.toolbar == o.toolbar - && o.dest == this.oldpos; + && o.dest == this.oldpos; } else { return false; } diff --git a/src/main/java/com/cburch/logisim/gui/opts/ToolbarList.java b/src/main/java/com/cburch/logisim/gui/opts/ToolbarList.java index 31945b0..1f31fc9 100644 --- a/src/main/java/com/cburch/logisim/gui/opts/ToolbarList.java +++ b/src/main/java/com/cburch/logisim/gui/opts/ToolbarList.java @@ -21,10 +21,10 @@ import javax.swing.JList; import javax.swing.ListSelectionModel; -class ToolbarList extends JList { +class ToolbarList extends JList { - private ToolbarData base; - private Model model; + private final ToolbarData base; + private final Model model; public ToolbarList(ToolbarData base) { this.base = base; @@ -45,7 +45,7 @@ public void localeChanged() { private static class ToolIcon implements Icon { - private Tool tool; + private final Tool tool; ToolIcon(Tool tool) { this.tool = tool; @@ -70,21 +70,21 @@ private static class ListRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, - int index, boolean isSelected, boolean cellHasFocus) { + int index, boolean isSelected, boolean cellHasFocus) { Component ret; Icon icon; if (value instanceof Tool) { Tool t = (Tool) value; ret = super.getListCellRendererComponent(list, t.getDisplayName(), - index, isSelected, cellHasFocus); + index, isSelected, cellHasFocus); icon = new ToolIcon(t); } else if (value == null) { ret = super.getListCellRendererComponent(list, "---", - index, isSelected, cellHasFocus); + index, isSelected, cellHasFocus); icon = null; } else { ret = super.getListCellRendererComponent(list, value.toString(), - index, isSelected, cellHasFocus); + index, isSelected, cellHasFocus); icon = null; } if (ret instanceof JLabel) { @@ -94,8 +94,8 @@ public Component getListCellRendererComponent(JList list, Object value, } } - private class Model extends AbstractListModel - implements ToolbarListener, AttributeListener, PropertyChangeListener { + private class Model extends AbstractListModel implements ToolbarListener, AttributeListener, + PropertyChangeListener { public int getSize() { return base.size(); diff --git a/src/main/java/com/cburch/logisim/gui/opts/ToolbarOptions.java b/src/main/java/com/cburch/logisim/gui/opts/ToolbarOptions.java index ca5d70e..aa11a9b 100644 --- a/src/main/java/com/cburch/logisim/gui/opts/ToolbarOptions.java +++ b/src/main/java/com/cburch/logisim/gui/opts/ToolbarOptions.java @@ -25,14 +25,14 @@ class ToolbarOptions extends OptionsPanel { - private Listener listener = new Listener(); - private ProjectExplorer explorer; - private JButton addTool; - private JButton addSeparator; - private JButton moveUp; - private JButton moveDown; - private JButton remove; - private ToolbarList list; + private final Listener listener = new Listener(); + private final ProjectExplorer explorer; + private final JButton addTool; + private final JButton addSeparator; + private final JButton moveUp; + private final JButton moveDown; + private final JButton remove; + private final ToolbarList list; public ToolbarOptions(OptionsFrame window) { super(window); @@ -67,11 +67,11 @@ public ToolbarOptions(OptionsFrame window) { GridBagConstraints gbc = new GridBagConstraints(); setLayout(gridbag); JScrollPane explorerPane = new JScrollPane(explorer, - ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); JScrollPane listPane = new JScrollPane(list, - ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0; gbc.weighty = 1.0; @@ -109,7 +109,7 @@ public void localeChanged() { } private class Listener - implements ProjectExplorerListener, ActionListener, ListSelectionListener { + implements ProjectExplorerListener, ActionListener, ListSelectionListener { public void selectionChanged(ProjectExplorerEvent event) { computeEnabled(); @@ -176,7 +176,7 @@ private void doMove(int delta) { ToolbarData data = getOptions().getToolbarData(); if (oldIndex >= 0 && newIndex >= 0 && newIndex < data.size()) { getProject().doAction(ToolbarActions.moveTool(data, - oldIndex, newIndex)); + oldIndex, newIndex)); list.setSelectedIndex(newIndex); } } diff --git a/src/main/java/com/cburch/logisim/gui/prefs/ExperimentalOptions.java b/src/main/java/com/cburch/logisim/gui/prefs/ExperimentalOptions.java index c3286a7..2a4f98b 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/ExperimentalOptions.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/ExperimentalOptions.java @@ -13,18 +13,18 @@ class ExperimentalOptions extends OptionsPanel { - private JLabel accelRestart = new JLabel(); - private PrefOptionList accel; + private final JLabel accelRestart = new JLabel(); + private final PrefOptionList accel; public ExperimentalOptions(PreferencesFrame window) { super(window); accel = new PrefOptionList(AppPreferences.GRAPHICS_ACCELERATION, - Strings.getter("accelLabel"), new PrefOption[]{ - new PrefOption(AppPreferences.ACCELERATION_DEFAULT, Strings.getter("accelDefault")), - new PrefOption(AppPreferences.ACCELERATION_NONE, Strings.getter("accelNone")), - new PrefOption(AppPreferences.ACCELERATION_OPENGL, Strings.getter("accelOpenGL")), - new PrefOption(AppPreferences.ACCELERATION_D3D, Strings.getter("accelD3D")), + Strings.getter("accelLabel"), new PrefOption[]{ + new PrefOption(AppPreferences.ACCELERATION_DEFAULT, Strings.getter("accelDefault")), + new PrefOption(AppPreferences.ACCELERATION_NONE, Strings.getter("accelNone")), + new PrefOption(AppPreferences.ACCELERATION_OPENGL, Strings.getter("accelOpenGL")), + new PrefOption(AppPreferences.ACCELERATION_D3D, Strings.getter("accelD3D")), }); JPanel accelPanel = new JPanel(new BorderLayout()); diff --git a/src/main/java/com/cburch/logisim/gui/prefs/IntlOptions.java b/src/main/java/com/cburch/logisim/gui/prefs/IntlOptions.java index 3038eb8..52cb760 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/IntlOptions.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/IntlOptions.java @@ -15,25 +15,25 @@ class IntlOptions extends OptionsPanel { - private JLabel localeLabel = new RestrictedLabel(); - private JComponent locale; - private PrefBoolean replAccents; - private PrefOptionList gateShape; + private final JLabel localeLabel = new RestrictedLabel(); + private final JComponent locale; + private final PrefBoolean replAccents; + private final PrefOptionList gateShape; public IntlOptions(PreferencesFrame window) { super(window); locale = Strings.createLocaleSelector(); replAccents = new PrefBoolean(AppPreferences.ACCENTS_REPLACE, - Strings.getter("intlReplaceAccents")); + Strings.getter("intlReplaceAccents")); gateShape = new PrefOptionList(AppPreferences.GATE_SHAPE, - Strings.getter("intlGateShape"), new PrefOption[]{ - new PrefOption(AppPreferences.SHAPE_SHAPED, - Strings.getter("shapeShaped")), - new PrefOption(AppPreferences.SHAPE_RECTANGULAR, - Strings.getter("shapeRectangular")), - new PrefOption(AppPreferences.SHAPE_DIN40700, - Strings.getter("shapeDIN40700"))}); + Strings.getter("intlGateShape"), new PrefOption[]{ + new PrefOption(AppPreferences.SHAPE_SHAPED, + Strings.getter("shapeShaped")), + new PrefOption(AppPreferences.SHAPE_RECTANGULAR, + Strings.getter("shapeRectangular")), + new PrefOption(AppPreferences.SHAPE_DIN40700, + Strings.getter("shapeDIN40700"))}); Box localePanel = new Box(BoxLayout.X_AXIS); localePanel.add(Box.createGlue()); diff --git a/src/main/java/com/cburch/logisim/gui/prefs/LayoutOptions.java b/src/main/java/com/cburch/logisim/gui/prefs/LayoutOptions.java index 222f761..c1857a6 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/LayoutOptions.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/LayoutOptions.java @@ -10,8 +10,8 @@ class LayoutOptions extends OptionsPanel { - private PrefBoolean[] checks; - private PrefOptionList afterAdd; + private final PrefBoolean[] checks; + private final PrefOptionList afterAdd; private PrefOptionList radix1; private PrefOptionList radix2; @@ -19,16 +19,16 @@ public LayoutOptions(PreferencesFrame window) { super(window); checks = new PrefBoolean[]{ - new PrefBoolean(AppPreferences.PRINTER_VIEW, - Strings.getter("layoutPrinterView")), - new PrefBoolean(AppPreferences.ATTRIBUTE_HALO, - Strings.getter("layoutAttributeHalo")), - new PrefBoolean(AppPreferences.COMPONENT_TIPS, - Strings.getter("layoutShowTips")), - new PrefBoolean(AppPreferences.MOVE_KEEP_CONNECT, - Strings.getter("layoutMoveKeepConnect")), - new PrefBoolean(AppPreferences.ADD_SHOW_GHOSTS, - Strings.getter("layoutAddShowGhosts")), + new PrefBoolean(AppPreferences.PRINTER_VIEW, + Strings.getter("layoutPrinterView")), + new PrefBoolean(AppPreferences.ATTRIBUTE_HALO, + Strings.getter("layoutAttributeHalo")), + new PrefBoolean(AppPreferences.COMPONENT_TIPS, + Strings.getter("layoutShowTips")), + new PrefBoolean(AppPreferences.MOVE_KEEP_CONNECT, + Strings.getter("layoutMoveKeepConnect")), + new PrefBoolean(AppPreferences.ADD_SHOW_GHOSTS, + Strings.getter("layoutAddShowGhosts")), }; for (int i = 0; i < 2; i++) { @@ -39,19 +39,19 @@ public LayoutOptions(PreferencesFrame window) { } if (i == 0) { radix1 = new PrefOptionList(AppPreferences.POKE_WIRE_RADIX1, - Strings.getter("layoutRadix1"), items); + Strings.getter("layoutRadix1"), items); } else { radix2 = new PrefOptionList(AppPreferences.POKE_WIRE_RADIX2, - Strings.getter("layoutRadix2"), items); + Strings.getter("layoutRadix2"), items); } } afterAdd = new PrefOptionList(AppPreferences.ADD_AFTER, - Strings.getter("layoutAddAfter"), - new PrefOption[]{ - new PrefOption(AppPreferences.ADD_AFTER_UNCHANGED, - Strings.getter("layoutAddAfterUnchanged")), - new PrefOption(AppPreferences.ADD_AFTER_EDIT, - Strings.getter("layoutAddAfterEdit"))}); + Strings.getter("layoutAddAfter"), + new PrefOption[]{ + new PrefOption(AppPreferences.ADD_AFTER_UNCHANGED, + Strings.getter("layoutAddAfterUnchanged")), + new PrefOption(AppPreferences.ADD_AFTER_EDIT, + Strings.getter("layoutAddAfterEdit"))}); JPanel panel = new JPanel(new TableLayout(2)); panel.add(afterAdd.getJLabel()); diff --git a/src/main/java/com/cburch/logisim/gui/prefs/OptionsPanel.java b/src/main/java/com/cburch/logisim/gui/prefs/OptionsPanel.java index 2364296..6562298 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/OptionsPanel.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/OptionsPanel.java @@ -8,7 +8,7 @@ abstract class OptionsPanel extends JPanel { - private PreferencesFrame optionsFrame; + private final PreferencesFrame optionsFrame; public OptionsPanel(PreferencesFrame frame) { super(); diff --git a/src/main/java/com/cburch/logisim/gui/prefs/PrefBoolean.java b/src/main/java/com/cburch/logisim/gui/prefs/PrefBoolean.java index bbf815d..8cdebc1 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/PrefBoolean.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/PrefBoolean.java @@ -11,11 +11,10 @@ import java.beans.PropertyChangeListener; import javax.swing.JCheckBox; -class PrefBoolean extends JCheckBox - implements ActionListener, PropertyChangeListener { +class PrefBoolean extends JCheckBox implements ActionListener, PropertyChangeListener { - private PrefMonitor pref; - private StringGetter title; + private final PrefMonitor pref; + private final StringGetter title; PrefBoolean(PrefMonitor pref, StringGetter title) { super(title.get()); diff --git a/src/main/java/com/cburch/logisim/gui/prefs/PrefOption.java b/src/main/java/com/cburch/logisim/gui/prefs/PrefOption.java index ba0f48c..1221931 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/PrefOption.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/PrefOption.java @@ -8,15 +8,15 @@ class PrefOption { - private Object value; - private StringGetter getter; + private final Object value; + private final StringGetter getter; PrefOption(String value, StringGetter getter) { this.value = value; this.getter = getter; } - static void setSelected(JComboBox combo, Object value) { + static void setSelected(JComboBox combo, Object value) { for (int i = combo.getItemCount() - 1; i >= 0; i--) { PrefOption opt = (PrefOption) combo.getItemAt(i); if (opt.getValue().equals(value)) { diff --git a/src/main/java/com/cburch/logisim/gui/prefs/PrefOptionList.java b/src/main/java/com/cburch/logisim/gui/prefs/PrefOptionList.java index 87188ed..f412de9 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/PrefOptionList.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/PrefOptionList.java @@ -15,19 +15,18 @@ class PrefOptionList implements ActionListener, PropertyChangeListener { - private PrefMonitor pref; - private StringGetter labelStr; - - private JLabel label; - private JComboBox combo; + private final JComboBox combo; + private final PrefMonitor pref; + private final StringGetter labelStr; + private final JLabel label; public PrefOptionList(PrefMonitor pref, StringGetter labelStr, - PrefOption[] options) { + PrefOption[] options) { this.pref = pref; this.labelStr = labelStr; label = new JLabel(labelStr.get() + " "); - combo = new JComboBox(); + combo = new JComboBox<>(); for (PrefOption opt : options) { combo.addItem(opt); } @@ -48,7 +47,7 @@ JLabel getJLabel() { return label; } - JComboBox getJComboBox() { + JComboBox getJComboBox() { return combo; } @@ -58,6 +57,7 @@ void localeChanged() { public void actionPerformed(ActionEvent e) { PrefOption x = (PrefOption) combo.getSelectedItem(); + assert x != null; pref.set((String) x.getValue()); } @@ -69,7 +69,7 @@ public void propertyChange(PropertyChangeEvent event) { private void selectOption(Object value) { for (int i = combo.getItemCount() - 1; i >= 0; i--) { - PrefOption opt = (PrefOption) combo.getItemAt(i); + PrefOption opt = combo.getItemAt(i); if (opt.getValue().equals(value)) { combo.setSelectedItem(opt); return; diff --git a/src/main/java/com/cburch/logisim/gui/prefs/PreferencesFrame.java b/src/main/java/com/cburch/logisim/gui/prefs/PreferencesFrame.java index 248344e..70566a3 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/PreferencesFrame.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/PreferencesFrame.java @@ -22,21 +22,21 @@ public class PreferencesFrame extends LFrame { private static WindowMenuManager MENU_MANAGER = null; - private MyListener myListener = new MyListener(); - private OptionsPanel[] panels; - private JTabbedPane tabbedPane; - private JButton close = new JButton(); + private final MyListener myListener = new MyListener(); + private final OptionsPanel[] panels; + private final JTabbedPane tabbedPane; + private final JButton close = new JButton(); private PreferencesFrame() { setDefaultCloseOperation(HIDE_ON_CLOSE); setJMenuBar(new LogisimMenuBar(this, null)); panels = new OptionsPanel[]{ - new TemplateOptions(this), - new IntlOptions(this), - new WindowOptions(this), - new LayoutOptions(this), - new ExperimentalOptions(this), + new TemplateOptions(this), + new IntlOptions(this), + new WindowOptions(this), + new LayoutOptions(this), + new ExperimentalOptions(this), }; tabbedPane = new JTabbedPane(); int intlIndex = -1; @@ -76,7 +76,7 @@ public static void showPreferences() { } private static class WindowMenuManager extends WindowMenuItemManager - implements LocaleListener { + implements LocaleListener { private PreferencesFrame window = null; @@ -102,13 +102,13 @@ public void localeChanged() { } private class MyListener - implements ActionListener, LocaleListener { + implements ActionListener, LocaleListener { public void actionPerformed(ActionEvent event) { Object src = event.getSource(); if (src == close) { WindowEvent e = new WindowEvent(PreferencesFrame.this, - WindowEvent.WINDOW_CLOSING); + WindowEvent.WINDOW_CLOSING); PreferencesFrame.this.processWindowEvent(e); } } diff --git a/src/main/java/com/cburch/logisim/gui/prefs/Strings.java b/src/main/java/com/cburch/logisim/gui/prefs/Strings.java index 331b6ee..0e2426c 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/Strings.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/Strings.java @@ -10,8 +10,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "prefs"); + private static final LocaleManager source = new LocaleManager("logisim", "prefs"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/gui/prefs/TemplateOptions.java b/src/main/java/com/cburch/logisim/gui/prefs/TemplateOptions.java index f0fbf31..d7143f8 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/TemplateOptions.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/TemplateOptions.java @@ -31,12 +31,12 @@ class TemplateOptions extends OptionsPanel { - private MyListener myListener = new MyListener(); - private JRadioButton plain = new JRadioButton(); - private JRadioButton empty = new JRadioButton(); - private JRadioButton custom = new JRadioButton(); - private JTextField templateField = new JTextField(40); - private JButton templateButton = new JButton(); + private final MyListener myListener = new MyListener(); + private final JRadioButton plain = new JRadioButton(); + private final JRadioButton empty = new JRadioButton(); + private final JRadioButton custom = new JRadioButton(); + private final JTextField templateField = new JTextField(40); + private final JButton templateButton = new JButton(); public TemplateOptions(PreferencesFrame window) { super(window); @@ -142,9 +142,9 @@ public void actionPerformed(ActionEvent event) { } catch (LoaderException ex) { } catch (IOException ex) { JOptionPane.showMessageDialog(getPreferencesFrame(), - StringUtil.format(Strings.get("templateErrorMessage"), ex.toString()), - Strings.get("templateErrorTitle"), - JOptionPane.ERROR_MESSAGE); + StringUtil.format(Strings.get("templateErrorMessage"), ex.toString()), + Strings.get("templateErrorTitle"), + JOptionPane.ERROR_MESSAGE); } finally { try { if (reader != null) { diff --git a/src/main/java/com/cburch/logisim/gui/prefs/WindowOptions.java b/src/main/java/com/cburch/logisim/gui/prefs/WindowOptions.java index 367cff3..a63bc72 100644 --- a/src/main/java/com/cburch/logisim/gui/prefs/WindowOptions.java +++ b/src/main/java/com/cburch/logisim/gui/prefs/WindowOptions.java @@ -10,32 +10,32 @@ class WindowOptions extends OptionsPanel { - private PrefBoolean[] checks; - private PrefOptionList toolbarPlacement; + private final PrefBoolean[] checks; + private final PrefOptionList toolbarPlacement; public WindowOptions(PreferencesFrame window) { super(window); checks = new PrefBoolean[]{ - new PrefBoolean(AppPreferences.SHOW_TICK_RATE, - Strings.getter("windowTickRate")), + new PrefBoolean(AppPreferences.SHOW_TICK_RATE, + Strings.getter("windowTickRate")), }; toolbarPlacement = new PrefOptionList(AppPreferences.TOOLBAR_PLACEMENT, - Strings.getter("windowToolbarLocation"), - new PrefOption[]{ - new PrefOption(Direction.NORTH.toString(), - Direction.NORTH.getDisplayGetter()), - new PrefOption(Direction.SOUTH.toString(), - Direction.SOUTH.getDisplayGetter()), - new PrefOption(Direction.EAST.toString(), - Direction.EAST.getDisplayGetter()), - new PrefOption(Direction.WEST.toString(), - Direction.WEST.getDisplayGetter()), - new PrefOption(AppPreferences.TOOLBAR_DOWN_MIDDLE, - Strings.getter("windowToolbarDownMiddle")), - new PrefOption(AppPreferences.TOOLBAR_HIDDEN, - Strings.getter("windowToolbarHidden"))}); + Strings.getter("windowToolbarLocation"), + new PrefOption[]{ + new PrefOption(Direction.NORTH.toString(), + Direction.NORTH.getDisplayGetter()), + new PrefOption(Direction.SOUTH.toString(), + Direction.SOUTH.getDisplayGetter()), + new PrefOption(Direction.EAST.toString(), + Direction.EAST.getDisplayGetter()), + new PrefOption(Direction.WEST.toString(), + Direction.WEST.getDisplayGetter()), + new PrefOption(AppPreferences.TOOLBAR_DOWN_MIDDLE, + Strings.getter("windowToolbarDownMiddle")), + new PrefOption(AppPreferences.TOOLBAR_HIDDEN, + Strings.getter("windowToolbarHidden"))}); JPanel panel = new JPanel(new TableLayout(2)); panel.add(toolbarPlacement.getJLabel()); @@ -60,8 +60,8 @@ public String getHelpText() { @Override public void localeChanged() { - for (int i = 0; i < checks.length; i++) { - checks[i].localeChanged(); + for (PrefBoolean check : checks) { + check.localeChanged(); } toolbarPlacement.localeChanged(); } diff --git a/src/main/java/com/cburch/logisim/gui/start/About.java b/src/main/java/com/cburch/logisim/gui/start/About.java index 12dc6b7..3789d26 100644 --- a/src/main/java/com/cburch/logisim/gui/start/About.java +++ b/src/main/java/com/cburch/logisim/gui/start/About.java @@ -45,7 +45,7 @@ public static void showAboutDialog(JFrame owner) { private static class PanelThread extends Thread { - private MyPanel panel; + private final MyPanel panel; private boolean running = true; PanelThread(MyPanel panel) { @@ -64,7 +64,7 @@ public void run() { panel.repaint(); try { Thread.sleep(20); - } catch (InterruptedException ex) { + } catch (InterruptedException ignored) { } } } @@ -81,7 +81,7 @@ private static class MyPanel extends JPanel implements AncestorListener { private Value upper = Value.FALSE; private Value lower = Value.TRUE; - private AboutCredits credits; + private final AboutCredits credits; private PanelThread thread = null; public MyPanel() { @@ -264,4 +264,4 @@ public void ancestorRemoved(AncestorEvent arg0) { public void ancestorMoved(AncestorEvent arg0) { } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/gui/start/AboutCredits.java b/src/main/java/com/cburch/logisim/gui/start/AboutCredits.java index 97058d6..d2a8cba 100644 --- a/src/main/java/com/cburch/logisim/gui/start/AboutCredits.java +++ b/src/main/java/com/cburch/logisim/gui/start/AboutCredits.java @@ -34,13 +34,13 @@ class AboutCredits extends JComponent { */ private static final String HENDRIX_PATH = "logisim/hendrix.png"; private static final int HENDRIX_WIDTH = 50; - private Color[] colorBase; - private Paint[] paintSteady; - private Font[] font; + private final Color[] colorBase; + private final Paint[] paintSteady; + private final Font[] font; + private final float fadeStop; + private final ArrayList lines; + private final int initialLines; // number of lines to show in initial freeze private int scroll; - private float fadeStop; - private ArrayList lines; - private int initialLines; // number of lines to show in initial freeze private int initialHeight; // computed in code based on above private int linesHeight; // computed in code based on above @@ -55,20 +55,20 @@ public AboutCredits() { fadeStop = (float) (About.IMAGE_HEIGHT / 4.0); colorBase = new Color[]{ - new Color(143, 0, 0), - new Color(48, 0, 96), - new Color(48, 0, 96), + new Color(143, 0, 0), + new Color(48, 0, 96), + new Color(48, 0, 96), }; font = new Font[]{ - new Font("Sans Serif", Font.ITALIC, 20), - new Font("Sans Serif", Font.BOLD, 24), - new Font("Sans Serif", Font.BOLD, 18), + new Font("Sans Serif", Font.ITALIC, 20), + new Font("Sans Serif", Font.BOLD, 24), + new Font("Sans Serif", Font.BOLD, 18), }; paintSteady = new Paint[colorBase.length]; for (int i = 0; i < colorBase.length; i++) { Color hue = colorBase[i]; paintSteady[i] = new GradientPaint(0.0f, 0.0f, derive(hue, 0), - 0.0f, fadeStop, hue); + 0.0f, fadeStop, hue); } URL url = AboutCredits.class.getClassLoader().getResource(HENDRIX_PATH); @@ -86,7 +86,7 @@ public AboutCredits() { linesHeight = 0; // computed in paintComponent lines.add(new CreditsLine(1, "www.cburch.com/logisim/")); lines.add(new CreditsLine(0, Strings.get("creditsRoleLead"), - hendrixLogo, HENDRIX_WIDTH)); + hendrixLogo, HENDRIX_WIDTH)); lines.add(new CreditsLine(1, "Carl Burch")); lines.add(new CreditsLine(2, "Hendrix College")); initialLines = lines.size(); @@ -96,27 +96,27 @@ public AboutCredits() { lines.add(new CreditsLine(0, Strings.get("creditsRoleGreek"))); lines.add(new CreditsLine(1, "Thanos Kakarountas")); lines.add( - new CreditsLine(2, "\u03A4.\u0395.\u0399 \u0399\u03BF\u03BD\u03AF\u03C9\u03BD \u039D\u03AE\u03C3\u03C9\u03BD")); + new CreditsLine(2, "\u03A4.\u0395.\u0399 \u0399\u03BF\u03BD\u03AF\u03C9\u03BD \u039D\u03AE\u03C3\u03C9\u03BD")); lines.add(new CreditsLine(0, Strings.get("creditsRolePortuguese"))); lines.add(new CreditsLine(1, "Theldo Cruz Franqueira")); lines.add(new CreditsLine(2, "PUC Minas")); lines.add(new CreditsLine(0, Strings.get("creditsRoleRussian"))); lines.add(new CreditsLine(1, "Ilia Lilov")); lines.add(new CreditsLine(2, - "\u041C\u043E\u0441\u043A\u043E\u0432\u0441\u043A\u0438\u0439 \u0433\u043E\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043D\u043D\u044B\u0439")); + "\u041C\u043E\u0441\u043A\u043E\u0432\u0441\u043A\u0438\u0439 \u0433\u043E\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043D\u043D\u044B\u0439")); lines.add(new CreditsLine(2, - "\u0443\u043D\u0438\u0432\u0435\u0440\u0441\u0438\u0442\u0435\u0442 \u043F\u0435\u0447\u0430\u0442\u0438")); + "\u0443\u043D\u0438\u0432\u0435\u0440\u0441\u0438\u0442\u0435\u0442 \u043F\u0435\u0447\u0430\u0442\u0438")); lines.add(new CreditsLine(0, Strings.get("creditsRoleTesting"))); lines.add(new CreditsLine(1, "Ilia Lilov")); lines.add(new CreditsLine(2, - "\u041C\u043E\u0441\u043A\u043E\u0432\u0441\u043A\u0438\u0439 \u0433\u043E\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043D\u043D\u044B\u0439")); + "\u041C\u043E\u0441\u043A\u043E\u0432\u0441\u043A\u0438\u0439 \u0433\u043E\u0441\u0443\u0434\u0430\u0440\u0441\u0442\u0432\u0435\u043D\u043D\u044B\u0439")); lines.add(new CreditsLine(2, - "\u0443\u043D\u0438\u0432\u0435\u0440\u0441\u0438\u0442\u0435\u0442 \u043F\u0435\u0447\u0430\u0442\u0438")); + "\u0443\u043D\u0438\u0432\u0435\u0440\u0441\u0438\u0442\u0435\u0442 \u043F\u0435\u0447\u0430\u0442\u0438")); /* If you fork Logisim, feel free to change the above lines, but * please do not change these last four lines! */ lines.add(new CreditsLine(0, Strings.get("creditsRoleOriginal"), - hendrixLogo, HENDRIX_WIDTH)); + hendrixLogo, HENDRIX_WIDTH)); lines.add(new CreditsLine(1, "Carl Burch")); lines.add(new CreditsLine(2, "Hendrix College")); lines.add(new CreditsLine(1, "www.cburch.com/logisim/")); @@ -174,7 +174,7 @@ protected void paintComponent(Graphics g) { for (int i = 0; i < paint.length; i++) { Color hue = colorBase[i]; paint[i] = new GradientPaint(0.0f, 0.0f, derive(hue, a), - 0.0f, fadeStop, hue); + 0.0f, fadeStop, hue); } } yPos = initY; @@ -224,11 +224,11 @@ protected void paintComponent(Graphics g) { private static class CreditsLine { + private final int type; + private final String text; + private final Image img; + private final int imgWidth; private int y; - private int type; - private String text; - private Image img; - private int imgWidth; public CreditsLine(int type, String text) { this(type, text, null, 0); @@ -242,4 +242,4 @@ public CreditsLine(int type, String text, Image img, int imgWidth) { this.imgWidth = imgWidth; } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/gui/start/SplashScreen.java b/src/main/java/com/cburch/logisim/gui/start/SplashScreen.java index 79f2ee1..b171468 100644 --- a/src/main/java/com/cburch/logisim/gui/start/SplashScreen.java +++ b/src/main/java/com/cburch/logisim/gui/start/SplashScreen.java @@ -31,16 +31,16 @@ public class SplashScreen extends JWindow implements ActionListener { private static final int PROGRESS_MAX = 3568; private static final boolean PRINT_TIMES = false; Marker[] markers = new Marker[]{ - new Marker(377, Strings.get("progressLibraries")), - new Marker(990, Strings.get("progressTemplateCreate")), - new Marker(1002, Strings.get("progressTemplateOpen")), - new Marker(1002, Strings.get("progressTemplateLoad")), - new Marker(1470, Strings.get("progressTemplateClose")), - new Marker(1478, Strings.get("progressGuiInitialize")), - new Marker(2114, Strings.get("progressFileCreate")), - new Marker(2114, Strings.get("progressFileLoad")), - new Marker(2383, Strings.get("progressProjectCreate")), - new Marker(2519, Strings.get("progressFrameCreate")), + new Marker(377, Strings.get("progressLibraries")), + new Marker(990, Strings.get("progressTemplateCreate")), + new Marker(1002, Strings.get("progressTemplateOpen")), + new Marker(1002, Strings.get("progressTemplateLoad")), + new Marker(1470, Strings.get("progressTemplateClose")), + new Marker(1478, Strings.get("progressGuiInitialize")), + new Marker(2114, Strings.get("progressFileCreate")), + new Marker(2114, Strings.get("progressFileLoad")), + new Marker(2383, Strings.get("progressProjectCreate")), + new Marker(2519, Strings.get("progressFrameCreate")), }; boolean inClose = false; // for avoiding mutual recursion JProgressBar progress = new JProgressBar(0, PROGRESS_MAX); @@ -66,10 +66,10 @@ public SplashScreen() { contents.add(buttonPanel, BorderLayout.SOUTH); contents.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2)); - Color bg = imagePanel.getBackground(); - contents.setBackground(bg); - buttonPanel.setBackground(bg); - setBackground(bg); + Color backgroundColor = imagePanel.getBackground(); + contents.setBackground(backgroundColor); + buttonPanel.setBackground(backgroundColor); + setBackground(backgroundColor); setContentPane(contents); } @@ -84,7 +84,7 @@ public void run() { }); if (PRINT_TIMES) { System.err.println((System.currentTimeMillis() - startTime) //OK - + " " + marker.message); + + " " + marker.message); } } else { if (PRINT_TIMES) { @@ -113,8 +113,7 @@ public void close() { setVisible(false); inClose = false; if (PRINT_TIMES) { - System.err.println((System.currentTimeMillis() - startTime) //OK - + " closed"); + System.err.println((System.currentTimeMillis() - startTime) + " closed"); //OK } markers = null; } diff --git a/src/main/java/com/cburch/logisim/gui/start/Startup.java b/src/main/java/com/cburch/logisim/gui/start/Startup.java index 18357b8..bf9bbfc 100644 --- a/src/main/java/com/cburch/logisim/gui/start/Startup.java +++ b/src/main/java/com/cburch/logisim/gui/start/Startup.java @@ -7,6 +7,7 @@ import static com.adlerd.logger.Logger.infoln; import static com.adlerd.logger.Logger.outputln; +import com.adlerd.logger.Logger; import com.cburch.logisim.Main; import com.cburch.logisim.file.LoadFailedException; import com.cburch.logisim.file.Loader; @@ -33,15 +34,15 @@ public class Startup { private static Startup startupTemp = null; // based on command line - private ArrayList filesToOpen = new ArrayList<>(); - private boolean isTty; + private final ArrayList filesToOpen = new ArrayList<>(); + private final boolean isTty; + private final ArrayList filesToPrint = new ArrayList<>(); + private final HashMap substitutions = new HashMap<>(); private boolean templateEmpty = false; private boolean templatePlain = false; private boolean showSplash; - private ArrayList filesToPrint = new ArrayList<>(); private File loadFile; private boolean initialized = false; - private HashMap substitutions = new HashMap<>(); private int ttyFormat = 0; // from other sources private SplashScreen monitor = null; @@ -141,7 +142,8 @@ public static Startup parseArgs(String[] args) { switch (os) { case "Mac": - theme = "javax.swing.plaf.nimbus.NimbusLookAndFeel"; +// theme = "javax.swing.plaf.nimbus.NimbusLookAndFeel"; + theme = UIManager.getCrossPlatformLookAndFeelClassName(); break; case "Linux": theme = UIManager.getCrossPlatformLookAndFeelClassName(); @@ -292,10 +294,10 @@ public static Startup parseArgs(String[] args) { startup.templateFile = new File(args[i]); if (!startup.templateFile.exists()) { errorln(StringUtil.format( //OK - Strings.get("templateMissingError"), args[i])); + Strings.get("templateMissingError"), args[i])); } else if (!startup.templateFile.canRead()) { errorln(StringUtil.format( //OK - Strings.get("templateCannotReadError"), args[i])); + Strings.get("templateCannotReadError"), args[i])); } } else if (arg.equals("-nosplash")) { startup.showSplash = false; @@ -409,11 +411,10 @@ public void run() { } Loader templateLoader = new Loader(monitor); int count = templateLoader.getBuiltin().getLibrary("Base").getTools().size() - + templateLoader.getBuiltin().getLibrary("Gates").getTools().size(); + + templateLoader.getBuiltin().getLibrary("Gates").getTools().size(); if (count < 0) { // this will never happen, but the optimizer doesn't know that... - errorln("FATAL ERROR - no components"); //OK - System.exit(-1); + Logger.errorln("FATAL ERROR - no components", true, -1); //OK } // load in template @@ -469,7 +470,7 @@ public void run() { } private void loadTemplate(Loader loader, File templateFile, - boolean templateEmpty) { + boolean templateEmpty) { if (showSplash) { monitor.setProgress(SplashScreen.TEMPLATE_OPEN); } diff --git a/src/main/java/com/cburch/logisim/gui/start/Strings.java b/src/main/java/com/cburch/logisim/gui/start/Strings.java index 221d000..91aa5a6 100644 --- a/src/main/java/com/cburch/logisim/gui/start/Strings.java +++ b/src/main/java/com/cburch/logisim/gui/start/Strings.java @@ -10,8 +10,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "start"); + private static final LocaleManager source = new LocaleManager("logisim", "start"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/gui/start/TtyInterface.java b/src/main/java/com/cburch/logisim/gui/start/TtyInterface.java index 536f90a..29bf055 100644 --- a/src/main/java/com/cburch/logisim/gui/start/TtyInterface.java +++ b/src/main/java/com/cburch/logisim/gui/start/TtyInterface.java @@ -100,7 +100,7 @@ public static void run(Startup args) { System.exit(-1); } } catch (IOException e) { - System.err.println(Strings.get("loadIoError") + ": " + e.toString()); //OK + System.err.println(Strings.get("loadIoError") + ": " + e); //OK System.exit(-1); } } @@ -119,26 +119,25 @@ private static void displayStatistics(LogisimFile file) { maxName = nameLength; } } - String fmt = "%" + countDigits(total.getUniqueCount()) + "d\t" - + "%" + countDigits(total.getRecursiveCount()) + "d\t"; + String fmt = "%" + countDigits(total.getUniqueCount()) + "d\t%" + countDigits(total.getRecursiveCount()) + "d\t"; String fmtNormal = fmt + "%-" + maxName + "s\t%s\n"; for (FileStatistics.Count count : stats.getCounts()) { Library lib = count.getLibrary(); String libName = lib == null ? "-" : lib.getDisplayName(); System.out.printf(fmtNormal, //OK - count.getUniqueCount(), - count.getRecursiveCount(), - count.getFactory().getDisplayName(), libName); + count.getUniqueCount(), + count.getRecursiveCount(), + count.getFactory().getDisplayName(), libName); } FileStatistics.Count totalWithout = stats.getTotalWithoutSubcircuits(); System.out.printf(fmt + "%s\n", //OK - totalWithout.getUniqueCount(), - totalWithout.getRecursiveCount(), - Strings.get("statsTotalWithout")); + totalWithout.getUniqueCount(), + totalWithout.getRecursiveCount(), + Strings.get("statsTotalWithout")); System.out.printf(fmt + "%s\n", //OK - total.getUniqueCount(), - total.getRecursiveCount(), - Strings.get("statsTotalWith")); + total.getUniqueCount(), + total.getRecursiveCount(), + Strings.get("statsTotalWith")); } private static int countDigits(int num) { @@ -152,7 +151,7 @@ private static int countDigits(int num) { } private static boolean loadRam(CircuitState circState, File loadFile) - throws IOException { + throws IOException { if (loadFile == null) { return false; } @@ -173,30 +172,28 @@ private static boolean loadRam(CircuitState circState, File loadFile) return found; } - private static boolean prepareForTty(CircuitState circState, - ArrayList keybStates) { + private static boolean prepareForTty(CircuitState circuitState, ArrayList keyboardStates) { boolean found = false; - for (Component comp : circState.getCircuit().getNonWires()) { + for (Component comp : circuitState.getCircuit().getNonWires()) { Object factory = comp.getFactory(); if (factory instanceof Tty) { Tty ttyFactory = (Tty) factory; - InstanceState ttyState = circState.getInstanceState(comp); + InstanceState ttyState = circuitState.getInstanceState(comp); ttyFactory.sendToStdout(ttyState); found = true; } else if (factory instanceof Keyboard) { - keybStates.add(circState.getInstanceState(comp)); + keyboardStates.add(circuitState.getInstanceState(comp)); found = true; } } - for (CircuitState sub : circState.getSubstates()) { - found |= prepareForTty(sub, keybStates); + for (CircuitState sub : circuitState.getSubstates()) { + found |= prepareForTty(sub, keyboardStates); } return found; } - private static int runSimulation(CircuitState circState, - ArrayList outputPins, Instance haltPin, int format) { + private static int runSimulation(CircuitState circuitState, ArrayList outputPins, Instance haltPin, int format) { boolean showTable = (format & FORMAT_TABLE) != 0; boolean showSpeed = (format & FORMAT_SPEED) != 0; boolean showTty = (format & FORMAT_TTY) != 0; @@ -206,7 +203,7 @@ private static int runSimulation(CircuitState circState, StdinThread stdinThread = null; if (showTty) { keyboardStates = new ArrayList<>(); - boolean ttyFound = prepareForTty(circState, keyboardStates); + boolean ttyFound = prepareForTty(circuitState, keyboardStates); if (!ttyFound) { System.err.println(Strings.get("ttyNoTtyError")); //OK System.exit(-1); @@ -224,11 +221,11 @@ private static int runSimulation(CircuitState circState, long start = System.currentTimeMillis(); boolean halted = false; ArrayList prevOutputs = null; - Propagator prop = circState.getPropagator(); + Propagator prop = circuitState.getPropagator(); while (true) { ArrayList curOutputs = new ArrayList<>(); for (Instance pin : outputPins) { - InstanceState pinState = circState.getInstanceState(pin); + InstanceState pinState = circuitState.getInstanceState(pin); Value val = Pin.FACTORY.getValue(pinState); if (pin == haltPin) { halted |= val.equals(Value.TRUE); @@ -279,7 +276,7 @@ private static int runSimulation(CircuitState circState, } private static void displayTableRow(ArrayList prevOutputs, - ArrayList curOutputs) { + ArrayList curOutputs) { boolean shouldPrint = false; if (prevOutputs == null) { shouldPrint = true; @@ -320,8 +317,7 @@ private static void displaySpeed(long tickCount, long elapse) { } hertz = (int) (hertz / precision) * precision; String hertzStr = hertz == (int) hertz ? "" + (int) hertz : "" + hertz; - System.out.println(StringUtil.format(Strings.get("ttySpeedMsg"), //OK - hertzStr, "" + tickCount, "" + elapse)); + System.out.println(StringUtil.format(Strings.get("ttySpeedMsg"), hertzStr, "" + tickCount, "" + elapse)); //OK } // It's possible to avoid using the separate thread using System.in.available(), @@ -329,7 +325,7 @@ private static void displaySpeed(long tickCount, long elapse) { // is not interactively echoed until System.in.read() is invoked. private static class StdinThread extends Thread { - private LinkedList queue; // of char[] + private final LinkedList queue; // of char[] public StdinThread() { queue = new LinkedList<>(); @@ -360,6 +356,8 @@ public void run() { } } } catch (IOException e) { + System.err.println("ERROR: TtyInterface.class"); + e.printStackTrace(); } } } diff --git a/src/main/java/com/cburch/logisim/instance/Instance.java b/src/main/java/com/cburch/logisim/instance/Instance.java index 9de9e05..433535d 100644 --- a/src/main/java/com/cburch/logisim/instance/Instance.java +++ b/src/main/java/com/cburch/logisim/instance/Instance.java @@ -14,10 +14,10 @@ public class Instance { - private InstanceComponent comp; + private final InstanceComponent component; - Instance(InstanceComponent comp) { - this.comp = comp; + Instance(InstanceComponent component) { + this.component = component; } public static Instance getInstanceFor(Component comp) { @@ -29,71 +29,70 @@ public static Instance getInstanceFor(Component comp) { } public static Component getComponentFor(Instance instance) { - return instance.comp; + return instance.component; } InstanceComponent getComponent() { - return comp; + return component; } public InstanceFactory getFactory() { - return (InstanceFactory) comp.getFactory(); + return (InstanceFactory) component.getFactory(); } public Location getLocation() { - return comp.getLocation(); + return component.getLocation(); } public Bounds getBounds() { - return comp.getBounds(); + return component.getBounds(); } public void setAttributeReadOnly(Attribute attr, boolean value) { - comp.getAttributeSet().setReadOnly(attr, value); + component.getAttributeSet().setReadOnly(attr, value); } public E getAttributeValue(Attribute attr) { - return comp.getAttributeSet().getValue(attr); + return component.getAttributeSet().getValue(attr); } public void addAttributeListener() { - comp.addAttributeListener(this); + component.addAttributeListener(this); } public AttributeSet getAttributeSet() { - return comp.getAttributeSet(); + return component.getAttributeSet(); } public List getPorts() { - return comp.getPorts(); + return component.getPorts(); } public void setPorts(Port[] ports) { - comp.setPorts(ports); + component.setPorts(ports); } public Location getPortLocation(int index) { - return comp.getEnd(index).getLocation(); + return component.getEnd(index).getLocation(); } public void recomputeBounds() { - comp.recomputeBounds(); + component.recomputeBounds(); } - public void setTextField(Attribute labelAttr, Attribute fontAttr, - int x, int y, int halign, int valign) { - comp.setTextField(labelAttr, fontAttr, x, y, halign, valign); + public void setTextField(Attribute labelAttr, Attribute fontAttr, int x, int y, int halign, int valign) { + component.setTextField(labelAttr, fontAttr, x, y, halign, valign); } public InstanceData getData(CircuitState state) { - return (InstanceData) state.getData(comp); + return (InstanceData) state.getData(component); } public void setData(CircuitState state, InstanceData data) { - state.setData(comp, data); + state.setData(component, data); } public void fireInvalidated() { - comp.fireInvalidated(); + component.fireInvalidated(); } } diff --git a/src/main/java/com/cburch/logisim/instance/InstanceComponent.java b/src/main/java/com/cburch/logisim/instance/InstanceComponent.java index d26de9d..fd5cb88 100644 --- a/src/main/java/com/cburch/logisim/instance/InstanceComponent.java +++ b/src/main/java/com/cburch/logisim/instance/InstanceComponent.java @@ -32,27 +32,27 @@ class InstanceComponent implements Component, AttributeListener, ToolTipMaker { + private final InstanceFactory factory; + private final Instance instance; + private final Location location; + private final AttributeSet attrs; private EventSourceWeakSupport listeners; - private InstanceFactory factory; - private Instance instance; - private Location loc; private Bounds bounds; private List portList; private EndData[] endArray; private List endList; private boolean hasToolTips; private HashSet> widthAttrs; - private AttributeSet attrs; private boolean attrListenRequested; private InstanceTextField textField; - InstanceComponent(InstanceFactory factory, Location loc, - AttributeSet attrs) { + InstanceComponent(InstanceFactory factory, Location location, + AttributeSet attrs) { this.listeners = null; this.factory = factory; this.instance = new Instance(this); - this.loc = loc; - this.bounds = factory.getOffsetBounds(attrs).translate(loc.getX(), loc.getY()); + this.location = location; + this.bounds = factory.getOffsetBounds(attrs).translate(location.getX(), location.getY()); this.portList = factory.getPorts(); this.endArray = null; this.hasToolTips = false; @@ -83,7 +83,7 @@ private void computeEnds() { for (int i = 0; pit.hasNext() || i < esOldLength; i++) { Port p = pit.hasNext() ? pit.next() : null; EndData oldEnd = i < esOldLength ? esOld[i] : null; - EndData newEnd = p == null ? null : p.toEnd(loc, attrs); + EndData newEnd = p == null ? null : p.toEnd(location, attrs); if (oldEnd == null || !oldEnd.equals(newEnd)) { if (newEnd != null) { es[i] = newEnd; @@ -153,7 +153,7 @@ public void removeComponentListener(ComponentListener l) { } private void fireEndsChanged(ArrayList oldEnds, - ArrayList newEnds) { + ArrayList newEnds) { EventSourceWeakSupport ls = listeners; if (ls != null) { ComponentEvent e = null; @@ -200,8 +200,7 @@ public Object getFeature(Object key) { return this; } } else if (key == TextEditable.class) { - InstanceTextField field = textField; - return field; + return textField; } return null; } @@ -210,7 +209,7 @@ public Object getFeature(Object key) { // location/extent methods // public Location getLocation() { - return loc; + return location; } public Bounds getBounds() { @@ -226,8 +225,8 @@ public Bounds getBounds(Graphics g) { return ret; } - public boolean contains(Location pt) { - Location translated = pt.translate(-loc.getX(), -loc.getY()); + public boolean contains(Location point) { + Location translated = point.translate(-location.getX(), -location.getY()); InstanceFactory factory = instance.getFactory(); return factory.contains(translated, instance.getAttributeSet()); } @@ -254,8 +253,8 @@ public EndData getEnd(int index) { public boolean endsAt(Location pt) { EndData[] ends = endArray; - for (int i = 0; i < ends.length; i++) { - if (ends[i].getLocation().equals(pt)) { + for (EndData end : ends) { + if (end.getLocation().equals(pt)) { return true; } } @@ -339,8 +338,8 @@ void setPorts(Port[] ports) { } void recomputeBounds() { - Location p = loc; - bounds = factory.getOffsetBounds(attrs).translate(p.getX(), p.getY()); + Location point = location; + bounds = factory.getOffsetBounds(attrs).translate(point.getX(), point.getY()); } void addAttributeListener(Instance instance) { @@ -353,7 +352,7 @@ void addAttributeListener(Instance instance) { } void setTextField(Attribute labelAttr, Attribute fontAttr, - int x, int y, int halign, int valign) { + int x, int y, int halign, int valign) { InstanceTextField field = textField; if (field == null) { field = new InstanceTextField(this); diff --git a/src/main/java/com/cburch/logisim/instance/InstanceFactory.java b/src/main/java/com/cburch/logisim/instance/InstanceFactory.java index fa721f3..93e570e 100644 --- a/src/main/java/com/cburch/logisim/instance/InstanceFactory.java +++ b/src/main/java/com/cburch/logisim/instance/InstanceFactory.java @@ -36,8 +36,8 @@ */ public abstract class InstanceFactory extends AbstractComponentFactory { - private String name; - private StringGetter displayName; + private final String name; + private final StringGetter displayName; private StringGetter defaultToolTip; private String iconName; private Icon icon; diff --git a/src/main/java/com/cburch/logisim/instance/InstanceLoggerAdapter.java b/src/main/java/com/cburch/logisim/instance/InstanceLoggerAdapter.java index 5d6d17a..76bbaf9 100644 --- a/src/main/java/com/cburch/logisim/instance/InstanceLoggerAdapter.java +++ b/src/main/java/com/cburch/logisim/instance/InstanceLoggerAdapter.java @@ -16,7 +16,7 @@ class InstanceLoggerAdapter implements Loggable { public InstanceLoggerAdapter(InstanceComponent comp, Class loggerClass) { try { this.comp = comp; - this.logger = loggerClass.newInstance(); + this.logger = loggerClass.getDeclaredConstructor().newInstance(); this.state = new InstanceStateImpl(null, comp); } catch (Throwable t) { handleError(t, loggerClass); diff --git a/src/main/java/com/cburch/logisim/instance/InstancePainter.java b/src/main/java/com/cburch/logisim/instance/InstancePainter.java index 8e47cbb..aa9db41 100644 --- a/src/main/java/com/cburch/logisim/instance/InstancePainter.java +++ b/src/main/java/com/cburch/logisim/instance/InstancePainter.java @@ -18,25 +18,24 @@ public class InstancePainter implements InstanceState { - private ComponentDrawContext context; - private InstanceComponent comp; + private final ComponentDrawContext context; + private InstanceComponent component; private InstanceFactory factory; private AttributeSet attrs; - public InstancePainter(ComponentDrawContext context, - InstanceComponent instance) { + public InstancePainter(ComponentDrawContext context, InstanceComponent instance) { this.context = context; - this.comp = instance; + this.component = instance; } void setFactory(InstanceFactory factory, AttributeSet attrs) { - this.comp = null; + this.component = null; this.factory = factory; this.attrs = attrs; } public InstanceFactory getFactory() { - return comp == null ? factory : (InstanceFactory) comp.getFactory(); + return component == null ? factory : (InstanceFactory) component.getFactory(); } // @@ -90,10 +89,10 @@ public Project getProject() { } public Value getPort(int portIndex) { - InstanceComponent c = comp; - CircuitState s = context.getCircuitState(); - if (c != null && s != null) { - return s.getValue(c.getEnd(portIndex).getLocation()); + InstanceComponent component = this.component; + CircuitState state = context.getCircuitState(); + if (component != null && state != null) { + return state.getValue(component.getEnd(portIndex).getLocation()); } else { return Value.UNKNOWN; } @@ -104,20 +103,20 @@ public void setPort(int portIndex, Value value, int delay) { } public InstanceData getData() { - CircuitState circState = context.getCircuitState(); - if (circState == null || comp == null) { + CircuitState circuitState = context.getCircuitState(); + if (circuitState == null || component == null) { throw new UnsupportedOperationException("setData on InstancePainter"); } else { - return (InstanceData) circState.getData(comp); + return (InstanceData) circuitState.getData(component); } } public void setData(InstanceData value) { - CircuitState circState = context.getCircuitState(); - if (circState == null || comp == null) { + CircuitState circuitState = context.getCircuitState(); + if (circuitState == null || component == null) { throw new UnsupportedOperationException("setData on InstancePainter"); } else { - circState.setData(comp, value); + circuitState.setData(component, value); } } @@ -125,69 +124,68 @@ public void setData(InstanceData value) { // methods related to the instance // public Instance getInstance() { - InstanceComponent c = comp; - return c == null ? null : c.getInstance(); + InstanceComponent component = this.component; + return component == null ? null : component.getInstance(); } void setInstance(InstanceComponent value) { - this.comp = value; + this.component = value; } public Location getLocation() { - InstanceComponent c = comp; - return c == null ? Location.create(0, 0) : c.getLocation(); + InstanceComponent component = this.component; + return component == null ? Location.create(0, 0) : component.getLocation(); } public boolean isPortConnected(int index) { - Circuit circ = context.getCircuit(); - Location loc = comp.getEnd(index).getLocation(); - return circ.isConnected(loc, comp); + Circuit circuit = context.getCircuit(); + Location location = component.getEnd(index).getLocation(); + return circuit.isConnected(location, component); } public Bounds getOffsetBounds() { - InstanceComponent c = comp; - if (c == null) { + InstanceComponent component = this.component; + if (component == null) { return factory.getOffsetBounds(attrs); } else { - Location loc = c.getLocation(); - return c.getBounds().translate(-loc.getX(), -loc.getY()); + Location location = component.getLocation(); + return component.getBounds().translate(-location.getX(), -location.getY()); } } public Bounds getBounds() { - InstanceComponent c = comp; - return c == null ? factory.getOffsetBounds(attrs) : c.getBounds(); + InstanceComponent component = this.component; + return component == null ? factory.getOffsetBounds(attrs) : component.getBounds(); } public AttributeSet getAttributeSet() { - InstanceComponent c = comp; - return c == null ? attrs : c.getAttributeSet(); + InstanceComponent component = this.component; + return component == null ? attrs : component.getAttributeSet(); } public E getAttributeValue(Attribute attr) { - InstanceComponent c = comp; - AttributeSet as = c == null ? attrs : c.getAttributeSet(); - return as.getValue(attr); + InstanceComponent component = this.component; + AttributeSet attributeSet = component == null ? attrs : component.getAttributeSet(); + return attributeSet.getValue(attr); } public void fireInvalidated() { - comp.fireInvalidated(); + component.fireInvalidated(); } // // helper methods for drawing common elements in components // public void drawBounds() { - context.drawBounds(comp); + context.drawBounds(component); } public void drawRectangle(Bounds bds, String label) { - context.drawRectangle(bds.getX(), bds.getY(), - bds.getWidth(), bds.getHeight(), label); + context.drawRectangle(bds.getX(), bds.getY(), bds.getWidth(), bds.getHeight(), label); } public void drawRectangle(int x, int y, - int width, int height, String label) { + int width, int height, String label) { context.drawRectangle(x, y, width, height, label); } @@ -196,23 +194,23 @@ public void drawDongle(int x, int y) { } public void drawPort(int i) { - context.drawPin(comp, i); + context.drawPin(component, i); } public void drawPort(int i, String label, Direction dir) { - context.drawPin(comp, i, label, dir); + context.drawPin(component, i, label, dir); } public void drawPorts() { - context.drawPins(comp); + context.drawPins(component); } public void drawClock(int i, Direction dir) { - context.drawClock(comp, i, dir); + context.drawClock(component, i, dir); } public void drawHandles() { - context.drawHandles(comp); + context.drawHandles(component); } public void drawHandle(Location loc) { @@ -224,8 +222,8 @@ public void drawHandle(int x, int y) { } public void drawLabel() { - if (comp != null) { - comp.drawLabel(context); + if (component != null) { + component.drawLabel(context); } } } diff --git a/src/main/java/com/cburch/logisim/instance/InstancePokerAdapter.java b/src/main/java/com/cburch/logisim/instance/InstancePokerAdapter.java index f1caf0d..f1cb7a7 100644 --- a/src/main/java/com/cburch/logisim/instance/InstancePokerAdapter.java +++ b/src/main/java/com/cburch/logisim/instance/InstancePokerAdapter.java @@ -3,6 +3,7 @@ package com.cburch.logisim.instance; +import com.adlerd.logger.Logger; import com.cburch.logisim.circuit.CircuitState; import com.cburch.logisim.comp.ComponentDrawContext; import com.cburch.logisim.comp.ComponentUserEvent; @@ -26,7 +27,7 @@ class InstancePokerAdapter extends AbstractCaret implements Pokable { public InstancePokerAdapter(InstanceComponent comp, Class pokerClass) { try { this.comp = comp; - poker = pokerClass.newInstance(); + poker = pokerClass.getDeclaredConstructor().newInstance(); } catch (Throwable t) { handleError(t, pokerClass); poker = null; @@ -35,11 +36,10 @@ public InstancePokerAdapter(InstanceComponent comp, Class pokerClass) { String className = pokerClass.getName(); - System.err.println("error while instantiating poker " + className //OK - + ": " + t.getClass().getName()); + Logger.errorln("error while instantiating poker " + className + ": " + t.getClass().getName()); // OK String msg = t.getMessage(); if (msg != null) { - System.err.println(" (" + msg + ")"); //OK + Logger.errorln(" (" + msg + ")"); // OK } } @@ -48,17 +48,16 @@ public Caret getPokeCaret(ComponentUserEvent event) { return null; } else { canvas = event.getCanvas(); - CircuitState circState = event.getCircuitState(); - InstanceStateImpl state = new InstanceStateImpl(circState, comp); - MouseEvent e = new MouseEvent(event.getCanvas(), - MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), 0, - event.getX(), event.getY(), 1, false); - boolean isAccepted = poker.init(state, e); + CircuitState circuitState = event.getCircuitState(); + InstanceStateImpl state = new InstanceStateImpl(circuitState, comp); + MouseEvent mouseEvent = new MouseEvent(event.getCanvas(), MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), + 0, event.getX(), event.getY(), 1, false); + boolean isAccepted = poker.init(state, mouseEvent); if (isAccepted) { this.state = state; - this.context = new ComponentDrawContext(event.getCanvas(), - event.getCanvas().getCircuit(), circState, null, null); - mousePressed(e); + this.context = new ComponentDrawContext(event.getCanvas(), event.getCanvas().getCircuit(), circuitState, + null, null); + mousePressed(mouseEvent); return this; } else { poker = null; @@ -145,10 +144,10 @@ public void draw(Graphics g) { private void checkCurrent() { if (state != null && canvas != null) { - CircuitState s0 = state.getCircuitState(); - CircuitState s1 = canvas.getCircuitState(); - if (s0 != s1) { - state = new InstanceStateImpl(s1, comp); + CircuitState state0 = state.getCircuitState(); + CircuitState state1 = canvas.getCircuitState(); + if (state0 != state1) { + state = new InstanceStateImpl(state1, comp); } } } diff --git a/src/main/java/com/cburch/logisim/instance/InstanceStateImpl.java b/src/main/java/com/cburch/logisim/instance/InstanceStateImpl.java index 40865be..cd39272 100644 --- a/src/main/java/com/cburch/logisim/instance/InstanceStateImpl.java +++ b/src/main/java/com/cburch/logisim/instance/InstanceStateImpl.java @@ -46,8 +46,8 @@ public Instance getInstance() { public InstanceFactory getFactory() { if (component instanceof InstanceComponent) { - InstanceComponent comp = (InstanceComponent) component; - return (InstanceFactory) comp.getFactory(); + InstanceComponent component = (InstanceComponent) this.component; + return (InstanceFactory) component.getFactory(); } else { return null; } @@ -67,9 +67,9 @@ public Value getPort(int portIndex) { } public boolean isPortConnected(int index) { - Circuit circ = circuitState.getCircuit(); - Location loc = component.getEnd(index).getLocation(); - return circ.isConnected(loc, component); + Circuit circuit = circuitState.getCircuit(); + Location location = component.getEnd(index).getLocation(); + return circuit.isConnected(location, component); } public void setPort(int portIndex, Value value, int delay) { @@ -78,8 +78,7 @@ public void setPort(int portIndex, Value value, int delay) { } public InstanceData getData() { - InstanceData ret = (InstanceData) circuitState.getData(component); - return ret; + return (InstanceData) circuitState.getData(component); } public void setData(InstanceData value) { diff --git a/src/main/java/com/cburch/logisim/instance/InstanceTextField.java b/src/main/java/com/cburch/logisim/instance/InstanceTextField.java index eeb2474..0978d60 100644 --- a/src/main/java/com/cburch/logisim/instance/InstanceTextField.java +++ b/src/main/java/com/cburch/logisim/instance/InstanceTextField.java @@ -24,9 +24,9 @@ import java.awt.Graphics; public class InstanceTextField implements AttributeListener, TextFieldListener, - TextEditable { + TextEditable { - private InstanceComponent component; + private final InstanceComponent component; private TextField field; private Attribute labelAttribute; private Attribute fontAttribute; @@ -43,7 +43,7 @@ public class InstanceTextField implements AttributeListener, TextFieldListener, } void update(Attribute labelAttribute, Attribute fontAttribute, - int x, int y, int hAlign, int vAlign) { + int x, int y, int hAlign, int vAlign) { boolean wasReg = shouldRegister(); this.labelAttribute = labelAttribute; this.fontAttribute = fontAttribute; diff --git a/src/main/java/com/cburch/logisim/instance/Port.java b/src/main/java/com/cburch/logisim/instance/Port.java index f4ccd2a..d76213e 100644 --- a/src/main/java/com/cburch/logisim/instance/Port.java +++ b/src/main/java/com/cburch/logisim/instance/Port.java @@ -19,12 +19,12 @@ public class Port { public static final String EXCLUSIVE = "exclusive"; public static final String SHARED = "shared"; - private int dx; - private int dy; - private int type; - private BitWidth widthFixed; - private Attribute widthAttr; - private boolean exclude; + private final int dx; + private final int dy; + private final int type; + private final BitWidth widthFixed; + private final Attribute widthAttr; + private final boolean exclude; private StringGetter toolTip; public Port(int dx, int dy, String type, BitWidth bits) { @@ -54,7 +54,7 @@ public Port(int dx, int dy, String type, Attribute attr) { } public Port(int dx, int dy, String type, Attribute attr, - String exclude) { + String exclude) { this.dx = dx; this.dy = dy; this.type = toType(type); diff --git a/src/main/java/com/cburch/logisim/instance/StdAttr.java b/src/main/java/com/cburch/logisim/instance/StdAttr.java index 92f724f..b06856c 100644 --- a/src/main/java/com/cburch/logisim/instance/StdAttr.java +++ b/src/main/java/com/cburch/logisim/instance/StdAttr.java @@ -22,9 +22,9 @@ public interface StdAttr { AttributeOption TRIG_LOW = new AttributeOption("low", Strings.getter("stdTriggerLow")); Attribute TRIGGER = Attributes.forOption("trigger", Strings.getter("stdTriggerAttr"), - new AttributeOption[]{TRIG_RISING, TRIG_FALLING, TRIG_HIGH, TRIG_LOW}); + new AttributeOption[]{TRIG_RISING, TRIG_FALLING, TRIG_HIGH, TRIG_LOW}); Attribute EDGE_TRIGGER = Attributes.forOption("trigger", Strings.getter("stdTriggerAttr"), - new AttributeOption[]{TRIG_RISING, TRIG_FALLING}); + new AttributeOption[]{TRIG_RISING, TRIG_FALLING}); Attribute LABEL = Attributes.forString("label", Strings.getter("stdLabelAttr")); diff --git a/src/main/java/com/cburch/logisim/instance/Strings.java b/src/main/java/com/cburch/logisim/instance/Strings.java index 1d5ea90..217c0d1 100644 --- a/src/main/java/com/cburch/logisim/instance/Strings.java +++ b/src/main/java/com/cburch/logisim/instance/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "std"); + private static final LocaleManager source = new LocaleManager("logisim", "std"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/prefs/AbstractPrefMonitor.java b/src/main/java/com/cburch/logisim/prefs/AbstractPrefMonitor.java index 5ec6d34..48ce540 100644 --- a/src/main/java/com/cburch/logisim/prefs/AbstractPrefMonitor.java +++ b/src/main/java/com/cburch/logisim/prefs/AbstractPrefMonitor.java @@ -8,7 +8,7 @@ abstract class AbstractPrefMonitor implements PrefMonitor { - private String name; + private final String name; AbstractPrefMonitor(String name) { this.name = name; diff --git a/src/main/java/com/cburch/logisim/prefs/AppPreferences.java b/src/main/java/com/cburch/logisim/prefs/AppPreferences.java index 0626f0b..ffe9754 100644 --- a/src/main/java/com/cburch/logisim/prefs/AppPreferences.java +++ b/src/main/java/com/cburch/logisim/prefs/AppPreferences.java @@ -38,7 +38,7 @@ public class AppPreferences { public static final String SHAPE_RECTANGULAR = "rectangular"; public static final String SHAPE_DIN40700 = "din40700"; public static final PrefMonitor GATE_SHAPE = create(new PrefMonitorStringOpts("gateShape", - new String[]{SHAPE_SHAPED, SHAPE_RECTANGULAR, SHAPE_DIN40700}, SHAPE_SHAPED)); + new String[]{SHAPE_SHAPED, SHAPE_RECTANGULAR, SHAPE_DIN40700}, SHAPE_SHAPED)); public static final PrefMonitor LOCALE = create(new LocalePreference()); public static final PrefMonitor ACCENTS_REPLACE = create(new PrefMonitorBoolean("accentsReplace", false)); // Window preferences @@ -46,63 +46,66 @@ public class AppPreferences { public static final String TOOLBAR_DOWN_MIDDLE = "downMiddle"; public static final PrefMonitor SHOW_TICK_RATE = create(new PrefMonitorBoolean("showTickRate", false)); public static final PrefMonitor TOOLBAR_PLACEMENT = create( - new PrefMonitorStringOpts("toolbarPlacement", new String[]{ - Direction.NORTH.toString(), Direction.SOUTH.toString(), - Direction.EAST.toString(), Direction.WEST.toString(), - TOOLBAR_DOWN_MIDDLE, TOOLBAR_HIDDEN}, - Direction.NORTH.toString())); + new PrefMonitorStringOpts("toolbarPlacement", new String[]{ + Direction.NORTH.toString(), Direction.SOUTH.toString(), + Direction.EAST.toString(), Direction.WEST.toString(), + TOOLBAR_DOWN_MIDDLE, TOOLBAR_HIDDEN}, + Direction.NORTH.toString())); // Layout preferences public static final String ADD_AFTER_UNCHANGED = "unchanged"; public static final String ADD_AFTER_EDIT = "edit"; public static final PrefMonitor PRINTER_VIEW - = create(new PrefMonitorBoolean("printerView", false)); + = create(new PrefMonitorBoolean("printerView", false)); public static final PrefMonitor ATTRIBUTE_HALO - = create(new PrefMonitorBoolean("attributeHalo", true)); + = create(new PrefMonitorBoolean("attributeHalo", true)); public static final PrefMonitor COMPONENT_TIPS - = create(new PrefMonitorBoolean("componentTips", true)); + = create(new PrefMonitorBoolean("componentTips", true)); public static final PrefMonitor MOVE_KEEP_CONNECT - = create(new PrefMonitorBoolean("keepConnected", true)); + = create(new PrefMonitorBoolean("keepConnected", true)); public static final PrefMonitor ADD_SHOW_GHOSTS - = create(new PrefMonitorBoolean("showGhosts", true)); + = create(new PrefMonitorBoolean("showGhosts", true)); public static final PrefMonitor ADD_AFTER - = create(new PrefMonitorStringOpts("afterAdd", - new String[]{ADD_AFTER_EDIT, ADD_AFTER_UNCHANGED}, ADD_AFTER_EDIT)); + = create(new PrefMonitorStringOpts("afterAdd", + new String[]{ADD_AFTER_EDIT, ADD_AFTER_UNCHANGED}, ADD_AFTER_EDIT)); // Experimental preferences public static final String ACCELERATION_DEFAULT = "default"; public static final String ACCELERATION_NONE = "none"; public static final String ACCELERATION_OPENGL = "opengl"; public static final String ACCELERATION_D3D = "d3d"; - public static final PrefMonitor GRAPHICS_ACCELERATION = create(new PrefMonitorStringOpts("graphicsAcceleration", - new String[]{ACCELERATION_DEFAULT, ACCELERATION_NONE, ACCELERATION_OPENGL, ACCELERATION_D3D}, ACCELERATION_DEFAULT)); + public static final PrefMonitor GRAPHICS_ACCELERATION + = create(new PrefMonitorStringOpts("graphicsAcceleration", + new String[]{ACCELERATION_DEFAULT, ACCELERATION_NONE, ACCELERATION_OPENGL, ACCELERATION_D3D}, ACCELERATION_DEFAULT) + ); // hidden window preferences - not part of the preferences dialog, changes // to preference does not affect current windows, and the values are not // saved until the application is closed public static final String RECENT_PROJECTS = "recentProjects"; public static final PrefMonitor TICK_FREQUENCY - = create(new PrefMonitorDouble("tickFrequency", 1.0)); + = create(new PrefMonitorDouble("tickFrequency", 1.0)); public static final PrefMonitor LAYOUT_SHOW_GRID - = create(new PrefMonitorBoolean("layoutGrid", true)); + = create(new PrefMonitorBoolean("layoutGrid", true)); public static final PrefMonitor LAYOUT_ZOOM - = create(new PrefMonitorDouble("layoutZoom", 1.0)); + = create(new PrefMonitorDouble("layoutZoom", 1.0)); public static final PrefMonitor APPEARANCE_SHOW_GRID - = create(new PrefMonitorBoolean("appearanceGrid", true)); + = create(new PrefMonitorBoolean("appearanceGrid", true)); public static final PrefMonitor APPEARANCE_ZOOM - = create(new PrefMonitorDouble("appearanceZoom", 1.0)); + = create(new PrefMonitorDouble("appearanceZoom", 1.0)); public static final PrefMonitor WINDOW_STATE - = create(new PrefMonitorInt("windowState", JFrame.NORMAL)); + = create(new PrefMonitorInt("windowState", JFrame.NORMAL)); public static final PrefMonitor WINDOW_WIDTH - = create(new PrefMonitorInt("windowWidth", 640)); + = create(new PrefMonitorInt("windowWidth", 640)); public static final PrefMonitor WINDOW_HEIGHT - = create(new PrefMonitorInt("windowHeight", 480)); + = create(new PrefMonitorInt("windowHeight", 480)); public static final PrefMonitor WINDOW_LOCATION - = create(new PrefMonitorString("windowLocation", "0,0")); + = create(new PrefMonitorString("windowLocation", "0,0")); public static final PrefMonitor WINDOW_MAIN_SPLIT - = create(new PrefMonitorDouble("windowMainSplit", 0.25)); + = create(new PrefMonitorDouble("windowMainSplit", 0.25)); public static final PrefMonitor WINDOW_LEFT_SPLIT - = create(new PrefMonitorDouble("windowLeftSplit", 0.5)); + = create(new PrefMonitorDouble("windowLeftSplit", 0.5)); public static final PrefMonitor DIALOG_DIRECTORY - = create(new PrefMonitorString("dialogDirectory", "")); + = create(new PrefMonitorString("dialogDirectory", "")); private static final String TEMPLATE = "template"; + private static final PropertyChangeWeakSupport propertySupport = new PropertyChangeWeakSupport(AppPreferences.class); private static final RecentProjects recentProjects = new RecentProjects(); public static PrefMonitor POKE_WIRE_RADIX1; public static PrefMonitor POKE_WIRE_RADIX2; @@ -110,7 +113,6 @@ public class AppPreferences { // internal variables, and other classes private static Preferences preferences = null; private static MyListener myListener = null; - private static PropertyChangeWeakSupport propertySupport = new PropertyChangeWeakSupport(AppPreferences.class); private static int templateType = TEMPLATE_PLAIN; private static File templateFile = null; private static Template plainTemplate = null; @@ -124,10 +126,9 @@ public class AppPreferences { for (int i = 0; i < radixOptions.length; i++) { radixStrings[i] = radixOptions[i].getSaveString(); } - POKE_WIRE_RADIX1 = create(new PrefMonitorStringOpts("pokeRadix1", - radixStrings, RadixOption.RADIX_2.getSaveString())); - POKE_WIRE_RADIX2 = create(new PrefMonitorStringOpts("pokeRadix2", - radixStrings, RadixOption.RADIX_10_SIGNED.getSaveString())); + POKE_WIRE_RADIX1 = create(new PrefMonitorStringOpts("pokeRadix1", radixStrings, RadixOption.RADIX_2.getSaveString())); + POKE_WIRE_RADIX2 = create( + new PrefMonitorStringOpts("pokeRadix2", radixStrings, RadixOption.RADIX_10_SIGNED.getSaveString())); } private static PrefMonitor create(PrefMonitor monitor) { @@ -354,7 +355,7 @@ public static void updateRecentFile(File file) { // methods for accessing preferences // private static class MyListener implements PreferenceChangeListener, - LocaleListener { + LocaleListener { public void preferenceChange(PreferenceChangeEvent event) { Preferences prefs = event.getNode(); diff --git a/src/main/java/com/cburch/logisim/prefs/PrefMonitorBoolean.java b/src/main/java/com/cburch/logisim/prefs/PrefMonitorBoolean.java index 0f02c8b..d243d87 100644 --- a/src/main/java/com/cburch/logisim/prefs/PrefMonitorBoolean.java +++ b/src/main/java/com/cburch/logisim/prefs/PrefMonitorBoolean.java @@ -8,7 +8,7 @@ class PrefMonitorBoolean extends AbstractPrefMonitor { - private boolean defaultValue; + private final boolean defaultValue; private boolean value; PrefMonitorBoolean(String name, boolean defaultValue) { diff --git a/src/main/java/com/cburch/logisim/prefs/PrefMonitorDouble.java b/src/main/java/com/cburch/logisim/prefs/PrefMonitorDouble.java index ff38558..487a1f7 100644 --- a/src/main/java/com/cburch/logisim/prefs/PrefMonitorDouble.java +++ b/src/main/java/com/cburch/logisim/prefs/PrefMonitorDouble.java @@ -8,16 +8,16 @@ class PrefMonitorDouble extends AbstractPrefMonitor { - private double dflt; + private final double defaultValue; private double value; - PrefMonitorDouble(String name, double dflt) { + PrefMonitorDouble(String name, double defaultValue) { super(name); - this.dflt = dflt; - this.value = dflt; - Preferences prefs = AppPreferences.getPreferences(); - set(prefs.getDouble(name, dflt)); - prefs.addPreferenceChangeListener(this); + this.defaultValue = defaultValue; + this.value = defaultValue; + Preferences preferences = AppPreferences.getPreferences(); + set(preferences.getDouble(name, defaultValue)); + preferences.addPreferenceChangeListener(this); } public Double get() { @@ -32,16 +32,16 @@ public void set(Double newValue) { } public void preferenceChange(PreferenceChangeEvent event) { - Preferences prefs = event.getNode(); + Preferences preferences = event.getNode(); String prop = event.getKey(); String name = getIdentifier(); if (prop.equals(name)) { double oldValue = value; - double newValue = prefs.getDouble(name, dflt); + double newValue = preferences.getDouble(name, defaultValue); if (newValue != oldValue) { value = newValue; AppPreferences.firePropertyChange(name, - oldValue, newValue); + oldValue, newValue); } } } diff --git a/src/main/java/com/cburch/logisim/prefs/PrefMonitorInt.java b/src/main/java/com/cburch/logisim/prefs/PrefMonitorInt.java index 2ccb6bd..70f91ca 100644 --- a/src/main/java/com/cburch/logisim/prefs/PrefMonitorInt.java +++ b/src/main/java/com/cburch/logisim/prefs/PrefMonitorInt.java @@ -8,16 +8,16 @@ class PrefMonitorInt extends AbstractPrefMonitor { - private int dflt; + private final int defaultValue; private int value; - PrefMonitorInt(String name, int dflt) { + PrefMonitorInt(String name, int defaultValue) { super(name); - this.dflt = dflt; - this.value = dflt; - Preferences prefs = AppPreferences.getPreferences(); - set(prefs.getInt(name, dflt)); - prefs.addPreferenceChangeListener(this); + this.defaultValue = defaultValue; + this.value = defaultValue; + Preferences preferences = AppPreferences.getPreferences(); + set(preferences.getInt(name, defaultValue)); + preferences.addPreferenceChangeListener(this); } public Integer get() { @@ -32,16 +32,16 @@ public void set(Integer newValue) { } public void preferenceChange(PreferenceChangeEvent event) { - Preferences prefs = event.getNode(); + Preferences preferences = event.getNode(); String prop = event.getKey(); String name = getIdentifier(); if (prop.equals(name)) { int oldValue = value; - int newValue = prefs.getInt(name, dflt); + int newValue = preferences.getInt(name, defaultValue); if (newValue != oldValue) { value = newValue; AppPreferences.firePropertyChange(name, - oldValue, newValue); + oldValue, newValue); } } } diff --git a/src/main/java/com/cburch/logisim/prefs/PrefMonitorString.java b/src/main/java/com/cburch/logisim/prefs/PrefMonitorString.java index ca4aaec..4925a3b 100644 --- a/src/main/java/com/cburch/logisim/prefs/PrefMonitorString.java +++ b/src/main/java/com/cburch/logisim/prefs/PrefMonitorString.java @@ -8,15 +8,15 @@ class PrefMonitorString extends AbstractPrefMonitor { - private String dflt; + private final String defaultValue; private String value; - PrefMonitorString(String name, String dflt) { + PrefMonitorString(String name, String defaultValue) { super(name); - this.dflt = dflt; - Preferences prefs = AppPreferences.getPreferences(); - this.value = prefs.get(name, dflt); - prefs.addPreferenceChangeListener(this); + this.defaultValue = defaultValue; + Preferences preferences = AppPreferences.getPreferences(); + this.value = preferences.get(name, defaultValue); + preferences.addPreferenceChangeListener(this); } private static boolean isSame(String a, String b) { @@ -36,12 +36,12 @@ public void set(String newValue) { } public void preferenceChange(PreferenceChangeEvent event) { - Preferences prefs = event.getNode(); + Preferences preferences = event.getNode(); String prop = event.getKey(); String name = getIdentifier(); if (prop.equals(name)) { String oldValue = value; - String newValue = prefs.get(name, dflt); + String newValue = preferences.get(name, defaultValue); if (!isSame(oldValue, newValue)) { value = newValue; AppPreferences.firePropertyChange(name, oldValue, newValue); diff --git a/src/main/java/com/cburch/logisim/prefs/PrefMonitorStringOpts.java b/src/main/java/com/cburch/logisim/prefs/PrefMonitorStringOpts.java index 9b06ea4..2d11f94 100644 --- a/src/main/java/com/cburch/logisim/prefs/PrefMonitorStringOpts.java +++ b/src/main/java/com/cburch/logisim/prefs/PrefMonitorStringOpts.java @@ -8,18 +8,18 @@ class PrefMonitorStringOpts extends AbstractPrefMonitor { - private String[] opts; + private final String[] opts; + private final String defaultValue; private String value; - private String dflt; - PrefMonitorStringOpts(String name, String[] opts, String dflt) { + PrefMonitorStringOpts(String name, String[] opts, String defaultValue) { super(name); this.opts = opts; this.value = opts[0]; - this.dflt = dflt; - Preferences prefs = AppPreferences.getPreferences(); - set(prefs.get(name, dflt)); - prefs.addPreferenceChangeListener(this); + this.defaultValue = defaultValue; + Preferences preferences = AppPreferences.getPreferences(); + set(preferences.get(name, defaultValue)); + preferences.addPreferenceChangeListener(this); } private static boolean isSame(String a, String b) { @@ -38,23 +38,22 @@ public void set(String newValue) { } public void preferenceChange(PreferenceChangeEvent event) { - Preferences prefs = event.getNode(); + Preferences preferences = event.getNode(); String prop = event.getKey(); String name = getIdentifier(); if (prop.equals(name)) { String oldValue = value; - String newValue = prefs.get(name, dflt); + String newValue = preferences.get(name, defaultValue); if (!isSame(oldValue, newValue)) { - String[] o = opts; String chosen = null; - for (int i = 0; i < o.length; i++) { - if (isSame(o[i], newValue)) { - chosen = o[i]; + for (String s : opts) { + if (isSame(s, newValue)) { + chosen = s; break; } } if (chosen == null) { - chosen = dflt; + chosen = defaultValue; } value = chosen; AppPreferences.firePropertyChange(name, oldValue, chosen); diff --git a/src/main/java/com/cburch/logisim/prefs/RecentProjects.java b/src/main/java/com/cburch/logisim/prefs/RecentProjects.java index 7598ad9..76b3d83 100644 --- a/src/main/java/com/cburch/logisim/prefs/RecentProjects.java +++ b/src/main/java/com/cburch/logisim/prefs/RecentProjects.java @@ -17,8 +17,8 @@ class RecentProjects implements PreferenceChangeListener { private static final String BASE_PROPERTY = "recent"; private static final int MAX_NUM_RECENT = 10; - private File[] recentFiles; - private long[] recentTimes; + private final File[] recentFiles; + private final long[] recentTimes; RecentProjects() { recentFiles = new File[MAX_NUM_RECENT]; @@ -30,7 +30,7 @@ class RecentProjects implements PreferenceChangeListener { // TODO: Fix error with recent files not loading for (int index = 0; index < MAX_NUM_RECENT; index++) { -// getAndDecode(preferences, index); + getAndDecode(preferences, index); } } @@ -127,8 +127,8 @@ public void preferenceChange(PreferenceChangeEvent event) { long newTime = recentTimes[index]; if (!isSame(oldValue, newValue) || oldTime != newTime) { AppPreferences.firePropertyChange(AppPreferences.RECENT_PROJECTS, - new FileTime(oldValue, oldTime), - new FileTime(newValue, newTime)); + new FileTime(oldValue, oldTime), + new FileTime(newValue, newTime)); } } } @@ -142,10 +142,10 @@ private void updateInto(int index, long time, File file) { recentTimes[index] = time; try { AppPreferences.getPreferences().put(BASE_PROPERTY + index, - "" + time + ";" + file.getCanonicalPath()); + "" + time + ";" + file.getCanonicalPath()); AppPreferences.firePropertyChange(AppPreferences.RECENT_PROJECTS, - new FileTime(oldFile, oldTime), - new FileTime(file, time)); + new FileTime(oldFile, oldTime), + new FileTime(file, time)); } catch (IOException e) { recentFiles[index] = oldFile; recentTimes[index] = oldTime; @@ -172,8 +172,8 @@ private void getAndDecode(Preferences prefs, int index) { private static class FileTime { - private long time; - private File file; + private final long time; + private final File file; private FileTime(File file, long time) { this.time = time; diff --git a/src/main/java/com/cburch/logisim/prefs/Strings.java b/src/main/java/com/cburch/logisim/prefs/Strings.java index 6c78789..c6075fc 100644 --- a/src/main/java/com/cburch/logisim/prefs/Strings.java +++ b/src/main/java/com/cburch/logisim/prefs/Strings.java @@ -9,7 +9,7 @@ class Strings { - private static LocaleManager source = new LocaleManager("/logisim", "proj"); + private static final LocaleManager source = new LocaleManager("/logisim", "proj"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/prefs/Template.java b/src/main/java/com/cburch/logisim/prefs/Template.java index 6a805bf..fbf1dc5 100644 --- a/src/main/java/com/cburch/logisim/prefs/Template.java +++ b/src/main/java/com/cburch/logisim/prefs/Template.java @@ -12,7 +12,7 @@ public class Template { - private String contents; + private final String contents; private Template(String contents) { this.contents = contents; @@ -21,11 +21,11 @@ private Template(String contents) { public static Template createEmpty() { String circName = Strings.get("newCircuitName"); String builder = "" - + "" - + " " - + ""; + + "" + + " " + + ""; return new Template(builder); } diff --git a/src/main/java/com/cburch/logisim/proj/Dependencies.java b/src/main/java/com/cburch/logisim/proj/Dependencies.java index f67ca24..2a60b84 100644 --- a/src/main/java/com/cburch/logisim/proj/Dependencies.java +++ b/src/main/java/com/cburch/logisim/proj/Dependencies.java @@ -17,19 +17,19 @@ public class Dependencies { - private MyListener myListener = new MyListener(); - private Dag depends = new Dag(); + private final MyListener myListener = new MyListener(); + private final Dag depends = new Dag(); Dependencies(LogisimFile file) { addDependencies(file); } - public boolean canRemove(Circuit circ) { - return !depends.hasPredecessors(circ); + public boolean canRemove(Circuit circuit) { + return !depends.hasPredecessors(circuit); } - public boolean canAdd(Circuit circ, Circuit sub) { - return depends.canFollow(sub, circ); + public boolean canAdd(Circuit circuit, Circuit subcircuit) { + return depends.canFollow(subcircuit, circuit); } private void addDependencies(LogisimFile file) { @@ -39,61 +39,63 @@ private void addDependencies(LogisimFile file) { } } - private void processCircuit(Circuit circ) { - circ.addCircuitListener(myListener); - for (Component comp : circ.getNonWires()) { - if (comp.getFactory() instanceof SubcircuitFactory) { - SubcircuitFactory factory = (SubcircuitFactory) comp.getFactory(); - depends.addEdge(circ, factory.getSubcircuit()); + private void processCircuit(Circuit circuit) { + circuit.addCircuitListener(myListener); + for (Component component : circuit.getNonWires()) { + if (component.getFactory() instanceof SubcircuitFactory) { + SubcircuitFactory factory = (SubcircuitFactory) component.getFactory(); + depends.addEdge(circuit, factory.getSubcircuit()); } } } private class MyListener - implements LibraryListener, CircuitListener { + implements LibraryListener, CircuitListener { public void libraryChanged(LibraryEvent e) { switch (e.getAction()) { - case LibraryEvent.ADD_TOOL: + case LibraryEvent.ADD_TOOL: { if (e.getData() instanceof AddTool) { ComponentFactory factory = ((AddTool) e.getData()).getFactory(); if (factory instanceof SubcircuitFactory) { - SubcircuitFactory circFact = (SubcircuitFactory) factory; - processCircuit(circFact.getSubcircuit()); + SubcircuitFactory subcircuitFactory = (SubcircuitFactory) factory; + processCircuit(subcircuitFactory.getSubcircuit()); } } break; - case LibraryEvent.REMOVE_TOOL: + } + case LibraryEvent.REMOVE_TOOL: { if (e.getData() instanceof AddTool) { ComponentFactory factory = ((AddTool) e.getData()).getFactory(); if (factory instanceof SubcircuitFactory) { - SubcircuitFactory circFact = (SubcircuitFactory) factory; - Circuit circ = circFact.getSubcircuit(); - depends.removeNode(circ); - circ.removeCircuitListener(this); + SubcircuitFactory subcircuitFactory = (SubcircuitFactory) factory; + Circuit circuit = subcircuitFactory.getSubcircuit(); + depends.removeNode(circuit); + circuit.removeCircuitListener(this); } } break; + } } } public void circuitChanged(CircuitEvent e) { - Component comp; + Component component; switch (e.getAction()) { case CircuitEvent.ACTION_ADD: - comp = (Component) e.getData(); - if (comp.getFactory() instanceof SubcircuitFactory) { - SubcircuitFactory factory = (SubcircuitFactory) comp.getFactory(); + component = (Component) e.getData(); + if (component.getFactory() instanceof SubcircuitFactory) { + SubcircuitFactory factory = (SubcircuitFactory) component.getFactory(); depends.addEdge(e.getCircuit(), factory.getSubcircuit()); } break; case CircuitEvent.ACTION_REMOVE: - comp = (Component) e.getData(); - if (comp.getFactory() instanceof SubcircuitFactory) { - SubcircuitFactory factory = (SubcircuitFactory) comp.getFactory(); + component = (Component) e.getData(); + if (component.getFactory() instanceof SubcircuitFactory) { + SubcircuitFactory factory = (SubcircuitFactory) component.getFactory(); boolean found = false; - for (Component o : e.getCircuit().getNonWires()) { - if (o.getFactory() == factory) { + for (Component comp : e.getCircuit().getNonWires()) { + if (comp.getFactory() == factory) { found = true; break; } diff --git a/src/main/java/com/cburch/logisim/proj/Project.java b/src/main/java/com/cburch/logisim/proj/Project.java index 86a9f21..e5dce70 100644 --- a/src/main/java/com/cburch/logisim/proj/Project.java +++ b/src/main/java/com/cburch/logisim/proj/Project.java @@ -31,21 +31,21 @@ public class Project { private static final int MAX_UNDO_SIZE = 64; - private Simulator simulator = new Simulator(); + private final Simulator simulator = new Simulator(); + private final HashMap stateMap = new HashMap<>(); + private final LinkedList undoLog = new LinkedList<>(); + private final EventSourceWeakSupport projectListeners = new EventSourceWeakSupport<>(); + private final EventSourceWeakSupport fileListeners = new EventSourceWeakSupport<>(); + private final EventSourceWeakSupport circuitListeners = new EventSourceWeakSupport<>(); + private final MyListener myListener = new MyListener(); private LogisimFile file; private CircuitState circuitState; - private HashMap stateMap = new HashMap<>(); private Frame frame = null; private OptionsFrame optionsFrame = null; private LogFrame logFrame = null; private Tool tool = null; - private LinkedList undoLog = new LinkedList<>(); private int undoMods = 0; - private EventSourceWeakSupport projectListeners = new EventSourceWeakSupport<>(); - private EventSourceWeakSupport fileListeners = new EventSourceWeakSupport<>(); - private EventSourceWeakSupport circuitListeners = new EventSourceWeakSupport<>(); private Dependencies depends; - private MyListener myListener = new MyListener(); private boolean startupScreen = false; public Project(LogisimFile file) { @@ -135,11 +135,11 @@ public Circuit getCurrentCircuit() { } public void setCurrentCircuit(Circuit circuit) { - CircuitState circState = stateMap.get(circuit); - if (circState == null) { - circState = new CircuitState(this, circuit); + CircuitState circuitState = stateMap.get(circuit); + if (circuitState == null) { + circuitState = new CircuitState(this, circuit); } - setCircuitState(circState); + setCircuitState(circuitState); } public CircuitState getCircuitState() { @@ -316,8 +316,8 @@ private void fireEvent(int action, Object data) { } private void fireEvent(ProjectEvent event) { - for (ProjectListener l : projectListeners) { - l.projectChanged(event); + for (ProjectListener listener : projectListeners) { + listener.projectChanged(event); } } diff --git a/src/main/java/com/cburch/logisim/proj/ProjectActions.java b/src/main/java/com/cburch/logisim/proj/ProjectActions.java index 192310c..6a8adcc 100644 --- a/src/main/java/com/cburch/logisim/proj/ProjectActions.java +++ b/src/main/java/com/cburch/logisim/proj/ProjectActions.java @@ -3,6 +3,7 @@ package com.cburch.logisim.proj; +import com.adlerd.logger.Logger; import com.cburch.logisim.circuit.Circuit; import com.cburch.logisim.file.LoadFailedException; import com.cburch.logisim.file.Loader; @@ -42,14 +43,13 @@ public static Project doNew(SplashScreen monitor, boolean isStartupScreen) { LogisimFile file = null; try { file = loader.openLogisimFile(templReader); - } catch (IOException ex) { - displayException(monitor, ex); - } catch (LoadFailedException ex) { + } catch (IOException | LoadFailedException ex) { displayException(monitor, ex); } finally { try { templReader.close(); } catch (IOException e) { + Logger.debugln(e.getMessage()); } } if (file == null) { @@ -59,8 +59,7 @@ public static Project doNew(SplashScreen monitor, boolean isStartupScreen) { } private static void displayException(Component parent, Exception ex) { - String msg = StringUtil.format(Strings.get("templateOpenError"), - ex.toString()); + String msg = StringUtil.format(Strings.get("templateOpenError"), ex.toString()); String ttl = Strings.get("templateOpenErrorTitle"); JOptionPane.showMessageDialog(parent, msg, ttl, JOptionPane.ERROR_MESSAGE); } @@ -77,13 +76,14 @@ private static LogisimFile createEmptyFile(Loader loader) { try { templReader.close(); } catch (IOException e) { + Logger.debugln(e.getMessage()); } } return file; } private static Project completeProject(SplashScreen monitor, Loader loader, - LogisimFile file, boolean isStartup) { + LogisimFile file, boolean isStartup) { if (monitor != null) { monitor.setProgress(SplashScreen.PROJECT_CREATE); } @@ -114,6 +114,7 @@ public static LogisimFile createNewFile(Project baseProject) { try { templReader.close(); } catch (IOException e) { + Logger.debugln(e.getMessage()); } } return file; @@ -142,7 +143,7 @@ public static Project doNew(Project baseProject) { } public static Project doOpen(SplashScreen monitor, File source, - Map substitutions) throws LoadFailedException { + Map substitutions) throws LoadFailedException { if (monitor != null) { monitor.setProgress(SplashScreen.FILE_LOAD); } @@ -177,7 +178,7 @@ public static void doOpen(Component parent, Project baseProject) { } public static Project doOpen(Component parent, - Project baseProject, File f) { + Project baseProject, File f) { Project proj = Projects.findProjectFor(f); Loader loader = null; if (proj != null) { @@ -185,16 +186,16 @@ public static Project doOpen(Component parent, loader = proj.getLogisimFile().getLoader(); if (proj.isFileDirty()) { String message = StringUtil.format(Strings.get("openAlreadyMessage"), - proj.getLogisimFile().getName()); + proj.getLogisimFile().getName()); String[] options = { - Strings.get("openAlreadyLoseChangesOption"), - Strings.get("openAlreadyNewWindowOption"), - Strings.get("openAlreadyCancelOption"), + Strings.get("openAlreadyLoseChangesOption"), + Strings.get("openAlreadyNewWindowOption"), + Strings.get("openAlreadyCancelOption"), }; int result = JOptionPane.showOptionDialog(proj.getFrame(), - message, Strings.get("openAlreadyTitle"), 0, - JOptionPane.QUESTION_MESSAGE, null, - options, options[2]); + message, Strings.get("openAlreadyTitle"), 0, + JOptionPane.QUESTION_MESSAGE, null, + options, options[2]); if (result == 0) { // keep proj as is, so that load happens into the window } else if (result == 1) { @@ -227,10 +228,10 @@ public static Project doOpen(Component parent, } catch (LoadFailedException ex) { if (!ex.isShown()) { JOptionPane.showMessageDialog(parent, - StringUtil.format(Strings.get("fileOpenError"), - ex.toString()), - Strings.get("fileOpenErrorTitle"), - JOptionPane.ERROR_MESSAGE); + StringUtil.format(Strings.get("fileOpenError"), + ex.toString()), + Strings.get("fileOpenErrorTitle"), + JOptionPane.ERROR_MESSAGE); } return null; } @@ -271,9 +272,9 @@ public static boolean doSaveAs(Project project) { String ttl = Strings.get("replaceExtensionTitle"); String message = Strings.get("replaceExtensionMessage", extension); Object[] options = { - Strings.get("replaceExtensionReplaceOpt", extension), - Strings.get("replaceExtensionAddOpt", circuitExtension), - Strings.get("replaceExtensionKeepOpt") + Strings.get("replaceExtensionReplaceOpt", extension), + Strings.get("replaceExtensionAddOpt", circuitExtension), + Strings.get("replaceExtensionKeepOpt") }; JOptionPane dialog = new JOptionPane(message); dialog.setMessageType(JOptionPane.QUESTION_MESSAGE); @@ -292,9 +293,9 @@ public static boolean doSaveAs(Project project) { if (selectedFile.exists()) { int confirm = JOptionPane.showConfirmDialog(project.getFrame(), - Strings.get("confirmOverwriteMessage"), - Strings.get("confirmOverwriteTitle"), - JOptionPane.YES_NO_OPTION); + Strings.get("confirmOverwriteMessage"), + Strings.get("confirmOverwriteTitle"), + JOptionPane.YES_NO_OPTION); if (confirm != JOptionPane.YES_OPTION) { return false; } @@ -339,9 +340,9 @@ public static void doQuit() { private static class CreateFrame implements Runnable { - private Loader loader; - private Project project; - private boolean isStartupScreen; + private final Loader loader; + private final Project project; + private final boolean isStartupScreen; private CreateFrame(Loader loader, Project project, boolean isStartup) { this.loader = loader; diff --git a/src/main/java/com/cburch/logisim/proj/ProjectEvent.java b/src/main/java/com/cburch/logisim/proj/ProjectEvent.java index 2ce1abd..c80c6f0 100644 --- a/src/main/java/com/cburch/logisim/proj/ProjectEvent.java +++ b/src/main/java/com/cburch/logisim/proj/ProjectEvent.java @@ -22,10 +22,10 @@ public class ProjectEvent { public static final int UNDO_COMPLETE = 9; // undo has completed public static final int REPAINT_REQUEST = 10; // canvas should be repainted - private int action; - private Project proj; + private final int action; + private final Project proj; + private final Object data; private Object old_data; - private Object data; ProjectEvent(int action, Project proj, Object old, Object data) { this.action = action; diff --git a/src/main/java/com/cburch/logisim/proj/Projects.java b/src/main/java/com/cburch/logisim/proj/Projects.java index 5090260..c2e7cb9 100644 --- a/src/main/java/com/cburch/logisim/proj/Projects.java +++ b/src/main/java/com/cburch/logisim/proj/Projects.java @@ -3,6 +3,7 @@ package com.cburch.logisim.proj; +import com.adlerd.logger.Logger; import com.cburch.logisim.file.Loader; import com.cburch.logisim.gui.main.Frame; import com.cburch.logisim.util.MacCompatibility; @@ -23,19 +24,17 @@ public class Projects { public static final String projectListProperty = "projectList"; - private static final WeakHashMap frameLocations - = new WeakHashMap<>(); + private static final WeakHashMap frameLocations = new WeakHashMap<>(); private static final MyListener myListener = new MyListener(); - private static final PropertyChangeWeakSupport propertySupport - = new PropertyChangeWeakSupport(Projects.class); - private static ArrayList openProjects = new ArrayList<>(); + private static final PropertyChangeWeakSupport propertySupport = new PropertyChangeWeakSupport(Projects.class); + private static final ArrayList openProjects = new ArrayList<>(); private static Frame mostRecentFrame = null; private Projects() { } private static void projectRemoved(Project proj, Frame frame, - MyListener listener) { + MyListener listener) { frame.removeWindowListener(listener); openProjects.remove(proj); proj.getSimulator().shutDown(); @@ -43,28 +42,28 @@ private static void projectRemoved(Project proj, Frame frame, } public static Frame getTopFrame() { - Frame ret = mostRecentFrame; - if (ret == null) { + Frame topFrame = mostRecentFrame; + if (topFrame == null) { Frame backup = null; for (Project proj : openProjects) { Frame frame = proj.getFrame(); - if (ret == null) { - ret = frame; + if (topFrame == null) { + topFrame = frame; } - if (ret.isVisible() && (ret.getExtendedState() & Frame.ICONIFIED) != 0) { - backup = ret; + if (topFrame.isVisible() && (topFrame.getExtendedState() & Frame.ICONIFIED) != 0) { + backup = topFrame; } } - if (ret == null) { - ret = backup; + if (topFrame == null) { + topFrame = backup; } } - return ret; + return topFrame; } - static void windowCreated(Project proj, Frame oldFrame, Frame frame) { + static void windowCreated(Project project, Frame oldFrame, Frame frame) { if (oldFrame != null) { - projectRemoved(proj, oldFrame, myListener); + projectRemoved(project, oldFrame, myListener); } if (frame == null) { @@ -73,14 +72,14 @@ static void windowCreated(Project proj, Frame oldFrame, Frame frame) { // locate the window Point lowest = null; - for (Project p : openProjects) { - Frame f = p.getFrame(); - if (f == null) { + for (Project openProject : openProjects) { + Frame projectFrame = openProject.getFrame(); + if (projectFrame == null) { continue; } - Point loc = p.getFrame().getLocation(); - if (lowest == null || loc.y > lowest.y) { - lowest = loc; + Point location = openProject.getFrame().getLocation(); + if (lowest == null || location.y > lowest.y) { + lowest = location; } } if (lowest != null) { @@ -96,8 +95,8 @@ static void windowCreated(Project proj, Frame oldFrame, Frame frame) { frame.setLocation(x, y); } - if (frame.isVisible() && !openProjects.contains(proj)) { - openProjects.add(proj); + if (frame.isVisible() && !openProjects.contains(project)) { + openProjects.add(project); propertySupport.firePropertyChange(projectListProperty, null, null); } frame.addWindowListener(myListener); @@ -169,6 +168,7 @@ public void windowClosing(WindowEvent event) { try { frameLocations.put(frame, frame.getLocationOnScreen()); } catch (Throwable t) { + Logger.debugln(t.getMessage()); } } } @@ -176,10 +176,10 @@ public void windowClosing(WindowEvent event) { @Override public void windowClosed(WindowEvent event) { Frame frame = (Frame) event.getSource(); - Project proj = frame.getProject(); + Project project = frame.getProject(); - if (frame == proj.getFrame()) { - projectRemoved(proj, frame, this); + if (frame == project.getFrame()) { + projectRemoved(project, frame, this); } if (openProjects.isEmpty() && !MacCompatibility.isSwingUsingScreenMenuBar()) { ProjectActions.doQuit(); @@ -189,10 +189,10 @@ public void windowClosed(WindowEvent event) { @Override public void windowOpened(WindowEvent event) { Frame frame = (Frame) event.getSource(); - Project proj = frame.getProject(); + Project project = frame.getProject(); - if (frame == proj.getFrame() && !openProjects.contains(proj)) { - openProjects.add(proj); + if (frame == project.getFrame() && !openProjects.contains(project)) { + openProjects.add(project); propertySupport.firePropertyChange(projectListProperty, null, null); } } diff --git a/src/main/java/com/cburch/logisim/proj/Strings.java b/src/main/java/com/cburch/logisim/proj/Strings.java index ee0846d..d5955cd 100644 --- a/src/main/java/com/cburch/logisim/proj/Strings.java +++ b/src/main/java/com/cburch/logisim/proj/Strings.java @@ -9,8 +9,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "proj"); + private static final LocaleManager source = new LocaleManager("logisim", "proj"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/std/Builtin.java b/src/main/java/com/cburch/logisim/std/Builtin.java index a5689b8..2c6576f 100644 --- a/src/main/java/com/cburch/logisim/std/Builtin.java +++ b/src/main/java/com/cburch/logisim/std/Builtin.java @@ -18,16 +18,16 @@ public class Builtin extends Library { - private List libraries; + private final List libraries; public Builtin() { libraries = Arrays.asList(new Base(), - new Gates(), - new Wiring(), - new Plexers(), - new Arithmetic(), - new Memory(), - new Io()); + new Gates(), + new Wiring(), + new Plexers(), + new Arithmetic(), + new Memory(), + new Io()); } @Override diff --git a/src/main/java/com/cburch/logisim/std/Strings.java b/src/main/java/com/cburch/logisim/std/Strings.java index 43e9354..23c248a 100644 --- a/src/main/java/com/cburch/logisim/std/Strings.java +++ b/src/main/java/com/cburch/logisim/std/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "std"); + private static final LocaleManager source = new LocaleManager("logisim", "std"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/std/arith/Adder.java b/src/main/java/com/cburch/logisim/std/arith/Adder.java index 57f8898..7c7abee 100644 --- a/src/main/java/com/cburch/logisim/std/arith/Adder.java +++ b/src/main/java/com/cburch/logisim/std/arith/Adder.java @@ -32,9 +32,9 @@ public class Adder extends InstanceFactory { public Adder() { super("Adder", Strings.getter("adderComponent")); setAttributes(new Attribute[]{ - StdAttr.WIDTH + StdAttr.WIDTH }, new Object[]{ - BitWidth.create(8) + BitWidth.create(8) }); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setOffsetBounds(Bounds.create(-40, -20, 40, 40)); @@ -67,12 +67,11 @@ static Value[] computeSum(BitWidth bitWidth, Value a, Value b, Value cIn) { long cx = (long) cIn.toIntValue() & mask; long sum = ax + bx + cx; return new Value[]{Value.createKnown(bitWidth, (int) sum), - ((sum >> width) & 1) == 0 ? Value.FALSE : Value.TRUE}; + ((sum >> width) & 1) == 0 ? Value.FALSE : Value.TRUE}; } else { int sum = a.toIntValue() + b.toIntValue() + cIn.toIntValue(); return new Value[]{ - Value.createKnown(bitWidth, sum), - ((sum >> width) & 1) == 0 ? Value.FALSE : Value.TRUE + Value.createKnown(bitWidth, sum), ((sum >> width) & 1) == 0 ? Value.FALSE : Value.TRUE }; } } else { @@ -93,9 +92,7 @@ static Value[] computeSum(BitWidth bitWidth, Value a, Value b, Value cIn) { bits[i] = Value.UNKNOWN; carry = Value.UNKNOWN; } else { - int sum = (ab == Value.TRUE ? 1 : 0) - + (bb == Value.TRUE ? 1 : 0) - + (carry == Value.TRUE ? 1 : 0); + int sum = (ab == Value.TRUE ? 1 : 0) + (bb == Value.TRUE ? 1 : 0) + (carry == Value.TRUE ? 1 : 0); bits[i] = (sum & 1) == 1 ? Value.TRUE : Value.FALSE; carry = (sum >= 2) ? Value.TRUE : Value.FALSE; } diff --git a/src/main/java/com/cburch/logisim/std/arith/Arithmetic.java b/src/main/java/com/cburch/logisim/std/arith/Arithmetic.java index 51f0c22..b401733 100644 --- a/src/main/java/com/cburch/logisim/std/arith/Arithmetic.java +++ b/src/main/java/com/cburch/logisim/std/arith/Arithmetic.java @@ -10,30 +10,31 @@ public class Arithmetic extends Library { - private static FactoryDescription[] DESCRIPTIONS = { - new FactoryDescription("Adder", Strings.getter("adderComponent"), - "adder.gif", "Adder"), - new FactoryDescription("Subtractor", Strings.getter("subtractorComponent"), - "subtractor.gif", "Subtractor"), - new FactoryDescription("Multiplier", Strings.getter("multiplierComponent"), - "multiplier.gif", "Multiplier"), - new FactoryDescription("Divider", Strings.getter("dividerComponent"), - "divider.gif", "Divider"), - new FactoryDescription("Negator", Strings.getter("negatorComponent"), - "negator.gif", "Negator"), - new FactoryDescription("Comparator", Strings.getter("comparatorComponent"), - "comparator.gif", "Comparator"), - new FactoryDescription("Shifter", Strings.getter("shifterComponent"), - "shifter.gif", "Shifter"), - new FactoryDescription("BitAdder", Strings.getter("bitAdderComponent"), - "bitadder.gif", "BitAdder"), - new FactoryDescription("BitFinder", Strings.getter("bitFinderComponent"), - "bitfindr.gif", "BitFinder"), + private static final FactoryDescription[] DESCRIPTIONS = { + new FactoryDescription("Adder", Strings.getter("adderComponent"), + "adder.gif", "Adder"), + new FactoryDescription("Subtractor", Strings.getter("subtractorComponent"), + "subtractor.gif", "Subtractor"), + new FactoryDescription("Multiplier", Strings.getter("multiplierComponent"), + "multiplier.gif", "Multiplier"), + new FactoryDescription("Divider", Strings.getter("dividerComponent"), + "divider.gif", "Divider"), + new FactoryDescription("Negator", Strings.getter("negatorComponent"), + "negator.gif", "Negator"), + new FactoryDescription("Comparator", Strings.getter("comparatorComponent"), + "comparator.gif", "Comparator"), + new FactoryDescription("Shifter", Strings.getter("shifterComponent"), + "shifter.gif", "Shifter"), + new FactoryDescription("BitAdder", Strings.getter("bitAdderComponent"), + "bitadder.gif", "BitAdder"), + new FactoryDescription("BitFinder", Strings.getter("bitFinderComponent"), + "bitfindr.gif", "BitFinder"), }; private List tools = null; - public Arithmetic() { } + public Arithmetic() { + } @Override public String getName() { diff --git a/src/main/java/com/cburch/logisim/std/arith/BitAdder.java b/src/main/java/com/cburch/logisim/std/arith/BitAdder.java index b05aace..12bc1c3 100644 --- a/src/main/java/com/cburch/logisim/std/arith/BitAdder.java +++ b/src/main/java/com/cburch/logisim/std/arith/BitAdder.java @@ -25,18 +25,18 @@ public class BitAdder extends InstanceFactory { static final Attribute NUM_INPUTS - = Attributes.forIntegerRange("inputs", Strings.getter("gateInputsAttr"), 1, 32); + = Attributes.forIntegerRange("inputs", Strings.getter("gateInputsAttr"), 1, 32); public BitAdder() { super("BitAdder", Strings.getter("bitAdderComponent")); setAttributes(new Attribute[]{ - StdAttr.WIDTH, NUM_INPUTS + StdAttr.WIDTH, NUM_INPUTS }, new Object[]{ - BitWidth.create(8), 1 + BitWidth.create(8), 1 }); setKeyConfigurator(JoinedConfigurator.create( - new IntegerConfigurator(NUM_INPUTS, 1, 32, 0), - new BitWidthConfigurator(StdAttr.WIDTH))); + new IntegerConfigurator(NUM_INPUTS, 1, 32, 0), + new BitWidthConfigurator(StdAttr.WIDTH))); setIconName("bitadder.gif"); } diff --git a/src/main/java/com/cburch/logisim/std/arith/BitFinder.java b/src/main/java/com/cburch/logisim/std/arith/BitFinder.java index 3fef628..f717c88 100644 --- a/src/main/java/com/cburch/logisim/std/arith/BitFinder.java +++ b/src/main/java/com/cburch/logisim/std/arith/BitFinder.java @@ -23,23 +23,23 @@ public class BitFinder extends InstanceFactory { static final AttributeOption LOW_ONE - = new AttributeOption("low1", Strings.getter("bitFinderLowOption", "1")); + = new AttributeOption("low1", Strings.getter("bitFinderLowOption", "1")); static final AttributeOption HIGH_ONE - = new AttributeOption("high1", Strings.getter("bitFinderHighOption", "1")); + = new AttributeOption("high1", Strings.getter("bitFinderHighOption", "1")); static final AttributeOption LOW_ZERO - = new AttributeOption("low0", Strings.getter("bitFinderLowOption", "0")); + = new AttributeOption("low0", Strings.getter("bitFinderLowOption", "0")); static final AttributeOption HIGH_ZERO - = new AttributeOption("high0", Strings.getter("bitFinderHighOption", "0")); + = new AttributeOption("high0", Strings.getter("bitFinderHighOption", "0")); static final Attribute TYPE - = Attributes.forOption("type", Strings.getter("bitFinderTypeAttr"), - new AttributeOption[]{LOW_ONE, HIGH_ONE, LOW_ZERO, HIGH_ZERO}); + = Attributes.forOption("type", Strings.getter("bitFinderTypeAttr"), + new AttributeOption[]{LOW_ONE, HIGH_ONE, LOW_ZERO, HIGH_ZERO}); public BitFinder() { super("BitFinder", Strings.getter("bitFinderComponent")); setAttributes(new Attribute[]{ - StdAttr.WIDTH, TYPE + StdAttr.WIDTH, TYPE }, new Object[]{ - BitWidth.create(8), LOW_ONE + BitWidth.create(8), LOW_ONE }); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setIconName("bitfindr.gif"); diff --git a/src/main/java/com/cburch/logisim/std/arith/Comparator.java b/src/main/java/com/cburch/logisim/std/arith/Comparator.java index 649d135..cb81b85 100644 --- a/src/main/java/com/cburch/logisim/std/arith/Comparator.java +++ b/src/main/java/com/cburch/logisim/std/arith/Comparator.java @@ -21,12 +21,12 @@ public class Comparator extends InstanceFactory { private static final AttributeOption SIGNED_OPTION - = new AttributeOption("twosComplement", "twosComplement", Strings.getter("twosComplementOption")); + = new AttributeOption("twosComplement", "twosComplement", Strings.getter("twosComplementOption")); private static final AttributeOption UNSIGNED_OPTION - = new AttributeOption("unsigned", "unsigned", Strings.getter("unsignedOption")); + = new AttributeOption("unsigned", "unsigned", Strings.getter("unsignedOption")); private static final Attribute MODE_ATTRIBUTE - = Attributes.forOption("mode", Strings.getter("comparatorType"), - new AttributeOption[]{SIGNED_OPTION, UNSIGNED_OPTION}); + = Attributes.forOption("mode", Strings.getter("comparatorType"), + new AttributeOption[]{SIGNED_OPTION, UNSIGNED_OPTION}); private static final int IN0 = 0; private static final int IN1 = 1; @@ -36,8 +36,7 @@ public class Comparator extends InstanceFactory { public Comparator() { super("Comparator", Strings.getter("comparatorComponent")); - setAttributes(new Attribute[]{StdAttr.WIDTH, MODE_ATTRIBUTE}, - new Object[]{BitWidth.create(8), SIGNED_OPTION}); + setAttributes(new Attribute[]{StdAttr.WIDTH, MODE_ATTRIBUTE}, new Object[]{BitWidth.create(8), SIGNED_OPTION}); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setOffsetBounds(Bounds.create(-40, -20, 40, 40)); setIconName("comparator.gif"); diff --git a/src/main/java/com/cburch/logisim/std/arith/Divider.java b/src/main/java/com/cburch/logisim/std/arith/Divider.java index 12d7f8c..685cf82 100644 --- a/src/main/java/com/cburch/logisim/std/arith/Divider.java +++ b/src/main/java/com/cburch/logisim/std/arith/Divider.java @@ -31,8 +31,7 @@ public class Divider extends InstanceFactory { public Divider() { super("Divider", Strings.getter("dividerComponent")); - setAttributes(new Attribute[]{StdAttr.WIDTH}, - new Object[]{BitWidth.create(8)}); + setAttributes(new Attribute[]{StdAttr.WIDTH}, new Object[]{BitWidth.create(8)}); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setOffsetBounds(Bounds.create(-40, -20, 40, 40)); setIconName("divider.gif"); @@ -57,8 +56,7 @@ static Value[] computeResult(BitWidth width, Value a, Value b, Value upper) { upper = Value.createKnown(width, 0); } if (a.isFullyDefined() && b.isFullyDefined() && upper.isFullyDefined()) { - long num = ((long) upper.toIntValue() << w) - | ((long) a.toIntValue() & 0xFFFFFFFFL); + long num = ((long) upper.toIntValue() << w) | ((long) a.toIntValue() & 0xFFFFFFFFL); long den = (long) b.toIntValue() & 0xFFFFFFFFL; if (den == 0) { den = 1; @@ -74,8 +72,7 @@ static Value[] computeResult(BitWidth width, Value a, Value b, Value upper) { result++; } } - return new Value[]{Value.createKnown(width, (int) result), - Value.createKnown(width, (int) rem)}; + return new Value[]{Value.createKnown(width, (int) result), Value.createKnown(width, (int) rem)}; } else if (a.isErrorValue() || b.isErrorValue() || upper.isErrorValue()) { return new Value[]{Value.createError(width), Value.createError(width)}; } else { diff --git a/src/main/java/com/cburch/logisim/std/arith/Multiplier.java b/src/main/java/com/cburch/logisim/std/arith/Multiplier.java index 4c986a7..0b00903 100644 --- a/src/main/java/com/cburch/logisim/std/arith/Multiplier.java +++ b/src/main/java/com/cburch/logisim/std/arith/Multiplier.java @@ -31,8 +31,7 @@ public class Multiplier extends InstanceFactory { public Multiplier() { super("Multiplier", Strings.getter("multiplierComponent")); - setAttributes(new Attribute[]{StdAttr.WIDTH}, - new Object[]{BitWidth.create(8)}); + setAttributes(new Attribute[]{StdAttr.WIDTH}, new Object[]{BitWidth.create(8)}); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setOffsetBounds(Bounds.create(-40, -20, 40, 40)); setIconName("multiplier.gif"); @@ -57,23 +56,21 @@ static Value[] computeProduct(BitWidth width, Value a, Value b, Value c_in) { c_in = Value.createKnown(width, 0); } if (a.isFullyDefined() && b.isFullyDefined() && c_in.isFullyDefined()) { - long sum = (long) a.toIntValue() * (long) b.toIntValue() - + (long) c_in.toIntValue(); - return new Value[]{Value.createKnown(width, (int) sum), - Value.createKnown(width, (int) (sum >> w))}; + long sum = (long) a.toIntValue() * (long) b.toIntValue() + (long) c_in.toIntValue(); + return new Value[]{Value.createKnown(width, (int) sum), Value.createKnown(width, (int) (sum >> w))}; } else { - Value[] avals = a.getAll(); - int aOk = findUnknown(avals); - int aErr = findError(avals); - int ax = getKnown(avals); - Value[] bvals = b.getAll(); - int bOk = findUnknown(bvals); - int bErr = findError(bvals); - int bx = getKnown(bvals); - Value[] cvals = c_in.getAll(); - int cOk = findUnknown(cvals); - int cErr = findError(cvals); - int cx = getKnown(cvals); + Value[] aValues = a.getAll(); + int aOk = findUnknown(aValues); + int aErr = findError(aValues); + int ax = getKnown(aValues); + Value[] bValues = b.getAll(); + int bOk = findUnknown(bValues); + int bErr = findError(bValues); + int bx = getKnown(bValues); + Value[] cValues = c_in.getAll(); + int cOk = findUnknown(cValues); + int cErr = findError(cValues); + int cx = getKnown(cValues); int known = Math.min(Math.min(aOk, bOk), cOk); int error = Math.min(Math.min(aErr, bErr), cErr); @@ -90,32 +87,32 @@ static Value[] computeProduct(BitWidth width, Value a, Value b, Value c_in) { } } return new Value[]{Value.create(bits), - error < w ? Value.createError(width) : Value.createUnknown(width)}; + error < w ? Value.createError(width) : Value.createUnknown(width)}; } } - private static int findUnknown(Value[] vals) { - for (int i = 0; i < vals.length; i++) { - if (!vals[i].isFullyDefined()) { + private static int findUnknown(Value[] values) { + for (int i = 0; i < values.length; i++) { + if (!values[i].isFullyDefined()) { return i; } } - return vals.length; + return values.length; } - private static int findError(Value[] vals) { - for (int i = 0; i < vals.length; i++) { - if (vals[i].isErrorValue()) { + private static int findError(Value[] values) { + for (int i = 0; i < values.length; i++) { + if (values[i].isErrorValue()) { return i; } } - return vals.length; + return values.length; } - private static int getKnown(Value[] vals) { + private static int getKnown(Value[] values) { int ret = 0; - for (int i = 0; i < vals.length; i++) { - int val = vals[i].toIntValue(); + for (int i = 0; i < values.length; i++) { + int val = values[i].toIntValue(); if (val < 0) { return ret; } @@ -153,9 +150,9 @@ public void paintInstance(InstancePainter painter) { painter.drawPort(C_IN, "c in", Direction.NORTH); painter.drawPort(C_OUT, "c out", Direction.SOUTH); - Location loc = painter.getLocation(); - int x = loc.getX(); - int y = loc.getY(); + Location location = painter.getLocation(); + int x = location.getX(); + int y = location.getY(); GraphicsUtil.switchToWidth(g, 2); g.setColor(Color.BLACK); g.drawLine(x - 15, y - 5, x - 5, y + 5); diff --git a/src/main/java/com/cburch/logisim/std/arith/Negator.java b/src/main/java/com/cburch/logisim/std/arith/Negator.java index e7f4322..5dd84f2 100644 --- a/src/main/java/com/cburch/logisim/std/arith/Negator.java +++ b/src/main/java/com/cburch/logisim/std/arith/Negator.java @@ -22,8 +22,7 @@ public class Negator extends InstanceFactory { public Negator() { super("Negator", Strings.getter("negatorComponent")); - setAttributes(new Attribute[]{StdAttr.WIDTH}, - new Object[]{BitWidth.create(8)}); + setAttributes(new Attribute[]{StdAttr.WIDTH}, new Object[]{BitWidth.create(8)}); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setOffsetBounds(Bounds.create(-40, -20, 40, 40)); setIconName("negator.gif"); diff --git a/src/main/java/com/cburch/logisim/std/arith/Shifter.java b/src/main/java/com/cburch/logisim/std/arith/Shifter.java index 140a3e3..72a08cd 100644 --- a/src/main/java/com/cburch/logisim/std/arith/Shifter.java +++ b/src/main/java/com/cburch/logisim/std/arith/Shifter.java @@ -24,19 +24,19 @@ public class Shifter extends InstanceFactory { static final AttributeOption SHIFT_LOGICAL_LEFT - = new AttributeOption("ll", Strings.getter("shiftLogicalLeft")); + = new AttributeOption("ll", Strings.getter("shiftLogicalLeft")); static final AttributeOption SHIFT_LOGICAL_RIGHT - = new AttributeOption("lr", Strings.getter("shiftLogicalRight")); + = new AttributeOption("lr", Strings.getter("shiftLogicalRight")); static final AttributeOption SHIFT_ARITHMETIC_RIGHT - = new AttributeOption("ar", Strings.getter("shiftArithmeticRight")); + = new AttributeOption("ar", Strings.getter("shiftArithmeticRight")); static final AttributeOption SHIFT_ROLL_LEFT - = new AttributeOption("rl", Strings.getter("shiftRollLeft")); + = new AttributeOption("rl", Strings.getter("shiftRollLeft")); static final AttributeOption SHIFT_ROLL_RIGHT - = new AttributeOption("rr", Strings.getter("shiftRollRight")); + = new AttributeOption("rr", Strings.getter("shiftRollRight")); static final Attribute ATTR_SHIFT - = Attributes.forOption("shift", Strings.getter("shifterShiftAttr"), - new AttributeOption[]{SHIFT_LOGICAL_LEFT, SHIFT_LOGICAL_RIGHT, - SHIFT_ARITHMETIC_RIGHT, SHIFT_ROLL_LEFT, SHIFT_ROLL_RIGHT}); + = Attributes.forOption("shift", Strings.getter("shifterShiftAttr"), + new AttributeOption[]{SHIFT_LOGICAL_LEFT, SHIFT_LOGICAL_RIGHT, + SHIFT_ARITHMETIC_RIGHT, SHIFT_ROLL_LEFT, SHIFT_ROLL_RIGHT}); private static final int IN0 = 0; private static final int IN1 = 1; @@ -45,9 +45,9 @@ public class Shifter extends InstanceFactory { public Shifter() { super("Shifter", Strings.getter("shifterComponent")); setAttributes(new Attribute[]{ - StdAttr.WIDTH, ATTR_SHIFT + StdAttr.WIDTH, ATTR_SHIFT }, new Object[]{ - BitWidth.create(8), SHIFT_LOGICAL_LEFT + BitWidth.create(8), SHIFT_LOGICAL_LEFT }); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setOffsetBounds(Bounds.create(-40, -20, 40, 40)); diff --git a/src/main/java/com/cburch/logisim/std/arith/Strings.java b/src/main/java/com/cburch/logisim/std/arith/Strings.java index fb02f60..02c4643 100644 --- a/src/main/java/com/cburch/logisim/std/arith/Strings.java +++ b/src/main/java/com/cburch/logisim/std/arith/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "std"); + private static final LocaleManager source = new LocaleManager("logisim", "std"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/std/arith/Subtractor.java b/src/main/java/com/cburch/logisim/std/arith/Subtractor.java index 09b8198..c718ca6 100644 --- a/src/main/java/com/cburch/logisim/std/arith/Subtractor.java +++ b/src/main/java/com/cburch/logisim/std/arith/Subtractor.java @@ -29,8 +29,7 @@ public class Subtractor extends InstanceFactory { public Subtractor() { super("Subtractor", Strings.getter("subtractorComponent")); - setAttributes(new Attribute[]{StdAttr.WIDTH}, - new Object[]{BitWidth.create(8)}); + setAttributes(new Attribute[]{StdAttr.WIDTH}, new Object[]{BitWidth.create(8)}); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setOffsetBounds(Bounds.create(-40, -20, 40, 40)); setIconName("subtractor.gif"); @@ -57,11 +56,11 @@ public void propagate(InstanceState state) { // compute outputs Value a = state.getPort(IN0); Value b = state.getPort(IN1); - Value b_in = state.getPort(B_IN); - if (b_in == Value.UNKNOWN || b_in == Value.NIL) { - b_in = Value.FALSE; + Value bIn = state.getPort(B_IN); + if (bIn == Value.UNKNOWN || bIn == Value.NIL) { + bIn = Value.FALSE; } - Value[] outs = Adder.computeSum(data, a, b.not(), b_in.not()); + Value[] outs = Adder.computeSum(data, a, b.not(), bIn.not()); // propagate them int delay = (data.getWidth() + 4) * Adder.PER_DELAY; @@ -81,9 +80,9 @@ public void paintInstance(InstancePainter painter) { painter.drawPort(B_IN, "b in", Direction.NORTH); painter.drawPort(B_OUT, "b out", Direction.SOUTH); - Location loc = painter.getLocation(); - int x = loc.getX(); - int y = loc.getY(); + Location location = painter.getLocation(); + int x = location.getX(); + int y = location.getY(); GraphicsUtil.switchToWidth(g, 2); g.setColor(Color.BLACK); g.drawLine(x - 15, y, x - 5, y); diff --git a/src/main/java/com/cburch/logisim/std/base/Base.java b/src/main/java/com/cburch/logisim/std/base/Base.java index a774f64..3de15f2 100644 --- a/src/main/java/com/cburch/logisim/std/base/Base.java +++ b/src/main/java/com/cburch/logisim/std/base/Base.java @@ -17,19 +17,19 @@ public class Base extends Library { - private List tools; + private final List tools; public Base() { SelectTool select = new SelectTool(); WiringTool wiring = new WiringTool(); tools = Arrays.asList(new PokeTool(), - new EditTool(select, wiring), - select, - wiring, - new TextTool(), - new MenuTool(), - new AddTool(Text.FACTORY)); + new EditTool(select, wiring), + select, + wiring, + new TextTool(), + new MenuTool(), + new AddTool(Text.FACTORY)); } @Override diff --git a/src/main/java/com/cburch/logisim/std/base/Strings.java b/src/main/java/com/cburch/logisim/std/base/Strings.java index 91f7d0c..30fc44f 100644 --- a/src/main/java/com/cburch/logisim/std/base/Strings.java +++ b/src/main/java/com/cburch/logisim/std/base/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "std"); + private static final LocaleManager source = new LocaleManager("logisim", "std"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/std/base/Text.java b/src/main/java/com/cburch/logisim/std/base/Text.java index 3924fc5..d432ae8 100644 --- a/src/main/java/com/cburch/logisim/std/base/Text.java +++ b/src/main/java/com/cburch/logisim/std/base/Text.java @@ -24,29 +24,29 @@ public class Text extends InstanceFactory { public static final Text FACTORY = new Text(); public static Attribute ATTR_TEXT = Attributes.forString("text", - Strings.getter("textTextAttr")); + Strings.getter("textTextAttr")); public static Attribute ATTR_FONT = Attributes.forFont("font", - Strings.getter("textFontAttr")); + Strings.getter("textFontAttr")); public static Attribute ATTR_HALIGN = Attributes.forOption("halign", - Strings.getter("textHorzAlignAttr"), new AttributeOption[]{ - new AttributeOption(TextField.H_LEFT, - "left", Strings.getter("textHorzAlignLeftOpt")), - new AttributeOption(TextField.H_RIGHT, - "right", Strings.getter("textHorzAlignRightOpt")), - new AttributeOption(TextField.H_CENTER, - "center", Strings.getter("textHorzAlignCenterOpt")), - }); + Strings.getter("textHorzAlignAttr"), new AttributeOption[]{ + new AttributeOption(TextField.H_LEFT, + "left", Strings.getter("textHorzAlignLeftOpt")), + new AttributeOption(TextField.H_RIGHT, + "right", Strings.getter("textHorzAlignRightOpt")), + new AttributeOption(TextField.H_CENTER, + "center", Strings.getter("textHorzAlignCenterOpt")), + }); public static Attribute ATTR_VALIGN = Attributes.forOption("valign", - Strings.getter("textVertAlignAttr"), new AttributeOption[]{ - new AttributeOption(TextField.V_TOP, - "top", Strings.getter("textVertAlignTopOpt")), - new AttributeOption(TextField.V_BASELINE, - "base", Strings.getter("textVertAlignBaseOpt")), - new AttributeOption(TextField.V_BOTTOM, - "bottom", Strings.getter("textVertAlignBottomOpt")), - new AttributeOption(TextField.H_CENTER, - "center", Strings.getter("textVertAlignCenterOpt")), - }); + Strings.getter("textVertAlignAttr"), new AttributeOption[]{ + new AttributeOption(TextField.V_TOP, + "top", Strings.getter("textVertAlignTopOpt")), + new AttributeOption(TextField.V_BASELINE, + "base", Strings.getter("textVertAlignBaseOpt")), + new AttributeOption(TextField.V_BOTTOM, + "bottom", Strings.getter("textVertAlignBottomOpt")), + new AttributeOption(TextField.H_CENTER, + "center", Strings.getter("textVertAlignCenterOpt")), + }); private Text() { super("Text", Strings.getter("textComponent")); @@ -129,7 +129,7 @@ public void paintGhost(InstancePainter painter) { newBds = Bounds.EMPTY_BOUNDS; } else { Rectangle bdsOut = GraphicsUtil.getTextBounds(g, textTrim, 0, 0, - halign, valign); + halign, valign); newBds = Bounds.create(bdsOut).expand(4); } if (attrs.setOffsetBounds(newBds)) { @@ -174,7 +174,7 @@ private void configureLabel(Instance instance) { TextAttributes attrs = (TextAttributes) instance.getAttributeSet(); Location loc = instance.getLocation(); instance.setTextField(ATTR_TEXT, ATTR_FONT, loc.getX(), loc.getY(), - attrs.getHorizontalAlign(), attrs.getVerticalAlign()); + attrs.getHorizontalAlign(), attrs.getVerticalAlign()); } @Override diff --git a/src/main/java/com/cburch/logisim/std/base/TextAttributes.java b/src/main/java/com/cburch/logisim/std/base/TextAttributes.java index a5f97c8..a79ad67 100644 --- a/src/main/java/com/cburch/logisim/std/base/TextAttributes.java +++ b/src/main/java/com/cburch/logisim/std/base/TextAttributes.java @@ -15,19 +15,19 @@ class TextAttributes extends AbstractAttributeSet { private static final List> ATTRIBUTES - = Arrays.asList(Text.ATTR_TEXT, Text.ATTR_FONT, Text.ATTR_HALIGN, Text.ATTR_VALIGN); + = Arrays.asList(Text.ATTR_TEXT, Text.ATTR_FONT, Text.ATTR_HALIGN, Text.ATTR_VALIGN); private String text; private Font font; - private AttributeOption halign; - private AttributeOption valign; + private AttributeOption hAlign; + private AttributeOption vAlign; private Bounds offsetBounds; public TextAttributes() { text = ""; font = StdAttr.DEFAULT_LABEL_FONT; - halign = Text.ATTR_HALIGN.parse("center"); - valign = Text.ATTR_VALIGN.parse("base"); + hAlign = Text.ATTR_HALIGN.parse("center"); + vAlign = Text.ATTR_VALIGN.parse("base"); offsetBounds = null; } @@ -40,11 +40,11 @@ Font getFont() { } int getHorizontalAlign() { - return (Integer) halign.getValue(); + return (Integer) hAlign.getValue(); } int getVerticalAlign() { - return (Integer) valign.getValue(); + return (Integer) vAlign.getValue(); } Bounds getOffsetBounds() { @@ -80,10 +80,10 @@ public V getValue(Attribute attr) { return (V) font; } if (attr == Text.ATTR_HALIGN) { - return (V) halign; + return (V) hAlign; } if (attr == Text.ATTR_VALIGN) { - return (V) valign; + return (V) vAlign; } return null; } @@ -95,9 +95,9 @@ public void setValue(Attribute attr, V value) { } else if (attr == Text.ATTR_FONT) { font = (Font) value; } else if (attr == Text.ATTR_HALIGN) { - halign = (AttributeOption) value; + hAlign = (AttributeOption) value; } else if (attr == Text.ATTR_VALIGN) { - valign = (AttributeOption) value; + vAlign = (AttributeOption) value; } else { throw new IllegalArgumentException("unknown attribute"); } diff --git a/src/main/java/com/cburch/logisim/std/gates/AbstractGate.java b/src/main/java/com/cburch/logisim/std/gates/AbstractGate.java index 6739a6a..ef4e0b6 100644 --- a/src/main/java/com/cburch/logisim/std/gates/AbstractGate.java +++ b/src/main/java/com/cburch/logisim/std/gates/AbstractGate.java @@ -38,8 +38,8 @@ abstract class AbstractGate extends InstanceFactory { - private String[] iconNames = new String[3]; - private Icon[] icons = new Icon[3]; + private final String[] iconNames = new String[3]; + private final Icon[] icons = new Icon[3]; private int bonusWidth = 0; private boolean negateOutput = false; private boolean isXor = false; @@ -55,9 +55,8 @@ protected AbstractGate(String name, StringGetter desc, boolean isXor) { this.isXor = isXor; setFacingAttribute(StdAttr.FACING); setKeyConfigurator(JoinedConfigurator.create( - new IntegerConfigurator(GateAttributes.ATTR_INPUTS, 2, - GateAttributes.MAX_INPUTS, 0), - new BitWidthConfigurator(StdAttr.WIDTH))); + new IntegerConfigurator(GateAttributes.ATTR_INPUTS, 2, GateAttributes.MAX_INPUTS, 0), + new BitWidthConfigurator(StdAttr.WIDTH))); } static Value pullOutput(Value value, Object outType) { @@ -131,18 +130,18 @@ public boolean contains(Location location, AttributeSet attributeSet) { return true; } else { Direction facing = attrs.facing; - Bounds bds = getOffsetBounds(attributeSet); - int delt; + Bounds bounds = getOffsetBounds(attributeSet); + int delta; if (facing == Direction.NORTH) { - delt = location.getY() - (bds.getY() + bds.getHeight()); + delta = location.getY() - (bounds.getY() + bounds.getHeight()); } else if (facing == Direction.SOUTH) { - delt = location.getY() - bds.getY(); + delta = location.getY() - bounds.getY(); } else if (facing == Direction.WEST) { - delt = location.getX() - (bds.getX() + bds.getHeight()); + delta = location.getX() - (bounds.getX() + bounds.getHeight()); } else { - delt = location.getX() - bds.getX(); + delta = location.getX() - bounds.getX(); } - if (Math.abs(delt) > 5) { + if (Math.abs(delta) > 5) { return true; } else { int inputs = attrs.inputs; @@ -183,10 +182,10 @@ private void paintBase(InstancePainter painter) { int negated = attrs.negated; Object shape = painter.getGateShape(); - Location loc = painter.getLocation(); - Bounds bds = painter.getOffsetBounds(); - int width = bds.getWidth(); - int height = bds.getHeight(); + Location location = painter.getLocation(); + Bounds bounds = painter.getOffsetBounds(); + int width = bounds.getWidth(); + int height = bounds.getHeight(); if (facing == Direction.NORTH || facing == Direction.SOUTH) { int t = width; width = height; @@ -206,14 +205,14 @@ private void paintBase(InstancePainter painter) { if (negatedBit == 1) { Location in = getInputOffset(attrs, i); Location cen = in.translate(facing, 5); - painter.drawDongle(loc.getX() + cen.getX(), - loc.getY() + cen.getY()); + painter.drawDongle(location.getX() + cen.getX(), + location.getY() + cen.getY()); } } } g.setColor(baseColor); - g.translate(loc.getX(), loc.getY()); + g.translate(location.getX(), location.getY()); double rotate = 0.0; if (facing != Direction.EAST && g instanceof Graphics2D) { rotate = -facing.toRadians(); @@ -239,7 +238,7 @@ private void paintBase(InstancePainter painter) { if (rotate != 0.0) { ((Graphics2D) g).rotate(-rotate); } - g.translate(-loc.getX(), -loc.getY()); + g.translate(-location.getX(), -location.getY()); painter.drawLabel(); } @@ -255,21 +254,21 @@ protected void setIconNames(String shaped, String rect, String din) { } private Icon getIcon(int type) { - Icon ret = icons[type]; - if (ret != null) { - return ret; + Icon icon = icons[type]; + if (icon != null) { + return icon; } else { String iconName = iconNames[type]; if (iconName == null) { return null; } else { - ret = Icons.getIcon(iconName); - if (ret == null) { + icon = Icons.getIcon(iconName); + if (icon == null) { iconNames[type] = null; } else { - icons[type] = ret; + icons[type] = icon; } - return ret; + return icon; } } } @@ -351,28 +350,23 @@ protected String getRectangularLabel(AttributeSet attrs) { // protected abstract Value getIdentity(); - protected abstract void paintShape(InstancePainter painter, - int width, int height); + protected abstract void paintShape(InstancePainter painter, int width, int height); - protected void paintRectangular(InstancePainter painter, - int width, int height) { + protected void paintRectangular(InstancePainter painter, int width, int height) { int don = negateOutput ? 10 : 0; AttributeSet attrs = painter.getAttributeSet(); painter.drawRectangle(-width, -height / 2, width - don, height, - getRectangularLabel(attrs)); + getRectangularLabel(attrs)); if (negateOutput) { painter.drawDongle(-5, 0); } } - protected abstract void paintDinShape(InstancePainter painter, - int width, int height, int inputs); + protected abstract void paintDinShape(InstancePainter painter, int width, int height, int inputs); - protected abstract Value computeOutput(Value[] inputs, int numInputs, - InstanceState state); + protected abstract Value computeOutput(Value[] inputs, int numInputs, InstanceState state); - protected abstract Expression computeExpression(Expression[] inputs, - int numInputs); + protected abstract Expression computeExpression(Expression[] inputs, int numInputs); protected boolean shouldRepairWire(Instance instance, WireRepairData data) { return false; @@ -394,8 +388,7 @@ protected void instanceAttributeChanged(Instance instance, Attribute attribut instance.recomputeBounds(); computePorts(instance); computeLabel(instance); - } else if (attribute == GateAttributes.ATTR_INPUTS - || attribute instanceof NegateAttribute) { + } else if (attribute == GateAttributes.ATTR_INPUTS || attribute instanceof NegateAttribute) { instance.recomputeBounds(); computePorts(instance); } else if (attribute == GateAttributes.ATTRIBUTE_XOR) { @@ -429,8 +422,7 @@ private void computeLabel(Instance instance) { cx = loc.getX() - axis; cy = loc.getY() + perp; } - instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, cx, cy, - TextField.H_CENTER, TextField.V_CENTER); + instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, cx, cy, TextField.H_CENTER, TextField.V_CENTER); } void computePorts(Instance instance) { @@ -452,8 +444,7 @@ public void propagate(InstanceState state) { int inputCount = attrs.inputs; int negated = attrs.negated; AttributeSet opts = state.getProject().getOptions().getAttributeSet(); - boolean errorIfUndefined = opts.getValue(Options.ATTR_GATE_UNDEFINED) - .equals(Options.GATE_UNDEFINED_ERROR); + boolean errorIfUndefined = opts.getValue(Options.ATTR_GATE_UNDEFINED).equals(Options.GATE_UNDEFINED_ERROR); Value[] inputs = new Value[inputCount]; int numInputs = 0; @@ -502,13 +493,13 @@ public void computeExpression(Map expressionMap) { Expression[] inputs = new Expression[inputCount]; int numInputs = 0; for (int i = 1; i <= inputCount; i++) { - Expression e = expressionMap.get(instance.getPortLocation(i)); - if (e != null) { + Expression expression = expressionMap.get(instance.getPortLocation(i)); + if (expression != null) { int negatedBit = (negated >> (i - 1)) & 1; if (negatedBit == 1) { - e = Expressions.not(e); + expression = Expressions.not(expression); } - inputs[numInputs] = e; + inputs[numInputs] = expression; ++numInputs; } } diff --git a/src/main/java/com/cburch/logisim/std/gates/AndGate.java b/src/main/java/com/cburch/logisim/std/gates/AndGate.java index e729c76..ef72171 100644 --- a/src/main/java/com/cburch/logisim/std/gates/AndGate.java +++ b/src/main/java/com/cburch/logisim/std/gates/AndGate.java @@ -42,7 +42,7 @@ protected void paintDinShape(InstancePainter painter, int width, int height, int @Override protected Value computeOutput(Value[] inputs, int numInputs, - InstanceState state) { + InstanceState state) { return GateFunctions.computeAnd(inputs, numInputs); } diff --git a/src/main/java/com/cburch/logisim/std/gates/Buffer.java b/src/main/java/com/cburch/logisim/std/gates/Buffer.java index 2bc53d8..4c53c90 100644 --- a/src/main/java/com/cburch/logisim/std/gates/Buffer.java +++ b/src/main/java/com/cburch/logisim/std/gates/Buffer.java @@ -33,16 +33,27 @@ class Buffer extends InstanceFactory { private Buffer() { super("Buffer", Strings.getter("bufferComponent")); - setAttributes(new Attribute[]{StdAttr.FACING, StdAttr.WIDTH, - GateAttributes.ATTRIBUTE_OUTPUT, StdAttr.LABEL, StdAttr.LABEL_FONT}, - new Object[]{Direction.EAST, BitWidth.ONE, - GateAttributes.OUTPUT_01, "", StdAttr.DEFAULT_LABEL_FONT}); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + StdAttr.WIDTH, + GateAttributes.ATTRIBUTE_OUTPUT, + StdAttr.LABEL, + StdAttr.LABEL_FONT + }, new Object[]{ + Direction.EAST, + BitWidth.ONE, + GateAttributes.OUTPUT_01, + "", + StdAttr.DEFAULT_LABEL_FONT + } + ); setIcon(Icons.getIcon("bufferGate.gif")); setFacingAttribute(StdAttr.FACING); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setPorts(new Port[]{ - new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH), - new Port(0, -20, Port.INPUT, StdAttr.WIDTH), + new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH), + new Port(0, -20, Port.INPUT, StdAttr.WIDTH), }); } @@ -92,9 +103,9 @@ public Bounds getOffsetBounds(AttributeSet attributes) { @Override public void propagate(InstanceState state) { - Value in = state.getPort(1); - in = Buffer.repair(state, in); - state.setPort(0, in, GateAttributes.DELAY); + Value value = state.getPort(1); + value = Buffer.repair(state, value); + state.setPort(0, value, GateAttributes.DELAY); } // @@ -160,9 +171,9 @@ public void paintInstance(InstancePainter painter) { private void paintBase(InstancePainter painter) { Direction facing = painter.getAttributeValue(StdAttr.FACING); - Location loc = painter.getLocation(); - int x = loc.getX(); - int y = loc.getY(); + Location location = painter.getLocation(); + int x = location.getX(); + int y = location.getY(); Graphics g = painter.getGraphics(); g.translate(x, y); double rotate = 0.0; diff --git a/src/main/java/com/cburch/logisim/std/gates/CircuitBuilder.java b/src/main/java/com/cburch/logisim/std/gates/CircuitBuilder.java index 0344a72..040a651 100644 --- a/src/main/java/com/cburch/logisim/std/gates/CircuitBuilder.java +++ b/src/main/java/com/cburch/logisim/std/gates/CircuitBuilder.java @@ -29,8 +29,7 @@ public class CircuitBuilder { private CircuitBuilder() { } - public static CircuitMutation build(Circuit destCirc, AnalyzerModel model, - boolean twoInputs, boolean useNands) { + public static CircuitMutation build(Circuit destCirc, AnalyzerModel model, boolean twoInputs, boolean useNands) { CircuitMutation result = new CircuitMutation(destCirc); result.clear(); @@ -86,28 +85,25 @@ public static CircuitMutation build(Circuit destCirc, AnalyzerModel model, // // layoutGates // - private static Layout layoutGates(CircuitDetermination det) { - return layoutGatesSub(det); + private static Layout layoutGates(CircuitDetermination determination) { + return layoutGatesSub(determination); } - private static Layout layoutGatesSub(CircuitDetermination det) { - if (det instanceof CircuitDetermination.Input) { - CircuitDetermination.Input input = (CircuitDetermination.Input) det; + private static Layout layoutGatesSub(CircuitDetermination determination) { + if (determination instanceof CircuitDetermination.Input) { + CircuitDetermination.Input input = (CircuitDetermination.Input) determination; return new Layout(input.getName()); - } else if (det instanceof CircuitDetermination.Value) { - CircuitDetermination.Value value = (CircuitDetermination.Value) det; + } else if (determination instanceof CircuitDetermination.Value) { + CircuitDetermination.Value value = (CircuitDetermination.Value) determination; ComponentFactory factory = Constant.FACTORY; AttributeSet attrs = factory.createAttributeSet(); - attrs.setValue(Constant.ATTRIBUTE_VALUE, - value.getValue()); + attrs.setValue(Constant.ATTRIBUTE_VALUE, value.getValue()); Bounds bds = factory.getOffsetBounds(attrs); - return new Layout(bds.getWidth(), bds.getHeight(), - -bds.getY(), factory, attrs, - new Layout[0], 0); + return new Layout(bds.getWidth(), bds.getHeight(), -bds.getY(), factory, attrs, new Layout[0], 0); } // We know det is a Gate. Determine sublayouts. - CircuitDetermination.Gate gate = (CircuitDetermination.Gate) det; + CircuitDetermination.Gate gate = (CircuitDetermination.Gate) determination; ComponentFactory factory = gate.getFactory(); ArrayList inputs = gate.getInputs(); @@ -150,25 +146,25 @@ private static Layout layoutGatesSub(CircuitDetermination det) { // ok; create and return the layout. return new Layout(width, height, outputY, factory, attrs, - sub, sub[0].width); + sub, sub[0].width); } } - Layout[] sub = new Layout[inputs.size()]; + Layout[] layouts = new Layout[inputs.size()]; int subWidth = 0; // maximum width of sublayouts int subHeight = 0; // total height of sublayouts - for (int i = 0; i < sub.length; i++) { - sub[i] = layoutGatesSub(inputs.get(i)); - if (sub.length % 2 == 0 && i == (sub.length + 1) / 2 - && sub[i - 1].height + sub[i].height == 0) { + for (int i = 0; i < layouts.length; i++) { + layouts[i] = layoutGatesSub(inputs.get(i)); + if (layouts.length % 2 == 0 && i == (layouts.length + 1) / 2 + && layouts[i - 1].height + layouts[i].height == 0) { // if there are an even number of inputs, then there is a // 20-tall gap between the middle two inputs. Ensure the two // middle inputs are at least 20 pixels apart. subHeight += 10; } - sub[i].y = subHeight; - subWidth = Math.max(subWidth, sub[i].width); - subHeight += sub[i].height + 10; + layouts[i].y = subHeight; + subWidth = Math.max(subWidth, layouts[i].width); + subHeight += layouts[i].height + 10; } subHeight -= 10; @@ -178,14 +174,14 @@ private static Layout layoutGatesSub(CircuitDetermination det) { } else { attrs.setValue(GateAttributes.ATTR_SIZE, GateAttributes.SIZE_NARROW); - int ins = sub.length; + int ins = layouts.length; attrs.setValue(GateAttributes.ATTR_INPUTS, ins); } // determine layout's width Bounds bds = factory.getOffsetBounds(attrs); - int betweenWidth = 40 + 10 * (sub.length / 2 - 1); - if (sub.length == 1) { + int betweenWidth = 40 + 10 * (layouts.length / 2 - 1); + if (layouts.length == 1) { betweenWidth = 20; } if (subWidth == 0) { @@ -195,14 +191,14 @@ private static Layout layoutGatesSub(CircuitDetermination det) { // determine outputY and layout's height. int outputY; - if (sub.length % 2 == 1) { // odd number - match the middle input - int i = (sub.length - 1) / 2; - outputY = sub[i].y + sub[i].outputY; + if (layouts.length % 2 == 1) { // odd number - match the middle input + int i = (layouts.length - 1) / 2; + outputY = layouts[i].y + layouts[i].outputY; } else { // even number - halfway between middle two inputs - int i0 = (sub.length / 2) - 1; - int i1 = (sub.length / 2); - int o0 = sub[i0].y + sub[i0].outputY; - int o1 = sub[i1].y + sub[i1].outputY; + int i0 = (layouts.length / 2) - 1; + int i1 = (layouts.length / 2); + int o0 = layouts[i0].y + layouts[i0].outputY; + int o1 = layouts[i1].y + layouts[i1].outputY; outputY = roundDown((o0 + o1) / 2); } int height = subHeight; @@ -211,8 +207,8 @@ private static Layout layoutGatesSub(CircuitDetermination det) { // we have to shift everything down because otherwise // the component will peek over the rectangle's top. int dy = minOutputY - outputY; - for (int i = 0; i < sub.length; i++) { - sub[i].y += dy; + for (Layout layout : layouts) { + layout.y += dy; } height += dy; outputY += dy; @@ -223,8 +219,7 @@ private static Layout layoutGatesSub(CircuitDetermination det) { } // ok; create and return the layout. - return new Layout(width, height, outputY, factory, attrs, - sub, subWidth); + return new Layout(width, height, outputY, factory, attrs, layouts, subWidth); } private static int roundDown(int value) { @@ -261,9 +256,8 @@ private static InputData computeInputData(AnalyzerModel model) { * @param inputData information about how to reach inputs. * @param output a point to which the output should be connected. */ - private static void placeComponents(CircuitMutation circuit, - Layout layout, int x, int y, InputData inputData, - Location output) { + private static void placeComponents(CircuitMutation circuit, Layout layout, int x, int y, InputData inputData, + Location output) { if (layout.inputName != null) { int inputX = inputData.getSpineX(layout.inputName); Location input = Location.create(inputX, output.getY()); @@ -273,16 +267,14 @@ private static void placeComponents(CircuitMutation circuit, } Location compOutput = Location.create(x + layout.width, output.getY()); - Component parent = layout.factory.createComponent(compOutput, - layout.attrs); + Component parent = layout.factory.createComponent(compOutput, layout.attrs); circuit.add(parent); if (!compOutput.equals(output)) { circuit.add(Wire.create(compOutput, output)); } // handle a NOT gate pattern implemented with NAND as a special case - if (layout.factory == NandGate.FACTORY && layout.subLayouts.length == 1 - && layout.subLayouts[0].inputName == null) { + if (layout.factory == NandGate.FACTORY && layout.subLayouts.length == 1 && layout.subLayouts[0].inputName == null) { Layout sub = layout.subLayouts[0]; Location input0 = parent.getEnd(1).getLocation(); @@ -324,8 +316,7 @@ private static void placeComponents(CircuitMutation circuit, int subOutputY = y + sub.y + sub.outputY; if (sub.inputName != null) { int destY = subDest.getY(); - if (i == 0 && destY < subOutputY - || i == layout.subLayouts.length - 1 && destY > subOutputY) { + if (i == 0 && destY < subOutputY || i == layout.subLayouts.length - 1 && destY > subOutputY) { subOutputY = destY; } } @@ -469,9 +460,8 @@ private static class Layout { Layout[] subLayouts; String inputName; // for references directly to inputs - Layout(int width, int height, int outputY, - ComponentFactory factory, AttributeSet attrs, - Layout[] subLayouts, int subX) { + Layout(int width, int height, int outputY, ComponentFactory factory, AttributeSet attrs, Layout[] subLayouts, + int subX) { this.width = width; this.height = roundUp(height); this.outputY = outputY; diff --git a/src/main/java/com/cburch/logisim/std/gates/CircuitDetermination.java b/src/main/java/com/cburch/logisim/std/gates/CircuitDetermination.java index cd3e67d..20593b6 100644 --- a/src/main/java/com/cburch/logisim/std/gates/CircuitDetermination.java +++ b/src/main/java/com/cburch/logisim/std/gates/CircuitDetermination.java @@ -59,8 +59,7 @@ boolean isNandNot() { static class Gate extends CircuitDetermination { private ComponentFactory factory; - private ArrayList inputs - = new ArrayList<>(); + private ArrayList inputs = new ArrayList<>(); private Gate(ComponentFactory factory) { this.factory = factory; @@ -99,8 +98,7 @@ void convertToTwoInputs() { } } - private CircuitDetermination convertToTwoInputsSub(int start, int stop, - ComponentFactory subFactory) { + private CircuitDetermination convertToTwoInputsSub(int start, int stop, ComponentFactory subFactory) { if (stop - start == 1) { CircuitDetermination a = inputs.get(start); a.convertToTwoInputs(); @@ -134,6 +132,7 @@ void convertToNands() { notAllInputs(); // the order of these two lines is significant notOutput(); } else if (factory == NandGate.FACTORY) { + // Ok? } else { throw new IllegalArgumentException("Cannot handle " + factory.getDisplayName()); } @@ -164,8 +163,7 @@ private void notAllInputs() { @Override boolean isNandNot() { - return factory == NandGate.FACTORY - && inputs.size() == 2 && inputs.get(0) == inputs.get(1); + return factory == NandGate.FACTORY && inputs.size() == 2 && inputs.get(0) == inputs.get(1); } @Override @@ -217,7 +215,7 @@ void repair() { static class Input extends CircuitDetermination { - private String name; + private final String name; private Input(String name) { this.name = name; @@ -230,7 +228,7 @@ String getName() { static class Value extends CircuitDetermination { - private int value; + private final int value; private Value(int value) { this.value = value; @@ -241,8 +239,7 @@ int getValue() { } } - private static class Determine - implements ExpressionVisitor { + private static class Determine implements ExpressionVisitor { public CircuitDetermination visitAnd(Expression a, Expression b) { return binary(a.visit(this), b.visit(this), AndGate.FACTORY); @@ -256,41 +253,40 @@ public CircuitDetermination visitXor(Expression a, Expression b) { return binary(a.visit(this), b.visit(this), XorGate.FACTORY); } - private Gate binary(CircuitDetermination aret, - CircuitDetermination bret, ComponentFactory factory) { - if (aret instanceof Gate) { - Gate a = (Gate) aret; + private Gate binary(CircuitDetermination aRet, CircuitDetermination bRet, ComponentFactory factory) { + if (aRet instanceof Gate) { + Gate a = (Gate) aRet; if (a.factory == factory) { - if (bret instanceof Gate) { - Gate b = (Gate) bret; + if (bRet instanceof Gate) { + Gate b = (Gate) bRet; if (b.factory == factory) { a.inputs.addAll(b.inputs); return a; } } - a.inputs.add(bret); + a.inputs.add(bRet); return a; } } - if (bret instanceof Gate) { - Gate b = (Gate) bret; + if (bRet instanceof Gate) { + Gate b = (Gate) bRet; if (b.factory == factory) { - b.inputs.add(aret); + b.inputs.add(aRet); return b; } } Gate ret = new Gate(factory); - ret.inputs.add(aret); - ret.inputs.add(bret); + ret.inputs.add(aRet); + ret.inputs.add(bRet); return ret; } public CircuitDetermination visitNot(Expression aBase) { - CircuitDetermination aret = aBase.visit(this); - if (aret instanceof Gate) { - Gate a = (Gate) aret; + CircuitDetermination aRet = aBase.visit(this); + if (aRet instanceof Gate) { + Gate a = (Gate) aRet; if (a.factory == AndGate.FACTORY) { a.factory = NandGate.FACTORY; return a; @@ -304,7 +300,7 @@ public CircuitDetermination visitNot(Expression aBase) { } Gate ret = new Gate(NotGate.FACTORY); - ret.inputs.add(aret); + ret.inputs.add(aRet); return ret; } diff --git a/src/main/java/com/cburch/logisim/std/gates/ControlledBuffer.java b/src/main/java/com/cburch/logisim/std/gates/ControlledBuffer.java index 534318a..b680f82 100644 --- a/src/main/java/com/cburch/logisim/std/gates/ControlledBuffer.java +++ b/src/main/java/com/cburch/logisim/std/gates/ControlledBuffer.java @@ -33,36 +33,58 @@ class ControlledBuffer extends InstanceFactory { private static final AttributeOption RIGHT_HANDED - = new AttributeOption("right", Strings.getter("controlledRightHanded")); + = new AttributeOption("right", Strings.getter("controlledRightHanded")); private static final AttributeOption LEFT_HANDED - = new AttributeOption("left", Strings.getter("controlledLeftHanded")); + = new AttributeOption("left", Strings.getter("controlledLeftHanded")); private static final Attribute ATTR_CONTROL - = Attributes.forOption("control", Strings.getter("controlledControlOption"), - new AttributeOption[]{RIGHT_HANDED, LEFT_HANDED}); + = Attributes.forOption("control", Strings.getter("controlledControlOption"), + new AttributeOption[]{RIGHT_HANDED, LEFT_HANDED}); private static final Icon ICON_BUFFER = Icons.getIcon("controlledBuffer.gif"); private static final Icon ICON_INVERTER = Icons.getIcon("controlledInverter.gif"); public static ComponentFactory FACTORY_BUFFER = new ControlledBuffer(false); public static ComponentFactory FACTORY_INVERTER = new ControlledBuffer(true); - private boolean isInverter; + private final boolean isInverter; private ControlledBuffer(boolean isInverter) { - super(isInverter ? "Controlled Inverter" : "Controlled Buffer", - isInverter ? Strings.getter("controlledInverterComponent") - : Strings.getter("controlledBufferComponent")); + super(isInverter ? "Controlled Inverter" : "Controlled Buffer", isInverter ? Strings.getter( + "controlledInverterComponent") : Strings.getter("controlledBufferComponent")); this.isInverter = isInverter; if (isInverter) { - setAttributes(new Attribute[]{StdAttr.FACING, StdAttr.WIDTH, - NotGate.ATTR_SIZE, ATTR_CONTROL, - StdAttr.LABEL, StdAttr.LABEL_FONT}, - new Object[]{Direction.EAST, BitWidth.ONE, - NotGate.SIZE_WIDE, RIGHT_HANDED, - "", StdAttr.DEFAULT_LABEL_FONT}); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + StdAttr.WIDTH, + NotGate.ATTR_SIZE, + ATTR_CONTROL, + StdAttr.LABEL, + StdAttr.LABEL_FONT + }, + new Object[]{ + Direction.EAST, + BitWidth.ONE, + NotGate.SIZE_WIDE, + RIGHT_HANDED, + "", + StdAttr.DEFAULT_LABEL_FONT + } + ); } else { - setAttributes(new Attribute[]{ - StdAttr.FACING, StdAttr.WIDTH, ATTR_CONTROL, - StdAttr.LABEL, StdAttr.LABEL_FONT}, - new Object[]{Direction.EAST, BitWidth.ONE, RIGHT_HANDED, - "", StdAttr.DEFAULT_LABEL_FONT}); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + StdAttr.WIDTH, + ATTR_CONTROL, + StdAttr.LABEL, + StdAttr.LABEL_FONT + }, + new Object[]{ + Direction.EAST, + BitWidth.ONE, + RIGHT_HANDED, + "", + StdAttr.DEFAULT_LABEL_FONT + } + ); } setFacingAttribute(StdAttr.FACING); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); @@ -71,8 +93,7 @@ private ControlledBuffer(boolean isInverter) { @Override public Bounds getOffsetBounds(AttributeSet attributes) { int w = 20; - if (isInverter && - !NotGate.SIZE_NARROW.equals(attributes.getValue(NotGate.ATTR_SIZE))) { + if (isInverter && !NotGate.SIZE_NARROW.equals(attributes.getValue(NotGate.ATTR_SIZE))) { w = 30; } Direction facing = attributes.getValue(StdAttr.FACING); @@ -234,7 +255,7 @@ public void propagate(InstanceState state) { if (control == Value.UNKNOWN || control == Value.NIL) { AttributeSet opts = state.getProject().getOptions().getAttributeSet(); if (opts.getValue(Options.ATTR_GATE_UNDEFINED) - .equals(Options.GATE_UNDEFINED_ERROR)) { + .equals(Options.GATE_UNDEFINED_ERROR)) { out = Value.createError(width); } else { out = Value.createUnknown(width); diff --git a/src/main/java/com/cburch/logisim/std/gates/EvenParityGate.java b/src/main/java/com/cburch/logisim/std/gates/EvenParityGate.java index eca7145..fa5dd32 100644 --- a/src/main/java/com/cburch/logisim/std/gates/EvenParityGate.java +++ b/src/main/java/com/cburch/logisim/std/gates/EvenParityGate.java @@ -30,8 +30,7 @@ protected void paintShape(InstancePainter painter, int width, int height) { } @Override - protected void paintDinShape(InstancePainter painter, int width, int height, - int inputs) { + protected void paintDinShape(InstancePainter painter, int width, int height, int inputs) { paintRectangular(painter, width, height); } @@ -42,11 +41,11 @@ protected Value computeOutput(Value[] inputs, int numInputs, InstanceState state @Override protected Expression computeExpression(Expression[] inputs, int numInputs) { - Expression ret = inputs[0]; + Expression expression = inputs[0]; for (int i = 1; i < numInputs; i++) { - ret = Expressions.xor(ret, inputs[i]); + expression = Expressions.xor(expression, inputs[i]); } - return Expressions.not(ret); + return Expressions.not(expression); } @Override diff --git a/src/main/java/com/cburch/logisim/std/gates/GateAttributeList.java b/src/main/java/com/cburch/logisim/std/gates/GateAttributeList.java index ac28320..a42b248 100644 --- a/src/main/java/com/cburch/logisim/std/gates/GateAttributeList.java +++ b/src/main/java/com/cburch/logisim/std/gates/GateAttributeList.java @@ -11,12 +11,12 @@ class GateAttributeList extends AbstractList> { private static final Attribute[] BASE_ATTRIBUTES = { - StdAttr.FACING, StdAttr.WIDTH, - GateAttributes.ATTR_SIZE, GateAttributes.ATTR_INPUTS, - GateAttributes.ATTRIBUTE_OUTPUT, StdAttr.LABEL, StdAttr.LABEL_FONT, + StdAttr.FACING, StdAttr.WIDTH, + GateAttributes.ATTR_SIZE, GateAttributes.ATTR_INPUTS, + GateAttributes.ATTRIBUTE_OUTPUT, StdAttr.LABEL, StdAttr.LABEL_FONT, }; - private GateAttributes attrs; + private final GateAttributes attrs; public GateAttributeList(GateAttributes attrs) { this.attrs = attrs; diff --git a/src/main/java/com/cburch/logisim/std/gates/GateAttributes.java b/src/main/java/com/cburch/logisim/std/gates/GateAttributes.java index 034f4eb..22117d5 100644 --- a/src/main/java/com/cburch/logisim/std/gates/GateAttributes.java +++ b/src/main/java/com/cburch/logisim/std/gates/GateAttributes.java @@ -17,26 +17,26 @@ class GateAttributes extends AbstractAttributeSet { static final int MAX_INPUTS = 32; public static final Attribute ATTR_INPUTS - = Attributes.forIntegerRange("inputs", Strings.getter("gateInputsAttr"), 2, MAX_INPUTS); + = Attributes.forIntegerRange("inputs", Strings.getter("gateInputsAttr"), 2, MAX_INPUTS); static final int DELAY = 1; static final AttributeOption SIZE_NARROW = new AttributeOption(30, Strings.getter("gateSizeNarrowOpt")); static final AttributeOption SIZE_MEDIUM = new AttributeOption(50, Strings.getter("gateSizeNormalOpt")); static final AttributeOption SIZE_WIDE = new AttributeOption(70, Strings.getter("gateSizeWideOpt")); public static final Attribute ATTR_SIZE - = Attributes.forOption("size", Strings.getter("gateSizeAttr"), - new AttributeOption[]{SIZE_NARROW, SIZE_MEDIUM, SIZE_WIDE}); + = Attributes.forOption("size", Strings.getter("gateSizeAttr"), + new AttributeOption[]{SIZE_NARROW, SIZE_MEDIUM, SIZE_WIDE}); static final AttributeOption XOR_ONE = new AttributeOption("1", Strings.getter("xorBehaviorOne")); static final AttributeOption XOR_ODD = new AttributeOption("odd", Strings.getter("xorBehaviorOdd")); public static final Attribute ATTRIBUTE_XOR - = Attributes.forOption("xor", Strings.getter("xorBehaviorAttr"), - new AttributeOption[]{XOR_ONE, XOR_ODD}); + = Attributes.forOption("xor", Strings.getter("xorBehaviorAttr"), + new AttributeOption[]{XOR_ONE, XOR_ODD}); static final AttributeOption OUTPUT_01 = new AttributeOption("01", Strings.getter("gateOutput01")); static final AttributeOption OUTPUT_0Z = new AttributeOption("0Z", Strings.getter("gateOutput0Z")); static final AttributeOption OUTPUT_Z1 = new AttributeOption("Z1", Strings.getter("gateOutputZ1")); public static final Attribute ATTRIBUTE_OUTPUT - = Attributes.forOption("out", Strings.getter("gateOutputAttr"), - new AttributeOption[]{OUTPUT_01, OUTPUT_0Z, OUTPUT_Z1}); + = Attributes.forOption("out", Strings.getter("gateOutputAttr"), + new AttributeOption[]{OUTPUT_01, OUTPUT_0Z, OUTPUT_Z1}); Direction facing = Direction.EAST; diff --git a/src/main/java/com/cburch/logisim/std/gates/GateFunctions.java b/src/main/java/com/cburch/logisim/std/gates/GateFunctions.java index a72e072..eca397e 100644 --- a/src/main/java/com/cburch/logisim/std/gates/GateFunctions.java +++ b/src/main/java/com/cburch/logisim/std/gates/GateFunctions.java @@ -19,11 +19,11 @@ static Value computeOr(Value[] inputs, int numInputs) { } static Value computeAnd(Value[] inputs, int numInputs) { - Value ret = inputs[0]; + Value input = inputs[0]; for (int i = 1; i < numInputs; i++) { - ret = ret.and(inputs[i]); + input = input.and(inputs[i]); } - return ret; + return input; } static Value computeOddParity(Value[] inputs, int numInputs) { diff --git a/src/main/java/com/cburch/logisim/std/gates/Gates.java b/src/main/java/com/cburch/logisim/std/gates/Gates.java index 7b52c26..c9b08ba 100644 --- a/src/main/java/com/cburch/logisim/std/gates/Gates.java +++ b/src/main/java/com/cburch/logisim/std/gates/Gates.java @@ -15,18 +15,18 @@ public class Gates extends Library { public Gates() { tools = Arrays.asList(new Tool[]{ - new AddTool(NotGate.FACTORY), - new AddTool(Buffer.FACTORY), - new AddTool(AndGate.FACTORY), - new AddTool(OrGate.FACTORY), - new AddTool(NandGate.FACTORY), - new AddTool(NorGate.FACTORY), - new AddTool(XorGate.FACTORY), - new AddTool(XnorGate.FACTORY), - new AddTool(OddParityGate.FACTORY), - new AddTool(EvenParityGate.FACTORY), - new AddTool(ControlledBuffer.FACTORY_BUFFER), - new AddTool(ControlledBuffer.FACTORY_INVERTER), + new AddTool(NotGate.FACTORY), + new AddTool(Buffer.FACTORY), + new AddTool(AndGate.FACTORY), + new AddTool(OrGate.FACTORY), + new AddTool(NandGate.FACTORY), + new AddTool(NorGate.FACTORY), + new AddTool(XorGate.FACTORY), + new AddTool(XnorGate.FACTORY), + new AddTool(OddParityGate.FACTORY), + new AddTool(EvenParityGate.FACTORY), + new AddTool(ControlledBuffer.FACTORY_BUFFER), + new AddTool(ControlledBuffer.FACTORY_INVERTER), }); } diff --git a/src/main/java/com/cburch/logisim/std/gates/NandGate.java b/src/main/java/com/cburch/logisim/std/gates/NandGate.java index 6289c8f..a86928e 100644 --- a/src/main/java/com/cburch/logisim/std/gates/NandGate.java +++ b/src/main/java/com/cburch/logisim/std/gates/NandGate.java @@ -38,24 +38,22 @@ protected void paintShape(InstancePainter painter, int width, int height) { } @Override - protected void paintDinShape(InstancePainter painter, int width, int height, - int inputs) { + protected void paintDinShape(InstancePainter painter, int width, int height, int inputs) { PainterDin.paintAnd(painter, width, height, true); } @Override - protected Value computeOutput(Value[] inputs, int numInputs, - InstanceState state) { + protected Value computeOutput(Value[] inputs, int numInputs, InstanceState state) { return GateFunctions.computeAnd(inputs, numInputs).not(); } @Override protected Expression computeExpression(Expression[] inputs, int numInputs) { - Expression ret = inputs[0]; + Expression expression = inputs[0]; for (int i = 1; i < numInputs; i++) { - ret = Expressions.and(ret, inputs[i]); + expression = Expressions.and(expression, inputs[i]); } - return Expressions.not(ret); + return Expressions.not(expression); } @Override diff --git a/src/main/java/com/cburch/logisim/std/gates/NegateAttribute.java b/src/main/java/com/cburch/logisim/std/gates/NegateAttribute.java index 22a4342..bfcc6d6 100644 --- a/src/main/java/com/cburch/logisim/std/gates/NegateAttribute.java +++ b/src/main/java/com/cburch/logisim/std/gates/NegateAttribute.java @@ -10,10 +10,9 @@ class NegateAttribute extends Attribute { - private static Attribute BOOLEAN_ATTR = Attributes.forBoolean("negateDummy"); - + private static final Attribute BOOLEAN_ATTR = Attributes.forBoolean("negateDummy"); + private final Direction side; int index; - private Direction side; public NegateAttribute(int index, Direction side) { super("negate" + index, null); @@ -24,8 +23,8 @@ public NegateAttribute(int index, Direction side) { @Override public boolean equals(Object other) { if (other instanceof NegateAttribute) { - NegateAttribute o = (NegateAttribute) other; - return this.index == o.index && this.side == o.side; + NegateAttribute attribute = (NegateAttribute) other; + return this.index == attribute.index && this.side == attribute.side; } else { return false; } diff --git a/src/main/java/com/cburch/logisim/std/gates/NorGate.java b/src/main/java/com/cburch/logisim/std/gates/NorGate.java index eeafba5..53e1966 100644 --- a/src/main/java/com/cburch/logisim/std/gates/NorGate.java +++ b/src/main/java/com/cburch/logisim/std/gates/NorGate.java @@ -40,14 +40,12 @@ protected void paintShape(InstancePainter painter, int width, int height) { } @Override - protected void paintDinShape(InstancePainter painter, int width, int height, - int inputs) { + protected void paintDinShape(InstancePainter painter, int width, int height, int inputs) { PainterDin.paintOr(painter, width, height, true); } @Override - protected Value computeOutput(Value[] inputs, int numInputs, - InstanceState state) { + protected Value computeOutput(Value[] inputs, int numInputs, InstanceState state) { return GateFunctions.computeOr(inputs, numInputs).not(); } @@ -58,11 +56,11 @@ protected boolean shouldRepairWire(Instance instance, WireRepairData data) { @Override protected Expression computeExpression(Expression[] inputs, int numInputs) { - Expression ret = inputs[0]; + Expression expression = inputs[0]; for (int i = 1; i < numInputs; i++) { - ret = Expressions.or(ret, inputs[i]); + expression = Expressions.or(expression, inputs[i]); } - return Expressions.not(ret); + return Expressions.not(expression); } @Override diff --git a/src/main/java/com/cburch/logisim/std/gates/NotGate.java b/src/main/java/com/cburch/logisim/std/gates/NotGate.java index f580a2f..12d46b8 100644 --- a/src/main/java/com/cburch/logisim/std/gates/NotGate.java +++ b/src/main/java/com/cburch/logisim/std/gates/NotGate.java @@ -36,32 +36,35 @@ class NotGate extends InstanceFactory { public static final AttributeOption SIZE_NARROW = new AttributeOption(20, Strings.getter("gateSizeNarrowOpt")); public static final AttributeOption SIZE_WIDE = new AttributeOption(30, Strings.getter("gateSizeWideOpt")); public static final Attribute ATTR_SIZE = Attributes - .forOption("size", Strings.getter("gateSizeAttr"), new AttributeOption[]{SIZE_NARROW, SIZE_WIDE}); - + .forOption("size", Strings.getter("gateSizeAttr"), new AttributeOption[]{SIZE_NARROW, SIZE_WIDE}); + public static final InstanceFactory FACTORY = new NotGate(); private static final String RECT_LABEL = "1"; private static final Icon toolIcon = Icons.getIcon("notGate.gif"); private static final Icon toolIconRect = Icons.getIcon("notGateRect.gif"); private static final Icon toolIconDin = Icons.getIcon("dinNotGate.gif"); - public static final InstanceFactory FACTORY = new NotGate(); - private NotGate() { super("NOT Gate", Strings.getter("notGateComponent")); setAttributes(new Attribute[]{ - StdAttr.FACING, StdAttr.WIDTH, ATTR_SIZE, - GateAttributes.ATTRIBUTE_OUTPUT, - StdAttr.LABEL, StdAttr.LABEL_FONT, + StdAttr.FACING, + StdAttr.WIDTH, + ATTR_SIZE, + GateAttributes.ATTRIBUTE_OUTPUT, + StdAttr.LABEL, + StdAttr.LABEL_FONT, }, new Object[]{ - Direction.EAST, BitWidth.ONE, SIZE_WIDE, - GateAttributes.OUTPUT_01, - "", StdAttr.DEFAULT_LABEL_FONT, + Direction.EAST, + BitWidth.ONE, + SIZE_WIDE, + GateAttributes.OUTPUT_01, + "", + StdAttr.DEFAULT_LABEL_FONT, }); setFacingAttribute(StdAttr.FACING); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); } - static void configureLabel(Instance instance, boolean isRectangular, - Location control) { + static void configureLabel(Instance instance, boolean isRectangular, Location control) { Object facing = instance.getAttributeValue(StdAttr.FACING); Bounds bounds = instance.getBounds(); int x; @@ -82,15 +85,14 @@ static void configureLabel(Instance instance, boolean isRectangular, horizntalAlignment = TextField.H_CENTER; } } - instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, x, y, - horizntalAlignment, TextField.V_BASELINE); + instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, x, y, horizntalAlignment, TextField.V_BASELINE); } @Override public Bounds getOffsetBounds(AttributeSet attributes) { Object value = attributes.getValue(ATTR_SIZE); + Direction facing = attributes.getValue(StdAttr.FACING); if (value == SIZE_NARROW) { - Direction facing = attributes.getValue(StdAttr.FACING); if (facing == Direction.SOUTH) { return Bounds.create(-9, -20, 18, 20); } @@ -102,7 +104,6 @@ public Bounds getOffsetBounds(AttributeSet attributes) { } return Bounds.create(-20, -9, 20, 18); } else { - Direction facing = attributes.getValue(StdAttr.FACING); if (facing == Direction.SOUTH) { return Bounds.create(-9, -30, 18, 30); } diff --git a/src/main/java/com/cburch/logisim/std/gates/OddParityGate.java b/src/main/java/com/cburch/logisim/std/gates/OddParityGate.java index 0253ea9..5cab138 100644 --- a/src/main/java/com/cburch/logisim/std/gates/OddParityGate.java +++ b/src/main/java/com/cburch/logisim/std/gates/OddParityGate.java @@ -47,24 +47,22 @@ protected void paintShape(InstancePainter painter, int width, int height) { } @Override - protected void paintDinShape(InstancePainter painter, int width, int height, - int inputs) { + protected void paintDinShape(InstancePainter painter, int width, int height, int inputs) { paintRectangular(painter, width, height); } @Override - protected Value computeOutput(Value[] inputs, int numInputs, - InstanceState state) { + protected Value computeOutput(Value[] inputs, int numInputs, InstanceState state) { return GateFunctions.computeOddParity(inputs, numInputs); } @Override protected Expression computeExpression(Expression[] inputs, int numInputs) { - Expression ret = inputs[0]; + Expression expression = inputs[0]; for (int i = 1; i < numInputs; i++) { - ret = Expressions.xor(ret, inputs[i]); + expression = Expressions.xor(expression, inputs[i]); } - return ret; + return expression; } @Override diff --git a/src/main/java/com/cburch/logisim/std/gates/OrGate.java b/src/main/java/com/cburch/logisim/std/gates/OrGate.java index 44ee7ea..4c189ed 100644 --- a/src/main/java/com/cburch/logisim/std/gates/OrGate.java +++ b/src/main/java/com/cburch/logisim/std/gates/OrGate.java @@ -38,30 +38,27 @@ protected void paintShape(InstancePainter painter, int width, int height) { } @Override - protected void paintDinShape(InstancePainter painter, int width, int height, - int inputs) { + protected void paintDinShape(InstancePainter painter, int width, int height, int inputs) { PainterDin.paintOr(painter, width, height, false); } @Override - protected Value computeOutput(Value[] inputs, int numInputs, - InstanceState state) { + protected Value computeOutput(Value[] inputs, int numInputs, InstanceState state) { return GateFunctions.computeOr(inputs, numInputs); } @Override protected boolean shouldRepairWire(Instance instance, WireRepairData data) { - boolean ret = !data.getPoint().equals(instance.getLocation()); - return ret; + return !data.getPoint().equals(instance.getLocation()); } @Override protected Expression computeExpression(Expression[] inputs, int numInputs) { - Expression ret = inputs[0]; + Expression expression = inputs[0]; for (int i = 1; i < numInputs; i++) { - ret = Expressions.or(ret, inputs[i]); + expression = Expressions.or(expression, inputs[i]); } - return ret; + return expression; } @Override diff --git a/src/main/java/com/cburch/logisim/std/gates/PainterDin.java b/src/main/java/com/cburch/logisim/std/gates/PainterDin.java index 97ea77c..d3623e8 100644 --- a/src/main/java/com/cburch/logisim/std/gates/PainterDin.java +++ b/src/main/java/com/cburch/logisim/std/gates/PainterDin.java @@ -17,33 +17,31 @@ class PainterDin { static final int OR = 1; static final int XOR = 2; static final int XNOR = 3; - private static HashMap orLenArrays = new HashMap<>(); + private static final HashMap orLenArrays = new HashMap<>(); private PainterDin() { } static void paintAnd(InstancePainter painter, int width, int height, - boolean drawBubble) { + boolean drawBubble) { paint(painter, width, height, drawBubble, AND); } static void paintOr(InstancePainter painter, int width, int height, - boolean drawBubble) { + boolean drawBubble) { paint(painter, width, height, drawBubble, OR); } - static void paintXor(InstancePainter painter, int width, int height, - boolean drawBubble) { + static void paintXor(InstancePainter painter, int width, int height, boolean drawBubble) { paint(painter, width, height, drawBubble, XOR); } - static void paintXnor(InstancePainter painter, int width, int height, - boolean drawBubble) { + static void paintXnor(InstancePainter painter, int width, int height, boolean drawBubble) { paint(painter, width, height, drawBubble, XNOR); } private static void paint(InstancePainter painter, int width, int height, - boolean drawBubble, int dinType) { + boolean drawBubble, int dinType) { Graphics g = painter.getGraphics(); int x = 0; int xMid = -width; @@ -98,8 +96,7 @@ private static void paint(InstancePainter painter, int width, int height, } } - private static void paintOrLines(InstancePainter painter, - int width, int height, boolean hasBubble) { + private static void paintOrLines(InstancePainter painter, int width, int height, boolean hasBubble) { GateAttributes baseAttrs = (GateAttributes) painter.getAttributeSet(); int inputs = baseAttrs.inputs; GateAttributes attrs = (GateAttributes) OrGate.FACTORY.createAttributeSet(); diff --git a/src/main/java/com/cburch/logisim/std/gates/PainterShaped.java b/src/main/java/com/cburch/logisim/std/gates/PainterShaped.java index 76cffcf..e751f5a 100644 --- a/src/main/java/com/cburch/logisim/std/gates/PainterShaped.java +++ b/src/main/java/com/cburch/logisim/std/gates/PainterShaped.java @@ -24,7 +24,7 @@ public class PainterShaped { private static final GeneralPath SHIELD_NARROW; private static final GeneralPath SHIELD_MEDIUM; private static final GeneralPath SHIELD_WIDE; - private static HashMap INPUT_LENGTHS = new HashMap<>(); + private static final HashMap INPUT_LENGTHS = new HashMap<>(); static { PATH_NARROW = new GeneralPath(); @@ -149,7 +149,7 @@ static void paintXor(InstancePainter painter, int width, int height) { } private static void paintShield(Graphics g, int xlate, - int width, int height) { + int width, int height) { GraphicsUtil.switchToWidth(g, 2); g.translate(xlate, 0); ((Graphics2D) g).draw(computeShield(width, height)); @@ -191,10 +191,10 @@ private static GeneralPath computeShield(int width, int height) { int dx = Math.min(20, wingHeight / 4); GeneralPath path = new GeneralPath(); - path.moveTo(-width, -height / 2); - path.quadTo(-width + dx, -(width + height) / 4, -width, -width / 2); + path.moveTo(-width, -height / 2.0); + path.quadTo(-width + dx, -(width + height) / 4.0, -width, -width / 2.0); path.append(base, true); - path.quadTo(-width + dx, (width + height) / 4, -width, height / 2); + path.quadTo(-width + dx, (width + height) / 4.0, -width, height / 2.0); return path; } } @@ -223,17 +223,17 @@ static void paintInputLines(InstancePainter painter, AbstractGate factory) { Color baseColor = g.getColor(); GraphicsUtil.switchToWidth(g, 3); for (int i = 0; i < inputs; i++) { - Location offs = factory.getInputOffset(attrs, i); - Location src = loc.translate(offs.getX(), offs.getY()); - int len = lengths[i]; - if (len != 0 && (!printView || painter.isPortConnected(i + 1))) { + Location offset = factory.getInputOffset(attrs, i); + Location src = loc.translate(offset.getX(), offset.getY()); + int length = lengths[i]; + if (length != 0 && (!printView || painter.isPortConnected(i + 1))) { if (painter.getShowState()) { Value val = painter.getPort(i + 1); g.setColor(val.getColor()); } else { g.setColor(baseColor); } - Location dst = src.translate(facing, len); + Location dst = src.translate(facing, length); g.drawLine(src.getX(), src.getY(), dst.getX(), dst.getY()); } if (((negated >> i) & 1) == 1) { diff --git a/src/main/java/com/cburch/logisim/std/gates/Strings.java b/src/main/java/com/cburch/logisim/std/gates/Strings.java index ac77db2..9fdfcef 100644 --- a/src/main/java/com/cburch/logisim/std/gates/Strings.java +++ b/src/main/java/com/cburch/logisim/std/gates/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "std"); + private static final LocaleManager source = new LocaleManager("logisim", "std"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/std/gates/XnorGate.java b/src/main/java/com/cburch/logisim/std/gates/XnorGate.java index 1355bba..10e5a33 100644 --- a/src/main/java/com/cburch/logisim/std/gates/XnorGate.java +++ b/src/main/java/com/cburch/logisim/std/gates/XnorGate.java @@ -47,8 +47,7 @@ protected void paintShape(InstancePainter painter, int width, int height) { } @Override - protected void paintDinShape(InstancePainter painter, int width, int height, - int inputs) { + protected void paintDinShape(InstancePainter painter, int width, int height, int inputs) { PainterDin.paintXnor(painter, width, height, false); } diff --git a/src/main/java/com/cburch/logisim/std/io/Button.java b/src/main/java/com/cburch/logisim/std/io/Button.java index 4d59159..d40ca6c 100644 --- a/src/main/java/com/cburch/logisim/std/io/Button.java +++ b/src/main/java/com/cburch/logisim/std/io/Button.java @@ -31,13 +31,19 @@ public class Button extends InstanceFactory { public Button() { super("Button", Strings.getter("buttonComponent")); setAttributes(new Attribute[]{ - StdAttr.FACING, Io.ATTR_COLOR, - StdAttr.LABEL, Io.ATTR_LABEL_LOCATION, - StdAttr.LABEL_FONT, Io.ATTR_LABEL_COLOR + StdAttr.FACING, + Io.ATTR_COLOR, + StdAttr.LABEL, + Io.ATTR_LABEL_LOCATION, + StdAttr.LABEL_FONT, + Io.ATTR_LABEL_COLOR }, new Object[]{ - Direction.EAST, Color.WHITE, - "", Io.LABEL_CENTER, - StdAttr.DEFAULT_LABEL_FONT, Color.BLACK + Direction.EAST, + Color.WHITE, + "", + Io.LABEL_CENTER, + StdAttr.DEFAULT_LABEL_FONT, + Color.BLACK }); setFacingAttribute(StdAttr.FACING); setIconName("button.gif"); @@ -104,7 +110,7 @@ private void computeTextField(Instance instance) { } instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, - x, y, halign, valign); + x, y, halign, valign); } @Override @@ -143,7 +149,7 @@ public void paintInstance(InstancePainter painter) { y += DEPTH; Object labelLoc = painter.getAttributeValue(Io.ATTR_LABEL_LOCATION); if (labelLoc == Io.LABEL_CENTER || labelLoc == Direction.NORTH - || labelLoc == Direction.WEST) { + || labelLoc == Direction.WEST) { depress = DEPTH; } else { depress = 0; diff --git a/src/main/java/com/cburch/logisim/std/io/DotMatrix.java b/src/main/java/com/cburch/logisim/std/io/DotMatrix.java index e36778b..d903766 100644 --- a/src/main/java/com/cburch/logisim/std/io/DotMatrix.java +++ b/src/main/java/com/cburch/logisim/std/io/DotMatrix.java @@ -26,41 +26,41 @@ public class DotMatrix extends InstanceFactory { static final AttributeOption INPUT_SELECT - = new AttributeOption("select", Strings.getter("ioInputSelect")); + = new AttributeOption("select", Strings.getter("ioInputSelect")); static final AttributeOption INPUT_COLUMN - = new AttributeOption("column", Strings.getter("ioInputColumn")); + = new AttributeOption("column", Strings.getter("ioInputColumn")); static final AttributeOption INPUT_ROW - = new AttributeOption("row", Strings.getter("ioInputRow")); + = new AttributeOption("row", Strings.getter("ioInputRow")); static final AttributeOption SHAPE_CIRCLE - = new AttributeOption("circle", Strings.getter("ioShapeCircle")); + = new AttributeOption("circle", Strings.getter("ioShapeCircle")); static final AttributeOption SHAPE_SQUARE - = new AttributeOption("square", Strings.getter("ioShapeSquare")); + = new AttributeOption("square", Strings.getter("ioShapeSquare")); static final Attribute ATTR_INPUT_TYPE - = Attributes.forOption("inputtype", Strings.getter("ioMatrixInput"), - new AttributeOption[]{INPUT_COLUMN, INPUT_ROW, INPUT_SELECT}); + = Attributes.forOption("inputtype", Strings.getter("ioMatrixInput"), + new AttributeOption[]{INPUT_COLUMN, INPUT_ROW, INPUT_SELECT}); static final Attribute ATTR_MATRIX_COLS - = Attributes.forIntegerRange("matrixcols", - Strings.getter("ioMatrixCols"), 1, Value.MAX_WIDTH); + = Attributes.forIntegerRange("matrixcols", + Strings.getter("ioMatrixCols"), 1, Value.MAX_WIDTH); static final Attribute ATTR_MATRIX_ROWS - = Attributes.forIntegerRange("matrixrows", - Strings.getter("ioMatrixRows"), 1, Value.MAX_WIDTH); + = Attributes.forIntegerRange("matrixrows", + Strings.getter("ioMatrixRows"), 1, Value.MAX_WIDTH); static final Attribute ATTR_DOT_SHAPE - = Attributes.forOption("dotshape", Strings.getter("ioMatrixShape"), - new AttributeOption[]{SHAPE_CIRCLE, SHAPE_SQUARE}); + = Attributes.forOption("dotshape", Strings.getter("ioMatrixShape"), + new AttributeOption[]{SHAPE_CIRCLE, SHAPE_SQUARE}); static final Attribute ATTR_PERSIST = new DurationAttribute("persist", - Strings.getter("ioMatrixPersistenceAttr"), 0, Integer.MAX_VALUE); + Strings.getter("ioMatrixPersistenceAttr"), 0, Integer.MAX_VALUE); public DotMatrix() { super("DotMatrix", Strings.getter("dotMatrixComponent")); setAttributes(new Attribute[]{ - ATTR_INPUT_TYPE, ATTR_MATRIX_COLS, ATTR_MATRIX_ROWS, - Io.ATTR_ON_COLOR, Io.ATTR_OFF_COLOR, - ATTR_PERSIST, ATTR_DOT_SHAPE + ATTR_INPUT_TYPE, ATTR_MATRIX_COLS, ATTR_MATRIX_ROWS, + Io.ATTR_ON_COLOR, Io.ATTR_OFF_COLOR, + ATTR_PERSIST, ATTR_DOT_SHAPE }, new Object[]{ - INPUT_COLUMN, 5, 7, - Color.GREEN, Color.DARK_GRAY, 0, SHAPE_SQUARE + INPUT_COLUMN, 5, 7, + Color.GREEN, Color.DARK_GRAY, 0, SHAPE_SQUARE }); setIconName("dotmat.gif"); } @@ -91,8 +91,7 @@ protected void configureNewInstance(Instance instance) { @Override protected void instanceAttributeChanged(Instance instance, Attribute attribute) { - if (attribute == ATTR_MATRIX_ROWS || attribute == ATTR_MATRIX_COLS - || attribute == ATTR_INPUT_TYPE) { + if (attribute == ATTR_MATRIX_ROWS || attribute == ATTR_MATRIX_COLS || attribute == ATTR_INPUT_TYPE) { instance.recomputeBounds(); updatePorts(instance); } @@ -120,8 +119,8 @@ private void updatePorts(Instance instance) { ps = new Port[]{new Port(0, 0, Port.INPUT, rows)}; } else { ps = new Port[]{ - new Port(0, 0, Port.INPUT, cols), - new Port(0, 10, Port.INPUT, rows) + new Port(0, 0, Port.INPUT, cols), + new Port(0, 10, Port.INPUT, rows) }; } } diff --git a/src/main/java/com/cburch/logisim/std/io/HexDigit.java b/src/main/java/com/cburch/logisim/std/io/HexDigit.java index ebcf2b6..92fa4b6 100644 --- a/src/main/java/com/cburch/logisim/std/io/HexDigit.java +++ b/src/main/java/com/cburch/logisim/std/io/HexDigit.java @@ -18,13 +18,19 @@ public class HexDigit extends InstanceFactory { public HexDigit() { super("Hex Digit Display", Strings.getter("hexDigitComponent")); - setAttributes(new Attribute[]{Io.ATTR_ON_COLOR, Io.ATTR_OFF_COLOR, - Io.ATTR_BACKGROUND}, - new Object[]{new Color(240, 0, 0), SevenSegment.DEFAULT_OFF, - Io.DEFAULT_BACKGROUND}); + setAttributes( + new Attribute[]{ + Io.ATTR_ON_COLOR, + Io.ATTR_OFF_COLOR, + Io.ATTR_BACKGROUND + }, new Object[]{ + new Color(240, 0, 0), + SevenSegment.DEFAULT_OFF, + Io.DEFAULT_BACKGROUND + }); setPorts(new Port[]{ - new Port(0, 0, Port.INPUT, 4), - new Port(10, 0, Port.INPUT, 1) + new Port(0, 0, Port.INPUT, 4), + new Port(10, 0, Port.INPUT, 1) }); setOffsetBounds(Bounds.create(-15, -60, 40, 60)); setIconName("hexdig.gif"); @@ -33,84 +39,84 @@ public HexDigit() { @Override public void propagate(InstanceState state) { int summary = 0; - Value baseVal = state.getPort(0); - if (baseVal == null) { - baseVal = Value.createUnknown(BitWidth.create(4)); + Value baseValue = state.getPort(0); + if (baseValue == null) { + baseValue = Value.createUnknown(BitWidth.create(4)); } - int segs; // each nibble is one segment, in top-down, left-to-right + int segment; // each nibble is one segment, in top-down, left-to-right // order: middle three nibbles are the three horizontal segments - switch (baseVal.toIntValue()) { + switch (baseValue.toIntValue()) { case 0: - segs = 0x1110111; + segment = 0x1110111; break; case 1: - segs = 0x0000011; + segment = 0x0000011; break; case 2: - segs = 0x0111110; + segment = 0x0111110; break; case 3: - segs = 0x0011111; + segment = 0x0011111; break; case 4: - segs = 0x1001011; + segment = 0x1001011; break; case 5: - segs = 0x1011101; + segment = 0x1011101; break; case 6: - segs = 0x1111101; + segment = 0x1111101; break; case 7: - segs = 0x0010011; + segment = 0x0010011; break; case 8: - segs = 0x1111111; + segment = 0x1111111; break; case 9: - segs = 0x1011011; + segment = 0x1011011; break; case 10: - segs = 0x1111011; + segment = 0x1111011; break; case 11: - segs = 0x1101101; + segment = 0x1101101; break; case 12: - segs = 0x1110100; + segment = 0x1110100; break; case 13: - segs = 0x0101111; + segment = 0x0101111; break; case 14: - segs = 0x1111100; + segment = 0x1111100; break; case 15: - segs = 0x1111000; + segment = 0x1111000; break; default: - segs = 0x0001000; + segment = 0x0001000; break; // a dash '-' } - if ((segs & 0x1) != 0) { + if ((segment & 0x1) != 0) { summary |= 4; // vertical seg in bottom right } - if ((segs & 0x10) != 0) { + if ((segment & 0x10) != 0) { summary |= 2; // vertical seg in top right } - if ((segs & 0x100) != 0) { + if ((segment & 0x100) != 0) { summary |= 8; // horizontal seg at bottom } - if ((segs & 0x1000) != 0) { + if ((segment & 0x1000) != 0) { summary |= 64; // horizontal seg at middle } - if ((segs & 0x10000) != 0) { + if ((segment & 0x10000) != 0) { summary |= 1; // horizontal seg at top } - if ((segs & 0x100000) != 0) { + if ((segment & 0x100000) != 0) { summary |= 16; // vertical seg at bottom left } - if ((segs & 0x1000000) != 0) { + if ((segment & 0x1000000) != 0) { summary |= 32; // vertical seg at top left } if (state.getPort(1) == Value.TRUE) { diff --git a/src/main/java/com/cburch/logisim/std/io/Io.java b/src/main/java/com/cburch/logisim/std/io/Io.java index 16cdfef..356dedd 100644 --- a/src/main/java/com/cburch/logisim/std/io/Io.java +++ b/src/main/java/com/cburch/logisim/std/io/Io.java @@ -18,41 +18,41 @@ public class Io extends Library { static final AttributeOption LABEL_CENTER = new AttributeOption("center", "center", Strings.getter("ioLabelCenter")); static final Attribute ATTR_COLOR = Attributes.forColor("color", - Strings.getter("ioColorAttr")); + Strings.getter("ioColorAttr")); static final Attribute ATTR_ON_COLOR - = Attributes.forColor("color", Strings.getter("ioOnColor")); + = Attributes.forColor("color", Strings.getter("ioOnColor")); static final Attribute ATTR_OFF_COLOR - = Attributes.forColor("offcolor", Strings.getter("ioOffColor")); + = Attributes.forColor("offcolor", Strings.getter("ioOffColor")); static final Attribute ATTR_BACKGROUND - = Attributes.forColor("bg", Strings.getter("ioBackgroundColor")); + = Attributes.forColor("bg", Strings.getter("ioBackgroundColor")); static final Attribute ATTR_LABEL_LOCATION = Attributes.forOption("labelloc", - Strings.getter("ioLabelLocAttr"), - new Object[]{LABEL_CENTER, Direction.NORTH, Direction.SOUTH, - Direction.EAST, Direction.WEST}); + Strings.getter("ioLabelLocAttr"), + new Object[]{LABEL_CENTER, Direction.NORTH, Direction.SOUTH, + Direction.EAST, Direction.WEST}); static final Attribute ATTR_LABEL_COLOR = Attributes.forColor("labelcolor", - Strings.getter("ioLabelColorAttr")); + Strings.getter("ioLabelColorAttr")); static final Attribute ATTR_ACTIVE = Attributes.forBoolean("active", - Strings.getter("ioActiveAttr")); + Strings.getter("ioActiveAttr")); static final Color DEFAULT_BACKGROUND = new Color(255, 255, 255, 0); - private static FactoryDescription[] DESCRIPTIONS = { - new FactoryDescription("Button", Strings.getter("buttonComponent"), - "button.gif", "Button"), - new FactoryDescription("Joystick", Strings.getter("joystickComponent"), - "joystick.gif", "Joystick"), - new FactoryDescription("Keyboard", Strings.getter("keyboardComponent"), - "keyboard.gif", "Keyboard"), - new FactoryDescription("LED", Strings.getter("ledComponent"), - "led.gif", "Led"), - new FactoryDescription("7-Segment Display", Strings.getter("sevenSegmentComponent"), - "7seg.gif", "SevenSegment"), - new FactoryDescription("Hex Digit Display", Strings.getter("hexDigitComponent"), - "hexdig.gif", "HexDigit"), - new FactoryDescription("DotMatrix", Strings.getter("dotMatrixComponent"), - "dotmat.gif", "DotMatrix"), - new FactoryDescription("TTY", Strings.getter("ttyComponent"), - "tty.gif", "Tty"), + private static final FactoryDescription[] DESCRIPTIONS = { + new FactoryDescription("Button", Strings.getter("buttonComponent"), + "button.gif", "Button"), + new FactoryDescription("Joystick", Strings.getter("joystickComponent"), + "joystick.gif", "Joystick"), + new FactoryDescription("Keyboard", Strings.getter("keyboardComponent"), + "keyboard.gif", "Keyboard"), + new FactoryDescription("LED", Strings.getter("ledComponent"), + "led.gif", "Led"), + new FactoryDescription("7-Segment Display", Strings.getter("sevenSegmentComponent"), + "7seg.gif", "SevenSegment"), + new FactoryDescription("Hex Digit Display", Strings.getter("hexDigitComponent"), + "hexdig.gif", "HexDigit"), + new FactoryDescription("DotMatrix", Strings.getter("dotMatrixComponent"), + "dotmat.gif", "DotMatrix"), + new FactoryDescription("TTY", Strings.getter("ttyComponent"), + "tty.gif", "Tty"), }; private List tools = null; diff --git a/src/main/java/com/cburch/logisim/std/io/Joystick.java b/src/main/java/com/cburch/logisim/std/io/Joystick.java index 7e21f33..90e646b 100644 --- a/src/main/java/com/cburch/logisim/std/io/Joystick.java +++ b/src/main/java/com/cburch/logisim/std/io/Joystick.java @@ -23,30 +23,34 @@ public class Joystick extends InstanceFactory { - static final Attribute ATTR_WIDTH = Attributes.forBitWidth("bits", - Strings.getter("ioBitWidthAttr"), 2, 5); + static final Attribute ATTR_WIDTH = Attributes.forBitWidth("bits", Strings.getter("ioBitWidthAttr"), 2, 5); public Joystick() { super("Joystick", Strings.getter("joystickComponent")); - setAttributes(new Attribute[]{ATTR_WIDTH, Io.ATTR_COLOR}, - new Object[]{BitWidth.create(4), Color.RED}); + setAttributes( + new Attribute[]{ + ATTR_WIDTH, + Io.ATTR_COLOR + }, new Object[]{ + BitWidth.create(4), + Color.RED + } + ); setKeyConfigurator(new BitWidthConfigurator(ATTR_WIDTH, 2, 5)); setOffsetBounds(Bounds.create(-30, -10, 30, 30)); setIconName("joystick.gif"); setPorts(new Port[]{ - new Port(0, 0, Port.OUTPUT, ATTR_WIDTH), - new Port(0, 10, Port.OUTPUT, ATTR_WIDTH), + new Port(0, 0, Port.OUTPUT, ATTR_WIDTH), + new Port(0, 10, Port.OUTPUT, ATTR_WIDTH), }); setInstancePoker(Poker.class); } - private static void drawBall(Graphics g, int x, int y, Color c, - boolean inColor) { + private static void drawBall(Graphics g, int x, int y, Color color, boolean inColor) { if (inColor) { - g.setColor(c == null ? Color.RED : c); + g.setColor(color == null ? Color.RED : color); } else { - int hue = c == null ? 128 - : (c.getRed() + c.getGreen() + c.getBlue()) / 3; + int hue = color == null ? 128 : (color.getRed() + color.getGreen() + color.getBlue()) / 3; g.setColor(new Color(hue, hue, hue)); } GraphicsUtil.switchToWidth(g, 1); @@ -100,8 +104,7 @@ public void paintInstance(InstancePainter painter) { Graphics g = painter.getGraphics(); g.drawRoundRect(x - 30, y - 10, 30, 30, 8, 8); g.drawRoundRect(x - 28, y - 8, 26, 26, 4, 4); - drawBall(g, x - 15, y + 5, painter.getAttributeValue(Io.ATTR_COLOR), - painter.shouldDrawColor()); + drawBall(g, x - 15, y + 5, painter.getAttributeValue(Io.ATTR_COLOR), painter.shouldDrawColor()); painter.drawPorts(); } diff --git a/src/main/java/com/cburch/logisim/std/io/Keyboard.java b/src/main/java/com/cburch/logisim/std/io/Keyboard.java index b1a6b3e..9879524 100644 --- a/src/main/java/com/cburch/logisim/std/io/Keyboard.java +++ b/src/main/java/com/cburch/logisim/std/io/Keyboard.java @@ -36,13 +36,20 @@ public class Keyboard extends InstanceFactory { private static final char FORM_FEED = '\u000c'; // control-L private static final Attribute ATTR_BUFFER - = Attributes.forIntegerRange("buflen", - Strings.getter("keybBufferLengthAttr"), 1, 256); + = Attributes.forIntegerRange("buflen", + Strings.getter("keybBufferLengthAttr"), 1, 256); public Keyboard() { super("Keyboard", Strings.getter("keyboardComponent")); - setAttributes(new Attribute[]{ATTR_BUFFER, StdAttr.EDGE_TRIGGER}, - new Object[]{32, StdAttr.TRIG_RISING}); + setAttributes( + new Attribute[]{ + ATTR_BUFFER, + StdAttr.EDGE_TRIGGER + }, new Object[]{ + 32, + StdAttr.TRIG_RISING + } + ); setOffsetBounds(Bounds.create(0, -15, WIDTH, HEIGHT)); setIconName("keyboard.gif"); setInstancePoker(Poker.class); @@ -83,18 +90,18 @@ private static KeyboardData getKeyboardState(InstanceState state) { public static void addToBuffer(InstanceState state, char[] newChars) { KeyboardData keyboardData = getKeyboardState(state); - for (int i = 0; i < newChars.length; i++) { - keyboardData.insert(newChars[i]); + for (char newChar : newChars) { + keyboardData.insert(newChar); } } @Override - public void propagate(InstanceState circState) { - Object trigger = circState.getAttributeValue(StdAttr.EDGE_TRIGGER); - KeyboardData state = getKeyboardState(circState); - Value clear = circState.getPort(CLR); - Value clock = circState.getPort(CK); - Value enable = circState.getPort(RE); + public void propagate(InstanceState circuitState) { + Object trigger = circuitState.getAttributeValue(StdAttr.EDGE_TRIGGER); + KeyboardData state = getKeyboardState(circuitState); + Value clear = circuitState.getPort(CLR); + Value clock = circuitState.getPort(CK); + Value enable = circuitState.getPort(RE); char c; synchronized (state) { @@ -116,8 +123,8 @@ public void propagate(InstanceState circState) { c = state.getChar(0); } Value out = Value.createKnown(BitWidth.create(7), c & 0x7F); - circState.setPort(OUT, out, DELAY0); - circState.setPort(AVL, c != '\0' ? Value.TRUE : Value.FALSE, DELAY1); + circuitState.setPort(OUT, out, DELAY0); + circuitState.setPort(AVL, c != '\0' ? Value.TRUE : Value.FALSE, DELAY1); } @Override @@ -133,8 +140,8 @@ public void paintInstance(InstancePainter painter) { if (showState) { String str; - int dispStart; - int dispEnd; + int displayStart; + int displayEnd; ArrayList specials = new ArrayList<>(); FontMetrics fm = null; KeyboardData state = getKeyboardState(painter); @@ -148,13 +155,13 @@ public void paintInstance(InstancePainter painter) { fm = g.getFontMetrics(DEFAULT_FONT); state.updateDisplay(fm); } - dispStart = state.getDisplayStart(); - dispEnd = state.getDisplayEnd(); + displayStart = state.getDisplayStart(); + displayEnd = state.getDisplayEnd(); } if (str.length() > 0) { Bounds bds = painter.getBounds(); - drawBuffer(g, fm, str, dispStart, dispEnd, specials, bds); + drawBuffer(g, fm, str, displayStart, displayEnd, specials, bds); } } else { Bounds bds = painter.getBounds(); @@ -184,48 +191,46 @@ private void drawDots(Graphics g, int x, int y, int width, int ascent) { } } - private void drawBuffer(Graphics g, FontMetrics fm, String str, - int dispStart, int dispEnd, ArrayList specials, Bounds bds) { - int x = bds.getX(); - int y = bds.getY(); + private void drawBuffer(Graphics g, FontMetrics fm, String str, int displayStart, int displayEnd, + ArrayList specials, Bounds bounds) { + int x = bounds.getX(); + int y = bounds.getY(); g.setFont(DEFAULT_FONT); if (fm == null) { fm = g.getFontMetrics(); } - int asc = fm.getAscent(); + int ascent = fm.getAscent(); int x0 = x + 8; - int ys = y + (HEIGHT + asc) / 2; + int ys = y + (HEIGHT + ascent) / 2; int dotsWidth = fm.stringWidth("m"); int xs; - if (dispStart > 0) { + if (displayStart > 0) { g.drawString(str.substring(0, 1), x0, ys); xs = x0 + fm.stringWidth(str.charAt(0) + "m"); - drawDots(g, xs - dotsWidth, ys, dotsWidth, asc); - String sub = str.substring(dispStart, dispEnd); + drawDots(g, xs - dotsWidth, ys, dotsWidth, ascent); + String sub = str.substring(displayStart, displayEnd); g.drawString(sub, xs, ys); - if (dispEnd < str.length()) { - drawDots(g, xs + fm.stringWidth(sub), ys, dotsWidth, asc); + if (displayEnd < str.length()) { + drawDots(g, xs + fm.stringWidth(sub), ys, dotsWidth, ascent); } - } else if (dispEnd < str.length()) { - String sub = str.substring(dispStart, dispEnd); + } else if (displayEnd < str.length()) { + String sub = str.substring(displayStart, displayEnd); xs = x0; g.drawString(sub, xs, ys); - drawDots(g, xs + fm.stringWidth(sub), ys, dotsWidth, asc); + drawDots(g, xs + fm.stringWidth(sub), ys, dotsWidth, ascent); } else { xs = x0; g.drawString(str, xs, ys); } if (specials.size() > 0) { - drawSpecials(specials, x0, xs, ys, asc, g, fm, - str, dispStart, dispEnd); + drawSpecials(specials, x0, xs, ys, ascent, g, fm, str, displayStart, displayEnd); } } - private void drawSpecials(ArrayList specials, int x0, int xs, int ys, - int asc, Graphics g, FontMetrics fm, - String str, int dispStart, int dispEnd) { + private void drawSpecials(ArrayList specials, int x0, int xs, int ys, int ascent, Graphics g, FontMetrics fm, + String str, int displayStart, int displayEnd) { int[] px = new int[3]; int[] py = new int[3]; for (Integer special : specials) { @@ -236,9 +241,9 @@ private void drawSpecials(ArrayList specials, int x0, int xs, int ys, if (pos == 0) { w0 = x0; w1 = x0 + fm.stringWidth(str.substring(0, 1)); - } else if (pos >= dispStart && pos < dispEnd) { - w0 = xs + fm.stringWidth(str.substring(dispStart, pos)); - w1 = xs + fm.stringWidth(str.substring(dispStart, pos + 1)); + } else if (pos >= displayStart && pos < displayEnd) { + w0 = xs + fm.stringWidth(str.substring(displayStart, pos)); + w1 = xs + fm.stringWidth(str.substring(displayStart, pos + 1)); } else { continue; // this character is not in current view } @@ -247,7 +252,7 @@ private void drawSpecials(ArrayList specials, int x0, int xs, int ys, int key = code >> 16; if (key == '\b') { - int y1 = ys - asc / 2; + int y1 = ys - ascent / 2; g.drawLine(w0, y1, w1, y1); px[0] = w0 + 3; py[0] = y1 - 3; @@ -259,7 +264,7 @@ private void drawSpecials(ArrayList specials, int x0, int xs, int ys, } else if (key == '\n') { int y1 = ys - 3; px[0] = w1; - py[0] = ys - asc; + py[0] = ys - ascent; px[1] = w1; py[1] = y1; px[2] = w0; @@ -273,7 +278,7 @@ private void drawSpecials(ArrayList specials, int x0, int xs, int ys, py[2] = y1 + 3; g.drawPolyline(px, py, 3); } else if (key == FORM_FEED) { - g.drawRect(w0, ys - asc, w1 - w0, asc); + g.drawRect(w0, ys - ascent, w1 - w0, ascent); } } } @@ -320,8 +325,7 @@ public void keyTyped(InstanceState state, KeyEvent e) { char ch = e.getKeyChar(); boolean changed = false; if (ch != KeyEvent.CHAR_UNDEFINED) { - if (!Character.isISOControl(ch) || ch == '\b' || ch == '\n' - || ch == FORM_FEED) { + if (!Character.isISOControl(ch) || ch == '\b' || ch == '\n' || ch == FORM_FEED) { synchronized (data) { changed = data.insert(ch); } @@ -341,21 +345,21 @@ public void draw(InstancePainter painter) { String str; int cursor; - int dispStart; + int displayStart; synchronized (data) { str = data.toString(); cursor = data.getCursorPosition(); if (!data.isDisplayValid()) { data.updateDisplay(fm); } - dispStart = data.getDisplayStart(); + displayStart = data.getDisplayStart(); } int asc = fm.getAscent(); int x = bds.getX() + 8; - if (dispStart > 0) { + if (displayStart > 0) { x += fm.stringWidth(str.charAt(0) + "m"); - x += fm.stringWidth(str.substring(dispStart, cursor)); + x += fm.stringWidth(str.substring(displayStart, cursor)); } else if (cursor >= str.length()) { x += fm.stringWidth(str); } else { diff --git a/src/main/java/com/cburch/logisim/std/io/KeyboardData.java b/src/main/java/com/cburch/logisim/std/io/KeyboardData.java index c4b6165..af2999e 100644 --- a/src/main/java/com/cburch/logisim/std/io/KeyboardData.java +++ b/src/main/java/com/cburch/logisim/std/io/KeyboardData.java @@ -14,9 +14,9 @@ class KeyboardData implements InstanceData, Cloneable { private String str; private int bufferLength; private int cursorPos; - private boolean dispValid; - private int dispStart; - private int dispEnd; + private boolean displayValid; + private int displayStart; + private int displayEnd; public KeyboardData(int capacity) { lastClock = Value.UNKNOWN; @@ -42,15 +42,15 @@ public Value setLastClock(Value newClock) { } public boolean isDisplayValid() { - return dispValid; + return displayValid; } public int getDisplayStart() { - return dispStart; + return displayStart; } public int getDisplayEnd() { - return dispEnd; + return displayEnd; } public int getCursorPosition() { @@ -74,7 +74,7 @@ public void updateBufferLength(int len) { } buffer = newBuf; str = null; - dispValid = false; + displayValid = false; } } } @@ -116,9 +116,9 @@ public void clear() { bufferLength = 0; cursorPos = 0; str = ""; - dispValid = false; - dispStart = 0; - dispEnd = 0; + displayValid = false; + displayStart = 0; + displayEnd = 0; } public char dequeue() { @@ -128,8 +128,8 @@ public char dequeue() { return '\0'; } char ret = buf[0]; - for (int i = 1; i < len; i++) { - buf[i - 1] = buf[i]; + if (len - 1 >= 0) { + System.arraycopy(buf, 1, buf, 0, len - 1); } bufferLength = len - 1; int pos = cursorPos; @@ -137,7 +137,7 @@ public char dequeue() { cursorPos = pos - 1; } str = null; - dispValid = false; + displayValid = false; return ret; } @@ -148,14 +148,14 @@ public boolean insert(char value) { return false; } int pos = cursorPos; - for (int i = len; i > pos; i--) { - buf[i] = buf[i - 1]; + if (len - pos >= 0) { + System.arraycopy(buf, pos, buf, pos + 1, len - pos); } buf[pos] = value; bufferLength = len + 1; cursorPos = pos + 1; str = null; - dispValid = false; + displayValid = false; return true; } @@ -166,12 +166,12 @@ public boolean delete() { if (pos >= len) { return false; } - for (int i = pos + 1; i < len; i++) { - buf[i - 1] = buf[i]; + if (len - (pos + 1) >= 0) { + System.arraycopy(buf, pos + 1, buf, pos + 1 - 1, len - (pos + 1)); } bufferLength = len - 1; str = null; - dispValid = false; + displayValid = false; return true; } @@ -183,7 +183,7 @@ public boolean moveCursorBy(int delta) { return false; } cursorPos = newPos; - dispValid = false; + displayValid = false; return true; } @@ -197,17 +197,17 @@ public boolean setCursor(int value) { return false; } cursorPos = value; - dispValid = false; + displayValid = false; return true; } public void updateDisplay(FontMetrics fm) { - if (dispValid) { + if (displayValid) { return; } - int pos = cursorPos; - int i0 = dispStart; - int i1 = dispEnd; + int cursorPos = this.cursorPos; + int i0 = displayStart; + int i1 = displayEnd; String str = toString(); int len = str.length(); int max = Keyboard.WIDTH - 8 - 4; @@ -218,29 +218,28 @@ public void updateDisplay(FontMetrics fm) { // grow to include end of string if possible int w0 = fm.stringWidth(str.charAt(0) + "m"); int w1 = fm.stringWidth("m"); - int w = i0 == 0 ? fm.stringWidth(str) - : w0 + fm.stringWidth(str.substring(i0)); + int w = i0 == 0 ? fm.stringWidth(str) : w0 + fm.stringWidth(str.substring(i0)); if (w <= max) { i1 = len; } // rearrange start/end so as to include cursor - if (pos <= i0) { - if (pos < i0) { - i1 += pos - i0; - i0 = pos; + if (cursorPos <= i0) { + if (cursorPos < i0) { + i1 += cursorPos - i0; + i0 = cursorPos; } - if (pos == i0 && i0 > 0) { + if (cursorPos == i0 && i0 > 0) { i0--; i1--; } } - if (pos >= i1) { - if (pos > i1) { - i0 += pos - i1; - i1 = pos; + if (cursorPos >= i1) { + if (cursorPos > i1) { + i0 += cursorPos - i1; + i1 = cursorPos; } - if (pos == i1 && i1 < len) { + if (cursorPos == i1 && i1 < len) { i0++; i1++; } @@ -258,7 +257,7 @@ public void updateDisplay(FontMetrics fm) { i0--; } } else { // should shrink - if (pos < (i0 + i1) / 2) { + if (cursorPos < (i0 + i1) / 2) { i1--; while (!fits(fm, str, w0, w1, i0, i1, max)) { i1--; @@ -275,13 +274,12 @@ public void updateDisplay(FontMetrics fm) { i0 = 0; } } - dispStart = i0; - dispEnd = i1; - dispValid = true; + displayStart = i0; + displayEnd = i1; + displayValid = true; } - private boolean fits(FontMetrics fm, String str, int w0, int w1, - int i0, int i1, int max) { + private boolean fits(FontMetrics fm, String str, int w0, int w1, int i0, int i1, int max) { if (i0 >= i1) { return true; } @@ -298,4 +296,4 @@ private boolean fits(FontMetrics fm, String str, int w0, int w1, } return w <= max; } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/io/Led.java b/src/main/java/com/cburch/logisim/std/io/Led.java index edf4dc6..b7e06b0 100644 --- a/src/main/java/com/cburch/logisim/std/io/Led.java +++ b/src/main/java/com/cburch/logisim/std/io/Led.java @@ -24,17 +24,27 @@ public class Led extends InstanceFactory { public Led() { super("LED", Strings.getter("ledComponent")); - setAttributes(new Attribute[]{ - StdAttr.FACING, Io.ATTR_ON_COLOR, Io.ATTR_OFF_COLOR, + setAttributes( + new Attribute[]{ + StdAttr.FACING, + Io.ATTR_ON_COLOR, + Io.ATTR_OFF_COLOR, Io.ATTR_ACTIVE, - StdAttr.LABEL, Io.ATTR_LABEL_LOCATION, - StdAttr.LABEL_FONT, Io.ATTR_LABEL_COLOR - }, new Object[]{ - Direction.WEST, new Color(240, 0, 0), Color.DARK_GRAY, + StdAttr.LABEL, + Io.ATTR_LABEL_LOCATION, + StdAttr.LABEL_FONT, + Io.ATTR_LABEL_COLOR + }, new Object[]{ + Direction.WEST, + new Color(240, 0, 0), + Color.DARK_GRAY, Boolean.TRUE, - "", Io.LABEL_CENTER, - StdAttr.DEFAULT_LABEL_FONT, Color.BLACK - }); + "", + Io.LABEL_CENTER, + StdAttr.DEFAULT_LABEL_FONT, + Color.BLACK + } + ); setFacingAttribute(StdAttr.FACING); setIconName("led.gif"); setPorts(new Port[]{new Port(0, 0, Port.INPUT, 1)}); @@ -95,8 +105,7 @@ private void computeTextField(Instance instance) { } } - instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, - x, y, hAlign, vAlign); + instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, x, y, hAlign, vAlign); } @Override @@ -115,8 +124,7 @@ public void paintGhost(InstancePainter painter) { Graphics graphics = painter.getGraphics(); Bounds bounds = painter.getBounds(); GraphicsUtil.switchToWidth(graphics, 2); - graphics.drawOval(bounds.getX() + 1, bounds.getY() + 1, - bounds.getWidth() - 2, bounds.getHeight() - 2); + graphics.drawOval(bounds.getX() + 1, bounds.getY() + 1, bounds.getWidth() - 2, bounds.getHeight() - 2); } @Override diff --git a/src/main/java/com/cburch/logisim/std/io/SevenSegment.java b/src/main/java/com/cburch/logisim/std/io/SevenSegment.java index 04045de..9bef58c 100644 --- a/src/main/java/com/cburch/logisim/std/io/SevenSegment.java +++ b/src/main/java/com/cburch/logisim/std/io/SevenSegment.java @@ -21,21 +21,30 @@ public class SevenSegment extends InstanceFactory { public SevenSegment() { super("7-Segment Display", Strings.getter("sevenSegmentComponent")); - setAttributes(new Attribute[]{Io.ATTR_ON_COLOR, Io.ATTR_OFF_COLOR, - Io.ATTR_BACKGROUND, Io.ATTR_ACTIVE}, - new Object[]{new Color(240, 0, 0), DEFAULT_OFF, - Io.DEFAULT_BACKGROUND, Boolean.TRUE}); + setAttributes( + new Attribute[]{ + Io.ATTR_ON_COLOR, + Io.ATTR_OFF_COLOR, + Io.ATTR_BACKGROUND, + Io.ATTR_ACTIVE + }, new Object[]{ + new Color(240, 0, 0), + DEFAULT_OFF, + Io.DEFAULT_BACKGROUND, + Boolean.TRUE + } + ); setOffsetBounds(Bounds.create(-5, 0, 40, 60)); setIconName("7seg.gif"); setPorts(new Port[]{ - new Port(20, 0, Port.INPUT, 1), - new Port(30, 0, Port.INPUT, 1), - new Port(20, 60, Port.INPUT, 1), - new Port(10, 60, Port.INPUT, 1), - new Port(0, 60, Port.INPUT, 1), - new Port(10, 0, Port.INPUT, 1), - new Port(0, 0, Port.INPUT, 1), - new Port(30, 60, Port.INPUT, 1), + new Port(20, 0, Port.INPUT, 1), + new Port(30, 0, Port.INPUT, 1), + new Port(20, 60, Port.INPUT, 1), + new Port(10, 60, Port.INPUT, 1), + new Port(0, 60, Port.INPUT, 1), + new Port(10, 0, Port.INPUT, 1), + new Port(0, 0, Port.INPUT, 1), + new Port(30, 60, Port.INPUT, 1), }); } @@ -78,13 +87,13 @@ static void drawBase(InstancePainter painter) { static void ensureSegments() { if (SEGMENTS == null) { SEGMENTS = new Bounds[]{ - Bounds.create(3, 8, 19, 4), - Bounds.create(23, 10, 4, 19), - Bounds.create(23, 30, 4, 19), - Bounds.create(3, 47, 19, 4), - Bounds.create(-2, 30, 4, 19), - Bounds.create(-2, 10, 4, 19), - Bounds.create(3, 28, 19, 4) + Bounds.create(3, 8, 19, 4), + Bounds.create(23, 10, 4, 19), + Bounds.create(23, 30, 4, 19), + Bounds.create(3, 47, 19, 4), + Bounds.create(-2, 30, 4, 19), + Bounds.create(-2, 10, 4, 19), + Bounds.create(3, 28, 19, 4) }; } } diff --git a/src/main/java/com/cburch/logisim/std/io/Strings.java b/src/main/java/com/cburch/logisim/std/io/Strings.java index 553e3b4..f985525 100644 --- a/src/main/java/com/cburch/logisim/std/io/Strings.java +++ b/src/main/java/com/cburch/logisim/std/io/Strings.java @@ -9,8 +9,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "std"); + private static final LocaleManager source = new LocaleManager("logisim", "std"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/std/io/Tty.java b/src/main/java/com/cburch/logisim/std/io/Tty.java index 3bc472c..f5938e7 100644 --- a/src/main/java/com/cburch/logisim/std/io/Tty.java +++ b/src/main/java/com/cburch/logisim/std/io/Tty.java @@ -36,46 +36,52 @@ public class Tty extends InstanceFactory { private static final Font DEFAULT_FONT = new Font("monospaced", Font.PLAIN, 12); private static final Attribute ATTR_COLUMNS - = Attributes.forIntegerRange("cols", - Strings.getter("ttyColsAttr"), 1, 120); + = Attributes.forIntegerRange("cols", Strings.getter("ttyColsAttr"), 1, 120); private static final Attribute ATTR_ROWS - = Attributes.forIntegerRange("rows", - Strings.getter("ttyRowsAttr"), 1, 48); + = Attributes.forIntegerRange("rows", Strings.getter("ttyRowsAttr"), 1, 48); public Tty() { super("TTY", Strings.getter("ttyComponent")); - setAttributes(new Attribute[]{ - ATTR_ROWS, ATTR_COLUMNS, StdAttr.EDGE_TRIGGER, - Io.ATTR_COLOR, Io.ATTR_BACKGROUND - }, new Object[]{ - 8, 32, StdAttr.TRIG_RISING, - Color.BLACK, DEFAULT_BACKGROUND - }); + setAttributes( + new Attribute[]{ + ATTR_ROWS, + ATTR_COLUMNS, + StdAttr.EDGE_TRIGGER, + Io.ATTR_COLOR, + Io.ATTR_BACKGROUND + }, new Object[]{ + 8, + 32, + StdAttr.TRIG_RISING, + Color.BLACK, + DEFAULT_BACKGROUND + } + ); setIconName("tty.gif"); - Port[] ps = new Port[4]; - ps[CLR] = new Port(20, 10, Port.INPUT, 1); - ps[CK] = new Port(0, 0, Port.INPUT, 1); - ps[WE] = new Port(10, 10, Port.INPUT, 1); - ps[IN] = new Port(0, -10, Port.INPUT, 7); - ps[CLR].setToolTip(Strings.getter("ttyClearTip")); - ps[CK].setToolTip(Strings.getter("ttyClockTip")); - ps[WE].setToolTip(Strings.getter("ttyEnableTip")); - ps[IN].setToolTip(Strings.getter("ttyInputTip")); - setPorts(ps); + Port[] ports = new Port[4]; + ports[CLR] = new Port(20, 10, Port.INPUT, 1); + ports[CK] = new Port(0, 0, Port.INPUT, 1); + ports[WE] = new Port(10, 10, Port.INPUT, 1); + ports[IN] = new Port(0, -10, Port.INPUT, 7); + ports[CLR].setToolTip(Strings.getter("ttyClearTip")); + ports[CK].setToolTip(Strings.getter("ttyClockTip")); + ports[WE].setToolTip(Strings.getter("ttyEnableTip")); + ports[IN].setToolTip(Strings.getter("ttyInputTip")); + setPorts(ports); } - private static int getRowCount(Object val) { - if (val instanceof Integer) { - return (Integer) val; + private static int getRowCount(Object value) { + if (value instanceof Integer) { + return (Integer) value; } else { return 4; } } - private static int getColumnCount(Object val) { - if (val instanceof Integer) { - return (Integer) val; + private static int getColumnCount(Object value) { + if (value instanceof Integer) { + return (Integer) value; } else { return 16; } @@ -139,26 +145,23 @@ public void propagate(InstanceState circState) { public void paintGhost(InstancePainter painter) { Graphics g = painter.getGraphics(); GraphicsUtil.switchToWidth(g, 2); - Bounds bds = painter.getBounds(); - g.drawRoundRect(bds.getX(), bds.getY(), bds.getWidth(), bds.getHeight(), - 10, 10); + Bounds bounds = painter.getBounds(); + g.drawRoundRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 10, 10); } @Override public void paintInstance(InstancePainter painter) { boolean showState = painter.getShowState(); Graphics g = painter.getGraphics(); - Bounds bds = painter.getBounds(); + Bounds bounds = painter.getBounds(); painter.drawClock(CK, Direction.EAST); if (painter.shouldDrawColor()) { g.setColor(painter.getAttributeValue(Io.ATTR_BACKGROUND)); - g.fillRoundRect(bds.getX(), bds.getY(), bds.getWidth(), bds.getHeight(), - 10, 10); + g.fillRoundRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 10, 10); } GraphicsUtil.switchToWidth(g, 2); g.setColor(Color.BLACK); - g.drawRoundRect(bds.getX(), bds.getY(), bds.getWidth(), bds.getHeight(), - 2 * BORDER, 2 * BORDER); + g.drawRoundRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 2 * BORDER, 2 * BORDER); GraphicsUtil.switchToWidth(g, 1); painter.drawPort(CLR); painter.drawPort(WE); @@ -183,8 +186,8 @@ public void paintInstance(InstancePainter painter) { g.setFont(DEFAULT_FONT); g.setColor(painter.getAttributeValue(Io.ATTR_COLOR)); FontMetrics fm = g.getFontMetrics(); - int x = bds.getX() + BORDER; - int y = bds.getY() + BORDER + (ROW_HEIGHT + fm.getAscent()) / 2; + int x = bounds.getX() + BORDER; + int y = bounds.getY() + BORDER + (ROW_HEIGHT + fm.getAscent()) / 2; for (int i = 0; i < rows; i++) { g.drawString(rowData[i], x, y); if (i == curRow) { @@ -197,12 +200,12 @@ public void paintInstance(InstancePainter painter) { String str = Strings.get("ttyDesc", "" + rows, "" + cols); FontMetrics fm = g.getFontMetrics(); int strWidth = fm.stringWidth(str); - if (strWidth + BORDER > bds.getWidth()) { + if (strWidth + BORDER > bounds.getWidth()) { str = Strings.get("ttyDescShort"); strWidth = fm.stringWidth(str); } - int x = bds.getX() + (bds.getWidth() - strWidth) / 2; - int y = bds.getY() + (bds.getHeight() + fm.getAscent()) / 2; + int x = bounds.getX() + (bounds.getWidth() - strWidth) / 2; + int y = bounds.getY() + (bounds.getHeight() + fm.getAscent()) / 2; g.drawString(str, x, y); } } diff --git a/src/main/java/com/cburch/logisim/std/io/TtyState.java b/src/main/java/com/cburch/logisim/std/io/TtyState.java index 05ffd81..5d0225a 100644 --- a/src/main/java/com/cburch/logisim/std/io/TtyState.java +++ b/src/main/java/com/cburch/logisim/std/io/TtyState.java @@ -10,10 +10,10 @@ class TtyState implements InstanceData, Cloneable { + private final StringBuffer lastRow; private Value lastClock; private String[] rowData; private int colCount; - private StringBuffer lastRow; private int row; private boolean sendStdout; @@ -117,8 +117,7 @@ public void updateSize(int rows, int cols) { int oldRows = rowData.length + 1; if (rows != oldRows) { String[] newData = new String[rows - 1]; - if (rows > oldRows // rows have been added, - || row < rows - 1) { // or rows removed but filled rows fit + if (rows > oldRows || row < rows - 1) { // rows added, or rows removed but filled rows fit System.arraycopy(rowData, 0, newData, 0, row); Arrays.fill(newData, row, rows - 1, ""); } else { // rows removed, and some filled rows must go diff --git a/src/main/java/com/cburch/logisim/std/memory/AbstractFlipFlop.java b/src/main/java/com/cburch/logisim/std/memory/AbstractFlipFlop.java index a5b21c2..9a554da 100644 --- a/src/main/java/com/cburch/logisim/std/memory/AbstractFlipFlop.java +++ b/src/main/java/com/cburch/logisim/std/memory/AbstractFlipFlop.java @@ -28,45 +28,50 @@ abstract class AbstractFlipFlop extends InstanceFactory { private static final int STD_PORTS = 6; - private Attribute triggerAttribute; + private final Attribute triggerAttribute; - protected AbstractFlipFlop(String name, String iconName, StringGetter desc, - int numInputs, boolean allowLevelTriggers) { + protected AbstractFlipFlop(String name, String iconName, StringGetter desc, int numInputs, boolean allowLevelTriggers) { super(name, desc); setIconName(iconName); triggerAttribute = allowLevelTriggers ? StdAttr.TRIGGER : StdAttr.EDGE_TRIGGER; - setAttributes(new Attribute[]{ - triggerAttribute, StdAttr.LABEL, StdAttr.LABEL_FONT - }, new Object[]{ - StdAttr.TRIG_RISING, "", StdAttr.DEFAULT_LABEL_FONT - }); + setAttributes( + new Attribute[]{ + triggerAttribute, + StdAttr.LABEL, + StdAttr.LABEL_FONT + }, new Object[]{ + StdAttr.TRIG_RISING, + "", + StdAttr.DEFAULT_LABEL_FONT + } + ); setOffsetBounds(Bounds.create(-40, -10, 40, 40)); setInstancePoker(Poker.class); setInstanceLogger(Logger.class); - Port[] ps = new Port[numInputs + STD_PORTS]; + Port[] ports = new Port[numInputs + STD_PORTS]; if (numInputs == 1) { - ps[0] = new Port(-40, 20, Port.INPUT, 1); - ps[1] = new Port(-40, 0, Port.INPUT, 1); + ports[0] = new Port(-40, 20, Port.INPUT, 1); + ports[1] = new Port(-40, 0, Port.INPUT, 1); } else if (numInputs == 2) { - ps[0] = new Port(-40, 0, Port.INPUT, 1); - ps[1] = new Port(-40, 20, Port.INPUT, 1); - ps[2] = new Port(-40, 10, Port.INPUT, 1); + ports[0] = new Port(-40, 0, Port.INPUT, 1); + ports[1] = new Port(-40, 20, Port.INPUT, 1); + ports[2] = new Port(-40, 10, Port.INPUT, 1); } else { throw new RuntimeException("flip-flop input > 2"); } - ps[numInputs + 1] = new Port(0, 0, Port.OUTPUT, 1); - ps[numInputs + 2] = new Port(0, 20, Port.OUTPUT, 1); - ps[numInputs + 3] = new Port(-10, 30, Port.INPUT, 1); - ps[numInputs + 4] = new Port(-30, 30, Port.INPUT, 1); - ps[numInputs + 5] = new Port(-20, 30, Port.INPUT, 1); - ps[numInputs].setToolTip(Strings.getter("flipFlopClockTip")); - ps[numInputs + 1].setToolTip(Strings.getter("flipFlopQTip")); - ps[numInputs + 2].setToolTip(Strings.getter("flipFlopNotQTip")); - ps[numInputs + 3].setToolTip(Strings.getter("flipFlopResetTip")); - ps[numInputs + 4].setToolTip(Strings.getter("flipFlopPresetTip")); - ps[numInputs + 5].setToolTip(Strings.getter("flipFlopEnableTip")); - setPorts(ps); + ports[numInputs + 1] = new Port(0, 0, Port.OUTPUT, 1); + ports[numInputs + 2] = new Port(0, 20, Port.OUTPUT, 1); + ports[numInputs + 3] = new Port(-10, 30, Port.INPUT, 1); + ports[numInputs + 4] = new Port(-30, 30, Port.INPUT, 1); + ports[numInputs + 5] = new Port(-20, 30, Port.INPUT, 1); + ports[numInputs].setToolTip(Strings.getter("flipFlopClockTip")); + ports[numInputs + 1].setToolTip(Strings.getter("flipFlopQTip")); + ports[numInputs + 2].setToolTip(Strings.getter("flipFlopNotQTip")); + ports[numInputs + 3].setToolTip(Strings.getter("flipFlopResetTip")); + ports[numInputs + 4].setToolTip(Strings.getter("flipFlopPresetTip")); + ports[numInputs + 5].setToolTip(Strings.getter("flipFlopEnableTip")); + setPorts(ports); } // @@ -75,25 +80,24 @@ protected AbstractFlipFlop(String name, String iconName, StringGetter desc, protected abstract String getInputName(int index); protected abstract Value computeValue(Value[] inputs, - Value curValue); + Value curValue); // // concrete methods not intended to be overridden // @Override protected void configureNewInstance(Instance instance) { - Bounds bds = instance.getBounds(); - instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, - bds.getX() + bds.getWidth() / 2, bds.getY() - 3, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + Bounds bounds = instance.getBounds(); + instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, bounds.getX() + bounds.getWidth() / 2, bounds.getY() - 3, + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); } @Override public void propagate(InstanceState state) { - boolean changed = false; + boolean isChanged = false; StateData data = (StateData) state.getData(); if (data == null) { - changed = true; + isChanged = true; data = new StateData(); state.setData(data); } @@ -103,10 +107,10 @@ public void propagate(InstanceState state) { boolean triggered = data.updateClock(state.getPort(n), triggerType); if (state.getPort(n + 3) == Value.TRUE) { // clear requested - changed |= data.curValue != Value.FALSE; + isChanged |= data.curValue != Value.FALSE; data.curValue = Value.FALSE; } else if (state.getPort(n + 4) == Value.TRUE) { // preset requested - changed |= data.curValue != Value.TRUE; + isChanged |= data.curValue != Value.TRUE; data.curValue = Value.TRUE; } else if (triggered && state.getPort(n + 5) != Value.FALSE) { // Clock has triggered and flip-flop is enabled: Update the state @@ -117,7 +121,7 @@ public void propagate(InstanceState state) { Value newVal = computeValue(inputs, data.curValue); if (newVal == Value.TRUE || newVal == Value.FALSE) { - changed |= data.curValue != newVal; + isChanged |= data.curValue != newVal; data.curValue = newVal; } } @@ -132,16 +136,15 @@ public void paintInstance(InstancePainter painter) { painter.drawBounds(); painter.drawLabel(); if (painter.getShowState()) { - Location loc = painter.getLocation(); + Location location = painter.getLocation(); StateData myState = (StateData) painter.getData(); if (myState != null) { - int x = loc.getX(); - int y = loc.getY(); + int x = location.getX(); + int y = location.getY(); g.setColor(myState.curValue.getColor()); g.fillOval(x - 26, y + 4, 13, 13); g.setColor(Color.WHITE); - GraphicsUtil.drawCenteredText(g, - myState.curValue.toDisplayString(), x - 19, y + 9); + GraphicsUtil.drawCenteredText(g, myState.curValue.toDisplayString(), x - 19, y + 9); g.setColor(Color.BLACK); } } @@ -169,14 +172,14 @@ public static class Logger extends InstanceLogger { @Override public String getLogName(InstanceState state, Object option) { - String ret = state.getAttributeValue(StdAttr.LABEL); - return ret != null && !ret.equals("") ? ret : null; + String name = state.getAttributeValue(StdAttr.LABEL); + return name != null && !name.equals("") ? name : null; } @Override public Value getLogValue(InstanceState state, Object option) { - StateData s = (StateData) state.getData(); - return s == null ? Value.FALSE : s.curValue; + StateData data = (StateData) state.getData(); + return data == null ? Value.FALSE : data.curValue; } } diff --git a/src/main/java/com/cburch/logisim/std/memory/Counter.java b/src/main/java/com/cburch/logisim/std/memory/Counter.java index a72903d..cd14d44 100644 --- a/src/main/java/com/cburch/logisim/std/memory/Counter.java +++ b/src/main/java/com/cburch/logisim/std/memory/Counter.java @@ -26,20 +26,18 @@ public class Counter extends InstanceFactory { static final AttributeOption ON_GOAL_WRAP = new AttributeOption("wrap", - "wrap", Strings.getter("counterGoalWrap")); + "wrap", Strings.getter("counterGoalWrap")); static final AttributeOption ON_GOAL_STAY = new AttributeOption("stay", - "stay", Strings.getter("counterGoalStay")); + "stay", Strings.getter("counterGoalStay")); static final AttributeOption ON_GOAL_CONT = new AttributeOption("continue", - "continue", Strings.getter("counterGoalContinue")); + "continue", Strings.getter("counterGoalContinue")); static final AttributeOption ON_GOAL_LOAD = new AttributeOption("load", - "load", Strings.getter("counterGoalLoad")); + "load", Strings.getter("counterGoalLoad")); static final Attribute ATTR_MAX = Attributes.forHexInteger("max", - Strings.getter("counterMaxAttr")); + Strings.getter("counterMaxAttr")); static final Attribute ATTR_ON_GOAL = Attributes.forOption("ongoal", - Strings.getter("counterGoalAttr"), - new AttributeOption[]{ON_GOAL_WRAP, ON_GOAL_STAY, ON_GOAL_CONT, - ON_GOAL_LOAD}); + Strings.getter("counterGoalAttr"), new AttributeOption[]{ON_GOAL_WRAP, ON_GOAL_STAY, ON_GOAL_CONT, ON_GOAL_LOAD}); private static final int DELAY = 8; private static final int OUT = 0; @@ -58,22 +56,22 @@ public Counter() { setInstanceLogger(RegisterLogger.class); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); - Port[] ps = new Port[7]; - ps[OUT] = new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH); - ps[IN] = new Port(-30, 0, Port.INPUT, StdAttr.WIDTH); - ps[CK] = new Port(-20, 20, Port.INPUT, 1); - ps[CLR] = new Port(-10, 20, Port.INPUT, 1); - ps[LD] = new Port(-30, -10, Port.INPUT, 1); - ps[CT] = new Port(-30, 10, Port.INPUT, 1); - ps[CARRY] = new Port(0, 10, Port.OUTPUT, 1); - ps[OUT].setToolTip(Strings.getter("counterQTip")); - ps[IN].setToolTip(Strings.getter("counterDataTip")); - ps[CK].setToolTip(Strings.getter("counterClockTip")); - ps[CLR].setToolTip(Strings.getter("counterResetTip")); - ps[LD].setToolTip(Strings.getter("counterLoadTip")); - ps[CT].setToolTip(Strings.getter("counterEnableTip")); - ps[CARRY].setToolTip(Strings.getter("counterCarryTip")); - setPorts(ps); + Port[] ports = new Port[7]; + ports[OUT] = new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH); + ports[IN] = new Port(-30, 0, Port.INPUT, StdAttr.WIDTH); + ports[CK] = new Port(-20, 20, Port.INPUT, 1); + ports[CLR] = new Port(-10, 20, Port.INPUT, 1); + ports[LD] = new Port(-30, -10, Port.INPUT, 1); + ports[CT] = new Port(-30, 10, Port.INPUT, 1); + ports[CARRY] = new Port(0, 10, Port.OUTPUT, 1); + ports[OUT].setToolTip(Strings.getter("counterQTip")); + ports[IN].setToolTip(Strings.getter("counterDataTip")); + ports[CK].setToolTip(Strings.getter("counterClockTip")); + ports[CLR].setToolTip(Strings.getter("counterResetTip")); + ports[LD].setToolTip(Strings.getter("counterLoadTip")); + ports[CT].setToolTip(Strings.getter("counterEnableTip")); + ports[CARRY].setToolTip(Strings.getter("counterCarryTip")); + setPorts(ports); } @Override @@ -83,10 +81,9 @@ public AttributeSet createAttributeSet() { @Override protected void configureNewInstance(Instance instance) { - Bounds bds = instance.getBounds(); - instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, - bds.getX() + bds.getWidth() / 2, bds.getY() - 3, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + Bounds bounds = instance.getBounds(); + instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, bounds.getX() + bounds.getWidth() / 2, bounds.getY() - 3, + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); } @Override @@ -103,53 +100,53 @@ public void propagate(InstanceState state) { Value clock = state.getPort(CK); boolean triggered = data.updateClock(clock, triggerType); - Value newValue; + Value value; boolean carry; if (state.getPort(CLR) == Value.TRUE) { - newValue = Value.createKnown(dataWidth, 0); + value = Value.createKnown(dataWidth, 0); carry = false; } else { boolean ld = state.getPort(LD) == Value.TRUE; boolean ct = state.getPort(CT) != Value.FALSE; - int oldVal = data.value; - int newVal; + int oldValue = data.value; + int newValue; if (!triggered) { - newVal = oldVal; + newValue = oldValue; } else if (ct) { // trigger, enable = 1: should increment or decrement int goal = ld ? 0 : max; - if (oldVal == goal) { + if (oldValue == goal) { Object onGoal = state.getAttributeValue(ATTR_ON_GOAL); if (onGoal == ON_GOAL_WRAP) { - newVal = ld ? max : 0; + newValue = ld ? max : 0; } else if (onGoal == ON_GOAL_STAY) { - newVal = oldVal; + newValue = oldValue; } else if (onGoal == ON_GOAL_LOAD) { Value in = state.getPort(IN); - newVal = in.isFullyDefined() ? in.toIntValue() : 0; - if (newVal > max) { - newVal &= max; + newValue = in.isFullyDefined() ? in.toIntValue() : 0; + if (newValue > max) { + newValue &= max; } } else if (onGoal == ON_GOAL_CONT) { - newVal = ld ? oldVal - 1 : oldVal + 1; + newValue = ld ? oldValue - 1 : oldValue + 1; } else { System.err.println("Invalid goal attribute " + onGoal); //OK - newVal = ld ? max : 0; + newValue = ld ? max : 0; } } else { - newVal = ld ? oldVal - 1 : oldVal + 1; + newValue = ld ? oldValue - 1 : oldValue + 1; } } else if (ld) { // trigger, enable = 0, load = 1: should load Value in = state.getPort(IN); - newVal = in.isFullyDefined() ? in.toIntValue() : 0; - if (newVal > max) { - newVal &= max; + newValue = in.isFullyDefined() ? in.toIntValue() : 0; + if (newValue > max) { + newValue &= max; } } else { // trigger, enable = 0, load = 0: no change - newVal = oldVal; + newValue = oldValue; } - newValue = Value.createKnown(dataWidth, newVal); - newVal = newValue.toIntValue(); - carry = newVal == (ld && ct ? 0 : max); + value = Value.createKnown(dataWidth, newValue); + newValue = value.toIntValue(); + carry = newValue == (ld && ct ? 0 : max); /* I would want this if I were worried about the carry signal * outrunning the clock. But the component's delay should be * enough to take care of it. @@ -163,25 +160,25 @@ public void propagate(InstanceState state) { */ } - data.value = newValue.toIntValue(); - state.setPort(OUT, newValue, DELAY); + data.value = value.toIntValue(); + state.setPort(OUT, value, DELAY); state.setPort(CARRY, carry ? Value.TRUE : Value.FALSE, DELAY); } @Override public void paintInstance(InstancePainter painter) { Graphics g = painter.getGraphics(); - Bounds bds = painter.getBounds(); + Bounds bounds = painter.getBounds(); RegisterData state = (RegisterData) painter.getData(); - BitWidth widthVal = painter.getAttributeValue(StdAttr.WIDTH); - int width = widthVal == null ? 8 : widthVal.getWidth(); + BitWidth widthValue = painter.getAttributeValue(StdAttr.WIDTH); + int width = widthValue == null ? 8 : widthValue.getWidth(); // determine text to draw in label String a; String b = null; if (painter.getShowState()) { - int val = state == null ? 0 : state.value; - String str = StringUtil.toHexString(width, val); + int value = state == null ? 0 : state.value; + String str = StringUtil.toHexString(width, value); if (str.length() <= 4) { a = str; } else { @@ -191,7 +188,7 @@ public void paintInstance(InstancePainter painter) { } } else { a = Strings.get("counterLabel"); - b = Strings.get("registerWidthLabel", "" + widthVal.getWidth()); + b = Strings.get("registerWidthLabel", "" + widthValue.getWidth()); } // draw boundary, label @@ -216,13 +213,10 @@ public void paintInstance(InstancePainter painter) { // draw contents if (b == null) { - GraphicsUtil.drawText(g, a, bds.getX() + 15, bds.getY() + 4, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.drawText(g, a, bounds.getX() + 15, bounds.getY() + 4, GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); } else { - GraphicsUtil.drawText(g, a, bds.getX() + 15, bds.getY() + 3, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); - GraphicsUtil.drawText(g, b, bds.getX() + 15, bds.getY() + 15, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.drawText(g, a, bounds.getX() + 15, bounds.getY() + 3, GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.drawText(g, b, bounds.getX() + 15, bounds.getY() + 15, GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/memory/CounterAttributes.java b/src/main/java/com/cburch/logisim/std/memory/CounterAttributes.java index 544a9e2..f0312b2 100644 --- a/src/main/java/com/cburch/logisim/std/memory/CounterAttributes.java +++ b/src/main/java/com/cburch/logisim/std/memory/CounterAttributes.java @@ -10,22 +10,30 @@ import com.cburch.logisim.data.BitWidth; import com.cburch.logisim.instance.StdAttr; import java.util.List; +import java.util.Objects; class CounterAttributes extends AbstractAttributeSet { private AttributeSet base; public CounterAttributes() { - base = AttributeSets.fixedSet(new Attribute[]{ - StdAttr.WIDTH, Counter.ATTR_MAX, Counter.ATTR_ON_GOAL, + base = AttributeSets.fixedSet( + new Attribute[]{ + StdAttr.WIDTH, + Counter.ATTR_MAX, + Counter.ATTR_ON_GOAL, StdAttr.EDGE_TRIGGER, - StdAttr.LABEL, StdAttr.LABEL_FONT - }, new Object[]{ - BitWidth.create(8), 0xFF, + StdAttr.LABEL, + StdAttr.LABEL_FONT + }, new Object[]{ + BitWidth.create(8), + 0xFF, Counter.ON_GOAL_WRAP, StdAttr.TRIG_RISING, - "", StdAttr.DEFAULT_LABEL_FONT - }); + "", + StdAttr.DEFAULT_LABEL_FONT + } + ); } @Override @@ -45,38 +53,37 @@ public V getValue(Attribute attr) { @Override public void setValue(Attribute attr, V value) { - Object oldValue = base.getValue(attr); - if (oldValue == null ? value == null : oldValue.equals(value)) { + Object baseValue = base.getValue(attr); + if (Objects.equals(baseValue, value)) { return; } Integer newMax = null; if (attr == StdAttr.WIDTH) { - BitWidth oldWidth = base.getValue(StdAttr.WIDTH); - BitWidth newWidth = (BitWidth) value; - int oldW = oldWidth.getWidth(); - int newW = newWidth.getWidth(); - Integer oldValObj = base.getValue(Counter.ATTR_MAX); - int oldVal = oldValObj; - base.setValue(StdAttr.WIDTH, newWidth); - if (newW > oldW) { - newMax = newWidth.getMask(); + BitWidth oldBitWidth = base.getValue(StdAttr.WIDTH); + BitWidth newBitWidth = (BitWidth) value; + int oldWidth = oldBitWidth.getWidth(); + int newWidth = newBitWidth.getWidth(); + int oldValue = base.getValue(Counter.ATTR_MAX); + base.setValue(StdAttr.WIDTH, newBitWidth); + if (newWidth > oldWidth) { + newMax = newBitWidth.getMask(); } else { - int v = oldVal & newWidth.getMask(); - if (v != oldVal) { + int v = oldValue & newBitWidth.getMask(); + if (v != oldValue) { Integer newValObj = v; base.setValue(Counter.ATTR_MAX, newValObj); fireAttributeValueChanged(Counter.ATTR_MAX, newValObj); } } - fireAttributeValueChanged(StdAttr.WIDTH, newWidth); + fireAttributeValueChanged(StdAttr.WIDTH, newBitWidth); } else if (attr == Counter.ATTR_MAX) { - int oldVal = base.getValue(Counter.ATTR_MAX); - BitWidth width = base.getValue(StdAttr.WIDTH); - int newVal = (Integer) value & width.getMask(); - if (newVal != oldVal) { + int oldValue = base.getValue(Counter.ATTR_MAX); + BitWidth bitWidth = base.getValue(StdAttr.WIDTH); + int newValue = (Integer) value & bitWidth.getMask(); + if (newValue != oldValue) { @SuppressWarnings("unchecked") - V val = (V) Integer.valueOf(newVal); + V val = (V) Integer.valueOf(newValue); value = val; } } diff --git a/src/main/java/com/cburch/logisim/std/memory/DFlipFlop.java b/src/main/java/com/cburch/logisim/std/memory/DFlipFlop.java index 93c88c4..89a8876 100644 --- a/src/main/java/com/cburch/logisim/std/memory/DFlipFlop.java +++ b/src/main/java/com/cburch/logisim/std/memory/DFlipFlop.java @@ -8,8 +8,7 @@ public class DFlipFlop extends AbstractFlipFlop { public DFlipFlop() { - super("D Flip-Flop", "dFlipFlop.gif", - Strings.getter("dFlipFlopComponent"), 1, true); + super("D Flip-Flop", "dFlipFlop.gif", Strings.getter("dFlipFlopComponent"), 1, true); } @Override diff --git a/src/main/java/com/cburch/logisim/std/memory/JKFlipFlop.java b/src/main/java/com/cburch/logisim/std/memory/JKFlipFlop.java index a48c88d..300d8ad 100644 --- a/src/main/java/com/cburch/logisim/std/memory/JKFlipFlop.java +++ b/src/main/java/com/cburch/logisim/std/memory/JKFlipFlop.java @@ -8,8 +8,7 @@ public class JKFlipFlop extends AbstractFlipFlop { public JKFlipFlop() { - super("J-K Flip-Flop", "jkFlipFlop.gif", - Strings.getter("jkFlipFlopComponent"), 2, false); + super("J-K Flip-Flop", "jkFlipFlop.gif", Strings.getter("jkFlipFlopComponent"), 2, false); } @Override @@ -18,10 +17,10 @@ protected String getInputName(int index) { } @Override - protected Value computeValue(Value[] inputs, Value curValue) { + protected Value computeValue(Value[] inputs, Value currentValue) { if (inputs[0] == Value.FALSE) { if (inputs[1] == Value.FALSE) { - return curValue; + return currentValue; } else if (inputs[1] == Value.TRUE) { return Value.FALSE; } @@ -29,7 +28,7 @@ protected Value computeValue(Value[] inputs, Value curValue) { if (inputs[1] == Value.FALSE) { return Value.TRUE; } else if (inputs[1] == Value.TRUE) { - return curValue.not(); + return currentValue.not(); } } return Value.UNKNOWN; diff --git a/src/main/java/com/cburch/logisim/std/memory/Mem.java b/src/main/java/com/cburch/logisim/std/memory/Mem.java index bcb186f..34c6616 100644 --- a/src/main/java/com/cburch/logisim/std/memory/Mem.java +++ b/src/main/java/com/cburch/logisim/std/memory/Mem.java @@ -42,9 +42,9 @@ abstract class Mem extends InstanceFactory { // size. And second, I'd alter the MemContents class's PAGE_SIZE_BITS constant // to 14 so that its "page table" isn't quite so big. public static final Attribute ADDR_ATTR = Attributes.forBitWidth( - "addrWidth", Strings.getter("ramAddrWidthAttr"), 2, 24); + "addrWidth", Strings.getter("ramAddrWidthAttr"), 2, 24); public static final Attribute DATA_ATTR = Attributes.forBitWidth( - "dataWidth", Strings.getter("ramDataWidthAttr")); + "dataWidth", Strings.getter("ramDataWidthAttr")); // port-related constants static final int DATA = 0; @@ -55,15 +55,15 @@ abstract class Mem extends InstanceFactory { // other constants static final int DELAY = 10; - private WeakHashMap currentInstanceFiles; + private final WeakHashMap currentInstanceFiles; - Mem(String name, StringGetter desc, int extraPorts) { - super(name, desc); + Mem(String name, StringGetter description, int extraPorts) { + super(name, description); currentInstanceFiles = new WeakHashMap<>(); setInstancePoker(MemPoker.class); setKeyConfigurator(JoinedConfigurator.create( - new BitWidthConfigurator(ADDR_ATTR, 2, 24, 0), - new BitWidthConfigurator(DATA_ATTR))); + new BitWidthConfigurator(ADDR_ATTR, 2, 24, 0), + new BitWidthConfigurator(DATA_ATTR))); setOffsetBounds(Bounds.create(-140, -40, 140, 80)); } @@ -99,7 +99,7 @@ void configureStandardPorts(Instance instance, Port[] ps) { @Override public void paintInstance(InstancePainter painter) { Graphics g = painter.getGraphics(); - Bounds bds = painter.getBounds(); + Bounds bounds = painter.getBounds(); // draw boundary painter.drawBounds(); @@ -107,43 +107,35 @@ public void paintInstance(InstancePainter painter) { // draw contents if (painter.getShowState()) { MemState state = getState(painter); - state.paint(painter.getGraphics(), bds.getX(), bds.getY()); + state.paint(painter.getGraphics(), bounds.getX(), bounds.getY()); } else { - BitWidth addr = painter.getAttributeValue(ADDR_ATTR); - int addrBits = addr.getWidth(); - int bytes = 1 << addrBits; + BitWidth address = painter.getAttributeValue(ADDR_ATTR); + int addressBits = address.getWidth(); + int bytes = 1 << addressBits; String label; if (this instanceof Rom) { - if (addrBits >= 30) { - label = StringUtil.format(Strings.get("romGigabyteLabel"), "" - + (bytes >>> 30)); - } else if (addrBits >= 20) { - label = StringUtil.format(Strings.get("romMegabyteLabel"), "" - + (bytes >> 20)); - } else if (addrBits >= 10) { - label = StringUtil.format(Strings.get("romKilobyteLabel"), "" - + (bytes >> 10)); + if (addressBits >= 30) { + label = StringUtil.format(Strings.get("romGigabyteLabel"), "" + (bytes >>> 30)); + } else if (addressBits >= 20) { + label = StringUtil.format(Strings.get("romMegabyteLabel"), "" + (bytes >> 20)); + } else if (addressBits >= 10) { + label = StringUtil.format(Strings.get("romKilobyteLabel"), "" + (bytes >> 10)); } else { - label = StringUtil.format(Strings.get("romByteLabel"), "" - + bytes); + label = StringUtil.format(Strings.get("romByteLabel"), "" + bytes); } } else { - if (addrBits >= 30) { - label = StringUtil.format(Strings.get("ramGigabyteLabel"), "" - + (bytes >>> 30)); - } else if (addrBits >= 20) { - label = StringUtil.format(Strings.get("ramMegabyteLabel"), "" - + (bytes >> 20)); - } else if (addrBits >= 10) { - label = StringUtil.format(Strings.get("ramKilobyteLabel"), "" - + (bytes >> 10)); + if (addressBits >= 30) { + label = StringUtil.format(Strings.get("ramGigabyteLabel"), "" + (bytes >>> 30)); + } else if (addressBits >= 20) { + label = StringUtil.format(Strings.get("ramMegabyteLabel"), "" + (bytes >> 20)); + } else if (addressBits >= 10) { + label = StringUtil.format(Strings.get("ramKilobyteLabel"), "" + (bytes >> 10)); } else { - label = StringUtil.format(Strings.get("ramByteLabel"), "" - + bytes); + label = StringUtil.format(Strings.get("ramByteLabel"), "" + bytes); } } - GraphicsUtil.drawCenteredText(g, label, bds.getX() + bds.getWidth() - / 2, bds.getY() + bds.getHeight() / 2); + GraphicsUtil.drawCenteredText(g, label, bounds.getX() + bounds.getWidth() / 2, + bounds.getY() + bounds.getHeight() / 2); } // draw input and output ports @@ -162,7 +154,7 @@ void setCurrentImage(Instance instance, File value) { } public void loadImage(InstanceState instanceState, File imageFile) - throws IOException { + throws IOException { MemState s = this.getState(instanceState); HexFile.open(s.getContents(), imageFile); this.setCurrentImage(instanceState.getInstance(), imageFile); @@ -187,8 +179,7 @@ static class MemListener implements HexModelListener { public void metaInfoChanged(HexModel source) { } - public void bytesChanged(HexModel source, long start, - long numBytes, int[] values) { + public void bytesChanged(HexModel source, long start, long numBytes, int[] values) { instance.fireInvalidated(); } } diff --git a/src/main/java/com/cburch/logisim/std/memory/MemContents.java b/src/main/java/com/cburch/logisim/std/memory/MemContents.java index 90503d9..df6b791 100644 --- a/src/main/java/com/cburch/logisim/std/memory/MemContents.java +++ b/src/main/java/com/cburch/logisim/std/memory/MemContents.java @@ -3,6 +3,7 @@ package com.cburch.logisim.std.memory; +import com.adlerd.logger.Logger; import com.cburch.hex.HexModel; import com.cburch.hex.HexModelListener; import com.cburch.logisim.util.EventSourceWeakSupport; @@ -15,13 +16,13 @@ class MemContents implements Cloneable, HexModel { private static final int PAGE_MASK = PAGE_SIZE - 1; private EventSourceWeakSupport listeners = null; private int width; - private int addrBits; + private int addressBits; private int mask; private MemContentsSub.ContentsInterface[] pages; - private MemContents(int addrBits, int width) { + private MemContents(int addressBits, int width) { listeners = null; - setDimensions(addrBits, width); + setDimensions(addressBits, width); } static MemContents create(int addrBits, int width) { @@ -48,29 +49,28 @@ public void removeHexModelListener(HexModelListener listener) { } } - private void fireMetainfoChanged() { + private void fireMetaInfoChanged() { if (listeners == null) { return; } boolean found = false; - for (HexModelListener l : listeners) { + for (HexModelListener listener : listeners) { found = true; - l.metaInfoChanged(this); + listener.metaInfoChanged(this); } if (!found) { listeners = null; } } - private void fireBytesChanged(long start, long numBytes, - int[] oldValues) { + private void fireBytesChanged(long start, long numBytes, int[] oldValues) { if (listeners == null) { return; } boolean found = false; - for (HexModelListener l : listeners) { + for (HexModelListener listener : listeners) { found = true; - l.bytesChanged(this, start, numBytes, oldValues); + listener.bytesChanged(this, start, numBytes, oldValues); } if (!found) { listeners = null; @@ -83,22 +83,23 @@ private void fireBytesChanged(long start, long numBytes, @Override public MemContents clone() { try { - MemContents ret = (MemContents) super.clone(); - ret.listeners = null; - ret.pages = new MemContentsSub.ContentsInterface[this.pages.length]; - for (int i = 0; i < ret.pages.length; i++) { + MemContents contents = (MemContents) super.clone(); + contents.listeners = null; + contents.pages = new MemContentsSub.ContentsInterface[this.pages.length]; + for (int i = 0; i < contents.pages.length; i++) { if (this.pages[i] != null) { - ret.pages[i] = this.pages[i].clone(); + contents.pages[i] = this.pages[i].clone(); } } - return ret; + return contents; } catch (CloneNotSupportedException ex) { + Logger.debugln(ex.getMessage()); return this; } } public int getLogLength() { - return addrBits; + return addressBits; } public int getWidth() { @@ -107,16 +108,15 @@ public int getWidth() { public int get(long addr) { int page = (int) (addr >>> PAGE_SIZE_BITS); - int offs = (int) (addr & PAGE_MASK); + int offset = (int) (addr & PAGE_MASK); if (page < 0 || page >= pages.length || pages[page] == null) { return 0; } - return pages[page].get(offs) & mask; + return pages[page].get(offset) & mask; } public boolean isClear() { - for (int i = 0; i < pages.length; i++) { - MemContentsSub.ContentsInterface page = pages[i]; + for (MemContentsSub.ContentsInterface page : pages) { if (page != null) { for (int j = page.getLength() - 1; j >= 0; j--) { if (page.get(j) != 0) { @@ -128,17 +128,17 @@ public boolean isClear() { return true; } - public void set(long addr, int value) { - int page = (int) (addr >>> PAGE_SIZE_BITS); - int offs = (int) (addr & PAGE_MASK); - int old = pages[page] == null ? 0 : pages[page].get(offs) & mask; + public void set(long address, int value) { + int page = (int) (address >>> PAGE_SIZE_BITS); + int offset = (int) (address & PAGE_MASK); + int old = pages[page] == null ? 0 : pages[page].get(offset) & mask; int val = value & mask; if (old != val) { if (pages[page] == null) { pages[page] = MemContentsSub.createContents(PAGE_SIZE, width); } - pages[page].set(offs, val); - fireBytesChanged(addr, 1, new int[]{old}); + pages[page].set(offset, val); + fireBytesChanged(address, 1, new int[]{old}); } } @@ -148,49 +148,49 @@ public void set(long start, int[] values) { } int pageStart = (int) (start >>> PAGE_SIZE_BITS); - int startOffs = (int) (start & PAGE_MASK); + int startOffset = (int) (start & PAGE_MASK); int pageEnd = (int) ((start + values.length - 1) >>> PAGE_SIZE_BITS); - int endOffs = (int) ((start + values.length - 1) & PAGE_MASK); + int endOffset = (int) ((start + values.length - 1) & PAGE_MASK); if (pageStart == pageEnd) { ensurePage(pageStart); MemContentsSub.ContentsInterface page = pages[pageStart]; - if (!page.matches(values, startOffs, mask)) { - int[] oldValues = page.get(startOffs, values.length); - page.load(startOffs, values, mask); + if (!page.matches(values, startOffset, mask)) { + int[] oldValues = page.get(startOffset, values.length); + page.load(startOffset, values, mask); if (page.isClear()) { pages[pageStart] = null; } fireBytesChanged(start, values.length, oldValues); } } else { - int nextOffs; - if (startOffs == 0) { + int nextOffset; + if (startOffset == 0) { pageStart--; - nextOffs = 0; + nextOffset = 0; } else { ensurePage(pageStart); - int[] vals = new int[PAGE_SIZE - startOffs]; + int[] vals = new int[PAGE_SIZE - startOffset]; System.arraycopy(values, 0, vals, 0, vals.length); MemContentsSub.ContentsInterface page = pages[pageStart]; - if (!page.matches(vals, startOffs, mask)) { - int[] oldValues = page.get(startOffs, vals.length); - page.load(startOffs, vals, mask); + if (!page.matches(vals, startOffset, mask)) { + int[] oldValues = page.get(startOffset, vals.length); + page.load(startOffset, vals, mask); if (page.isClear()) { pages[pageStart] = null; } fireBytesChanged(start, PAGE_SIZE - pageStart, oldValues); } - nextOffs = vals.length; + nextOffset = vals.length; } int[] vals = new int[PAGE_SIZE]; - int offs = nextOffs; - for (int i = pageStart + 1; i < pageEnd; i++, offs += PAGE_SIZE) { + int offset = nextOffset; + for (int i = pageStart + 1; i < pageEnd; i++, offset += PAGE_SIZE) { MemContentsSub.ContentsInterface page = pages[i]; if (page == null) { boolean allZeroes = true; for (int j = 0; j < PAGE_SIZE; j++) { - if ((values[offs + j] & mask) != 0) { + if ((values[offset + j] & mask) != 0) { allZeroes = false; break; } @@ -201,8 +201,8 @@ public void set(long start, int[] values) { } } if (page != null) { - System.arraycopy(values, offs, vals, 0, PAGE_SIZE); - if (!page.matches(vals, startOffs, mask)) { + System.arraycopy(values, offset, vals, 0, PAGE_SIZE); + if (!page.matches(vals, startOffset, mask)) { int[] oldValues = page.get(0, PAGE_SIZE); page.load(0, vals, mask); if (page.isClear()) { @@ -212,61 +212,61 @@ public void set(long start, int[] values) { } } } - if (endOffs >= 0) { + if (endOffset >= 0) { ensurePage(pageEnd); - vals = new int[endOffs + 1]; - System.arraycopy(values, offs, vals, 0, endOffs + 1); + vals = new int[endOffset + 1]; + System.arraycopy(values, offset, vals, 0, endOffset + 1); MemContentsSub.ContentsInterface page = pages[pageEnd]; - if (!page.matches(vals, startOffs, mask)) { - int[] oldValues = page.get(0, endOffs + 1); + if (!page.matches(vals, startOffset, mask)) { + int[] oldValues = page.get(0, endOffset + 1); page.load(0, vals, mask); if (page.isClear()) { pages[pageEnd] = null; } - fireBytesChanged((long) pageEnd << PAGE_SIZE_BITS, endOffs + 1, oldValues); + fireBytesChanged((long) pageEnd << PAGE_SIZE_BITS, endOffset + 1, oldValues); } } } } - public void fill(long start, long len, int value) { - if (len == 0) { + public void fill(long start, long length, int value) { + if (length == 0) { return; } int pageStart = (int) (start >>> PAGE_SIZE_BITS); - int startOffs = (int) (start & PAGE_MASK); - int pageEnd = (int) ((start + len - 1) >>> PAGE_SIZE_BITS); - int endOffs = (int) ((start + len - 1) & PAGE_MASK); + int startOffset = (int) (start & PAGE_MASK); + int pageEnd = (int) ((start + length - 1) >>> PAGE_SIZE_BITS); + int endOffset = (int) ((start + length - 1) & PAGE_MASK); value &= mask; if (pageStart == pageEnd) { ensurePage(pageStart); - int[] vals = new int[(int) len]; + int[] vals = new int[(int) length]; Arrays.fill(vals, value); MemContentsSub.ContentsInterface page = pages[pageStart]; - if (!page.matches(vals, startOffs, mask)) { - int[] oldValues = page.get(startOffs, (int) len); - page.load(startOffs, vals, mask); + if (!page.matches(vals, startOffset, mask)) { + int[] oldValues = page.get(startOffset, (int) length); + page.load(startOffset, vals, mask); if (value == 0 && page.isClear()) { pages[pageStart] = null; } - fireBytesChanged(start, len, oldValues); + fireBytesChanged(start, length, oldValues); } } else { - if (startOffs == 0) { + if (startOffset == 0) { pageStart--; } else { if (value == 0 && pages[pageStart] == null) { // nothing to do } else { ensurePage(pageStart); - int[] vals = new int[PAGE_SIZE - startOffs]; + int[] vals = new int[PAGE_SIZE - startOffset]; Arrays.fill(vals, value); MemContentsSub.ContentsInterface page = pages[pageStart]; - if (!page.matches(vals, startOffs, mask)) { - int[] oldValues = page.get(startOffs, vals.length); - page.load(startOffs, vals, mask); + if (!page.matches(vals, startOffset, mask)) { + int[] oldValues = page.get(startOffset, vals.length); + page.load(startOffset, vals, mask); if (value == 0 && page.isClear()) { pages[pageStart] = null; } @@ -293,21 +293,21 @@ public void fill(long start, long len, int value) { } } } - if (endOffs >= 0) { + if (endOffset >= 0) { MemContentsSub.ContentsInterface page = pages[pageEnd]; if (value == 0 && page == null) { // nothing to do } else { ensurePage(pageEnd); - int[] vals = new int[endOffs + 1]; + int[] vals = new int[endOffset + 1]; Arrays.fill(vals, value); if (!page.matches(vals, 0, mask)) { - int[] oldValues = page.get(0, endOffs + 1); + int[] oldValues = page.get(0, endOffset + 1); page.load(0, vals, mask); if (value == 0 && page.isClear()) { pages[pageEnd] = null; } - fireBytesChanged((long) pageEnd << PAGE_SIZE_BITS, endOffs + 1, oldValues); + fireBytesChanged((long) pageEnd << PAGE_SIZE_BITS, endOffset + 1, oldValues); } } } @@ -337,26 +337,26 @@ private void clearPage(int index) { } if (changed) { pages[index] = null; - fireBytesChanged(index << PAGE_SIZE_BITS, oldValues.length, oldValues); + fireBytesChanged((long) index << PAGE_SIZE_BITS, oldValues.length, oldValues); } } - public void setDimensions(int addrBits, int width) { - if (addrBits == this.addrBits && width == this.width) { + public void setDimensions(int addressBits, int width) { + if (addressBits == this.addressBits && width == this.width) { return; } - this.addrBits = addrBits; + this.addressBits = addressBits; this.width = width; this.mask = width == 32 ? 0xffffffff : ((1 << width) - 1); MemContentsSub.ContentsInterface[] oldPages = pages; int pageCount; int pageLength; - if (addrBits < PAGE_SIZE_BITS) { + if (addressBits < PAGE_SIZE_BITS) { pageCount = 1; - pageLength = 1 << addrBits; + pageLength = 1 << addressBits; } else { - pageCount = 1 << (addrBits - PAGE_SIZE_BITS); + pageCount = 1 << (addressBits - PAGE_SIZE_BITS); pageLength = PAGE_SIZE; } pages = new MemContentsSub.ContentsInterface[pageCount]; @@ -375,7 +375,7 @@ public void setDimensions(int addrBits, int width) { if (pageCount == 0 && pages[0] == null) { pages[0] = MemContentsSub.createContents(pageLength, width); } - fireMetainfoChanged(); + fireMetaInfoChanged(); } public long getFirstOffset() { @@ -383,7 +383,7 @@ public long getFirstOffset() { } public long getLastOffset() { - return (1L << addrBits) - 1; + return (1L << addressBits) - 1; } public int getValueWidth() { diff --git a/src/main/java/com/cburch/logisim/std/memory/MemContentsSub.java b/src/main/java/com/cburch/logisim/std/memory/MemContentsSub.java index 5327a63..89b0fd1 100644 --- a/src/main/java/com/cburch/logisim/std/memory/MemContentsSub.java +++ b/src/main/java/com/cburch/logisim/std/memory/MemContentsSub.java @@ -50,8 +50,8 @@ boolean matches(int[] values, int start, int mask) { return true; } - int[] get(int start, int len) { - int[] ret = new int[len]; + int[] get(int start, int length) { + int[] ret = new int[length]; for (int i = 0; i < ret.length; i++) { ret[i] = get(start + i); } @@ -78,10 +78,10 @@ public ByteContents(int size) { @Override public ByteContents clone() { - ByteContents ret = (ByteContents) super.clone(); - ret.data = new byte[this.data.length]; - System.arraycopy(this.data, 0, ret.data, 0, this.data.length); - return ret; + ByteContents contents = (ByteContents) super.clone(); + contents.data = new byte[this.data.length]; + System.arraycopy(this.data, 0, contents.data, 0, this.data.length); + return contents; } // @@ -93,16 +93,16 @@ int getLength() { } @Override - int get(int addr) { - return addr >= 0 && addr < data.length ? data[addr] : 0; + int get(int address) { + return address >= 0 && address < data.length ? data[address] : 0; } @Override - void set(int addr, int value) { - if (addr >= 0 && addr < data.length) { - byte oldValue = data[addr]; + void set(int address, int value) { + if (address >= 0 && address < data.length) { + byte oldValue = data[address]; if (value != oldValue) { - data[addr] = (byte) value; + data[address] = (byte) value; } } } @@ -131,10 +131,10 @@ public ShortContents(int size) { @Override public ShortContents clone() { - ShortContents ret = (ShortContents) super.clone(); - ret.data = new short[this.data.length]; - System.arraycopy(this.data, 0, ret.data, 0, this.data.length); - return ret; + ShortContents contents = (ShortContents) super.clone(); + contents.data = new short[this.data.length]; + System.arraycopy(this.data, 0, contents.data, 0, this.data.length); + return contents; } // @@ -146,16 +146,16 @@ int getLength() { } @Override - int get(int addr) { - return addr >= 0 && addr < data.length ? data[addr] : 0; + int get(int address) { + return address >= 0 && address < data.length ? data[address] : 0; } @Override - void set(int addr, int value) { - if (addr >= 0 && addr < data.length) { - short oldValue = data[addr]; + void set(int address, int value) { + if (address >= 0 && address < data.length) { + short oldValue = data[address]; if (value != oldValue) { - data[addr] = (short) value; + data[address] = (short) value; } } } @@ -184,10 +184,10 @@ public IntContents(int size) { @Override public IntContents clone() { - IntContents ret = (IntContents) super.clone(); - ret.data = new int[this.data.length]; - System.arraycopy(this.data, 0, ret.data, 0, this.data.length); - return ret; + IntContents contents = (IntContents) super.clone(); + contents.data = new int[this.data.length]; + System.arraycopy(this.data, 0, contents.data, 0, this.data.length); + return contents; } // @@ -199,16 +199,16 @@ int getLength() { } @Override - int get(int addr) { - return addr >= 0 && addr < data.length ? data[addr] : 0; + int get(int address) { + return address >= 0 && address < data.length ? data[address] : 0; } @Override - void set(int addr, int value) { - if (addr >= 0 && addr < data.length) { - int oldValue = data[addr]; + void set(int address, int value) { + if (address >= 0 && address < data.length) { + int oldValue = data[address]; if (value != oldValue) { - data[addr] = value; + data[address] = value; } } } diff --git a/src/main/java/com/cburch/logisim/std/memory/MemMenu.java b/src/main/java/com/cburch/logisim/std/memory/MemMenu.java index 0024a23..c99ca37 100644 --- a/src/main/java/com/cburch/logisim/std/memory/MemMenu.java +++ b/src/main/java/com/cburch/logisim/std/memory/MemMenu.java @@ -21,92 +21,92 @@ class MemMenu implements ActionListener, MenuExtender { - private Mem factory; - private Instance instance; - private Project proj; + private final Mem factory; + private final Instance instance; + private Project project; private Frame frame; - private CircuitState circState; - private JMenuItem edit; - private JMenuItem clear; - private JMenuItem load; - private JMenuItem save; + private CircuitState circuitState; + private JMenuItem editItem; + private JMenuItem clearItem; + private JMenuItem loadItem; + private JMenuItem saveItem; MemMenu(Mem factory, Instance instance) { this.factory = factory; this.instance = instance; } - public void configureMenu(JPopupMenu menu, Project proj) { - this.proj = proj; - this.frame = proj.getFrame(); - this.circState = proj.getCircuitState(); + public void configureMenu(JPopupMenu menu, Project project) { + this.project = project; + this.frame = project.getFrame(); + this.circuitState = project.getCircuitState(); Object attrs = instance.getAttributeSet(); if (attrs instanceof RomAttributes) { - ((RomAttributes) attrs).setProject(proj); + ((RomAttributes) attrs).setProject(project); } - boolean enabled = circState != null; - edit = createItem(enabled, Strings.get("ramEditMenuItem")); - clear = createItem(enabled, Strings.get("ramClearMenuItem")); - load = createItem(enabled, Strings.get("ramLoadMenuItem")); - save = createItem(enabled, Strings.get("ramSaveMenuItem")); + boolean enabled = circuitState != null; + editItem = createItem(enabled, Strings.get("ramEditMenuItem")); + clearItem = createItem(enabled, Strings.get("ramClearMenuItem")); + loadItem = createItem(enabled, Strings.get("ramLoadMenuItem")); + saveItem = createItem(enabled, Strings.get("ramSaveMenuItem")); menu.addSeparator(); - menu.add(edit); - menu.add(clear); - menu.add(load); - menu.add(save); + menu.add(editItem); + menu.add(clearItem); + menu.add(loadItem); + menu.add(saveItem); } private JMenuItem createItem(boolean enabled, String label) { - JMenuItem ret = new JMenuItem(label); - ret.setEnabled(enabled); - ret.addActionListener(this); - return ret; + JMenuItem menuItem = new JMenuItem(label); + menuItem.setEnabled(enabled); + menuItem.addActionListener(this); + return menuItem; } public void actionPerformed(ActionEvent evt) { - Object src = evt.getSource(); - if (src == edit) { + Object source = evt.getSource(); + if (source == editItem) { doEdit(); - } else if (src == clear) { + } else if (source == clearItem) { doClear(); - } else if (src == load) { + } else if (source == loadItem) { doLoad(); - } else if (src == save) { + } else if (source == saveItem) { doSave(); } } private void doEdit() { - MemState s = factory.getState(instance, circState); - if (s == null) { + MemState state = factory.getState(instance, circuitState); + if (state == null) { return; } - HexFrame frame = factory.getHexFrame(proj, instance, circState); + HexFrame frame = factory.getHexFrame(project, instance, circuitState); frame.setVisible(true); frame.toFront(); } private void doClear() { - MemState s = factory.getState(instance, circState); - boolean isAllZero = s.getContents().isClear(); + MemState state = factory.getState(instance, circuitState); + boolean isAllZero = state.getContents().isClear(); if (isAllZero) { return; } int choice = JOptionPane.showConfirmDialog(frame, - Strings.get("ramConfirmClearMsg"), - Strings.get("ramConfirmClearTitle"), - JOptionPane.YES_NO_OPTION); + Strings.get("ramConfirmClearMsg"), + Strings.get("ramConfirmClearTitle"), + JOptionPane.YES_NO_OPTION); if (choice == JOptionPane.YES_OPTION) { - s.getContents().clear(); + state.getContents().clear(); } } private void doLoad() { - JFileChooser chooser = proj.createChooser(); + JFileChooser chooser = project.createChooser(); File oldSelected = factory.getCurrentImage(instance); if (oldSelected != null) { chooser.setSelectedFile(oldSelected); @@ -116,18 +116,20 @@ private void doLoad() { if (choice == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); try { - factory.loadImage(circState.getInstanceState(instance), f); + factory.loadImage(circuitState.getInstanceState(instance), f); } catch (IOException e) { - JOptionPane.showMessageDialog(frame, e.getMessage(), - Strings.get("ramLoadErrorTitle"), JOptionPane.ERROR_MESSAGE); + JOptionPane.showMessageDialog(frame, + e.getMessage(), + Strings.get("ramLoadErrorTitle"), + JOptionPane.ERROR_MESSAGE); } } } private void doSave() { - MemState s = factory.getState(instance, circState); + MemState state = factory.getState(instance, circuitState); - JFileChooser chooser = proj.createChooser(); + JFileChooser chooser = project.createChooser(); File oldSelected = factory.getCurrentImage(instance); if (oldSelected != null) { chooser.setSelectedFile(oldSelected); @@ -137,11 +139,13 @@ private void doSave() { if (choice == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); try { - HexFile.save(f, s.getContents()); + HexFile.save(f, state.getContents()); factory.setCurrentImage(instance, f); } catch (IOException e) { - JOptionPane.showMessageDialog(frame, e.getMessage(), - Strings.get("ramSaveErrorTitle"), JOptionPane.ERROR_MESSAGE); + JOptionPane.showMessageDialog(frame, + e.getMessage(), + Strings.get("ramSaveErrorTitle"), + JOptionPane.ERROR_MESSAGE); } } } diff --git a/src/main/java/com/cburch/logisim/std/memory/MemPoker.java b/src/main/java/com/cburch/logisim/std/memory/MemPoker.java index acc30db..4319ad6 100644 --- a/src/main/java/com/cburch/logisim/std/memory/MemPoker.java +++ b/src/main/java/com/cburch/logisim/std/memory/MemPoker.java @@ -19,10 +19,9 @@ public class MemPoker extends InstancePoker { @Override public boolean init(InstanceState state, MouseEvent event) { - Bounds bds = state.getInstance().getBounds(); + Bounds bounds = state.getInstance().getBounds(); MemState data = (MemState) state.getData(); - long addr = data.getAddressAt(event.getX() - bds.getX(), - event.getY() - bds.getY()); + long addr = data.getAddressAt(event.getX() - bounds.getX(), event.getY() - bounds.getY()); // See if outside box if (addr < 0) { @@ -51,18 +50,18 @@ public void keyTyped(InstanceState state, KeyEvent e) { private static class DataPoker extends MemPoker { int initValue; - int curValue; + int currentValue; - private DataPoker(InstanceState state, MemState data, long addr) { - data.setCursor(addr); + private DataPoker(InstanceState state, MemState data, long address) { + data.setCursor(address); initValue = data.getContents().get(data.getCursor()); - curValue = initValue; + currentValue = initValue; Object attrs = state.getInstance().getAttributeSet(); if (attrs instanceof RomAttributes) { - Project proj = state.getProject(); - if (proj != null) { - ((RomAttributes) attrs).setProject(proj); + Project project = state.getProject(); + if (project != null) { + ((RomAttributes) attrs).setProject(project); } } } @@ -76,10 +75,10 @@ public Bounds getBounds(InstancePainter painter) { @Override public void paint(InstancePainter painter) { - Bounds bds = getBounds(painter); + Bounds bounds = getBounds(painter); Graphics g = painter.getGraphics(); g.setColor(Color.RED); - g.drawRect(bds.getX(), bds.getY(), bds.getWidth(), bds.getHeight()); + g.drawRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); g.setColor(Color.BLACK); } @@ -92,11 +91,11 @@ public void stopEditing(InstanceState state) { @Override public void keyTyped(InstanceState state, KeyEvent e) { char c = e.getKeyChar(); - int val = Character.digit(e.getKeyChar(), 16); + int value = Character.digit(e.getKeyChar(), 16); MemState data = (MemState) state.getData(); - if (val >= 0) { - curValue = curValue * 16 + val; - data.getContents().set(data.getCursor(), curValue); + if (value >= 0) { + currentValue = currentValue * 16 + value; + data.getContents().set(data.getCursor(), currentValue); state.fireInvalidated(); } else if (c == ' ' || c == '\t') { moveTo(data, data.getCursor() + 1); @@ -108,11 +107,11 @@ public void keyTyped(InstanceState state, KeyEvent e) { } private void moveTo(MemState data, long addr) { - if (data.isValidAddr(addr)) { + if (data.isValidAddress(addr)) { data.setCursor(addr); data.scrollToShow(addr); initValue = data.getContents().get(addr); - curValue = initValue; + currentValue = initValue; } } } @@ -127,23 +126,23 @@ public Bounds getBounds(InstancePainter painter) { @Override public void paint(InstancePainter painter) { - Bounds bds = getBounds(painter); + Bounds bounds = getBounds(painter); Graphics g = painter.getGraphics(); g.setColor(Color.RED); - g.drawRect(bds.getX(), bds.getY(), bds.getWidth(), bds.getHeight()); + g.drawRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); g.setColor(Color.BLACK); } @Override public void keyTyped(InstanceState state, KeyEvent e) { char c = e.getKeyChar(); - int val = Character.digit(e.getKeyChar(), 16); + int value = Character.digit(e.getKeyChar(), 16); MemState data = (MemState) state.getData(); - if (val >= 0) { - long newScroll = (data.getScroll() * 16 + val) & (data.getLastAddress()); + if (value >= 0) { + long newScroll = (data.getScroll() * 16 + value) & (data.getLastAddress()); data.setScroll(newScroll); } else if (c == ' ') { - data.setScroll(data.getScroll() + (data.getRows() - 1) * data.getColumns()); + data.setScroll(data.getScroll() + (long) (data.getRows() - 1) * data.getColumns()); } else if (c == '\r' || c == '\n') { data.setScroll(data.getScroll() + data.getColumns()); } else if (c == '\u0008' || c == '\u007f') { @@ -151,4 +150,4 @@ public void keyTyped(InstanceState state, KeyEvent e) { } } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/memory/MemState.java b/src/main/java/com/cburch/logisim/std/memory/MemState.java index 2f187c5..ac32be8 100644 --- a/src/main/java/com/cburch/logisim/std/memory/MemState.java +++ b/src/main/java/com/cburch/logisim/std/memory/MemState.java @@ -3,6 +3,7 @@ package com.cburch.logisim.std.memory; +import com.adlerd.logger.Logger; import com.cburch.hex.HexModel; import com.cburch.hex.HexModelListener; import com.cburch.logisim.data.Bounds; @@ -16,23 +17,23 @@ class MemState implements InstanceData, Cloneable, HexModelListener { private static final int ROWS = 4; // rows in memory display - private static final int TABLE_WIDTH12 = 80; // width of table for addr bits <= 12 - private static final int TABLE_WIDTH32 = 65; // width of table for addr bits > 12 + private static final int TABLE_WIDTH_12 = 80; // width of table for addr bits <= 12 + private static final int TABLE_WIDTH_32 = 65; // width of table for addr bits > 12 private static final int ENTRY_HEIGHT = 15; // pixels high per entry - private static final int ENTRY_XOFFS12 = 40; // x offset for entries for addr bits <= 12 - private static final int ENTRY_XOFFS32 = 60; // x offset for entries for addr bits > 12 + private static final int ENTRY_X_OFFSET_12 = 40; // x offset for entries for addr bits <= 12 + private static final int ENTRY_X_OFFSET_32 = 60; // x offset for entries for addr bits > 12 - private static final int ENTRY_YOFFS = 5; // y offset for entries + private static final int ENTRY_Y_OFFSET = 5; // y offset for entries private static final int ADDR_WIDTH_PER_CHAR = 10; // pixels wide per address character private MemContents contents; private int columns; - private long curScroll = 0; - private long cursorLoc = -1; - private long curAddr = -1; + private long currentScroll = 0; + private long cursorLocation = -1; + private long currentAddress = -1; MemState(MemContents contents) { this.contents = contents; @@ -43,11 +44,12 @@ class MemState implements InstanceData, Cloneable, HexModelListener { @Override public MemState clone() { try { - MemState ret = (MemState) super.clone(); - ret.contents = contents.clone(); - ret.contents.addHexModelListener(ret); - return ret; + MemState state = (MemState) super.clone(); + state.contents = contents.clone(); + state.contents.addHexModelListener(state); + return state; } catch (CloneNotSupportedException e) { + Logger.debugln(e.getMessage()); return null; } } @@ -55,13 +57,13 @@ public MemState clone() { // // methods for accessing the address bits // - private void setBits(int addrBits, int dataBits) { + private void setBits(int addressBits, int dataBits) { if (contents == null) { - contents = MemContents.create(addrBits, dataBits); + contents = MemContents.create(addressBits, dataBits); } else { - contents.setDimensions(addrBits, dataBits); + contents.setDimensions(addressBits, dataBits); } - if (addrBits <= 12) { + if (addressBits <= 12) { if (dataBits <= 8) { columns = dataBits <= 4 ? 8 : 4; } else { @@ -72,15 +74,15 @@ private void setBits(int addrBits, int dataBits) { } long newLast = contents.getLastOffset(); // I do subtraction in the next two conditions to account for possibility of overflow - if (cursorLoc > newLast) { - cursorLoc = newLast; + if (cursorLocation > newLast) { + cursorLocation = newLast; } - if (curAddr - newLast > 0) { - curAddr = -1; + if (currentAddress - newLast > 0) { + currentAddress = -1; } - long maxScroll = Math.max(0, newLast + 1 - (ROWS - 1) * columns); - if (curScroll > maxScroll) { - curScroll = maxScroll; + long maxScroll = Math.max(0, newLast + 1 - (long) (ROWS - 1) * columns); + if (currentScroll > maxScroll) { + currentScroll = maxScroll; } } @@ -91,7 +93,7 @@ public MemContents getContents() { // // methods for accessing data within memory // - int getAddrBits() { + int getAddressBits() { return contents.getLogLength(); } @@ -103,9 +105,9 @@ long getLastAddress() { return (1L << contents.getLogLength()) - 1; } - boolean isValidAddr(long addr) { + boolean isValidAddress(long address) { int addrBits = contents.getLogLength(); - return addr >>> addrBits == 0; + return address >>> addrBits == 0; } int getRows() { @@ -120,46 +122,46 @@ int getColumns() { // methods for manipulating cursor and scroll location // long getCursor() { - return cursorLoc; + return cursorLocation; } void setCursor(long value) { - cursorLoc = isValidAddr(value) ? value : -1L; + cursorLocation = isValidAddress(value) ? value : -1L; } long getCurrent() { - return curAddr; + return currentAddress; } void setCurrent(long value) { - curAddr = isValidAddr(value) ? value : -1L; + currentAddress = isValidAddress(value) ? value : -1L; } long getScroll() { - return curScroll; + return currentScroll; } - void setScroll(long addr) { - long maxAddr = getLastAddress() - ROWS * columns; - if (addr > maxAddr) { - addr = maxAddr; // note: maxAddr could be negative + void setScroll(long address) { + long maxAddress = getLastAddress() - (long) ROWS * columns; + if (address > maxAddress) { + address = maxAddress; // note: maxAddress could be negative } - if (addr < 0) { - addr = 0; + if (address < 0) { + address = 0; } - curScroll = addr; + currentScroll = address; } - void scrollToShow(long addr) { - if (isValidAddr(addr)) { - addr = addr / columns * columns; - long curTop = curScroll / columns * columns; - if (addr < curTop) { - curScroll = addr; - } else if (addr >= curTop + ROWS * columns) { - curScroll = addr - (ROWS - 1) * columns; - if (curScroll < 0) { - curScroll = 0; + void scrollToShow(long address) { + if (isValidAddress(address)) { + address = address / columns * columns; + long currentTop = currentScroll / columns * columns; + if (address < currentTop) { + currentScroll = address; + } else if (address >= currentTop + (long) ROWS * columns) { + currentScroll = address - (long) (ROWS - 1) * columns; + if (currentScroll < 0) { + currentScroll = 0; } } } @@ -169,105 +171,100 @@ void scrollToShow(long addr) { // graphical methods // public long getAddressAt(int x, int y) { - int addrBits = getAddrBits(); - int boxX = addrBits <= 12 ? ENTRY_XOFFS12 : ENTRY_XOFFS32; - int boxW = addrBits <= 12 ? TABLE_WIDTH12 : TABLE_WIDTH32; + int addressBits = getAddressBits(); + int boxX = addressBits <= 12 ? ENTRY_X_OFFSET_12 : ENTRY_X_OFFSET_32; + int boxW = addressBits <= 12 ? TABLE_WIDTH_12 : TABLE_WIDTH_32; // See if outside box - if (x < boxX || x >= boxX + boxW || y <= ENTRY_YOFFS - || y >= ENTRY_YOFFS + ROWS * ENTRY_HEIGHT) { + if (x < boxX || x >= boxX + boxW || y <= ENTRY_Y_OFFSET || y >= ENTRY_Y_OFFSET + ROWS * ENTRY_HEIGHT) { return -1; } - int col = (x - boxX) / (boxW / columns); - int row = (y - ENTRY_YOFFS) / ENTRY_HEIGHT; - long ret = (curScroll / columns * columns) + columns * row + col; - return isValidAddr(ret) ? ret : getLastAddress(); + int column = (x - boxX) / (boxW / columns); + int row = (y - ENTRY_Y_OFFSET) / ENTRY_HEIGHT; + long address = (currentScroll / columns * columns) + (long) columns * row + column; + return isValidAddress(address) ? address : getLastAddress(); } - public Bounds getBounds(long addr, Bounds bds) { - int addrBits = getAddrBits(); - int boxX = bds.getX() + (addrBits <= 12 ? ENTRY_XOFFS12 : ENTRY_XOFFS32); - int boxW = addrBits <= 12 ? TABLE_WIDTH12 : TABLE_WIDTH32; - if (addr < 0) { - int addrLen = (contents.getWidth() + 3) / 4; - int width = ADDR_WIDTH_PER_CHAR * addrLen; - return Bounds.create(boxX - width, bds.getY() + ENTRY_YOFFS, - width, ENTRY_HEIGHT); + public Bounds getBounds(long address, Bounds bounds) { + int addressBits = getAddressBits(); + int boxX = bounds.getX() + (addressBits <= 12 ? ENTRY_X_OFFSET_12 : ENTRY_X_OFFSET_32); + int boxW = addressBits <= 12 ? TABLE_WIDTH_12 : TABLE_WIDTH_32; + if (address < 0) { + int addressLength = (contents.getWidth() + 3) / 4; + int width = ADDR_WIDTH_PER_CHAR * addressLength; + return Bounds.create(boxX - width, bounds.getY() + ENTRY_Y_OFFSET, width, ENTRY_HEIGHT); } else { - int bdsX = addrToX(bds, addr); - int bdsY = addrToY(bds, addr); - return Bounds.create(bdsX, bdsY, boxW / columns, ENTRY_HEIGHT); + int boundsX = addressToX(bounds, address); + int boundsY = addressToY(bounds, address); + return Bounds.create(boundsX, boundsY, boxW / columns, ENTRY_HEIGHT); } } public void paint(Graphics g, int leftX, int topY) { - int addrBits = getAddrBits(); + int addressBits = getAddressBits(); int dataBits = contents.getWidth(); - int boxX = leftX + (addrBits <= 12 ? ENTRY_XOFFS12 : ENTRY_XOFFS32); - int boxY = topY + ENTRY_YOFFS; - int boxW = addrBits <= 12 ? TABLE_WIDTH12 : TABLE_WIDTH32; + int boxX = leftX + (addressBits <= 12 ? ENTRY_X_OFFSET_12 : ENTRY_X_OFFSET_32); + int boxY = topY + ENTRY_Y_OFFSET; + int boxW = addressBits <= 12 ? TABLE_WIDTH_12 : TABLE_WIDTH_32; int boxH = ROWS * ENTRY_HEIGHT; GraphicsUtil.switchToWidth(g, 1); g.drawRect(boxX, boxY, boxW, boxH); int entryWidth = boxW / columns; for (int row = 0; row < ROWS; row++) { - long addr = (curScroll / columns * columns) + columns * row; + long address = (currentScroll / columns * columns) + (long) columns * row; int x = boxX; int y = boxY + ENTRY_HEIGHT * row; - int yoffs = ENTRY_HEIGHT - 3; - if (isValidAddr(addr)) { + int yOffset = ENTRY_HEIGHT - 3; + if (isValidAddress(address)) { g.setColor(Color.GRAY); - GraphicsUtil.drawText(g, StringUtil.toHexString(getAddrBits(), (int) addr), - x - 2, y + yoffs, - GraphicsUtil.H_RIGHT, GraphicsUtil.V_BASELINE); + GraphicsUtil.drawText(g, StringUtil.toHexString(getAddressBits(), (int) address), x - 2, y + yOffset, + GraphicsUtil.H_RIGHT, GraphicsUtil.V_BASELINE); } g.setColor(Color.BLACK); - for (int col = 0; col < columns && isValidAddr(addr); col++) { - int val = contents.get(addr); - if (addr == curAddr) { + for (int column = 0; column < columns && isValidAddress(address); column++) { + int value = contents.get(address); + if (address == currentAddress) { g.fillRect(x, y, entryWidth, ENTRY_HEIGHT); g.setColor(Color.WHITE); - GraphicsUtil.drawText(g, StringUtil.toHexString(dataBits, val), - x + entryWidth / 2, y + yoffs, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + GraphicsUtil.drawText(g, StringUtil.toHexString(dataBits, value), x + entryWidth / 2, y + yOffset, + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); g.setColor(Color.BLACK); } else { - GraphicsUtil.drawText(g, StringUtil.toHexString(dataBits, val), - x + entryWidth / 2, y + yoffs, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + GraphicsUtil.drawText(g, StringUtil.toHexString(dataBits, value), x + entryWidth / 2, y + yOffset, + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); } - addr++; + address++; x += entryWidth; } } } - private int addrToX(Bounds bds, long addr) { - int addrBits = getAddrBits(); - int boxX = bds.getX() + (addrBits <= 12 ? ENTRY_XOFFS12 : ENTRY_XOFFS32); - int boxW = addrBits <= 12 ? TABLE_WIDTH12 : TABLE_WIDTH32; + private int addressToX(Bounds bounds, long address) { + int addressBits = getAddressBits(); + int boxX = bounds.getX() + (addressBits <= 12 ? ENTRY_X_OFFSET_12 : ENTRY_X_OFFSET_32); + int boxW = addressBits <= 12 ? TABLE_WIDTH_12 : TABLE_WIDTH_32; - long topRow = curScroll / columns; - long row = addr / columns; + long topRow = currentScroll / columns; + long row = address / columns; if (row < topRow || row >= topRow + ROWS) { return -1; } - int col = (int) (addr - row * columns); - if (col < 0 || col >= columns) { + int column = (int) (address - row * columns); + if (column < 0 || column >= columns) { return -1; } - return boxX + boxW * col / columns; + return boxX + boxW * column / columns; } - private int addrToY(Bounds bds, long addr) { - long topRow = curScroll / columns; - long row = addr / columns; + private int addressToY(Bounds bounds, long address) { + long topRow = currentScroll / columns; + long row = address / columns; if (row < topRow || row >= topRow + ROWS) { return -1; } - return (int) (bds.getY() + ENTRY_YOFFS + ENTRY_HEIGHT * (row - topRow)); + return (int) (bounds.getY() + ENTRY_Y_OFFSET + ENTRY_HEIGHT * (row - topRow)); } public void metaInfoChanged(HexModel source) { diff --git a/src/main/java/com/cburch/logisim/std/memory/Memory.java b/src/main/java/com/cburch/logisim/std/memory/Memory.java index e284376..91105cc 100644 --- a/src/main/java/com/cburch/logisim/std/memory/Memory.java +++ b/src/main/java/com/cburch/logisim/std/memory/Memory.java @@ -12,27 +12,27 @@ public class Memory extends Library { protected static final int DELAY = 5; - private static FactoryDescription[] DESCRIPTIONS = { - new FactoryDescription("D Flip-Flop", Strings.getter("dFlipFlopComponent"), - "dFlipFlop.gif", "DFlipFlop"), - new FactoryDescription("T Flip-Flop", Strings.getter("tFlipFlopComponent"), - "tFlipFlop.gif", "TFlipFlop"), - new FactoryDescription("J-K Flip-Flop", Strings.getter("jkFlipFlopComponent"), - "jkFlipFlop.gif", "JKFlipFlop"), - new FactoryDescription("S-R Flip-Flop", Strings.getter("srFlipFlopComponent"), - "srFlipFlop.gif", "SRFlipFlop"), - new FactoryDescription("Register", Strings.getter("registerComponent"), - "register.gif", "Register"), - new FactoryDescription("Counter", Strings.getter("counterComponent"), - "counter.gif", "Counter"), - new FactoryDescription("Shift Register", Strings.getter("shiftRegisterComponent"), - "shiftreg.gif", "ShiftRegister"), - new FactoryDescription("Random", Strings.getter("randomComponent"), - "random.gif", "Random"), - new FactoryDescription("RAM", Strings.getter("ramComponent"), - "ram.gif", "Ram"), - new FactoryDescription("ROM", Strings.getter("romComponent"), - "rom.gif", "Rom"), + private static final FactoryDescription[] DESCRIPTIONS = { + new FactoryDescription("D Flip-Flop", Strings.getter("dFlipFlopComponent"), + "dFlipFlop.gif", "DFlipFlop"), + new FactoryDescription("T Flip-Flop", Strings.getter("tFlipFlopComponent"), + "tFlipFlop.gif", "TFlipFlop"), + new FactoryDescription("J-K Flip-Flop", Strings.getter("jkFlipFlopComponent"), + "jkFlipFlop.gif", "JKFlipFlop"), + new FactoryDescription("S-R Flip-Flop", Strings.getter("srFlipFlopComponent"), + "srFlipFlop.gif", "SRFlipFlop"), + new FactoryDescription("Register", Strings.getter("registerComponent"), + "register.gif", "Register"), + new FactoryDescription("Counter", Strings.getter("counterComponent"), + "counter.gif", "Counter"), + new FactoryDescription("Shift Register", Strings.getter("shiftRegisterComponent"), + "shiftreg.gif", "ShiftRegister"), + new FactoryDescription("Random", Strings.getter("randomComponent"), + "random.gif", "Random"), + new FactoryDescription("RAM", Strings.getter("ramComponent"), + "ram.gif", "Ram"), + new FactoryDescription("ROM", Strings.getter("romComponent"), + "rom.gif", "Rom"), }; private List tools = null; diff --git a/src/main/java/com/cburch/logisim/std/memory/Ram.java b/src/main/java/com/cburch/logisim/std/memory/Ram.java index 7dc126b..dc3f5d5 100644 --- a/src/main/java/com/cburch/logisim/std/memory/Ram.java +++ b/src/main/java/com/cburch/logisim/std/memory/Ram.java @@ -31,27 +31,27 @@ public class Ram extends Mem { static final AttributeOption BUS_COMBINED - = new AttributeOption("combined", Strings.getter("ramBusSynchCombined")); + = new AttributeOption("combined", Strings.getter("ramBusSynchCombined")); static final AttributeOption BUS_ASYNCH - = new AttributeOption("asynch", Strings.getter("ramBusAsynchCombined")); + = new AttributeOption("asynch", Strings.getter("ramBusAsynchCombined")); static final AttributeOption BUS_SEPARATE - = new AttributeOption("separate", Strings.getter("ramBusSeparate")); + = new AttributeOption("separate", Strings.getter("ramBusSeparate")); - static final Attribute ATTR_BUS = Attributes.forOption("bus", - Strings.getter("ramBusAttr"), - new AttributeOption[]{BUS_COMBINED, BUS_ASYNCH, BUS_SEPARATE}); + static final Attribute ATTR_BUS + = Attributes.forOption("bus", Strings.getter("ramBusAttr"), new AttributeOption[]{BUS_COMBINED, BUS_ASYNCH, + BUS_SEPARATE}); private static final int OE = MEM_INPUTS + 0; private static final int CLR = MEM_INPUTS + 1; private static final int CLK = MEM_INPUTS + 2; private static final int WE = MEM_INPUTS + 3; private static final int DIN = MEM_INPUTS + 4; - private static Attribute[] ATTRIBUTES = { - Mem.ADDR_ATTR, Mem.DATA_ATTR, ATTR_BUS + private static final Attribute[] ATTRIBUTES = { + Mem.ADDR_ATTR, Mem.DATA_ATTR, ATTR_BUS }; - private static Object[] DEFAULTS = { - BitWidth.create(8), BitWidth.create(8), BUS_COMBINED + private static final Object[] DEFAULTS = { + BitWidth.create(8), BitWidth.create(8), BUS_COMBINED }; - private static Object[][] logOptions = new Object[9][]; + private static final Object[][] logOptions = new Object[9][]; public Ram() { super("RAM", Strings.getter("ramComponent"), 3); @@ -117,12 +117,12 @@ public AttributeSet createAttributeSet() { @Override MemState getState(InstanceState state) { - BitWidth addrBits = state.getAttributeValue(ADDR_ATTR); + BitWidth addressBits = state.getAttributeValue(ADDR_ATTR); BitWidth dataBits = state.getAttributeValue(DATA_ATTR); RamState myState = (RamState) state.getData(); if (myState == null) { - MemContents contents = MemContents.create(addrBits.getWidth(), dataBits.getWidth()); + MemContents contents = MemContents.create(addressBits.getWidth(), dataBits.getWidth()); Instance instance = state.getInstance(); myState = new RamState(instance, contents, new MemListener(instance)); state.setData(myState); @@ -134,12 +134,12 @@ MemState getState(InstanceState state) { @Override MemState getState(Instance instance, CircuitState state) { - BitWidth addrBits = instance.getAttributeValue(ADDR_ATTR); + BitWidth addressBits = instance.getAttributeValue(ADDR_ATTR); BitWidth dataBits = instance.getAttributeValue(DATA_ATTR); RamState myState = (RamState) instance.getData(state); if (myState == null) { - MemContents contents = MemContents.create(addrBits.getWidth(), dataBits.getWidth()); + MemContents contents = MemContents.create(addressBits.getWidth(), dataBits.getWidth()); myState = new RamState(instance, contents, new MemListener(instance)); instance.setData(state, myState); } else { @@ -149,22 +149,22 @@ MemState getState(Instance instance, CircuitState state) { } @Override - HexFrame getHexFrame(Project proj, Instance instance, CircuitState circState) { - RamState state = (RamState) getState(instance, circState); - return state.getHexFrame(proj); + HexFrame getHexFrame(Project project, Instance instance, CircuitState circuitState) { + RamState state = (RamState) getState(instance, circuitState); + return state.getHexFrame(project); } @Override public void propagate(InstanceState state) { RamState myState = (RamState) getState(state); BitWidth dataBits = state.getAttributeValue(DATA_ATTR); - Object busVal = state.getAttributeValue(ATTR_BUS); - boolean asynch = busVal != null && busVal.equals(BUS_ASYNCH); - boolean separate = busVal != null && busVal.equals(BUS_SEPARATE); + Object busValue = state.getAttributeValue(ATTR_BUS); + boolean isAsynch = busValue != null && busValue.equals(BUS_ASYNCH); + boolean isSeparate = busValue != null && busValue.equals(BUS_SEPARATE); - Value addrValue = state.getPort(ADDR); + Value addressValue = state.getPort(ADDR); boolean chipSelect = state.getPort(CS) != Value.FALSE; - boolean triggered = asynch || myState.setClock(state.getPort(CLK), StdAttr.TRIG_RISING); + boolean isTriggered = isAsynch || myState.setClock(state.getPort(CLK), StdAttr.TRIG_RISING); boolean outputEnabled = state.getPort(OE) != Value.FALSE; boolean shouldClear = state.getPort(CLR) == Value.TRUE; @@ -178,31 +178,31 @@ public void propagate(InstanceState state) { return; } - int addr = addrValue.toIntValue(); - if (!addrValue.isFullyDefined() || addr < 0) { + int address = addressValue.toIntValue(); + if (!addressValue.isFullyDefined() || address < 0) { return; } - if (addr != myState.getCurrent()) { - myState.setCurrent(addr); - myState.scrollToShow(addr); + if (address != myState.getCurrent()) { + myState.setCurrent(address); + myState.scrollToShow(address); } - if (!shouldClear && triggered) { + if (!shouldClear && isTriggered) { boolean shouldStore; - if (separate) { + if (isSeparate) { shouldStore = state.getPort(WE) != Value.FALSE; } else { shouldStore = !outputEnabled; } if (shouldStore) { - Value dataValue = state.getPort(separate ? DIN : DATA); - myState.getContents().set(addr, dataValue.toIntValue()); + Value dataValue = state.getPort(isSeparate ? DIN : DATA); + myState.getContents().set(address, dataValue.toIntValue()); } } if (outputEnabled) { - int val = myState.getContents().get(addr); - state.setPort(DATA, Value.createKnown(dataBits, val), DELAY); + int value = myState.getContents().get(address); + state.setPort(DATA, Value.createKnown(dataBits, value), DELAY); } else { state.setPort(DATA, Value.createUnknown(dataBits), DELAY); } @@ -211,28 +211,27 @@ public void propagate(InstanceState state) { @Override public void paintInstance(InstancePainter painter) { super.paintInstance(painter); - Object busVal = painter.getAttributeValue(ATTR_BUS); - boolean asynch = busVal != null && busVal.equals(BUS_ASYNCH); - boolean separate = busVal != null && busVal.equals(BUS_SEPARATE); + Object busValue = painter.getAttributeValue(ATTR_BUS); + boolean isAsynch = busValue != null && busValue.equals(BUS_ASYNCH); + boolean isSeparate = busValue != null && busValue.equals(BUS_SEPARATE); - if (!asynch) { + if (!isAsynch) { painter.drawClock(CLK, Direction.NORTH); } painter.drawPort(OE, Strings.get("ramOELabel"), Direction.SOUTH); painter.drawPort(CLR, Strings.get("ramClrLabel"), Direction.SOUTH); - if (separate) { + if (isSeparate) { painter.drawPort(WE, Strings.get("ramWELabel"), Direction.SOUTH); painter.getGraphics().setColor(Color.BLACK); painter.drawPort(DIN, Strings.get("ramDataLabel"), Direction.EAST); } } - private static class RamState extends MemState - implements InstanceData, AttributeListener { + private static class RamState extends MemState implements InstanceData, AttributeListener { + private final MemListener listener; private Instance parent; - private MemListener listener; private HexFrame hexFrame = null; private ClockState clockState; @@ -262,17 +261,17 @@ void setRam(Instance value) { @Override public RamState clone() { - RamState ret = (RamState) super.clone(); - ret.parent = null; - ret.clockState = this.clockState.clone(); - ret.getContents().addHexModelListener(listener); - return ret; + RamState state = (RamState) super.clone(); + state.parent = null; + state.clockState = this.clockState.clone(); + state.getContents().addHexModelListener(listener); + return state; } // Retrieves a HexFrame for editing within a separate window - public HexFrame getHexFrame(Project proj) { + public HexFrame getHexFrame(Project project) { if (hexFrame == null) { - hexFrame = new HexFrame(proj, getContents()); + hexFrame = new HexFrame(project, getContents()); hexFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { @@ -295,9 +294,9 @@ public void attributeListChanged(AttributeEvent e) { public void attributeValueChanged(AttributeEvent e) { AttributeSet attrs = e.getSource(); - BitWidth addrBits = attrs.getValue(Mem.ADDR_ATTR); + BitWidth addressBits = attrs.getValue(Mem.ADDR_ATTR); BitWidth dataBits = attrs.getValue(Mem.DATA_ATTR); - getContents().setDimensions(addrBits.getWidth(), dataBits.getWidth()); + getContents().setDimensions(addressBits.getWidth(), dataBits.getWidth()); } } @@ -305,29 +304,29 @@ public static class Logger extends InstanceLogger { @Override public Object[] getLogOptions(InstanceState state) { - int addrBits = state.getAttributeValue(ADDR_ATTR).getWidth(); - if (addrBits >= logOptions.length) { - addrBits = logOptions.length - 1; + int addressBits = state.getAttributeValue(ADDR_ATTR).getWidth(); + if (addressBits >= logOptions.length) { + addressBits = logOptions.length - 1; } synchronized (logOptions) { - Object[] ret = logOptions[addrBits]; - if (ret == null) { - ret = new Object[1 << addrBits]; - logOptions[addrBits] = ret; - for (int i = 0; i < ret.length; i++) { - ret[i] = i; + Object[] options = logOptions[addressBits]; + if (options == null) { + options = new Object[1 << addressBits]; + logOptions[addressBits] = options; + for (int i = 0; i < options.length; i++) { + options[i] = i; } } - return ret; + return options; } } @Override public String getLogName(InstanceState state, Object option) { if (option instanceof Integer) { - String disp = Strings.get("ramComponent"); + String display = Strings.get("ramComponent"); Location loc = state.getInstance().getLocation(); - return disp + loc + "[" + option + "]"; + return display + loc + "[" + option + "]"; } else { return null; } @@ -336,10 +335,9 @@ public String getLogName(InstanceState state, Object option) { @Override public Value getLogValue(InstanceState state, Object option) { if (option instanceof Integer) { - MemState s = (MemState) state.getData(); - int addr = (Integer) option; - return Value.createKnown(BitWidth.create(s.getDataBits()), - s.getContents().get(addr)); + MemState memState = (MemState) state.getData(); + int address = (Integer) option; + return Value.createKnown(BitWidth.create(memState.getDataBits()), memState.getContents().get(address)); } else { return Value.NIL; } diff --git a/src/main/java/com/cburch/logisim/std/memory/Random.java b/src/main/java/com/cburch/logisim/std/memory/Random.java index a6bf706..6a15d5c 100644 --- a/src/main/java/com/cburch/logisim/std/memory/Random.java +++ b/src/main/java/com/cburch/logisim/std/memory/Random.java @@ -24,8 +24,7 @@ public class Random extends InstanceFactory { - private static final Attribute ATTR_SEED - = Attributes.forInteger("seed", Strings.getter("randomSeedAttr")); + private static final Attribute ATTR_SEED = Attributes.forInteger("seed", Strings.getter("randomSeedAttr")); private static final int OUT = 0; private static final int CK = 1; @@ -34,37 +33,44 @@ public class Random extends InstanceFactory { public Random() { super("Random", Strings.getter("randomComponent")); - setAttributes(new Attribute[]{ - StdAttr.WIDTH, ATTR_SEED, StdAttr.EDGE_TRIGGER, - StdAttr.LABEL, StdAttr.LABEL_FONT - }, new Object[]{ - BitWidth.create(8), 0, StdAttr.TRIG_RISING, - "", StdAttr.DEFAULT_LABEL_FONT - }); + setAttributes( + new Attribute[]{ + StdAttr.WIDTH, + ATTR_SEED, + StdAttr.EDGE_TRIGGER, + StdAttr.LABEL, + StdAttr.LABEL_FONT + }, new Object[]{ + BitWidth.create(8), + 0, + StdAttr.TRIG_RISING, + "", + StdAttr.DEFAULT_LABEL_FONT + } + ); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setOffsetBounds(Bounds.create(-30, -20, 30, 40)); setIconName("random.gif"); setInstanceLogger(Logger.class); - Port[] ps = new Port[4]; - ps[OUT] = new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH); - ps[CK] = new Port(-30, -10, Port.INPUT, 1); - ps[NXT] = new Port(-30, 10, Port.INPUT, 1); - ps[RST] = new Port(-20, 20, Port.INPUT, 1); - ps[OUT].setToolTip(Strings.getter("randomQTip")); - ps[CK].setToolTip(Strings.getter("randomClockTip")); - ps[NXT].setToolTip(Strings.getter("randomNextTip")); - ps[RST].setToolTip(Strings.getter("randomResetTip")); - setPorts(ps); + Port[] ports = new Port[4]; + ports[OUT] = new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH); + ports[CK] = new Port(-30, -10, Port.INPUT, 1); + ports[NXT] = new Port(-30, 10, Port.INPUT, 1); + ports[RST] = new Port(-20, 20, Port.INPUT, 1); + ports[OUT].setToolTip(Strings.getter("randomQTip")); + ports[CK].setToolTip(Strings.getter("randomClockTip")); + ports[NXT].setToolTip(Strings.getter("randomNextTip")); + ports[RST].setToolTip(Strings.getter("randomResetTip")); + setPorts(ports); } @Override protected void configureNewInstance(Instance instance) { - Bounds bds = instance.getBounds(); - instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, - bds.getX() + bds.getWidth() / 2, bds.getY() - 3, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + Bounds bounds = instance.getBounds(); + instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, bounds.getX() + bounds.getWidth() / 2, bounds.getY() - 3, + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); } @Override @@ -91,10 +97,10 @@ public void propagate(InstanceState state) { @Override public void paintInstance(InstancePainter painter) { Graphics g = painter.getGraphics(); - Bounds bds = painter.getBounds(); + Bounds bounds = painter.getBounds(); StateData state = (StateData) painter.getData(); - BitWidth widthVal = painter.getAttributeValue(StdAttr.WIDTH); - int width = widthVal == null ? 8 : widthVal.getWidth(); + BitWidth widthValue = painter.getAttributeValue(StdAttr.WIDTH); + int width = widthValue == null ? 8 : widthValue.getWidth(); // draw boundary, label painter.drawBounds(); @@ -108,20 +114,16 @@ public void paintInstance(InstancePainter painter) { // draw contents if (painter.getShowState()) { - int val = state == null ? 0 : state.value; - String str = StringUtil.toHexString(width, val); + int value = state == null ? 0 : state.value; + String str = StringUtil.toHexString(width, value); if (str.length() <= 4) { - GraphicsUtil.drawText(g, str, - bds.getX() + 15, bds.getY() + 4, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.drawText(g, str, bounds.getX() + 15, bounds.getY() + 4, GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); } else { int split = str.length() - 4; - GraphicsUtil.drawText(g, str.substring(0, split), - bds.getX() + 15, bds.getY() + 3, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); - GraphicsUtil.drawText(g, str.substring(split), - bds.getX() + 15, bds.getY() + 15, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.drawText(g, str.substring(0, split), bounds.getX() + 15, bounds.getY() + 3, + GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.drawText(g, str.substring(split), bounds.getX() + 15, bounds.getY() + 15, GraphicsUtil.H_CENTER, + GraphicsUtil.V_TOP); } } } @@ -132,8 +134,8 @@ private static class StateData extends ClockState implements InstanceData { private final static long addend = 0xBL; private final static long mask = (1L << 48) - 1; - private long initSeed; - private long curSeed; + private long initialSeed; + private long currentSeed; private int value; public StateData(Object seed) { @@ -147,20 +149,20 @@ void reset(Object seed) { // the StateData's creation. It seems more likely that what // would be intended was starting a new sequence entirely... start = (System.currentTimeMillis() ^ multiplier) & mask; - if (start == initSeed) { + if (start == initialSeed) { start = (start + multiplier) & mask; } } - this.initSeed = start; - this.curSeed = start; + this.initialSeed = start; + this.currentSeed = start; this.value = (int) start; } void step() { - long v = curSeed; - v = (v * multiplier + addend) & mask; - curSeed = v; - value = (int) (v >> 12); + long value = currentSeed; + value = (value * multiplier + addend) & mask; + currentSeed = value; + this.value = (int) (value >> 12); } } @@ -168,8 +170,8 @@ public static class Logger extends InstanceLogger { @Override public String getLogName(InstanceState state, Object option) { - String ret = state.getAttributeValue(StdAttr.LABEL); - return ret != null && !ret.equals("") ? ret : null; + String name = state.getAttributeValue(StdAttr.LABEL); + return name != null && !name.equals("") ? name : null; } @Override @@ -185,4 +187,4 @@ public Value getLogValue(InstanceState state, Object option) { return Value.createKnown(dataWidth, data.value); } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/memory/Register.java b/src/main/java/com/cburch/logisim/std/memory/Register.java index 4d75b50..4ea046a 100644 --- a/src/main/java/com/cburch/logisim/std/memory/Register.java +++ b/src/main/java/com/cburch/logisim/std/memory/Register.java @@ -31,39 +31,44 @@ public class Register extends InstanceFactory { public Register() { super("Register", Strings.getter("registerComponent")); - setAttributes(new Attribute[]{ - StdAttr.WIDTH, StdAttr.TRIGGER, - StdAttr.LABEL, StdAttr.LABEL_FONT - }, new Object[]{ - BitWidth.create(8), StdAttr.TRIG_RISING, - "", StdAttr.DEFAULT_LABEL_FONT - }); + setAttributes( + new Attribute[]{ + StdAttr.WIDTH, + StdAttr.TRIGGER, + StdAttr.LABEL, + StdAttr.LABEL_FONT + }, new Object[]{ + BitWidth.create(8), + StdAttr.TRIG_RISING, + "", + StdAttr.DEFAULT_LABEL_FONT + } + ); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setOffsetBounds(Bounds.create(-30, -20, 30, 40)); setIconName("register.gif"); setInstancePoker(RegisterPoker.class); setInstanceLogger(RegisterLogger.class); - Port[] ps = new Port[5]; - ps[OUT] = new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH); - ps[IN] = new Port(-30, 0, Port.INPUT, StdAttr.WIDTH); - ps[CK] = new Port(-20, 20, Port.INPUT, 1); - ps[CLR] = new Port(-10, 20, Port.INPUT, 1); - ps[EN] = new Port(-30, 10, Port.INPUT, 1); - ps[OUT].setToolTip(Strings.getter("registerQTip")); - ps[IN].setToolTip(Strings.getter("registerDTip")); - ps[CK].setToolTip(Strings.getter("registerClkTip")); - ps[CLR].setToolTip(Strings.getter("registerClrTip")); - ps[EN].setToolTip(Strings.getter("registerEnableTip")); - setPorts(ps); + Port[] ports = new Port[5]; + ports[OUT] = new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH); + ports[IN] = new Port(-30, 0, Port.INPUT, StdAttr.WIDTH); + ports[CK] = new Port(-20, 20, Port.INPUT, 1); + ports[CLR] = new Port(-10, 20, Port.INPUT, 1); + ports[EN] = new Port(-30, 10, Port.INPUT, 1); + ports[OUT].setToolTip(Strings.getter("registerQTip")); + ports[IN].setToolTip(Strings.getter("registerDTip")); + ports[CK].setToolTip(Strings.getter("registerClkTip")); + ports[CLR].setToolTip(Strings.getter("registerClrTip")); + ports[EN].setToolTip(Strings.getter("registerEnableTip")); + setPorts(ports); } @Override protected void configureNewInstance(Instance instance) { - Bounds bds = instance.getBounds(); - instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, - bds.getX() + bds.getWidth() / 2, bds.getY() - 3, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + Bounds bounds = instance.getBounds(); + instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, bounds.getX() + bounds.getWidth() / 2, bounds.getY() - 3, + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); } @Override @@ -76,11 +81,11 @@ public void propagate(InstanceState state) { BitWidth dataWidth = state.getAttributeValue(StdAttr.WIDTH); Object triggerType = state.getAttributeValue(StdAttr.TRIGGER); - boolean triggered = data.updateClock(state.getPort(CK), triggerType); + boolean isTriggered = data.updateClock(state.getPort(CK), triggerType); if (state.getPort(CLR) == Value.TRUE) { data.value = 0; - } else if (triggered && state.getPort(EN) != Value.FALSE) { + } else if (isTriggered && state.getPort(EN) != Value.FALSE) { Value in = state.getPort(IN); if (in.isFullyDefined()) { data.value = in.toIntValue(); @@ -93,17 +98,17 @@ public void propagate(InstanceState state) { @Override public void paintInstance(InstancePainter painter) { Graphics g = painter.getGraphics(); - Bounds bds = painter.getBounds(); - RegisterData state = (RegisterData) painter.getData(); - BitWidth widthVal = painter.getAttributeValue(StdAttr.WIDTH); - int width = widthVal == null ? 8 : widthVal.getWidth(); + Bounds bounds = painter.getBounds(); + RegisterData data = (RegisterData) painter.getData(); + BitWidth widthValue = painter.getAttributeValue(StdAttr.WIDTH); + int width = widthValue == null ? 8 : widthValue.getWidth(); // determine text to draw in label String a; String b = null; if (painter.getShowState()) { - int val = state == null ? 0 : state.value; - String str = StringUtil.toHexString(width, val); + int value = data == null ? 0 : data.value; + String str = StringUtil.toHexString(width, value); if (str.length() <= 4) { a = str; } else { @@ -113,7 +118,7 @@ public void paintInstance(InstancePainter painter) { } } else { a = Strings.get("registerLabel"); - b = Strings.get("registerWidthLabel", "" + widthVal.getWidth()); + b = Strings.get("registerWidthLabel", "" + widthValue.getWidth()); } // draw boundary, label @@ -136,13 +141,10 @@ public void paintInstance(InstancePainter painter) { // draw contents if (b == null) { - GraphicsUtil.drawText(g, a, bds.getX() + 15, bds.getY() + 4, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.drawText(g, a, bounds.getX() + 15, bounds.getY() + 4, GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); } else { - GraphicsUtil.drawText(g, a, bds.getX() + 15, bds.getY() + 3, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); - GraphicsUtil.drawText(g, b, bds.getX() + 15, bds.getY() + 15, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.drawText(g, a, bounds.getX() + 15, bounds.getY() + 3, GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.drawText(g, b, bounds.getX() + 15, bounds.getY() + 15, GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/memory/RegisterLogger.java b/src/main/java/com/cburch/logisim/std/memory/RegisterLogger.java index 35bfe5b..20a0b93 100644 --- a/src/main/java/com/cburch/logisim/std/memory/RegisterLogger.java +++ b/src/main/java/com/cburch/logisim/std/memory/RegisterLogger.java @@ -13,8 +13,8 @@ public class RegisterLogger extends InstanceLogger { @Override public String getLogName(InstanceState state, Object option) { - String ret = state.getAttributeValue(StdAttr.LABEL); - return ret != null && !ret.equals("") ? ret : null; + String name = state.getAttributeValue(StdAttr.LABEL); + return name != null && !name.equals("") ? name : null; } @Override diff --git a/src/main/java/com/cburch/logisim/std/memory/RegisterPoker.java b/src/main/java/com/cburch/logisim/std/memory/RegisterPoker.java index d06f859..a42af9c 100644 --- a/src/main/java/com/cburch/logisim/std/memory/RegisterPoker.java +++ b/src/main/java/com/cburch/logisim/std/memory/RegisterPoker.java @@ -16,8 +16,8 @@ public class RegisterPoker extends InstancePoker { - private int initValue; - private int curValue; + private int initialValue; + private int currentValue; @Override public boolean init(InstanceState state, MouseEvent e) { @@ -26,33 +26,33 @@ public boolean init(InstanceState state, MouseEvent e) { data = new RegisterData(); state.setData(data); } - initValue = data.value; - curValue = initValue; + initialValue = data.value; + currentValue = initialValue; return true; } @Override public void paint(InstancePainter painter) { - Bounds bds = painter.getBounds(); + Bounds bounds = painter.getBounds(); BitWidth dataWidth = painter.getAttributeValue(StdAttr.WIDTH); int width = dataWidth == null ? 8 : dataWidth.getWidth(); - int len = (width + 3) / 4; + int length = (width + 3) / 4; Graphics g = painter.getGraphics(); g.setColor(Color.RED); - if (len > 4) { - g.drawRect(bds.getX(), bds.getY() + 3, bds.getWidth(), 25); + if (length > 4) { + g.drawRect(bounds.getX(), bounds.getY() + 3, bounds.getWidth(), 25); } else { - int wid = 7 * len + 2; - g.drawRect(bds.getX() + (bds.getWidth() - wid) / 2, bds.getY() + 4, wid, 15); + int wid = 7 * length + 2; + g.drawRect(bounds.getX() + (bounds.getWidth() - wid) / 2, bounds.getY() + 4, wid, 15); } g.setColor(Color.BLACK); } @Override public void keyTyped(InstanceState state, KeyEvent e) { - int val = Character.digit(e.getKeyChar(), 16); - if (val < 0) { + int value = Character.digit(e.getKeyChar(), 16); + if (value < 0) { return; } @@ -60,9 +60,9 @@ public void keyTyped(InstanceState state, KeyEvent e) { if (dataWidth == null) { dataWidth = BitWidth.create(8); } - curValue = (curValue * 16 + val) & dataWidth.getMask(); + currentValue = (currentValue * 16 + value) & dataWidth.getMask(); RegisterData data = (RegisterData) state.getData(); - data.value = curValue; + data.value = currentValue; state.fireInvalidated(); } diff --git a/src/main/java/com/cburch/logisim/std/memory/Rom.java b/src/main/java/com/cburch/logisim/std/memory/Rom.java index fc39002..532508d 100644 --- a/src/main/java/com/cburch/logisim/std/memory/Rom.java +++ b/src/main/java/com/cburch/logisim/std/memory/Rom.java @@ -3,6 +3,7 @@ package com.cburch.logisim.std.memory; +import com.adlerd.logger.Logger; import com.cburch.logisim.circuit.CircuitState; import com.cburch.logisim.data.Attribute; import com.cburch.logisim.data.AttributeSet; @@ -32,7 +33,7 @@ public class Rom extends Mem { // The following is so that instance's MemListeners aren't freed by the // garbage collector until the instance itself is ready to be freed. - private WeakHashMap memListeners; + private final WeakHashMap memListeners; public Rom() { super("ROM", Strings.getter("romComponent"), 0); @@ -42,9 +43,9 @@ public Rom() { @Override void configurePorts(Instance instance) { - Port[] ps = new Port[MEM_INPUTS]; - configureStandardPorts(instance, ps); - instance.setPorts(ps); + Port[] ports = new Port[MEM_INPUTS]; + configureStandardPorts(instance, ports); + instance.setPorts(ports); } @Override @@ -54,29 +55,29 @@ public AttributeSet createAttributeSet() { @Override MemState getState(Instance instance, CircuitState state) { - MemState ret = (MemState) instance.getData(state); - if (ret == null) { + MemState memState = (MemState) instance.getData(state); + if (memState == null) { MemContents contents = getMemContents(instance); - ret = new MemState(contents); - instance.setData(state, ret); + memState = new MemState(contents); + instance.setData(state, memState); } - return ret; + return memState; } @Override MemState getState(InstanceState state) { - MemState ret = (MemState) state.getData(); - if (ret == null) { + MemState memState = (MemState) state.getData(); + if (memState == null) { MemContents contents = getMemContents(state.getInstance()); - ret = new MemState(contents); - state.setData(ret); + memState = new MemState(contents); + state.setData(memState); } - return ret; + return memState; } @Override - HexFrame getHexFrame(Project proj, Instance instance, CircuitState state) { - return RomAttributes.getHexFrame(getMemContents(instance), proj); + HexFrame getHexFrame(Project project, Instance instance, CircuitState state) { + return RomAttributes.getHexFrame(getMemContents(instance), project); } // TODO - maybe delete this method? @@ -89,7 +90,7 @@ public void propagate(InstanceState state) { MemState myState = getState(state); BitWidth dataBits = state.getAttributeValue(DATA_ATTR); - Value addrValue = state.getPort(ADDR); + Value addressValue = state.getPort(ADDR); boolean chipSelect = state.getPort(CS) != Value.FALSE; if (!chipSelect) { @@ -98,17 +99,17 @@ public void propagate(InstanceState state) { return; } - int addr = addrValue.toIntValue(); - if (!addrValue.isFullyDefined() || addr < 0) { + int address = addressValue.toIntValue(); + if (!addressValue.isFullyDefined() || address < 0) { return; } - if (addr != myState.getCurrent()) { - myState.setCurrent(addr); - myState.scrollToShow(addr); + if (address != myState.getCurrent()) { + myState.setCurrent(address); + myState.scrollToShow(address); } - int val = myState.getContents().get(addr); - state.setPort(DATA, Value.createKnown(dataBits, val), DELAY); + int value = myState.getContents().get(address); + state.setPort(DATA, Value.createKnown(dataBits, value), DELAY); } @Override @@ -129,12 +130,12 @@ public ContentsAttribute() { @Override public java.awt.Component getCellEditor(Window source, MemContents value) { if (source instanceof Frame) { - Project proj = ((Frame) source).getProject(); - RomAttributes.register(value, proj); + Project project = ((Frame) source).getProject(); + RomAttributes.register(value, project); } - ContentsCell ret = new ContentsCell(source, value); - ret.mouseClicked(null); - return ret; + ContentsCell cell = new ContentsCell(source, value); + cell.mouseClicked(null); + return cell; } @Override @@ -144,15 +145,16 @@ public String toDisplayString(MemContents value) { @Override public String toStandardString(MemContents state) { - int addr = state.getLogLength(); + int address = state.getLogLength(); int data = state.getWidth(); - StringWriter ret = new StringWriter(); - ret.write("addr/data: " + addr + " " + data + "\n"); + StringWriter writer = new StringWriter(); + writer.write("address/data: " + address + " " + data + "\n"); try { - HexFile.save(ret, state); + HexFile.save(writer, state); } catch (IOException e) { + Logger.debugln(e.getMessage()); } - return ret.toString(); + return writer.toString(); } @Override @@ -160,29 +162,24 @@ public MemContents parse(String value) { int lineBreak = value.indexOf('\n'); String first = lineBreak < 0 ? value : value.substring(0, lineBreak); String rest = lineBreak < 0 ? "" : value.substring(lineBreak + 1); - StringTokenizer toks = new StringTokenizer(first); + StringTokenizer tokens = new StringTokenizer(first); try { - String header = toks.nextToken(); + String header = tokens.nextToken(); if (!header.equals("addr/data:")) { return null; } - int addr = Integer.parseInt(toks.nextToken()); - int data = Integer.parseInt(toks.nextToken()); - MemContents ret = MemContents.create(addr, data); + int address = Integer.parseInt(tokens.nextToken()); + int data = Integer.parseInt(tokens.nextToken()); + MemContents ret = MemContents.create(address, data); HexFile.open(ret, new StringReader(rest)); return ret; - } catch (IOException e) { - return null; - } catch (NumberFormatException e) { - return null; - } catch (NoSuchElementException e) { + } catch (IOException | NumberFormatException | NoSuchElementException e) { return null; } } } - private static class ContentsCell extends JLabel - implements MouseListener { + private static class ContentsCell extends JLabel implements MouseListener { Window source; MemContents contents; diff --git a/src/main/java/com/cburch/logisim/std/memory/RomAttributes.java b/src/main/java/com/cburch/logisim/std/memory/RomAttributes.java index 86715a5..2380424 100644 --- a/src/main/java/com/cburch/logisim/std/memory/RomAttributes.java +++ b/src/main/java/com/cburch/logisim/std/memory/RomAttributes.java @@ -14,50 +14,47 @@ class RomAttributes extends AbstractAttributeSet { - private static List> ATTRIBUTES = Arrays.asList(Mem.ADDR_ATTR, Mem.DATA_ATTR, Rom.CONTENTS_ATTR); - - private static WeakHashMap listenerRegistry - = new WeakHashMap<>(); - private static WeakHashMap windowRegistry - = new WeakHashMap<>(); - private BitWidth addrBits = BitWidth.create(8); + private static final List> ATTRIBUTES = Arrays.asList(Mem.ADDR_ATTR, Mem.DATA_ATTR, Rom.CONTENTS_ATTR); + private static final WeakHashMap listenerRegistry = new WeakHashMap<>(); + private static final WeakHashMap windowRegistry = new WeakHashMap<>(); + private BitWidth addressBits = BitWidth.create(8); private BitWidth dataBits = BitWidth.create(8); private MemContents contents; RomAttributes() { - contents = MemContents.create(addrBits.getWidth(), dataBits.getWidth()); + contents = MemContents.create(addressBits.getWidth(), dataBits.getWidth()); } - static void register(MemContents value, Project proj) { - if (proj == null || listenerRegistry.containsKey(value)) { + static void register(MemContents value, Project project) { + if (project == null || listenerRegistry.containsKey(value)) { return; } - RomContentsListener l = new RomContentsListener(proj); + RomContentsListener l = new RomContentsListener(project); value.addHexModelListener(l); listenerRegistry.put(value, l); } - static HexFrame getHexFrame(MemContents value, Project proj) { + static HexFrame getHexFrame(MemContents value, Project project) { synchronized (windowRegistry) { - HexFrame ret = windowRegistry.get(value); - if (ret == null) { - ret = new HexFrame(proj, value); - windowRegistry.put(value, ret); + HexFrame frame = windowRegistry.get(value); + if (frame == null) { + frame = new HexFrame(project, value); + windowRegistry.put(value, frame); } - return ret; + return frame; } } - void setProject(Project proj) { - register(contents, proj); + void setProject(Project project) { + register(contents, project); } @Override - protected void copyInto(AbstractAttributeSet dest) { - RomAttributes d = (RomAttributes) dest; - d.addrBits = addrBits; - d.dataBits = dataBits; - d.contents = contents.clone(); + protected void copyInto(AbstractAttributeSet destination) { + RomAttributes romAttributes = (RomAttributes) destination; + romAttributes.addressBits = addressBits; + romAttributes.dataBits = dataBits; + romAttributes.contents = contents.clone(); } @Override @@ -69,7 +66,7 @@ public List> getAttributes() { @SuppressWarnings("unchecked") public V getValue(Attribute attr) { if (attr == Mem.ADDR_ATTR) { - return (V) addrBits; + return (V) addressBits; } if (attr == Mem.DATA_ATTR) { return (V) dataBits; @@ -83,11 +80,11 @@ public V getValue(Attribute attr) { @Override public void setValue(Attribute attr, V value) { if (attr == Mem.ADDR_ATTR) { - addrBits = (BitWidth) value; - contents.setDimensions(addrBits.getWidth(), dataBits.getWidth()); + addressBits = (BitWidth) value; + contents.setDimensions(addressBits.getWidth(), dataBits.getWidth()); } else if (attr == Mem.DATA_ATTR) { dataBits = (BitWidth) value; - contents.setDimensions(addrBits.getWidth(), dataBits.getWidth()); + contents.setDimensions(addressBits.getWidth(), dataBits.getWidth()); } else if (attr == Rom.CONTENTS_ATTR) { contents = (MemContents) value; } diff --git a/src/main/java/com/cburch/logisim/std/memory/RomContentsListener.java b/src/main/java/com/cburch/logisim/std/memory/RomContentsListener.java index 3cc9458..3af3a1c 100644 --- a/src/main/java/com/cburch/logisim/std/memory/RomContentsListener.java +++ b/src/main/java/com/cburch/logisim/std/memory/RomContentsListener.java @@ -10,11 +10,11 @@ class RomContentsListener implements HexModelListener { - Project proj; + Project project; boolean enabled = true; - RomContentsListener(Project proj) { - this.proj = proj; + RomContentsListener(Project project) { + this.project = project; } void setEnabled(boolean value) { @@ -26,30 +26,27 @@ public void metaInfoChanged(HexModel source) { // action } - public void bytesChanged(HexModel source, long start, - long numBytes, int[] oldValues) { - if (enabled && proj != null && oldValues != null) { + public void bytesChanged(HexModel source, long start, long numBytes, int[] oldValues) { + if (enabled && project != null && oldValues != null) { // this change needs to be logged in the undo log int[] newValues = new int[oldValues.length]; for (int i = 0; i < newValues.length; i++) { newValues[i] = source.get(start + i); } - proj.doAction(new Change(this, (MemContents) source, - start, oldValues, newValues)); + project.doAction(new Change(this, (MemContents) source, start, oldValues, newValues)); } } private static class Change extends Action { - private RomContentsListener source; - private MemContents contents; - private long start; - private int[] oldValues; - private int[] newValues; + private final RomContentsListener source; + private final MemContents contents; + private final long start; + private final int[] oldValues; + private final int[] newValues; private boolean completed = true; - Change(RomContentsListener source, MemContents contents, - long start, int[] oldValues, int[] newValues) { + Change(RomContentsListener source, MemContents contents, long start, int[] oldValues, int[] newValues) { this.source = source; this.contents = contents; this.start = start; @@ -63,7 +60,7 @@ public String getName() { } @Override - public void doIt(Project proj) { + public void doIt(Project project) { if (!completed) { completed = true; try { @@ -76,7 +73,7 @@ public void doIt(Project proj) { } @Override - public void undo(Project proj) { + public void undo(Project project) { if (completed) { completed = false; try { @@ -91,10 +88,10 @@ public void undo(Project proj) { @Override public boolean shouldAppendTo(Action other) { if (other instanceof Change) { - Change o = (Change) other; - long oEnd = o.start + o.newValues.length; + Change change = (Change) other; + long oEnd = change.start + change.newValues.length; long end = start + newValues.length; - if (oEnd >= start && end >= o.start) { + if (oEnd >= start && end >= change.start) { return true; } } @@ -104,18 +101,18 @@ public boolean shouldAppendTo(Action other) { @Override public Action append(Action other) { if (other instanceof Change) { - Change o = (Change) other; - long oEnd = o.start + o.newValues.length; + Change change = (Change) other; + long oEnd = change.start + change.newValues.length; long end = start + newValues.length; - if (oEnd >= start && end >= o.start) { - long nStart = Math.min(start, o.start); + if (oEnd >= start && end >= change.start) { + long nStart = Math.min(start, change.start); long nEnd = Math.max(end, oEnd); int[] nOld = new int[(int) (nEnd - nStart)]; int[] nNew = new int[(int) (nEnd - nStart)]; - System.arraycopy(o.oldValues, 0, nOld, (int) (o.start - nStart), o.oldValues.length); + System.arraycopy(change.oldValues, 0, nOld, (int) (change.start - nStart), change.oldValues.length); System.arraycopy(oldValues, 0, nOld, (int) (start - nStart), oldValues.length); System.arraycopy(newValues, 0, nNew, (int) (start - nStart), newValues.length); - System.arraycopy(o.newValues, 0, nNew, (int) (o.start - nStart), o.newValues.length); + System.arraycopy(change.newValues, 0, nNew, (int) (change.start - nStart), change.newValues.length); return new Change(source, contents, nStart, nOld, nNew); } } diff --git a/src/main/java/com/cburch/logisim/std/memory/SRFlipFlop.java b/src/main/java/com/cburch/logisim/std/memory/SRFlipFlop.java index 2ad668c..3e9620b 100644 --- a/src/main/java/com/cburch/logisim/std/memory/SRFlipFlop.java +++ b/src/main/java/com/cburch/logisim/std/memory/SRFlipFlop.java @@ -8,8 +8,7 @@ public class SRFlipFlop extends AbstractFlipFlop { public SRFlipFlop() { - super("S-R Flip-Flop", "srFlipFlop.gif", - Strings.getter("srFlipFlopComponent"), 2, true); + super("S-R Flip-Flop", "srFlipFlop.gif", Strings.getter("srFlipFlopComponent"), 2, true); } @Override @@ -18,10 +17,10 @@ protected String getInputName(int index) { } @Override - protected Value computeValue(Value[] inputs, Value curValue) { + protected Value computeValue(Value[] inputs, Value currentValue) { if (inputs[0] == Value.FALSE) { if (inputs[1] == Value.FALSE) { - return curValue; + return currentValue; } else if (inputs[1] == Value.TRUE) { return Value.FALSE; } diff --git a/src/main/java/com/cburch/logisim/std/memory/ShiftRegister.java b/src/main/java/com/cburch/logisim/std/memory/ShiftRegister.java index 13bb886..c807385 100644 --- a/src/main/java/com/cburch/logisim/std/memory/ShiftRegister.java +++ b/src/main/java/com/cburch/logisim/std/memory/ShiftRegister.java @@ -25,9 +25,9 @@ public class ShiftRegister extends InstanceFactory { static final Attribute ATTR_LENGTH = Attributes.forIntegerRange("length", - Strings.getter("shiftRegLengthAttr"), 1, 32); + Strings.getter("shiftRegLengthAttr"), 1, 32); static final Attribute ATTR_LOAD = Attributes.forBoolean("parallel", - Strings.getter("shiftRegParallelAttr")); + Strings.getter("shiftRegParallelAttr")); private static final int IN = 0; private static final int SH = 1; @@ -38,16 +38,27 @@ public class ShiftRegister extends InstanceFactory { public ShiftRegister() { super("Shift Register", Strings.getter("shiftRegisterComponent")); - setAttributes(new Attribute[]{ - StdAttr.WIDTH, ATTR_LENGTH, ATTR_LOAD, StdAttr.EDGE_TRIGGER, - StdAttr.LABEL, StdAttr.LABEL_FONT - }, new Object[]{ - BitWidth.ONE, 8, Boolean.TRUE, - StdAttr.TRIG_RISING, "", StdAttr.DEFAULT_LABEL_FONT - }); + setAttributes( + new Attribute[]{ + StdAttr.WIDTH, + ATTR_LENGTH, + ATTR_LOAD, + StdAttr.EDGE_TRIGGER, + StdAttr.LABEL, + StdAttr.LABEL_FONT + }, new Object[]{ + BitWidth.ONE, + 8, + Boolean.TRUE, + StdAttr.TRIG_RISING, + "", + StdAttr.DEFAULT_LABEL_FONT + } + ); setKeyConfigurator(JoinedConfigurator.create( - new IntegerConfigurator(ATTR_LENGTH, 1, 32, 0), - new BitWidthConfigurator(StdAttr.WIDTH))); + new IntegerConfigurator(ATTR_LENGTH, 1, 32, 0), + new BitWidthConfigurator(StdAttr.WIDTH) + )); setIconName("shiftreg.gif"); setInstanceLogger(ShiftRegisterLogger.class); @@ -56,8 +67,8 @@ public ShiftRegister() { @Override public Bounds getOffsetBounds(AttributeSet attributes) { - Object parallel = attributes.getValue(ATTR_LOAD); - if (parallel == null || (Boolean) parallel) { + Boolean parallel = attributes.getValue(ATTR_LOAD); + if (parallel == null || parallel) { int len = attributes.getValue(ATTR_LENGTH); return Bounds.create(0, -20, 20 + 10 * len, 40); } else { @@ -83,43 +94,41 @@ private void configurePorts(Instance instance) { BitWidth widthObj = instance.getAttributeValue(StdAttr.WIDTH); int width = widthObj.getWidth(); Boolean parallelObj = instance.getAttributeValue(ATTR_LOAD); - Bounds bds = instance.getBounds(); - Port[] ps; + Bounds bounds = instance.getBounds(); + Port[] ports; if (parallelObj == null || parallelObj) { - Integer lenObj = instance.getAttributeValue(ATTR_LENGTH); - int len = lenObj == null ? 8 : lenObj; - ps = new Port[6 + 2 * len]; - ps[LD] = new Port(10, -20, Port.INPUT, 1); - ps[LD].setToolTip(Strings.getter("shiftRegLoadTip")); - for (int i = 0; i < len; i++) { - ps[6 + 2 * i] = new Port(20 + 10 * i, -20, Port.INPUT, width); - ps[6 + 2 * i + 1] = new Port(20 + 10 * i, 20, Port.OUTPUT, width); + Integer lengthObject = instance.getAttributeValue(ATTR_LENGTH); + int length = lengthObject == null ? 8 : lengthObject; + ports = new Port[6 + 2 * length]; + ports[LD] = new Port(10, -20, Port.INPUT, 1); + ports[LD].setToolTip(Strings.getter("shiftRegLoadTip")); + for (int i = 0; i < length; i++) { + ports[6 + 2 * i] = new Port(20 + 10 * i, -20, Port.INPUT, width); + ports[6 + 2 * i + 1] = new Port(20 + 10 * i, 20, Port.OUTPUT, width); } } else { - ps = new Port[5]; + ports = new Port[5]; } - ps[OUT] = new Port(bds.getWidth(), 0, Port.OUTPUT, width); - ps[SH] = new Port(0, -10, Port.INPUT, 1); - ps[IN] = new Port(0, 0, Port.INPUT, width); - ps[CK] = new Port(0, 10, Port.INPUT, 1); - ps[CLR] = new Port(10, 20, Port.INPUT, 1); - ps[OUT].setToolTip(Strings.getter("shiftRegOutTip")); - ps[SH].setToolTip(Strings.getter("shiftRegShiftTip")); - ps[IN].setToolTip(Strings.getter("shiftRegInTip")); - ps[CK].setToolTip(Strings.getter("shiftRegClockTip")); - ps[CLR].setToolTip(Strings.getter("shiftRegClearTip")); - instance.setPorts(ps); - - instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, - bds.getX() + bds.getWidth() / 2, - bds.getY() + bds.getHeight() / 4, - GraphicsUtil.H_CENTER, GraphicsUtil.V_CENTER); + ports[OUT] = new Port(bounds.getWidth(), 0, Port.OUTPUT, width); + ports[SH] = new Port(0, -10, Port.INPUT, 1); + ports[IN] = new Port(0, 0, Port.INPUT, width); + ports[CK] = new Port(0, 10, Port.INPUT, 1); + ports[CLR] = new Port(10, 20, Port.INPUT, 1); + ports[OUT].setToolTip(Strings.getter("shiftRegOutTip")); + ports[SH].setToolTip(Strings.getter("shiftRegShiftTip")); + ports[IN].setToolTip(Strings.getter("shiftRegInTip")); + ports[CK].setToolTip(Strings.getter("shiftRegClockTip")); + ports[CLR].setToolTip(Strings.getter("shiftRegClearTip")); + instance.setPorts(ports); + + instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, bounds.getX() + bounds.getWidth() / 2, + bounds.getY() + bounds.getHeight() / 4, GraphicsUtil.H_CENTER, GraphicsUtil.V_CENTER); } private ShiftRegisterData getData(InstanceState state) { BitWidth width = state.getAttributeValue(StdAttr.WIDTH); - Integer lenObj = state.getAttributeValue(ATTR_LENGTH); - int length = lenObj == null ? 8 : lenObj; + Integer lengthObject = state.getAttributeValue(ATTR_LENGTH); + int length = lengthObject == null ? 8 : lengthObject; ShiftRegisterData data = (ShiftRegisterData) state.getData(); if (data == null) { data = new ShiftRegisterData(width, length); @@ -135,7 +144,7 @@ public void propagate(InstanceState state) { Object triggerType = state.getAttributeValue(StdAttr.EDGE_TRIGGER); boolean parallel = state.getAttributeValue(ATTR_LOAD); ShiftRegisterData data = getData(state); - int len = data.getLength(); + int length = data.getLength(); boolean triggered = data.updateClock(state.getPort(CK), triggerType); if (state.getPort(CLR) == Value.TRUE) { @@ -143,7 +152,7 @@ public void propagate(InstanceState state) { } else if (triggered) { if (parallel && state.getPort(LD) == Value.TRUE) { data.clear(); - for (int i = len - 1; i >= 0; i--) { + for (int i = length - 1; i >= 0; i--) { data.push(state.getPort(6 + 2 * i)); } } else if (state.getPort(SH) != Value.FALSE) { @@ -153,8 +162,8 @@ public void propagate(InstanceState state) { state.setPort(OUT, data.get(0), 4); if (parallel) { - for (int i = 0; i < len; i++) { - state.setPort(6 + 2 * i + 1, data.get(len - 1 - i), 4); + for (int i = 0; i < length; i++) { + state.setPort(6 + 2 * i + 1, data.get(length - 1 - i), 4); } } } @@ -168,43 +177,42 @@ public void paintInstance(InstancePainter painter) { // draw state boolean parallel = painter.getAttributeValue(ATTR_LOAD); if (parallel) { - BitWidth widObj = painter.getAttributeValue(StdAttr.WIDTH); - int wid = widObj.getWidth(); - Integer lenObj = painter.getAttributeValue(ATTR_LENGTH); - int len = lenObj == null ? 8 : lenObj; + BitWidth widthObject = painter.getAttributeValue(StdAttr.WIDTH); + int width = widthObject.getWidth(); + Integer lengthObject = painter.getAttributeValue(ATTR_LENGTH); + int length = lengthObject == null ? 8 : lengthObject; if (painter.getShowState()) { - if (wid <= 4) { + if (width <= 4) { ShiftRegisterData data = getData(painter); - Bounds bds = painter.getBounds(); - int x = bds.getX() + 20; - int y = bds.getY(); + Bounds bounds = painter.getBounds(); + int x = bounds.getX() + 20; + int y = bounds.getY(); Object label = painter.getAttributeValue(StdAttr.LABEL); if (label == null || label.equals("")) { - y += bds.getHeight() / 2; + y += bounds.getHeight() / 2; } else { - y += 3 * bds.getHeight() / 4; + y += 3 * bounds.getHeight() / 4; } Graphics g = painter.getGraphics(); - for (int i = 0; i < len; i++) { - String s = data.get(len - 1 - i).toHexString(); + for (int i = 0; i < length; i++) { + String s = data.get(length - 1 - i).toHexString(); GraphicsUtil.drawCenteredText(g, s, x, y); x += 10; } } } else { - Bounds bds = painter.getBounds(); - int x = bds.getX() + bds.getWidth() / 2; - int y = bds.getY(); - int h = bds.getHeight(); + Bounds bounds = painter.getBounds(); + int x = bounds.getX() + bounds.getWidth() / 2; + int y = bounds.getY(); + int height = bounds.getHeight(); Graphics g = painter.getGraphics(); Object label = painter.getAttributeValue(StdAttr.LABEL); if (label == null || label.equals("")) { String a = Strings.get("shiftRegisterLabel1"); - GraphicsUtil.drawCenteredText(g, a, x, y + h / 4); + GraphicsUtil.drawCenteredText(g, a, x, y + height / 4); } - String b = Strings.get("shiftRegisterLabel2", "" + len, - "" + wid); - GraphicsUtil.drawCenteredText(g, b, x, y + 3 * h / 4); + String b = Strings.get("shiftRegisterLabel2", "" + length, "" + width); + GraphicsUtil.drawCenteredText(g, b, x, y + 3 * height / 4); } } @@ -217,4 +225,4 @@ public void paintInstance(InstancePainter painter) { } painter.drawClock(CK, Direction.EAST); } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterData.java b/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterData.java index 1671954..a8aee05 100644 --- a/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterData.java +++ b/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterData.java @@ -11,85 +11,85 @@ class ShiftRegisterData extends ClockState implements InstanceData { private BitWidth width; - private Value[] vs; - private int vsPos; + private Value[] values; + private int valuesPosition; - public ShiftRegisterData(BitWidth width, int len) { + public ShiftRegisterData(BitWidth width, int length) { this.width = width; - this.vs = new Value[len]; - Arrays.fill(this.vs, Value.createKnown(width, 0)); - this.vsPos = 0; + this.values = new Value[length]; + Arrays.fill(this.values, Value.createKnown(width, 0)); + this.valuesPosition = 0; } @Override public ShiftRegisterData clone() { ShiftRegisterData ret = (ShiftRegisterData) super.clone(); - ret.vs = this.vs.clone(); + ret.values = this.values.clone(); return ret; } public int getLength() { - return vs.length; + return values.length; } - public void setDimensions(BitWidth newWidth, int newLength) { - Value[] v = vs; - BitWidth oldWidth = width; - int oldW = oldWidth.getWidth(); - int newW = newWidth.getWidth(); - if (v.length != newLength) { - Value[] newV = new Value[newLength]; - int j = vsPos; - int copy = Math.min(newLength, v.length); + public void setDimensions(BitWidth newBitWidth, int newLength) { + Value[] values = this.values; + BitWidth oldBitWidth = width; + int oldWidth = oldBitWidth.getWidth(); + int newWidth = newBitWidth.getWidth(); + if (values.length != newLength) { + Value[] newValues = new Value[newLength]; + int j = valuesPosition; + int copy = Math.min(newLength, values.length); for (int i = 0; i < copy; i++) { - newV[i] = v[j]; + newValues[i] = values[j]; j++; - if (j == v.length) { + if (j == values.length) { j = 0; } } - Arrays.fill(newV, copy, newLength, Value.createKnown(newWidth, 0)); - v = newV; - vsPos = 0; - vs = newV; + Arrays.fill(newValues, copy, newLength, Value.createKnown(newBitWidth, 0)); + values = newValues; + valuesPosition = 0; + this.values = newValues; } - if (oldW != newW) { - for (int i = 0; i < v.length; i++) { - Value vi = v[i]; - if (vi.getWidth() != newW) { - v[i] = vi.extendWidth(newW, Value.FALSE); + if (oldWidth != newWidth) { + for (int i = 0; i < values.length; i++) { + Value vi = values[i]; + if (vi.getWidth() != newWidth) { + values[i] = vi.extendWidth(newWidth, Value.FALSE); } } - width = newWidth; + width = newBitWidth; } } public void clear() { - Arrays.fill(vs, Value.createKnown(width, 0)); - vsPos = 0; + Arrays.fill(values, Value.createKnown(width, 0)); + valuesPosition = 0; } - public void push(Value v) { - int pos = vsPos; - vs[pos] = v; - vsPos = pos >= vs.length - 1 ? 0 : pos + 1; + public void push(Value value) { + int position = valuesPosition; + values[position] = value; + valuesPosition = position >= values.length - 1 ? 0 : position + 1; } public Value get(int index) { - int i = vsPos + index; - Value[] v = vs; + int i = valuesPosition + index; + Value[] v = values; if (i >= v.length) { i -= v.length; } return v[i]; } - public void set(int index, Value val) { - int i = vsPos + index; - Value[] v = vs; - if (i >= v.length) { - i -= v.length; + public void set(int index, Value value) { + int i = valuesPosition + index; + Value[] values = this.values; + if (i >= values.length) { + i -= values.length; } - v[i] = val; + values[i] = value; } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterLogger.java b/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterLogger.java index 1a583b4..d660ae4 100644 --- a/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterLogger.java +++ b/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterLogger.java @@ -23,15 +23,14 @@ public Object[] getLogOptions(InstanceState state) { @Override public String getLogName(InstanceState state, Object option) { - String inName = state.getAttributeValue(StdAttr.LABEL); - if (inName == null || inName.equals("")) { - inName = Strings.get("shiftRegisterComponent") - + state.getInstance().getLocation(); + String name = state.getAttributeValue(StdAttr.LABEL); + if (name == null || name.equals("")) { + name = Strings.get("shiftRegisterComponent") + state.getInstance().getLocation(); } if (option instanceof Integer) { - return inName + "[" + option + "]"; + return name + "[" + option + "]"; } else { - return inName; + return name; } } diff --git a/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterPoker.java b/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterPoker.java index a6ebc73..a0c4f3b 100644 --- a/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterPoker.java +++ b/src/main/java/com/cburch/logisim/std/memory/ShiftRegisterPoker.java @@ -3,6 +3,7 @@ package com.cburch.logisim.std.memory; +import com.adlerd.logger.Logger; import com.cburch.logisim.data.BitWidth; import com.cburch.logisim.data.Bounds; import com.cburch.logisim.data.Value; @@ -17,37 +18,37 @@ public class ShiftRegisterPoker extends InstancePoker { - private int loc; + private int location; @Override public boolean init(InstanceState state, MouseEvent e) { - loc = computeStage(state, e); - return loc >= 0; + location = computeStage(state, e); + return location >= 0; } private int computeStage(InstanceState state, MouseEvent e) { - Integer lenObj = state.getAttributeValue(ShiftRegister.ATTR_LENGTH); - BitWidth widObj = state.getAttributeValue(StdAttr.WIDTH); - Boolean loadObj = state.getAttributeValue(ShiftRegister.ATTR_LOAD); - Bounds bds = state.getInstance().getBounds(); + Integer lengthObject = state.getAttributeValue(ShiftRegister.ATTR_LENGTH); + BitWidth widthObject = state.getAttributeValue(StdAttr.WIDTH); + Boolean loadObject = state.getAttributeValue(ShiftRegister.ATTR_LOAD); + Bounds bounds = state.getInstance().getBounds(); - int y = bds.getY(); + int y = bounds.getY(); String label = state.getAttributeValue(StdAttr.LABEL); if (label == null || label.equals("")) { - y += bds.getHeight() / 2; + y += bounds.getHeight() / 2; } else { - y += 3 * bds.getHeight() / 4; + y += 3 * bounds.getHeight() / 4; } y = e.getY() - y; if (y <= -6 || y >= 8) { return -1; } - int x = e.getX() - (bds.getX() + 15); - if (!loadObj || widObj.getWidth() > 4) { + int x = e.getX() - (bounds.getX() + 15); + if (!loadObject || widthObject.getWidth() > 4) { return -1; } - if (x < 0 || x >= lenObj * 10) { + if (x < 0 || x >= lengthObject * 10) { return -1; } return x / 10; @@ -55,18 +56,18 @@ private int computeStage(InstanceState state, MouseEvent e) { @Override public void paint(InstancePainter painter) { - int loc = this.loc; - if (loc < 0) { + int location = this.location; + if (location < 0) { return; } - Bounds bds = painter.getInstance().getBounds(); - int x = bds.getX() + 15 + loc * 10; - int y = bds.getY(); + Bounds bounds = painter.getInstance().getBounds(); + int x = bounds.getX() + 15 + location * 10; + int y = bounds.getY(); String label = painter.getAttributeValue(StdAttr.LABEL); if (label == null || label.equals("")) { - y += bds.getHeight() / 2; + y += bounds.getHeight() / 2; } else { - y += 3 * bds.getHeight() / 4; + y += 3 * bounds.getHeight() / 4; } Graphics g = painter.getGraphics(); g.setColor(Color.RED); @@ -75,28 +76,28 @@ public void paint(InstancePainter painter) { @Override public void mousePressed(InstanceState state, MouseEvent e) { - loc = computeStage(state, e); + location = computeStage(state, e); } @Override public void mouseReleased(InstanceState state, MouseEvent e) { - int oldLoc = loc; - if (oldLoc < 0) { + int oldLocation = location; + if (oldLocation < 0) { return; } - BitWidth widObj = state.getAttributeValue(StdAttr.WIDTH); - if (widObj.equals(BitWidth.ONE)) { - int newLoc = computeStage(state, e); - if (oldLoc == newLoc) { + BitWidth widthObject = state.getAttributeValue(StdAttr.WIDTH); + if (widthObject.equals(BitWidth.ONE)) { + int newLocation = computeStage(state, e); + if (oldLocation == newLocation) { ShiftRegisterData data = (ShiftRegisterData) state.getData(); - int i = data.getLength() - 1 - loc; - Value v = data.get(i); - if (v == Value.FALSE) { - v = Value.TRUE; + int i = data.getLength() - 1 - location; + Value value = data.get(i); + if (value == Value.FALSE) { + value = Value.TRUE; } else { - v = Value.FALSE; + value = Value.FALSE; } - data.set(i, v); + data.set(i, value); state.fireInvalidated(); } } @@ -104,38 +105,38 @@ public void mouseReleased(InstanceState state, MouseEvent e) { @Override public void keyTyped(InstanceState state, KeyEvent e) { - int loc = this.loc; - if (loc < 0) { + int location = this.location; + if (location < 0) { return; } char c = e.getKeyChar(); if (c == ' ') { - Integer lenObj = state.getAttributeValue(ShiftRegister.ATTR_LENGTH); - if (loc < lenObj - 1) { - this.loc = loc + 1; + Integer lengthObject = state.getAttributeValue(ShiftRegister.ATTR_LENGTH); + if (location < lengthObject - 1) { + this.location = location + 1; state.fireInvalidated(); } } else if (c == '\u0008') { - if (loc > 0) { - this.loc = loc - 1; + if (location > 0) { + this.location = location - 1; state.fireInvalidated(); } } else { try { - int val = Integer.parseInt("" + e.getKeyChar(), 16); - BitWidth widObj = state.getAttributeValue(StdAttr.WIDTH); - if ((val & ~widObj.getMask()) != 0) { + int value = Integer.parseInt("" + e.getKeyChar(), 16); + BitWidth widthObject = state.getAttributeValue(StdAttr.WIDTH); + if ((value & ~widthObject.getMask()) != 0) { return; } - Value valObj = Value.createKnown(widObj, val); + Value valueObject = Value.createKnown(widthObject, value); ShiftRegisterData data = (ShiftRegisterData) state.getData(); - int i = data.getLength() - 1 - loc; - if (!data.get(i).equals(valObj)) { - data.set(i, valObj); + int index = data.getLength() - 1 - location; + if (!data.get(index).equals(valueObject)) { + data.set(index, valueObject); state.fireInvalidated(); } } catch (NumberFormatException ex) { - return; + Logger.debugln(ex.getMessage()); } } } diff --git a/src/main/java/com/cburch/logisim/std/memory/Strings.java b/src/main/java/com/cburch/logisim/std/memory/Strings.java index 7911742..b41167b 100644 --- a/src/main/java/com/cburch/logisim/std/memory/Strings.java +++ b/src/main/java/com/cburch/logisim/std/memory/Strings.java @@ -9,8 +9,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "std"); + private static final LocaleManager source = new LocaleManager("logisim", "std"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/std/memory/TFlipFlop.java b/src/main/java/com/cburch/logisim/std/memory/TFlipFlop.java index a20f19a..a90116c 100644 --- a/src/main/java/com/cburch/logisim/std/memory/TFlipFlop.java +++ b/src/main/java/com/cburch/logisim/std/memory/TFlipFlop.java @@ -8,8 +8,7 @@ public class TFlipFlop extends AbstractFlipFlop { public TFlipFlop() { - super("T Flip-Flop", "tFlipFlop.gif", - Strings.getter("tFlipFlopComponent"), 1, false); + super("T Flip-Flop", "tFlipFlop.gif", Strings.getter("tFlipFlopComponent"), 1, false); } @Override @@ -18,14 +17,14 @@ protected String getInputName(int index) { } @Override - protected Value computeValue(Value[] inputs, Value curValue) { - if (curValue == Value.UNKNOWN) { - curValue = Value.FALSE; + protected Value computeValue(Value[] inputs, Value currentValue) { + if (currentValue == Value.UNKNOWN) { + currentValue = Value.FALSE; } if (inputs[0] == Value.TRUE) { - return curValue.not(); + return currentValue.not(); } else { - return curValue; + return currentValue; } } } diff --git a/src/main/java/com/cburch/logisim/std/plexers/BitSelector.java b/src/main/java/com/cburch/logisim/std/plexers/BitSelector.java index 2a59855..a9e8fe1 100644 --- a/src/main/java/com/cburch/logisim/std/plexers/BitSelector.java +++ b/src/main/java/com/cburch/logisim/std/plexers/BitSelector.java @@ -26,18 +26,25 @@ public class BitSelector extends InstanceFactory { public static final Attribute GROUP_ATTR - = Attributes.forBitWidth("group", Strings.getter("bitSelectorGroupAttr")); + = Attributes.forBitWidth("group", Strings.getter("bitSelectorGroupAttr")); public BitSelector() { super("BitSelector", Strings.getter("bitSelectorComponent")); - setAttributes(new Attribute[]{ - StdAttr.FACING, StdAttr.WIDTH, GROUP_ATTR - }, new Object[]{ - Direction.EAST, BitWidth.create(8), BitWidth.ONE - }); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + StdAttr.WIDTH, + GROUP_ATTR + }, new Object[]{ + Direction.EAST, + BitWidth.create(8), + BitWidth.ONE + } + ); setKeyConfigurator(JoinedConfigurator.create( - new BitWidthConfigurator(GROUP_ATTR, 1, Value.MAX_WIDTH, 0), - new BitWidthConfigurator(StdAttr.WIDTH))); + new BitWidthConfigurator(GROUP_ATTR, 1, Value.MAX_WIDTH, 0), + new BitWidthConfigurator(StdAttr.WIDTH) + )); setIconName("bitSelector.gif"); setFacingAttribute(StdAttr.FACING); @@ -138,7 +145,7 @@ public void propagate(InstanceState state) { @Override public void paintGhost(InstancePainter painter) { Plexers.drawTrapezoid(painter.getGraphics(), painter.getBounds(), - painter.getAttributeValue(StdAttr.FACING), 9); + painter.getAttributeValue(StdAttr.FACING), 9); } @Override @@ -149,9 +156,7 @@ public void paintInstance(InstancePainter painter) { Plexers.drawTrapezoid(g, painter.getBounds(), facing, 9); Bounds bds = painter.getBounds(); g.setColor(Color.BLACK); - GraphicsUtil.drawCenteredText(g, "Sel", - bds.getX() + bds.getWidth() / 2, - bds.getY() + bds.getHeight() / 2); + GraphicsUtil.drawCenteredText(g, "Sel", bds.getX() + bds.getWidth() / 2, bds.getY() + bds.getHeight() / 2); painter.drawPorts(); } } diff --git a/src/main/java/com/cburch/logisim/std/plexers/Decoder.java b/src/main/java/com/cburch/logisim/std/plexers/Decoder.java index 795ae9a..34096fd 100644 --- a/src/main/java/com/cburch/logisim/std/plexers/Decoder.java +++ b/src/main/java/com/cburch/logisim/std/plexers/Decoder.java @@ -26,13 +26,23 @@ public class Decoder extends InstanceFactory { public Decoder() { super("Decoder", Strings.getter("decoderComponent")); - setAttributes(new Attribute[]{ - StdAttr.FACING, Plexers.ATTR_SELECT_LOC, Plexers.ATTR_SELECT, - Plexers.ATTR_TRISTATE, Plexers.ATTR_DISABLED, Plexers.ATTR_ENABLE - }, new Object[]{ - Direction.EAST, Plexers.SELECT_BOTTOM_LEFT, Plexers.DEFAULT_SELECT, - Plexers.DEFAULT_TRISTATE, Plexers.DISABLED_FLOATING, Boolean.TRUE - }); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + Plexers.ATTR_SELECT_LOC, + Plexers.ATTR_SELECT, + Plexers.ATTR_TRISTATE, + Plexers.ATTR_DISABLED, + Plexers.ATTR_ENABLE + }, new Object[]{ + Direction.EAST, + Plexers.SELECT_BOTTOM_LEFT, + Plexers.DEFAULT_SELECT, + Plexers.DEFAULT_TRISTATE, + Plexers.DISABLED_FLOATING, + Boolean.TRUE + } + ); setKeyConfigurator(new BitWidthConfigurator(Plexers.ATTR_SELECT, 1, 5, 0)); setIconName("decoder.gif"); setFacingAttribute(StdAttr.FACING); @@ -84,8 +94,7 @@ protected void configureNewInstance(Instance instance) { @Override protected void instanceAttributeChanged(Instance instance, Attribute attribute) { - if (attribute == StdAttr.FACING || attribute == Plexers.ATTR_SELECT_LOC - || attribute == Plexers.ATTR_SELECT) { + if (attribute == StdAttr.FACING || attribute == Plexers.ATTR_SELECT_LOC || attribute == Plexers.ATTR_SELECT) { instance.recomputeBounds(); updatePorts(instance); } else if (attribute == Plexers.ATTR_SELECT || attribute == Plexers.ATTR_ENABLE) { @@ -97,17 +106,17 @@ protected void instanceAttributeChanged(Instance instance, Attribute attribut private void updatePorts(Instance instance) { Direction facing = instance.getAttributeValue(StdAttr.FACING); - Object selectLoc = instance.getAttributeValue(Plexers.ATTR_SELECT_LOC); + Object selectLocation = instance.getAttributeValue(Plexers.ATTR_SELECT_LOC); BitWidth select = instance.getAttributeValue(Plexers.ATTR_SELECT); boolean enable = instance.getAttributeValue(Plexers.ATTR_ENABLE); int outputs = 1 << select.getWidth(); - Port[] ps = new Port[outputs + (enable ? 2 : 1)]; + Port[] ports = new Port[outputs + (enable ? 2 : 1)]; if (outputs == 2) { Location end0; Location end1; if (facing == Direction.NORTH || facing == Direction.SOUTH) { int y = facing == Direction.NORTH ? -10 : 10; - if (selectLoc == Plexers.SELECT_TOP_RIGHT) { + if (selectLocation == Plexers.SELECT_TOP_RIGHT) { end0 = Location.create(-30, y); end1 = Location.create(-10, y); } else { @@ -116,7 +125,7 @@ private void updatePorts(Instance instance) { } } else { int x = facing == Direction.WEST ? -10 : 10; - if (selectLoc == Plexers.SELECT_TOP_RIGHT) { + if (selectLocation == Plexers.SELECT_TOP_RIGHT) { end0 = Location.create(x, 10); end1 = Location.create(x, 30); } else { @@ -124,8 +133,8 @@ private void updatePorts(Instance instance) { end1 = Location.create(x, -10); } } - ps[0] = new Port(end0.getX(), end0.getY(), Port.OUTPUT, 1); - ps[1] = new Port(end1.getX(), end1.getY(), Port.OUTPUT, 1); + ports[0] = new Port(end0.getX(), end0.getY(), Port.OUTPUT, 1); + ports[1] = new Port(end1.getX(), end1.getY(), Port.OUTPUT, 1); } else { int dx; int ddx; @@ -134,33 +143,33 @@ private void updatePorts(Instance instance) { if (facing == Direction.NORTH || facing == Direction.SOUTH) { dy = facing == Direction.NORTH ? -20 : 20; ddy = 0; - dx = selectLoc == Plexers.SELECT_TOP_RIGHT ? -10 * outputs : 0; + dx = selectLocation == Plexers.SELECT_TOP_RIGHT ? -10 * outputs : 0; ddx = 10; } else { dx = facing == Direction.WEST ? -20 : 20; ddx = 0; - dy = selectLoc == Plexers.SELECT_TOP_RIGHT ? 0 : -10 * outputs; + dy = selectLocation == Plexers.SELECT_TOP_RIGHT ? 0 : -10 * outputs; ddy = 10; } for (int i = 0; i < outputs; i++) { - ps[i] = new Port(dx, dy, Port.OUTPUT, 1); + ports[i] = new Port(dx, dy, Port.OUTPUT, 1); dx += ddx; dy += ddy; } } - Location en = Location.create(0, 0).translate(facing, -10); - ps[outputs] = new Port(0, 0, Port.INPUT, select.getWidth()); + Location location = Location.create(0, 0).translate(facing, -10); + ports[outputs] = new Port(0, 0, Port.INPUT, select.getWidth()); if (enable) { - ps[outputs + 1] = new Port(en.getX(), en.getY(), Port.INPUT, BitWidth.ONE); + ports[outputs + 1] = new Port(location.getX(), location.getY(), Port.INPUT, BitWidth.ONE); } for (int i = 0; i < outputs; i++) { - ps[i].setToolTip(Strings.getter("decoderOutTip", "" + i)); + ports[i].setToolTip(Strings.getter("decoderOutTip", "" + i)); } - ps[outputs].setToolTip(Strings.getter("decoderSelectTip")); + ports[outputs].setToolTip(Strings.getter("decoderSelectTip")); if (enable) { - ps[outputs + 1].setToolTip(Strings.getter("decoderEnableTip")); + ports[outputs + 1].setToolTip(Strings.getter("decoderEnableTip")); } - instance.setPorts(ps); + instance.setPorts(ports); } @Override @@ -183,12 +192,12 @@ public void propagate(InstanceState state) { // determine selected output value int outIndex = -1; // the special output Value out = null; - Value en = enable ? state.getPort(outputs + 1) : Value.TRUE; - if (en == Value.FALSE) { + Value enabled = enable ? state.getPort(outputs + 1) : Value.TRUE; + if (enabled == Value.FALSE) { Object opt = state.getAttributeValue(Plexers.ATTR_DISABLED); Value base = opt == Plexers.DISABLED_ZERO ? Value.FALSE : Value.UNKNOWN; others = Value.repeat(base, data.getWidth()); - } else if (en == Value.ERROR && state.isPortConnected(outputs + 1)) { + } else if (enabled == Value.ERROR && state.isPortConnected(outputs + 1)) { others = Value.createError(data); } else { Value sel = state.getPort(outputs); @@ -213,13 +222,13 @@ public void paintGhost(InstancePainter painter) { Direction facing = painter.getAttributeValue(StdAttr.FACING); BitWidth select = painter.getAttributeValue(Plexers.ATTR_SELECT); Plexers.drawTrapezoid(painter.getGraphics(), painter.getBounds(), - facing.reverse(), select.getWidth() == 1 ? 10 : 20); + facing.reverse(), select.getWidth() == 1 ? 10 : 20); } @Override public void paintInstance(InstancePainter painter) { Graphics g = painter.getGraphics(); - Bounds bds = painter.getBounds(); + Bounds bounds = painter.getBounds(); Direction facing = painter.getAttributeValue(StdAttr.FACING); Object selectLoc = painter.getAttributeValue(Plexers.ATTR_SELECT_LOC); BitWidth select = painter.getAttributeValue(Plexers.ATTR_SELECT); @@ -250,7 +259,7 @@ public void paintInstance(InstancePainter painter) { GraphicsUtil.switchToWidth(g, 1); // draw a circle indicating where the select input is located - Multiplexer.drawSelectCircle(g, bds, painter.getInstance().getPortLocation(outputs)); + Multiplexer.drawSelectCircle(g, bounds, painter.getInstance().getPortLocation(outputs)); // draw "0" int x0; @@ -266,23 +275,22 @@ public void paintInstance(InstancePainter painter) { halign = GraphicsUtil.H_CENTER; } else if (facing == Direction.SOUTH) { x0 = 10; - y0 = bds.getHeight() - 3; + y0 = bounds.getHeight() - 3; halign = GraphicsUtil.H_CENTER; } else { - x0 = bds.getWidth() - 3; + x0 = bounds.getWidth() - 3; y0 = 15; halign = GraphicsUtil.H_RIGHT; } g.setColor(Color.GRAY); - GraphicsUtil.drawText(g, "0", bds.getX() + x0, bds.getY() + y0, - halign, GraphicsUtil.V_BASELINE); + GraphicsUtil.drawText(g, "0", bounds.getX() + x0, bounds.getY() + y0, halign, GraphicsUtil.V_BASELINE); // draw trapezoid, "Decd", and ports g.setColor(Color.BLACK); - Plexers.drawTrapezoid(g, bds, facing.reverse(), outputs == 2 ? 10 : 20); + Plexers.drawTrapezoid(g, bounds, facing.reverse(), outputs == 2 ? 10 : 20); GraphicsUtil.drawCenteredText(g, "Decd", - bds.getX() + bds.getWidth() / 2, - bds.getY() + bds.getHeight() / 2); + bounds.getX() + bounds.getWidth() / 2, + bounds.getY() + bounds.getHeight() / 2); painter.drawPorts(); } } diff --git a/src/main/java/com/cburch/logisim/std/plexers/Demultiplexer.java b/src/main/java/com/cburch/logisim/std/plexers/Demultiplexer.java index 19aa1c0..e8b2051 100644 --- a/src/main/java/com/cburch/logisim/std/plexers/Demultiplexer.java +++ b/src/main/java/com/cburch/logisim/std/plexers/Demultiplexer.java @@ -27,16 +27,29 @@ public class Demultiplexer extends InstanceFactory { public Demultiplexer() { super("Demultiplexer", Strings.getter("demultiplexerComponent")); - setAttributes(new Attribute[]{ - StdAttr.FACING, Plexers.ATTR_SELECT_LOC, Plexers.ATTR_SELECT, StdAttr.WIDTH, - Plexers.ATTR_TRISTATE, Plexers.ATTR_DISABLED, Plexers.ATTR_ENABLE - }, new Object[]{ - Direction.EAST, Plexers.SELECT_BOTTOM_LEFT, Plexers.DEFAULT_SELECT, BitWidth.ONE, - Plexers.DEFAULT_TRISTATE, Plexers.DISABLED_FLOATING, Boolean.TRUE - }); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + Plexers.ATTR_SELECT_LOC, + Plexers.ATTR_SELECT, + StdAttr.WIDTH, + Plexers.ATTR_TRISTATE, + Plexers.ATTR_DISABLED, + Plexers.ATTR_ENABLE + }, new Object[]{ + Direction.EAST, + Plexers.SELECT_BOTTOM_LEFT, + Plexers.DEFAULT_SELECT, + BitWidth.ONE, + Plexers.DEFAULT_TRISTATE, + Plexers.DISABLED_FLOATING, + Boolean.TRUE + } + ); setKeyConfigurator(JoinedConfigurator.create( - new BitWidthConfigurator(Plexers.ATTR_SELECT, 1, 5, 0), - new BitWidthConfigurator(StdAttr.WIDTH))); + new BitWidthConfigurator(Plexers.ATTR_SELECT, 1, 5, 0), + new BitWidthConfigurator(StdAttr.WIDTH) + )); setFacingAttribute(StdAttr.FACING); setIconName("demultiplexer.gif"); } @@ -56,14 +69,13 @@ public Bounds getOffsetBounds(AttributeSet attributes) { Direction facing = attributes.getValue(StdAttr.FACING); BitWidth select = attributes.getValue(Plexers.ATTR_SELECT); int outputs = 1 << select.getWidth(); - Bounds bds; + Bounds bounds; if (outputs == 2) { - bds = Bounds.create(0, -20, 30, 40); + bounds = Bounds.create(0, -20, 30, 40); } else { - bds = Bounds.create(0, -(outputs / 2) * 10 - 10, - 40, outputs * 10 + 20); + bounds = Bounds.create(0, -(outputs / 2) * 10 - 10, 40, outputs * 10 + 20); } - return bds.rotate(Direction.EAST, facing, 0, 0); + return bounds.rotate(Direction.EAST, facing, 0, 0); } @Override @@ -80,8 +92,7 @@ protected void configureNewInstance(Instance instance) { @Override protected void instanceAttributeChanged(Instance instance, Attribute attribute) { - if (attribute == StdAttr.FACING || attribute == Plexers.ATTR_SELECT_LOC - || attribute == Plexers.ATTR_SELECT) { + if (attribute == StdAttr.FACING || attribute == Plexers.ATTR_SELECT_LOC || attribute == Plexers.ATTR_SELECT) { instance.recomputeBounds(); updatePorts(instance); } else if (attribute == StdAttr.WIDTH || attribute == Plexers.ATTR_ENABLE) { @@ -217,8 +228,7 @@ public void propagate(InstanceState state) { public void paintGhost(InstancePainter painter) { Direction facing = painter.getAttributeValue(StdAttr.FACING); BitWidth select = painter.getAttributeValue(Plexers.ATTR_SELECT); - Plexers.drawTrapezoid(painter.getGraphics(), painter.getBounds(), - facing.reverse(), select.getWidth() == 1 ? 10 : 20); + Plexers.drawTrapezoid(painter.getGraphics(), painter.getBounds(), facing.reverse(), select.getWidth() == 1 ? 10 : 20); } @Override @@ -279,15 +289,14 @@ public void paintInstance(InstancePainter painter) { halign = GraphicsUtil.H_RIGHT; } g.setColor(Color.GRAY); - GraphicsUtil.drawText(g, "0", bds.getX() + x0, bds.getY() + y0, - halign, GraphicsUtil.V_BASELINE); + GraphicsUtil.drawText(g, "0", bds.getX() + x0, bds.getY() + y0, halign, GraphicsUtil.V_BASELINE); // draw trapezoid, "DMX" label, and ports g.setColor(Color.BLACK); Plexers.drawTrapezoid(g, bds, facing.reverse(), select.getWidth() == 1 ? 10 : 20); GraphicsUtil.drawCenteredText(g, "DMX", - bds.getX() + bds.getWidth() / 2, - bds.getY() + bds.getHeight() / 2); + bds.getX() + bds.getWidth() / 2, + bds.getY() + bds.getHeight() / 2); painter.drawPorts(); } } diff --git a/src/main/java/com/cburch/logisim/std/plexers/Multiplexer.java b/src/main/java/com/cburch/logisim/std/plexers/Multiplexer.java index 2898a02..10f8ddb 100644 --- a/src/main/java/com/cburch/logisim/std/plexers/Multiplexer.java +++ b/src/main/java/com/cburch/logisim/std/plexers/Multiplexer.java @@ -27,38 +27,49 @@ public class Multiplexer extends InstanceFactory { public Multiplexer() { super("Multiplexer", Strings.getter("multiplexerComponent")); - setAttributes(new Attribute[]{ - StdAttr.FACING, Plexers.ATTR_SELECT_LOC, Plexers.ATTR_SELECT, StdAttr.WIDTH, - Plexers.ATTR_DISABLED, Plexers.ATTR_ENABLE - }, new Object[]{ - Direction.EAST, Plexers.SELECT_BOTTOM_LEFT, Plexers.DEFAULT_SELECT, BitWidth.ONE, - Plexers.DISABLED_FLOATING, Boolean.TRUE - }); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + Plexers.ATTR_SELECT_LOC, + Plexers.ATTR_SELECT, + StdAttr.WIDTH, + Plexers.ATTR_DISABLED, + Plexers.ATTR_ENABLE + }, new Object[]{ + Direction.EAST, + Plexers.SELECT_BOTTOM_LEFT, + Plexers.DEFAULT_SELECT, + BitWidth.ONE, + Plexers.DISABLED_FLOATING, + Boolean.TRUE + } + ); setKeyConfigurator(JoinedConfigurator.create( - new BitWidthConfigurator(Plexers.ATTR_SELECT, 1, 5, 0), - new BitWidthConfigurator(StdAttr.WIDTH))); + new BitWidthConfigurator(Plexers.ATTR_SELECT, 1, 5, 0), + new BitWidthConfigurator(StdAttr.WIDTH) + )); setIconName("multiplexer.gif"); setFacingAttribute(StdAttr.FACING); } - static void drawSelectCircle(Graphics g, Bounds bds, Location loc) { - int locDelta = Math.max(bds.getHeight(), bds.getWidth()) <= 50 ? 8 : 6; - Location circLoc; - if (bds.getHeight() >= bds.getWidth()) { // vertically oriented - if (loc.getY() < bds.getY() + bds.getHeight() / 2) { // at top - circLoc = loc.translate(0, locDelta); + static void drawSelectCircle(Graphics g, Bounds bounds, Location location) { + int locationDelta = Math.max(bounds.getHeight(), bounds.getWidth()) <= 50 ? 8 : 6; + Location circuitLoc; + if (bounds.getHeight() >= bounds.getWidth()) { // vertically oriented + if (location.getY() < bounds.getY() + bounds.getHeight() / 2) { // at top + circuitLoc = location.translate(0, locationDelta); } else { // at bottom - circLoc = loc.translate(0, -locDelta); + circuitLoc = location.translate(0, -locationDelta); } } else { - if (loc.getX() < bds.getX() + bds.getWidth() / 2) { // at left - circLoc = loc.translate(locDelta, 0); + if (location.getX() < bounds.getX() + bounds.getWidth() / 2) { // at left + circuitLoc = location.translate(locationDelta, 0); } else { // at right - circLoc = loc.translate(-locDelta, 0); + circuitLoc = location.translate(-locationDelta, 0); } } g.setColor(Color.LIGHT_GRAY); - g.fillOval(circLoc.getX() - 3, circLoc.getY() - 3, 6, 6); + g.fillOval(circuitLoc.getX() - 3, circuitLoc.getY() - 3, 6, 6); } @Override @@ -99,8 +110,7 @@ protected void configureNewInstance(Instance instance) { @Override protected void instanceAttributeChanged(Instance instance, Attribute attribute) { - if (attribute == StdAttr.FACING || attribute == Plexers.ATTR_SELECT_LOC - || attribute == Plexers.ATTR_SELECT) { + if (attribute == StdAttr.FACING || attribute == Plexers.ATTR_SELECT_LOC || attribute == Plexers.ATTR_SELECT) { instance.recomputeBounds(); updatePorts(instance); } else if (attribute == StdAttr.WIDTH || attribute == Plexers.ATTR_ENABLE) { @@ -119,7 +129,7 @@ private void updatePorts(Instance instance) { int selMult = selectLoc == Plexers.SELECT_BOTTOM_LEFT ? 1 : -1; int inputs = 1 << select.getWidth(); - Port[] ps = new Port[inputs + (enable ? 3 : 2)]; + Port[] ports = new Port[inputs + (enable ? 3 : 2)]; Location sel; if (inputs == 2) { Location end0; @@ -141,8 +151,8 @@ private void updatePorts(Instance instance) { end1 = Location.create(-30, 10); sel = Location.create(-20, selMult * 20); } - ps[0] = new Port(end0.getX(), end0.getY(), Port.INPUT, data.getWidth()); - ps[1] = new Port(end1.getX(), end1.getY(), Port.INPUT, data.getWidth()); + ports[0] = new Port(end0.getX(), end0.getY(), Port.INPUT, data.getWidth()); + ports[1] = new Port(end1.getX(), end1.getY(), Port.INPUT, data.getWidth()); } else { int dx = -(inputs / 2) * 10; int ddx = 10; @@ -166,28 +176,28 @@ private void updatePorts(Instance instance) { sel = Location.create(-20, selMult * (dy + 10 * inputs)); } for (int i = 0; i < inputs; i++) { - ps[i] = new Port(dx, dy, Port.INPUT, data.getWidth()); + ports[i] = new Port(dx, dy, Port.INPUT, data.getWidth()); dx += ddx; dy += ddy; } } Location en = sel.translate(dir, 10); - ps[inputs] = new Port(sel.getX(), sel.getY(), Port.INPUT, select.getWidth()); + ports[inputs] = new Port(sel.getX(), sel.getY(), Port.INPUT, select.getWidth()); if (enable) { - ps[inputs + 1] = new Port(en.getX(), en.getY(), Port.INPUT, BitWidth.ONE); + ports[inputs + 1] = new Port(en.getX(), en.getY(), Port.INPUT, BitWidth.ONE); } - ps[ps.length - 1] = new Port(0, 0, Port.OUTPUT, data.getWidth()); + ports[ports.length - 1] = new Port(0, 0, Port.OUTPUT, data.getWidth()); for (int i = 0; i < inputs; i++) { - ps[i].setToolTip(Strings.getter("multiplexerInTip", "" + i)); + ports[i].setToolTip(Strings.getter("multiplexerInTip", "" + i)); } - ps[inputs].setToolTip(Strings.getter("multiplexerSelectTip")); + ports[inputs].setToolTip(Strings.getter("multiplexerSelectTip")); if (enable) { - ps[inputs + 1].setToolTip(Strings.getter("multiplexerEnableTip")); + ports[inputs + 1].setToolTip(Strings.getter("multiplexerEnableTip")); } - ps[ps.length - 1].setToolTip(Strings.getter("multiplexerOutTip")); + ports[ports.length - 1].setToolTip(Strings.getter("multiplexerOutTip")); - instance.setPorts(ps); + instance.setPorts(ports); } @Override @@ -196,13 +206,13 @@ public void propagate(InstanceState state) { BitWidth select = state.getAttributeValue(Plexers.ATTR_SELECT); boolean enable = state.getAttributeValue(Plexers.ATTR_ENABLE); int inputs = 1 << select.getWidth(); - Value en = enable ? state.getPort(inputs + 1) : Value.TRUE; + Value enabled = enable ? state.getPort(inputs + 1) : Value.TRUE; Value out; - if (en == Value.FALSE) { + if (enabled == Value.FALSE) { Object opt = state.getAttributeValue(Plexers.ATTR_DISABLED); Value base = opt == Plexers.DISABLED_ZERO ? Value.FALSE : Value.UNKNOWN; out = Value.repeat(base, data.getWidth()); - } else if (en == Value.ERROR && state.isPortConnected(inputs + 1)) { + } else if (enabled == Value.ERROR && state.isPortConnected(inputs + 1)) { out = Value.createError(data); } else { Value sel = state.getPort(inputs); @@ -221,14 +231,13 @@ public void propagate(InstanceState state) { public void paintGhost(InstancePainter painter) { Direction facing = painter.getAttributeValue(StdAttr.FACING); BitWidth select = painter.getAttributeValue(Plexers.ATTR_SELECT); - Plexers.drawTrapezoid(painter.getGraphics(), painter.getBounds(), - facing, select.getWidth() == 1 ? 10 : 20); + Plexers.drawTrapezoid(painter.getGraphics(), painter.getBounds(), facing, select.getWidth() == 1 ? 10 : 20); } @Override public void paintInstance(InstancePainter painter) { Graphics g = painter.getGraphics(); - Bounds bds = painter.getBounds(); + Bounds bounds = painter.getBounds(); Direction facing = painter.getAttributeValue(StdAttr.FACING); BitWidth select = painter.getAttributeValue(Plexers.ATTR_SELECT); boolean enable = painter.getAttributeValue(Plexers.ATTR_ENABLE); @@ -246,53 +255,52 @@ public void paintInstance(InstancePainter painter) { if (painter.getShowState()) { g.setColor(painter.getPort(inputs).getColor()); } - g.drawLine(pt.getX() - 2 * dx, pt.getY() - 2 * dy, - pt.getX(), pt.getY()); + g.drawLine(pt.getX() - 2 * dx, pt.getY() - 2 * dy, pt.getX(), pt.getY()); } if (enable) { - Location en = painter.getInstance().getPortLocation(inputs + 1); + Location portLocation = painter.getInstance().getPortLocation(inputs + 1); if (painter.getShowState()) { g.setColor(painter.getPort(inputs + 1).getColor()); } int len = inputs == 2 ? 6 : 4; - g.drawLine(en.getX() - len * dx, en.getY() - len * dy, - en.getX(), en.getY()); + g.drawLine(portLocation.getX() - len * dx, portLocation.getY() - len * dy, portLocation.getX(), + portLocation.getY()); } GraphicsUtil.switchToWidth(g, 1); // draw a circle indicating where the select input is located - Multiplexer.drawSelectCircle(g, bds, painter.getInstance().getPortLocation(inputs)); + Multiplexer.drawSelectCircle(g, bounds, painter.getInstance().getPortLocation(inputs)); // draw a 0 indicating where the numbering starts for inputs int x0; int y0; - int halign; + int hAlign; if (facing == Direction.WEST) { - x0 = bds.getX() + bds.getWidth() - 3; - y0 = bds.getY() + 15; - halign = GraphicsUtil.H_RIGHT; + x0 = bounds.getX() + bounds.getWidth() - 3; + y0 = bounds.getY() + 15; + hAlign = GraphicsUtil.H_RIGHT; } else if (facing == Direction.NORTH) { - x0 = bds.getX() + 10; - y0 = bds.getY() + bds.getHeight() - 2; - halign = GraphicsUtil.H_CENTER; + x0 = bounds.getX() + 10; + y0 = bounds.getY() + bounds.getHeight() - 2; + hAlign = GraphicsUtil.H_CENTER; } else if (facing == Direction.SOUTH) { - x0 = bds.getX() + 10; - y0 = bds.getY() + 12; - halign = GraphicsUtil.H_CENTER; + x0 = bounds.getX() + 10; + y0 = bounds.getY() + 12; + hAlign = GraphicsUtil.H_CENTER; } else { - x0 = bds.getX() + 3; - y0 = bds.getY() + 15; - halign = GraphicsUtil.H_LEFT; + x0 = bounds.getX() + 3; + y0 = bounds.getY() + 15; + hAlign = GraphicsUtil.H_LEFT; } g.setColor(Color.GRAY); - GraphicsUtil.drawText(g, "0", x0, y0, halign, GraphicsUtil.V_BASELINE); + GraphicsUtil.drawText(g, "0", x0, y0, hAlign, GraphicsUtil.V_BASELINE); // draw the trapezoid, "MUX" string, the individual ports g.setColor(Color.BLACK); - Plexers.drawTrapezoid(g, bds, facing, select.getWidth() == 1 ? 10 : 20); + Plexers.drawTrapezoid(g, bounds, facing, select.getWidth() == 1 ? 10 : 20); GraphicsUtil.drawCenteredText(g, "MUX", - bds.getX() + bds.getWidth() / 2, - bds.getY() + bds.getHeight() / 2); + bounds.getX() + bounds.getWidth() / 2, + bounds.getY() + bounds.getHeight() / 2); painter.drawPorts(); } } diff --git a/src/main/java/com/cburch/logisim/std/plexers/Plexers.java b/src/main/java/com/cburch/logisim/std/plexers/Plexers.java index c1ef179..4dc6c34 100644 --- a/src/main/java/com/cburch/logisim/std/plexers/Plexers.java +++ b/src/main/java/com/cburch/logisim/std/plexers/Plexers.java @@ -20,42 +20,42 @@ public class Plexers extends Library { public static final Attribute ATTR_SELECT - = Attributes.forBitWidth("select", Strings.getter("plexerSelectBitsAttr"), 1, 5); + = Attributes.forBitWidth("select", Strings.getter("plexerSelectBitsAttr"), 1, 5); public static final Object DEFAULT_SELECT = BitWidth.create(1); public static final Attribute ATTR_TRISTATE - = Attributes.forBoolean("tristate", Strings.getter("plexerThreeStateAttr")); + = Attributes.forBoolean("tristate", Strings.getter("plexerThreeStateAttr")); public static final Object DEFAULT_TRISTATE = Boolean.FALSE; public static final AttributeOption DISABLED_FLOATING - = new AttributeOption("Z", Strings.getter("plexerDisabledFloating")); + = new AttributeOption("Z", Strings.getter("plexerDisabledFloating")); public static final AttributeOption DISABLED_ZERO - = new AttributeOption("0", Strings.getter("plexerDisabledZero")); + = new AttributeOption("0", Strings.getter("plexerDisabledZero")); public static final Attribute ATTR_DISABLED - = Attributes.forOption("disabled", Strings.getter("plexerDisabledAttr"), - new AttributeOption[]{DISABLED_FLOATING, DISABLED_ZERO}); + = Attributes.forOption("disabled", Strings.getter("plexerDisabledAttr"), + new AttributeOption[]{DISABLED_FLOATING, DISABLED_ZERO}); public static final Attribute ATTR_ENABLE - = Attributes.forBoolean("enable", Strings.getter("plexerEnableAttr")); + = Attributes.forBoolean("enable", Strings.getter("plexerEnableAttr")); protected static final int DELAY = 3; static final AttributeOption SELECT_BOTTOM_LEFT - = new AttributeOption("bl", Strings.getter("plexerSelectBottomLeftOption")); + = new AttributeOption("bl", Strings.getter("plexerSelectBottomLeftOption")); static final AttributeOption SELECT_TOP_RIGHT - = new AttributeOption("tr", Strings.getter("plexerSelectTopRightOption")); + = new AttributeOption("tr", Strings.getter("plexerSelectTopRightOption")); static final Attribute ATTR_SELECT_LOC = Attributes.forOption("selloc", - Strings.getter("plexerSelectLocAttr"), - new AttributeOption[]{SELECT_BOTTOM_LEFT, SELECT_TOP_RIGHT}); - private static FactoryDescription[] DESCRIPTIONS = { - new FactoryDescription("Multiplexer", Strings.getter("multiplexerComponent"), - "multiplexer.gif", "Multiplexer"), - new FactoryDescription("Demultiplexer", Strings.getter("demultiplexerComponent"), - "demultiplexer.gif", "Demultiplexer"), - new FactoryDescription("Decoder", Strings.getter("decoderComponent"), - "decoder.gif", "Decoder"), - new FactoryDescription("Priority Encoder", Strings.getter("priorityEncoderComponent"), - "priencod.gif", "PriorityEncoder"), - new FactoryDescription("BitSelector", Strings.getter("bitSelectorComponent"), - "bitSelector.gif", "BitSelector"), + Strings.getter("plexerSelectLocAttr"), + new AttributeOption[]{SELECT_BOTTOM_LEFT, SELECT_TOP_RIGHT}); + private static final FactoryDescription[] DESCRIPTIONS = { + new FactoryDescription("Multiplexer", Strings.getter("multiplexerComponent"), + "multiplexer.gif", "Multiplexer"), + new FactoryDescription("Demultiplexer", Strings.getter("demultiplexerComponent"), + "demultiplexer.gif", "Demultiplexer"), + new FactoryDescription("Decoder", Strings.getter("decoderComponent"), + "decoder.gif", "Decoder"), + new FactoryDescription("Priority Encoder", Strings.getter("priorityEncoderComponent"), + "priencod.gif", "PriorityEncoder"), + new FactoryDescription("BitSelector", Strings.getter("bitSelectorComponent"), + "bitSelector.gif", "BitSelector"), }; private List tools = null; @@ -64,7 +64,7 @@ public Plexers() { } static void drawTrapezoid(Graphics g, Bounds bds, Direction facing, - int facingLean) { + int facingLean) { int wid = bds.getWidth(); int ht = bds.getHeight(); int x0 = bds.getX(); diff --git a/src/main/java/com/cburch/logisim/std/plexers/PriorityEncoder.java b/src/main/java/com/cburch/logisim/std/plexers/PriorityEncoder.java index 7dfdaa2..f71a4a8 100644 --- a/src/main/java/com/cburch/logisim/std/plexers/PriorityEncoder.java +++ b/src/main/java/com/cburch/logisim/std/plexers/PriorityEncoder.java @@ -29,11 +29,17 @@ public class PriorityEncoder extends InstanceFactory { public PriorityEncoder() { super("Priority Encoder", Strings.getter("priorityEncoderComponent")); - setAttributes(new Attribute[]{ - StdAttr.FACING, Plexers.ATTR_SELECT, Plexers.ATTR_DISABLED - }, new Object[]{ - Direction.EAST, BitWidth.create(3), Plexers.DISABLED_FLOATING - }); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + Plexers.ATTR_SELECT, + Plexers.ATTR_DISABLED + }, new Object[]{ + Direction.EAST, + BitWidth.create(3), + Plexers.DISABLED_FLOATING + } + ); setKeyConfigurator(new BitWidthConfigurator(Plexers.ATTR_SELECT, 1, 5, 0)); setIconName("priencod.gif"); setFacingAttribute(StdAttr.FACING); @@ -41,16 +47,16 @@ public PriorityEncoder() { @Override public Bounds getOffsetBounds(AttributeSet attributes) { - Direction dir = attributes.getValue(StdAttr.FACING); + Direction direction = attributes.getValue(StdAttr.FACING); BitWidth select = attributes.getValue(Plexers.ATTR_SELECT); int inputs = 1 << select.getWidth(); int offs = -5 * inputs; int len = 10 * inputs + 10; - if (dir == Direction.NORTH) { + if (direction == Direction.NORTH) { return Bounds.create(offs, 0, len, 40); - } else if (dir == Direction.SOUTH) { + } else if (direction == Direction.SOUTH) { return Bounds.create(offs, -40, len, 40); - } else if (dir == Direction.WEST) { + } else if (direction == Direction.WEST) { return Bounds.create(0, offs, 40, len); } else { // dir == Direction.EAST return Bounds.create(-40, offs, 40, len); @@ -76,54 +82,54 @@ protected void instanceAttributeChanged(Instance instance, Attribute attribut } private void updatePorts(Instance instance) { - Object dir = instance.getAttributeValue(StdAttr.FACING); + Object direction = instance.getAttributeValue(StdAttr.FACING); BitWidth select = instance.getAttributeValue(Plexers.ATTR_SELECT); int n = 1 << select.getWidth(); - Port[] ps = new Port[n + 4]; - if (dir == Direction.NORTH || dir == Direction.SOUTH) { + Port[] ports = new Port[n + 4]; + if (direction == Direction.NORTH || direction == Direction.SOUTH) { int x = -5 * n + 10; - int y = dir == Direction.NORTH ? 40 : -40; + int y = direction == Direction.NORTH ? 40 : -40; for (int i = 0; i < n; i++) { - ps[i] = new Port(x + 10 * i, y, Port.INPUT, 1); + ports[i] = new Port(x + 10 * i, y, Port.INPUT, 1); } - ps[n + OUT] = new Port(0, 0, Port.OUTPUT, select.getWidth()); - ps[n + EN_IN] = new Port(x + 10 * n, y / 2, Port.INPUT, 1); - ps[n + EN_OUT] = new Port(x - 10, y / 2, Port.OUTPUT, 1); - ps[n + GS] = new Port(10, 0, Port.OUTPUT, 1); + ports[n + OUT] = new Port(0, 0, Port.OUTPUT, select.getWidth()); + ports[n + EN_IN] = new Port(x + 10 * n, y / 2, Port.INPUT, 1); + ports[n + EN_OUT] = new Port(x - 10, y / 2, Port.OUTPUT, 1); + ports[n + GS] = new Port(10, 0, Port.OUTPUT, 1); } else { - int x = dir == Direction.EAST ? -40 : 40; + int x = direction == Direction.EAST ? -40 : 40; int y = -5 * n + 10; for (int i = 0; i < n; i++) { - ps[i] = new Port(x, y + 10 * i, Port.INPUT, 1); + ports[i] = new Port(x, y + 10 * i, Port.INPUT, 1); } - ps[n + OUT] = new Port(0, 0, Port.OUTPUT, select.getWidth()); - ps[n + EN_IN] = new Port(x / 2, y + 10 * n, Port.INPUT, 1); - ps[n + EN_OUT] = new Port(x / 2, y - 10, Port.OUTPUT, 1); - ps[n + GS] = new Port(0, 10, Port.OUTPUT, 1); + ports[n + OUT] = new Port(0, 0, Port.OUTPUT, select.getWidth()); + ports[n + EN_IN] = new Port(x / 2, y + 10 * n, Port.INPUT, 1); + ports[n + EN_OUT] = new Port(x / 2, y - 10, Port.OUTPUT, 1); + ports[n + GS] = new Port(0, 10, Port.OUTPUT, 1); } for (int i = 0; i < n; i++) { - ps[i].setToolTip(Strings.getter("priorityEncoderInTip", "" + i)); + ports[i].setToolTip(Strings.getter("priorityEncoderInTip", "" + i)); } - ps[n + OUT].setToolTip(Strings.getter("priorityEncoderOutTip")); - ps[n + EN_IN].setToolTip(Strings.getter("priorityEncoderEnableInTip")); - ps[n + EN_OUT].setToolTip(Strings.getter("priorityEncoderEnableOutTip")); - ps[n + GS].setToolTip(Strings.getter("priorityEncoderGroupSignalTip")); + ports[n + OUT].setToolTip(Strings.getter("priorityEncoderOutTip")); + ports[n + EN_IN].setToolTip(Strings.getter("priorityEncoderEnableInTip")); + ports[n + EN_OUT].setToolTip(Strings.getter("priorityEncoderEnableOutTip")); + ports[n + GS].setToolTip(Strings.getter("priorityEncoderGroupSignalTip")); - instance.setPorts(ps); + instance.setPorts(ports); } @Override public void propagate(InstanceState state) { BitWidth select = state.getAttributeValue(Plexers.ATTR_SELECT); - int n = 1 << select.getWidth(); - boolean enabled = state.getPort(n + EN_IN) != Value.FALSE; + int index = 1 << select.getWidth(); + boolean enabled = state.getPort(index + EN_IN) != Value.FALSE; int out = -1; Value outDefault; if (enabled) { outDefault = Value.createUnknown(select); - for (int i = n - 1; i >= 0; i--) { + for (int i = index - 1; i >= 0; i--) { if (state.getPort(i) == Value.TRUE) { out = i; break; @@ -135,13 +141,13 @@ public void propagate(InstanceState state) { outDefault = Value.repeat(base, select.getWidth()); } if (out < 0) { - state.setPort(n + OUT, outDefault, Plexers.DELAY); - state.setPort(n + EN_OUT, enabled ? Value.TRUE : Value.FALSE, Plexers.DELAY); - state.setPort(n + GS, Value.FALSE, Plexers.DELAY); + state.setPort(index + OUT, outDefault, Plexers.DELAY); + state.setPort(index + EN_OUT, enabled ? Value.TRUE : Value.FALSE, Plexers.DELAY); + state.setPort(index + GS, Value.FALSE, Plexers.DELAY); } else { - state.setPort(n + OUT, Value.createKnown(select, out), Plexers.DELAY); - state.setPort(n + EN_OUT, Value.FALSE, Plexers.DELAY); - state.setPort(n + GS, Value.TRUE, Plexers.DELAY); + state.setPort(index + OUT, Value.createKnown(select, out), Plexers.DELAY); + state.setPort(index + EN_OUT, Value.FALSE, Plexers.DELAY); + state.setPort(index + GS, Value.TRUE, Plexers.DELAY); } } @@ -155,29 +161,29 @@ public void paintInstance(InstancePainter painter) { g.setColor(Color.GRAY); int x0; int y0; - int halign; + int hAlign; if (facing == Direction.WEST) { x0 = bds.getX() + bds.getWidth() - 3; y0 = bds.getY() + 15; - halign = GraphicsUtil.H_RIGHT; + hAlign = GraphicsUtil.H_RIGHT; } else if (facing == Direction.NORTH) { x0 = bds.getX() + 10; y0 = bds.getY() + bds.getHeight() - 2; - halign = GraphicsUtil.H_CENTER; + hAlign = GraphicsUtil.H_CENTER; } else if (facing == Direction.SOUTH) { x0 = bds.getX() + 10; y0 = bds.getY() + 12; - halign = GraphicsUtil.H_CENTER; + hAlign = GraphicsUtil.H_CENTER; } else { x0 = bds.getX() + 3; y0 = bds.getY() + 15; - halign = GraphicsUtil.H_LEFT; + hAlign = GraphicsUtil.H_LEFT; } - GraphicsUtil.drawText(g, "0", x0, y0, halign, GraphicsUtil.V_BASELINE); + GraphicsUtil.drawText(g, "0", x0, y0, hAlign, GraphicsUtil.V_BASELINE); g.setColor(Color.BLACK); GraphicsUtil.drawCenteredText(g, "Pri", - bds.getX() + bds.getWidth() / 2, - bds.getY() + bds.getHeight() / 2); + bds.getX() + bds.getWidth() / 2, + bds.getY() + bds.getHeight() / 2); painter.drawPorts(); } } diff --git a/src/main/java/com/cburch/logisim/std/plexers/Strings.java b/src/main/java/com/cburch/logisim/std/plexers/Strings.java index e6dc31d..ddc611b 100644 --- a/src/main/java/com/cburch/logisim/std/plexers/Strings.java +++ b/src/main/java/com/cburch/logisim/std/plexers/Strings.java @@ -9,8 +9,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "std"); + private static final LocaleManager source = new LocaleManager("logisim", "std"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/std/wiring/BitExtender.java b/src/main/java/com/cburch/logisim/std/wiring/BitExtender.java index d20e893..7826cc2 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/BitExtender.java +++ b/src/main/java/com/cburch/logisim/std/wiring/BitExtender.java @@ -27,25 +27,34 @@ public class BitExtender extends InstanceFactory { public static final BitExtender FACTORY = new BitExtender(); private static final Attribute ATTR_IN_WIDTH = Attributes - .forBitWidth("in_width", Strings.getter("extenderInAttr")); + .forBitWidth("in_width", Strings.getter("extenderInAttr")); private static final Attribute ATTR_OUT_WIDTH = Attributes - .forBitWidth("out_width", Strings.getter("extenderOutAttr")); + .forBitWidth("out_width", Strings.getter("extenderOutAttr")); private static final Attribute ATTR_TYPE = Attributes.forOption("type", Strings.getter("extenderTypeAttr"), - new AttributeOption[]{ - new AttributeOption("zero", "zero", Strings.getter("extenderZeroType")), - new AttributeOption("one", "one", Strings.getter("extenderOneType")), - new AttributeOption("sign", "sign", Strings.getter("extenderSignType")), - new AttributeOption("input", "input", Strings.getter("extenderInputType")), - }); + new AttributeOption[]{ + new AttributeOption("zero", "zero", Strings.getter("extenderZeroType")), + new AttributeOption("one", "one", Strings.getter("extenderOneType")), + new AttributeOption("sign", "sign", Strings.getter("extenderSignType")), + new AttributeOption("input", "input", Strings.getter("extenderInputType")), + }); public BitExtender() { super("Bit Extender", Strings.getter("extenderComponent")); setIconName("extender.gif"); - setAttributes(new Attribute[]{ATTR_IN_WIDTH, ATTR_OUT_WIDTH, ATTR_TYPE}, - new Object[]{BitWidth.create(8), BitWidth.create(16), ATTR_TYPE.parse("zero")}); + setAttributes( + new Attribute[]{ + ATTR_IN_WIDTH, + ATTR_OUT_WIDTH, + ATTR_TYPE + }, new Object[]{ + BitWidth.create(8), + BitWidth.create(16), + ATTR_TYPE.parse("zero") + } + ); setFacingAttribute(StdAttr.FACING); setKeyConfigurator(JoinedConfigurator.create(new BitWidthConfigurator(ATTR_OUT_WIDTH), - new BitWidthConfigurator(ATTR_IN_WIDTH, 1, Value.MAX_WIDTH, 0))); + new BitWidthConfigurator(ATTR_IN_WIDTH, 1, Value.MAX_WIDTH, 0))); setOffsetBounds(Bounds.create(-40, -20, 40, 40)); } @@ -81,14 +90,12 @@ public void paintInstance(InstancePainter painter) { break; } String mainLabel = Strings.get("extenderMainLabel"); - Bounds bds = painter.getBounds(); - int x = bds.getX() + bds.getWidth() / 2; - int y0 = bds.getY() + (bds.getHeight() / 2 + ascent) / 2; - int y1 = bds.getY() + (3 * bds.getHeight() / 2 + ascent) / 2; - GraphicsUtil.drawText(graphics, label, x, y0, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); - GraphicsUtil.drawText(graphics, mainLabel, x, y1, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + Bounds bounds = painter.getBounds(); + int x = bounds.getX() + bounds.getWidth() / 2; + int y0 = bounds.getY() + (bounds.getHeight() / 2 + ascent) / 2; + int y1 = bounds.getY() + (3 * bounds.getHeight() / 2 + ascent) / 2; + GraphicsUtil.drawText(graphics, label, x, y0, GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + GraphicsUtil.drawText(graphics, mainLabel, x, y1, GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); BitWidth w0 = painter.getAttributeValue(ATTR_OUT_WIDTH); BitWidth w1 = painter.getAttributeValue(ATTR_IN_WIDTH); @@ -112,20 +119,18 @@ protected void configureNewInstance(Instance instance) { protected void instanceAttributeChanged(Instance instance, Attribute attribute) { if (attribute == ATTR_TYPE) { configurePorts(instance); - instance.fireInvalidated(); - } else { - instance.fireInvalidated(); } + instance.fireInvalidated(); } private void configurePorts(Instance instance) { - Port p0 = new Port(0, 0, Port.OUTPUT, ATTR_OUT_WIDTH); - Port p1 = new Port(-40, 0, Port.INPUT, ATTR_IN_WIDTH); + Port port0 = new Port(0, 0, Port.OUTPUT, ATTR_OUT_WIDTH); + Port port1 = new Port(-40, 0, Port.INPUT, ATTR_IN_WIDTH); String type = getType(instance.getAttributeSet()); if (type.equals("input")) { - instance.setPorts(new Port[]{p0, p1, new Port(-20, -20, Port.INPUT, 1)}); + instance.setPorts(new Port[]{port0, port1, new Port(-20, -20, Port.INPUT, 1)}); } else { - instance.setPorts(new Port[]{p0, p1}); + instance.setPorts(new Port[]{port0, port1}); } } @@ -135,18 +140,27 @@ public void propagate(InstanceState state) { BitWidth wout = state.getAttributeValue(ATTR_OUT_WIDTH); String type = getType(state.getAttributeSet()); Value extend; - if (type.equals("one")) { - extend = Value.TRUE; - } else if (type.equals("sign")) { - int win = in.getWidth(); - extend = win > 0 ? in.get(win - 1) : Value.ERROR; - } else if (type.equals("input")) { - extend = state.getPort(2); - if (extend.getWidth() != 1) { - extend = Value.ERROR; + switch (type) { + case "one": { + extend = Value.TRUE; + break; + } + case "sign": { + int win = in.getWidth(); + extend = win > 0 ? in.get(win - 1) : Value.ERROR; + break; + } + case "input": { + extend = state.getPort(2); + if (extend.getWidth() != 1) { + extend = Value.ERROR; + } + break; + } + default: { + extend = Value.FALSE; + break; } - } else { - extend = Value.FALSE; } Value out = in.extendWidth(wout.getWidth(), extend); @@ -158,4 +172,4 @@ private String getType(AttributeSet attrs) { AttributeOption topt = attrs.getValue(ATTR_TYPE); return (String) topt.getValue(); } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/wiring/Clock.java b/src/main/java/com/cburch/logisim/std/wiring/Clock.java index 8873b30..83780ac 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/Clock.java +++ b/src/main/java/com/cburch/logisim/std/wiring/Clock.java @@ -31,26 +31,31 @@ public class Clock extends InstanceFactory { public static final Attribute ATTR_HIGH - = new DurationAttribute("highDuration", Strings.getter("clockHighAttr"), - 1, Integer.MAX_VALUE); - + = new DurationAttribute("highDuration", Strings.getter("clockHighAttr"), 1, Integer.MAX_VALUE); public static final Attribute ATTR_LOW - = new DurationAttribute("lowDuration", Strings.getter("clockLowAttr"), - 1, Integer.MAX_VALUE); - + = new DurationAttribute("lowDuration", Strings.getter("clockLowAttr"), 1, Integer.MAX_VALUE); public static final Clock FACTORY = new Clock(); - private static final Icon toolIcon = Icons.getIcon("clock.gif"); public Clock() { super("Clock", Strings.getter("clockComponent")); - setAttributes(new Attribute[]{ - StdAttr.FACING, ATTR_HIGH, ATTR_LOW, - StdAttr.LABEL, Pin.ATTR_LABEL_LOC, StdAttr.LABEL_FONT - }, new Object[]{ - Direction.EAST, 1, 1, - "", Direction.WEST, StdAttr.DEFAULT_LABEL_FONT - }); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + ATTR_HIGH, + ATTR_LOW, + StdAttr.LABEL, + Pin.ATTR_LABEL_LOC, + StdAttr.LABEL_FONT + }, new Object[]{ + Direction.EAST, + 1, + 1, + "", + Direction.WEST, + StdAttr.DEFAULT_LABEL_FONT + } + ); setFacingAttribute(StdAttr.FACING); setInstanceLogger(ClockLogger.class); setInstancePoker(ClockPoker.class); @@ -59,23 +64,23 @@ public Clock() { // // package methods // - public static boolean tick(CircuitState circState, int ticks, Component comp) { - AttributeSet attrs = comp.getAttributeSet(); + public static boolean tick(CircuitState circuitState, int ticks, Component component) { + AttributeSet attrs = component.getAttributeSet(); int durationHigh = attrs.getValue(ATTR_HIGH); int durationLow = attrs.getValue(ATTR_LOW); - ClockState state = (ClockState) circState.getData(comp); + ClockState state = (ClockState) circuitState.getData(component); if (state == null) { state = new ClockState(); - circState.setData(comp, state); + circuitState.setData(component, state); } - boolean curValue = ticks % (durationHigh + durationLow) < durationLow; + boolean currentValue = ticks % (durationHigh + durationLow) < durationLow; if (state.clicks % 2 == 1) { - curValue = !curValue; + currentValue = !currentValue; } - Value desired = (curValue ? Value.FALSE : Value.TRUE); + Value desired = (currentValue ? Value.FALSE : Value.TRUE); if (!state.sending.equals(desired)) { state.sending = desired; - Instance.getInstanceFor(comp).fireInvalidated(); + Instance.getInstanceFor(component).fireInvalidated(); return true; } else { return false; @@ -83,19 +88,19 @@ public static boolean tick(CircuitState circState, int ticks, Component comp) { } private static ClockState getState(InstanceState state) { - ClockState ret = (ClockState) state.getData(); - if (ret == null) { - ret = new ClockState(); - state.setData(ret); + ClockState clockState = (ClockState) state.getData(); + if (clockState == null) { + clockState = new ClockState(); + state.setData(clockState); } - return ret; + return clockState; } @Override public Bounds getOffsetBounds(AttributeSet attributes) { return Probe.getOffsetBounds( - attributes.getValue(StdAttr.FACING), - BitWidth.ONE, RadixOption.RADIX_2); + attributes.getValue(StdAttr.FACING), + BitWidth.ONE, RadixOption.RADIX_2); } // @@ -109,36 +114,37 @@ public void paintIcon(InstancePainter painter) { } else { g.drawRect(4, 4, 13, 13); g.setColor(Value.FALSE.getColor()); - g.drawPolyline(new int[]{6, 6, 10, 10, 14, 14}, - new int[]{10, 6, 6, 14, 14, 10}, 6); + g.drawPolyline(new int[]{6, 6, 10, 10, 14, 14}, new int[]{10, 6, 6, 14, 14, 10}, 6); } - Direction dir = painter.getAttributeValue(StdAttr.FACING); - int pinx = 15; - int piny = 8; - if (dir == Direction.EAST) { // keep defaults - } else if (dir == Direction.WEST) { - pinx = 3; - } else if (dir == Direction.NORTH) { - pinx = 8; - piny = 3; - } else if (dir == Direction.SOUTH) { - pinx = 8; - piny = 15; + Direction direction = painter.getAttributeValue(StdAttr.FACING); + int pinX = 15; + int pinY = 8; + if (direction == Direction.EAST) { + // keep defaults + } else if (direction == Direction.WEST) { + pinX = 3; + } else if (direction == Direction.NORTH) { + pinX = 8; + pinY = 3; + } else if (direction == Direction.SOUTH) { + pinX = 8; + pinY = 15; } g.setColor(Value.TRUE.getColor()); - g.fillOval(pinx, piny, 3, 3); + g.fillOval(pinX, pinY, 3, 3); } @Override public void paintInstance(InstancePainter painter) { java.awt.Graphics g = painter.getGraphics(); - Bounds bds = painter.getInstance().getBounds(); // intentionally with no graphics object - we don't want label included - int x = bds.getX(); - int y = bds.getY(); + Bounds bounds = painter.getInstance() + .getBounds(); // intentionally with no graphics object - we don't want label included + int x = bounds.getX(); + int y = bounds.getY(); GraphicsUtil.switchToWidth(g, 2); g.setColor(Color.BLACK); - g.drawRect(x, y, bds.getWidth(), bds.getHeight()); + g.drawRect(x, y, bounds.getWidth(), bounds.getHeight()); painter.drawLabel(); @@ -199,8 +205,8 @@ public void propagate(InstanceState state) { // private void configureLabel(Instance instance) { Direction facing = instance.getAttributeValue(StdAttr.FACING); - Direction labelLoc = instance.getAttributeValue(Pin.ATTR_LABEL_LOC); - Probe.configureLabel(instance, labelLoc, facing); + Direction labelLocation = instance.getAttributeValue(Pin.ATTR_LABEL_LOC); + Probe.configureLabel(instance, labelLocation, facing); } private static class ClockState implements InstanceData, Cloneable { @@ -253,8 +259,8 @@ public void mouseReleased(InstanceState state, MouseEvent e) { } private boolean isInside(InstanceState state, MouseEvent e) { - Bounds bds = state.getInstance().getBounds(); - return bds.contains(e.getX(), e.getY()); + Bounds bounds = state.getInstance().getBounds(); + return bounds.contains(e.getX(), e.getY()); } } } diff --git a/src/main/java/com/cburch/logisim/std/wiring/Constant.java b/src/main/java/com/cburch/logisim/std/wiring/Constant.java index 47e3f57..378d929 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/Constant.java +++ b/src/main/java/com/cburch/logisim/std/wiring/Constant.java @@ -33,18 +33,15 @@ public class Constant extends InstanceFactory { public static final Attribute ATTRIBUTE_VALUE - = Attributes.forHexInteger("value", Strings.getter("constantValueAttr")); - private static final Color BACKGROUND_COLOR = new Color(230, 230, 230); - private static final List> ATTRIBUTES - = Arrays.asList(StdAttr.FACING, StdAttr.WIDTH, ATTRIBUTE_VALUE); + = Attributes.forHexInteger("value", Strings.getter("constantValueAttr")); public static final InstanceFactory FACTORY = new Constant(); + private static final Color BACKGROUND_COLOR = new Color(230, 230, 230); + private static final List> ATTRIBUTES = Arrays.asList(StdAttr.FACING, StdAttr.WIDTH, ATTRIBUTE_VALUE); public Constant() { super("Constant", Strings.getter("constantComponent")); setFacingAttribute(StdAttr.FACING); - setKeyConfigurator(JoinedConfigurator.create( - new ConstantConfigurator(), - new BitWidthConfigurator(StdAttr.WIDTH))); + setKeyConfigurator(JoinedConfigurator.create(new ConstantConfigurator(), new BitWidthConfigurator(StdAttr.WIDTH))); } @Override @@ -96,120 +93,120 @@ public Bounds getOffsetBounds(AttributeSet attributes) { BitWidth width = attributes.getValue(StdAttr.WIDTH); int chars = (width.getWidth() + 3) / 4; - Bounds ret = null; + Bounds bounds = null; if (facing == Direction.EAST) { switch (chars) { case 1: - ret = Bounds.create(-16, -8, 16, 16); + bounds = Bounds.create(-16, -8, 16, 16); break; case 2: - ret = Bounds.create(-16, -8, 16, 16); + bounds = Bounds.create(-16, -8, 16, 16); break; case 3: - ret = Bounds.create(-26, -8, 26, 16); + bounds = Bounds.create(-26, -8, 26, 16); break; case 4: - ret = Bounds.create(-36, -8, 36, 16); + bounds = Bounds.create(-36, -8, 36, 16); break; case 5: - ret = Bounds.create(-46, -8, 46, 16); + bounds = Bounds.create(-46, -8, 46, 16); break; case 6: - ret = Bounds.create(-56, -8, 56, 16); + bounds = Bounds.create(-56, -8, 56, 16); break; case 7: - ret = Bounds.create(-66, -8, 66, 16); + bounds = Bounds.create(-66, -8, 66, 16); break; case 8: - ret = Bounds.create(-76, -8, 76, 16); + bounds = Bounds.create(-76, -8, 76, 16); break; } } else if (facing == Direction.WEST) { switch (chars) { case 1: - ret = Bounds.create(0, -8, 16, 16); + bounds = Bounds.create(0, -8, 16, 16); break; case 2: - ret = Bounds.create(0, -8, 16, 16); + bounds = Bounds.create(0, -8, 16, 16); break; case 3: - ret = Bounds.create(0, -8, 26, 16); + bounds = Bounds.create(0, -8, 26, 16); break; case 4: - ret = Bounds.create(0, -8, 36, 16); + bounds = Bounds.create(0, -8, 36, 16); break; case 5: - ret = Bounds.create(0, -8, 46, 16); + bounds = Bounds.create(0, -8, 46, 16); break; case 6: - ret = Bounds.create(0, -8, 56, 16); + bounds = Bounds.create(0, -8, 56, 16); break; case 7: - ret = Bounds.create(0, -8, 66, 16); + bounds = Bounds.create(0, -8, 66, 16); break; case 8: - ret = Bounds.create(0, -8, 76, 16); + bounds = Bounds.create(0, -8, 76, 16); break; } } else if (facing == Direction.SOUTH) { switch (chars) { case 1: - ret = Bounds.create(-8, -16, 16, 16); + bounds = Bounds.create(-8, -16, 16, 16); break; case 2: - ret = Bounds.create(-8, -16, 16, 16); + bounds = Bounds.create(-8, -16, 16, 16); break; case 3: - ret = Bounds.create(-13, -16, 26, 16); + bounds = Bounds.create(-13, -16, 26, 16); break; case 4: - ret = Bounds.create(-18, -16, 36, 16); + bounds = Bounds.create(-18, -16, 36, 16); break; case 5: - ret = Bounds.create(-23, -16, 46, 16); + bounds = Bounds.create(-23, -16, 46, 16); break; case 6: - ret = Bounds.create(-28, -16, 56, 16); + bounds = Bounds.create(-28, -16, 56, 16); break; case 7: - ret = Bounds.create(-33, -16, 66, 16); + bounds = Bounds.create(-33, -16, 66, 16); break; case 8: - ret = Bounds.create(-38, -16, 76, 16); + bounds = Bounds.create(-38, -16, 76, 16); break; } } else if (facing == Direction.NORTH) { switch (chars) { case 1: - ret = Bounds.create(-8, 0, 16, 16); + bounds = Bounds.create(-8, 0, 16, 16); break; case 2: - ret = Bounds.create(-8, 0, 16, 16); + bounds = Bounds.create(-8, 0, 16, 16); break; case 3: - ret = Bounds.create(-13, 0, 26, 16); + bounds = Bounds.create(-13, 0, 26, 16); break; case 4: - ret = Bounds.create(-18, 0, 36, 16); + bounds = Bounds.create(-18, 0, 36, 16); break; case 5: - ret = Bounds.create(-23, 0, 46, 16); + bounds = Bounds.create(-23, 0, 46, 16); break; case 6: - ret = Bounds.create(-28, 0, 56, 16); + bounds = Bounds.create(-28, 0, 56, 16); break; case 7: - ret = Bounds.create(-33, 0, 66, 16); + bounds = Bounds.create(-33, 0, 66, 16); break; case 8: - ret = Bounds.create(-38, 0, 76, 16); + bounds = Bounds.create(-38, 0, 76, 16); break; } } - if (ret == null) { + if (bounds == null) { throw new IllegalArgumentException("unrecognized arguments " + facing + " " + width); } - return ret; + return bounds; } // @@ -256,7 +253,7 @@ public void paintGhost(InstancePainter painter) { GraphicsUtil.switchToWidth(graphics, 2); graphics.fillOval(-2, -2, 5, 5); GraphicsUtil.drawCenteredText(graphics, valueStr, bounds.getX() + bounds.getWidth() / 2, - bounds.getY() + bounds.getHeight() / 2); + bounds.getY() + bounds.getHeight() / 2); } @Override @@ -279,13 +276,13 @@ public void paintInstance(InstancePainter painter) { graphics.setColor(value.getColor()); } GraphicsUtil.drawCenteredText(graphics, value.toString(), - x + bounds.getX() + bounds.getWidth() / 2, - y + bounds.getY() + bounds.getHeight() / 2 - 2); + x + bounds.getX() + bounds.getWidth() / 2, + y + bounds.getY() + bounds.getHeight() / 2 - 2); } else { graphics.setColor(Color.BLACK); GraphicsUtil.drawCenteredText(graphics, value.toHexString(), - x + bounds.getX() + bounds.getWidth() / 2, - y + bounds.getY() + bounds.getHeight() / 2 - 2); + x + bounds.getX() + bounds.getWidth() / 2, + y + bounds.getY() + bounds.getHeight() / 2 - 2); } painter.drawPorts(); } @@ -331,7 +328,7 @@ public void setValue(Attribute attribute, V value) { } else if (attribute == StdAttr.WIDTH) { width = (BitWidth) value; this.value = this.value.extendWidth(width.getWidth(), - this.value.get(this.value.getWidth() - 1)); + this.value.get(this.value.getWidth() - 1)); } else if (attribute == ATTRIBUTE_VALUE) { int val = (Integer) value; this.value = Value.createKnown(width, val); @@ -344,7 +341,7 @@ public void setValue(Attribute attribute, V value) { private static class ConstantExpression implements ExpressionComputer { - private Instance instance; + private final Instance instance; private ConstantExpression(Instance instance) { this.instance = instance; @@ -355,7 +352,7 @@ public void computeExpression(Map expressionMap) { int intValue = attrs.getValue(ATTRIBUTE_VALUE); expressionMap.put(instance.getLocation(), - Expressions.constant(intValue)); + Expressions.constant(intValue)); } } diff --git a/src/main/java/com/cburch/logisim/std/wiring/ConstantConfigurator.java b/src/main/java/com/cburch/logisim/std/wiring/ConstantConfigurator.java index 7bc930b..9077ef8 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/ConstantConfigurator.java +++ b/src/main/java/com/cburch/logisim/std/wiring/ConstantConfigurator.java @@ -17,9 +17,9 @@ public ConstantConfigurator() { @Override public int getMaximumValue(AttributeSet attrs) { BitWidth width = attrs.getValue(StdAttr.WIDTH); - int ret = width.getMask(); - if (ret >= 0) { - return ret; + int mask = width.getMask(); + if (mask >= 0) { + return mask; } else { return Integer.MAX_VALUE; } diff --git a/src/main/java/com/cburch/logisim/std/wiring/DurationAttribute.java b/src/main/java/com/cburch/logisim/std/wiring/DurationAttribute.java index dc35e68..9f7fdfe 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/DurationAttribute.java +++ b/src/main/java/com/cburch/logisim/std/wiring/DurationAttribute.java @@ -10,8 +10,8 @@ public class DurationAttribute extends Attribute { - private int min; - private int max; + private final int min; + private final int max; public DurationAttribute(String name, StringGetter disp, int min, int max) { super(name, disp); @@ -22,7 +22,7 @@ public DurationAttribute(String name, StringGetter disp, int min, int max) { @Override public Integer parse(String value) { try { - Integer ret = Integer.valueOf(value); + int ret = Integer.parseInt(value); if (ret < min) { throw new NumberFormatException(StringUtil.format(Strings.get("durationSmallMessage"), "" + min)); } else if (ret > max) { @@ -39,8 +39,7 @@ public String toDisplayString(Integer value) { if (value.equals(1)) { return Strings.get("clockDurationOneValue"); } else { - return StringUtil.format(Strings.get("clockDurationValue"), - value.toString()); + return StringUtil.format(Strings.get("clockDurationValue"), value.toString()); } } diff --git a/src/main/java/com/cburch/logisim/std/wiring/Ground.java b/src/main/java/com/cburch/logisim/std/wiring/Ground.java index 136ef4e..8db84fe 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/Ground.java +++ b/src/main/java/com/cburch/logisim/std/wiring/Ground.java @@ -30,8 +30,15 @@ public class Ground extends InstanceFactory { public Ground() { super("Ground", Strings.getter("groundComponent")); setIconName("ground.gif"); - setAttributes(new Attribute[]{StdAttr.FACING, StdAttr.WIDTH}, - new Object[]{Direction.SOUTH, BitWidth.ONE}); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + StdAttr.WIDTH + }, new Object[]{ + Direction.SOUTH, + BitWidth.ONE + } + ); setFacingAttribute(StdAttr.FACING); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setPorts(new Port[]{new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH)}); @@ -52,7 +59,7 @@ protected void instanceAttributeChanged(Instance instance, Attribute attribut @Override public Bounds getOffsetBounds(AttributeSet attributes) { return Bounds.create(0, -8, 14, 16) - .rotate(Direction.EAST, attributes.getValue(StdAttr.FACING), 0, 0); + .rotate(Direction.EAST, attributes.getValue(StdAttr.FACING), 0, 0); } @Override @@ -74,8 +81,8 @@ public void paintGhost(InstancePainter painter) { private void drawInstance(InstancePainter painter, boolean isGhost) { Graphics2D g = (Graphics2D) painter.getGraphics().create(); - Location loc = painter.getLocation(); - g.translate(loc.getX(), loc.getY()); + Location location = painter.getLocation(); + g.translate(location.getX(), location.getY()); Direction from = painter.getAttributeValue(StdAttr.FACING); int degrees = Direction.EAST.toDegrees() - from.toDegrees(); diff --git a/src/main/java/com/cburch/logisim/std/wiring/Pin.java b/src/main/java/com/cburch/logisim/std/wiring/Pin.java index 70f2757..cc994b8 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/Pin.java +++ b/src/main/java/com/cburch/logisim/std/wiring/Pin.java @@ -42,21 +42,20 @@ public class Pin extends InstanceFactory { public static final Attribute ATTR_TRISTATE - = Attributes.forBoolean("tristate", Strings.getter("pinThreeStateAttr")); + = Attributes.forBoolean("tristate", Strings.getter("pinThreeStateAttr")); public static final Attribute ATTR_TYPE - = Attributes.forBoolean("output", Strings.getter("pinOutputAttr")); + = Attributes.forBoolean("output", Strings.getter("pinOutputAttr")); public static final Attribute ATTR_LABEL_LOC - = Attributes.forDirection("labelloc", Strings.getter("pinLabelLocAttr")); - + = Attributes.forDirection("labelloc", Strings.getter("pinLabelLocAttr")); public static final AttributeOption PULL_NONE - = new AttributeOption("none", Strings.getter("pinPullNoneOption")); + = new AttributeOption("none", Strings.getter("pinPullNoneOption")); public static final AttributeOption PULL_UP - = new AttributeOption("up", Strings.getter("pinPullUpOption")); + = new AttributeOption("up", Strings.getter("pinPullUpOption")); public static final AttributeOption PULL_DOWN - = new AttributeOption("down", Strings.getter("pinPullDownOption")); + = new AttributeOption("down", Strings.getter("pinPullDownOption")); public static final Attribute ATTR_PULL - = Attributes.forOption("pull", Strings.getter("pinPullAttr"), - new AttributeOption[]{PULL_NONE, PULL_UP, PULL_DOWN}); + = Attributes.forOption("pull", Strings.getter("pinPullAttr"), + new AttributeOption[]{PULL_NONE, PULL_UP, PULL_DOWN}); public static final Pin FACTORY = new Pin(); @@ -69,21 +68,21 @@ public Pin() { super("Pin", Strings.getter("pinComponent")); setFacingAttribute(StdAttr.FACING); setKeyConfigurator(JoinedConfigurator.create( - new BitWidthConfigurator(StdAttr.WIDTH), - new DirectionConfigurator(ATTR_LABEL_LOC, KeyEvent.ALT_DOWN_MASK))); + new BitWidthConfigurator(StdAttr.WIDTH), + new DirectionConfigurator(ATTR_LABEL_LOC, KeyEvent.ALT_DOWN_MASK))); setInstanceLogger(PinLogger.class); setInstancePoker(PinPoker.class); } private static Value pull2(Value mod, BitWidth expectedWidth, Value pullTo) { if (mod.getWidth() == expectedWidth.getWidth()) { - Value[] vs = mod.getAll(); - for (int i = 0; i < vs.length; i++) { - if (vs[i] == Value.UNKNOWN) { - vs[i] = pullTo; + Value[] values = mod.getAll(); + for (int i = 0; i < values.length; i++) { + if (values[i] == Value.UNKNOWN) { + values[i] = pullTo; } } - return Value.create(vs); + return Value.create(values); } else { return Value.createKnown(expectedWidth, 0); } @@ -92,25 +91,25 @@ private static Value pull2(Value mod, BitWidth expectedWidth, Value pullTo) { private static PinState getState(InstanceState state) { PinAttributes attrs = (PinAttributes) state.getAttributeSet(); BitWidth width = attrs.width; - PinState ret = (PinState) state.getData(); - if (ret == null) { - Value val = attrs.threeState ? Value.UNKNOWN : Value.FALSE; + PinState pinState = (PinState) state.getData(); + if (pinState == null) { + Value value = attrs.threeState ? Value.UNKNOWN : Value.FALSE; if (width.getWidth() > 1) { Value[] arr = new Value[width.getWidth()]; - java.util.Arrays.fill(arr, val); - val = Value.create(arr); + java.util.Arrays.fill(arr, value); + value = Value.create(arr); } - ret = new PinState(val, val); - state.setData(ret); + pinState = new PinState(value, value); + state.setData(pinState); } - if (ret.intendedValue.getWidth() != width.getWidth()) { - ret.intendedValue = ret.intendedValue.extendWidth(width.getWidth(), - attrs.threeState ? Value.UNKNOWN : Value.FALSE); + if (pinState.intendedValue.getWidth() != width.getWidth()) { + pinState.intendedValue = pinState.intendedValue.extendWidth(width.getWidth(), + attrs.threeState ? Value.UNKNOWN : Value.FALSE); } - if (ret.foundValue.getWidth() != width.getWidth()) { - ret.foundValue = ret.foundValue.extendWidth(width.getWidth(), Value.UNKNOWN); + if (pinState.foundValue.getWidth() != width.getWidth()) { + pinState.foundValue = pinState.foundValue.extendWidth(width.getWidth(), Value.UNKNOWN); } - return ret; + return pinState; } @Override @@ -131,12 +130,12 @@ public Bounds getOffsetBounds(AttributeSet attributes) { @Override public void paintIcon(InstancePainter painter) { paintIconBase(painter); - BitWidth w = painter.getAttributeValue(StdAttr.WIDTH); - if (!w.equals(BitWidth.ONE)) { + BitWidth width = painter.getAttributeValue(StdAttr.WIDTH); + if (!width.equals(BitWidth.ONE)) { Graphics g = painter.getGraphics(); g.setColor(ICON_WIDTH_COLOR); g.setFont(ICON_WIDTH_FONT); - GraphicsUtil.drawCenteredText(g, "" + w.getWidth(), 10, 9); + GraphicsUtil.drawCenteredText(g, "" + width.getWidth(), 10, 9); g.setColor(Color.BLACK); } } @@ -148,28 +147,27 @@ private void paintIconBase(InstancePainter painter) { Graphics g = painter.getGraphics(); if (output) { if (ICON_OUT != null) { - Icons.paintRotated(g, 2, 2, dir, ICON_OUT, - painter.getDestination()); + Icons.paintRotated(g, 2, 2, dir, ICON_OUT, painter.getDestination()); return; } } else { if (ICON_IN != null) { - Icons.paintRotated(g, 2, 2, dir, ICON_IN, - painter.getDestination()); + Icons.paintRotated(g, 2, 2, dir, ICON_IN, painter.getDestination()); return; } } - int pinx = 16; - int piny = 9; - if (dir == Direction.EAST) { // keep defaults + int pinX = 16; + int pinY = 9; + if (dir == Direction.EAST) { + // keep defaults } else if (dir == Direction.WEST) { - pinx = 4; + pinX = 4; } else if (dir == Direction.NORTH) { - pinx = 9; - piny = 4; + pinX = 9; + pinY = 4; } else if (dir == Direction.SOUTH) { - pinx = 9; - piny = 16; + pinX = 9; + pinY = 16; } g.setColor(Color.black); @@ -180,31 +178,29 @@ private void paintIconBase(InstancePainter painter) { } g.setColor(Value.TRUE.getColor()); g.fillOval(7, 7, 8, 8); - g.fillOval(pinx, piny, 3, 3); + g.fillOval(pinX, pinY, 3, 3); } @Override public void paintGhost(InstancePainter painter) { PinAttributes attrs = (PinAttributes) painter.getAttributeSet(); - Location loc = painter.getLocation(); + Location location = painter.getLocation(); Bounds bds = painter.getOffsetBounds(); - int x = loc.getX(); - int y = loc.getY(); + int x = location.getX(); + int y = location.getY(); Graphics g = painter.getGraphics(); GraphicsUtil.switchToWidth(g, 2); boolean output = attrs.isOutput(); if (output) { BitWidth width = attrs.getValue(StdAttr.WIDTH); if (width == BitWidth.ONE) { - g.drawOval(x + bds.getX() + 1, y + bds.getY() + 1, - bds.getWidth() - 1, bds.getHeight() - 1); + g.drawOval(x + bds.getX() + 1, y + bds.getY() + 1, bds.getWidth() - 1, bds.getHeight() - 1); } else { - g.drawRoundRect(x + bds.getX() + 1, y + bds.getY() + 1, - bds.getWidth() - 1, bds.getHeight() - 1, 6, 6); + g.drawRoundRect(x + bds.getX() + 1, y + bds.getY() + 1, bds.getWidth() - 1, + bds.getHeight() - 1, 6, 6); } } else { - g.drawRect(x + bds.getX() + 1, y + bds.getY() + 1, - bds.getWidth() - 1, bds.getHeight() - 1); + g.drawRect(x + bds.getX() + 1, y + bds.getY() + 1, bds.getWidth() - 1, bds.getHeight() - 1); } } @@ -212,30 +208,28 @@ public void paintGhost(InstancePainter painter) { public void paintInstance(InstancePainter painter) { PinAttributes attrs = (PinAttributes) painter.getAttributeSet(); Graphics g = painter.getGraphics(); - Bounds bds = painter.getInstance().getBounds(); // intentionally with no graphics object - we don't want label included - int x = bds.getX(); - int y = bds.getY(); + Bounds bounds = painter.getInstance() + .getBounds(); // intentionally with no graphics object - we don't want label included + int x = bounds.getX(); + int y = bounds.getY(); GraphicsUtil.switchToWidth(g, 2); g.setColor(Color.black); if (attrs.type == EndData.OUTPUT_ONLY) { if (attrs.width.getWidth() == 1) { - g.drawOval(x + 1, y + 1, - bds.getWidth() - 1, bds.getHeight() - 1); + g.drawOval(x + 1, y + 1, bounds.getWidth() - 1, bounds.getHeight() - 1); } else { - g.drawRoundRect(x + 1, y + 1, - bds.getWidth() - 1, bds.getHeight() - 1, 6, 6); + g.drawRoundRect(x + 1, y + 1, bounds.getWidth() - 1, bounds.getHeight() - 1, 6, 6); } } else { - g.drawRect(x + 1, y + 1, - bds.getWidth() - 1, bds.getHeight() - 1); + g.drawRect(x + 1, y + 1, bounds.getWidth() - 1, bounds.getHeight() - 1); } painter.drawLabel(); if (!painter.getShowState()) { g.setColor(Color.BLACK); - GraphicsUtil.drawCenteredText(g, "x" + attrs.width.getWidth(), - bds.getX() + bds.getWidth() / 2, bds.getY() + bds.getHeight() / 2); + GraphicsUtil.drawCenteredText(g, "x" + attrs.width.getWidth(), bounds.getX() + bounds.getWidth() / 2, + bounds.getY() + bounds.getHeight() / 2); } else { PinState state = getState(painter); if (attrs.width.getWidth() <= 1) { @@ -245,14 +239,12 @@ public void paintInstance(InstancePainter painter) { if (attrs.width.getWidth() == 1) { g.setColor(Color.WHITE); - GraphicsUtil.drawCenteredText(g, - state.intendedValue.toDisplayString(), x + 11, y + 9); + GraphicsUtil.drawCenteredText(g, state.intendedValue.toDisplayString(), x + 11, y + 9); } } else { Probe.paintValue(painter, state.intendedValue); } } - painter.drawPorts(); } @@ -264,18 +256,17 @@ protected void configureNewInstance(Instance instance) { PinAttributes attrs = (PinAttributes) instance.getAttributeSet(); instance.addAttributeListener(); configurePorts(instance); - Probe.configureLabel(instance, attrs.labelloc, attrs.facing); + Probe.configureLabel(instance, attrs.labelLocation, attrs.facing); } @Override protected void instanceAttributeChanged(Instance instance, Attribute attribute) { if (attribute == ATTR_TYPE) { configurePorts(instance); - } else if (attribute == StdAttr.WIDTH || attribute == StdAttr.FACING - || attribute == Pin.ATTR_LABEL_LOC) { + } else if (attribute == StdAttr.WIDTH || attribute == StdAttr.FACING || attribute == Pin.ATTR_LABEL_LOC) { instance.recomputeBounds(); PinAttributes attrs = (PinAttributes) instance.getAttributeSet(); - Probe.configureLabel(instance, attrs.labelloc, attrs.facing); + Probe.configureLabel(instance, attrs.labelLocation, attrs.facing); } else if (attribute == Pin.ATTR_TRISTATE || attribute == Pin.ATTR_PULL) { instance.fireInvalidated(); } @@ -296,15 +287,14 @@ private void configurePorts(Instance instance) { @Override public void propagate(InstanceState state) { PinAttributes attrs = (PinAttributes) state.getAttributeSet(); - PinState q = getState(state); + PinState pinState = getState(state); + Value found = state.getPort(0); if (attrs.type == EndData.OUTPUT_ONLY) { - Value found = state.getPort(0); - q.intendedValue = found; - q.foundValue = found; + pinState.intendedValue = found; + pinState.foundValue = found; state.setPort(0, Value.createUnknown(attrs.width), 1); } else { - Value found = state.getPort(0); - Value toSend = q.intendedValue; + Value toSend = pinState.intendedValue; Object pull = attrs.pull; Value pullTo = null; @@ -318,11 +308,11 @@ public void propagate(InstanceState state) { if (pullTo != null) { toSend = pull2(toSend, attrs.width, pullTo); if (state.isCircuitRoot()) { - q.intendedValue = toSend; + pinState.intendedValue = toSend; } } - q.foundValue = found; + pinState.foundValue = found; if (!toSend.equals(found)) { // ignore if no change state.setPort(0, toSend, 1); } @@ -430,35 +420,35 @@ private void handleBitPress(InstanceState state, int bit, MouseEvent e) { return; } - java.awt.Component sourceComp = e.getComponent(); - if (sourceComp instanceof Canvas && !state.isCircuitRoot()) { + java.awt.Component sourceComponent = e.getComponent(); + if (sourceComponent instanceof Canvas && !state.isCircuitRoot()) { Canvas canvas = (Canvas) e.getComponent(); - CircuitState circState = canvas.getCircuitState(); + CircuitState circuitState = canvas.getCircuitState(); java.awt.Component frame = SwingUtilities.getRoot(canvas); int choice = JOptionPane.showConfirmDialog(frame, - Strings.get("pinFrozenQuestion"), - Strings.get("pinFrozenTitle"), - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.WARNING_MESSAGE); + Strings.get("pinFrozenQuestion"), + Strings.get("pinFrozenTitle"), + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.OK_OPTION) { - circState = circState.cloneState(); - canvas.getProject().setCircuitState(circState); - state = circState.getInstanceState(state.getInstance()); + circuitState = circuitState.cloneState(); + canvas.getProject().setCircuitState(circuitState); + state = circuitState.getInstanceState(state.getInstance()); } else { return; } } PinState pinState = getState(state); - Value val = pinState.intendedValue.get(bit); - if (val == Value.FALSE) { - val = Value.TRUE; - } else if (val == Value.TRUE) { - val = attrs.threeState && attrs.pull == PULL_NONE ? Value.UNKNOWN : Value.FALSE; + Value value = pinState.intendedValue.get(bit); + if (value == Value.FALSE) { + value = Value.TRUE; + } else if (value == Value.TRUE) { + value = attrs.threeState && attrs.pull == PULL_NONE ? Value.UNKNOWN : Value.FALSE; } else { - val = Value.FALSE; + value = Value.FALSE; } - pinState.intendedValue = pinState.intendedValue.set(bit, val); + pinState.intendedValue = pinState.intendedValue.set(bit, value); state.fireInvalidated(); } @@ -467,10 +457,10 @@ private int getBit(InstanceState state, MouseEvent e) { if (width.getWidth() == 1) { return 0; } else { - Bounds bds = state.getInstance() - .getBounds(); // intentionally with no graphics object - we don't want label included - int i = (bds.getX() + bds.getWidth() - e.getX()) / 10; - int j = (bds.getY() + bds.getHeight() - e.getY()) / 20; + Bounds bounds = state.getInstance() + .getBounds(); // intentionally with no graphics object - we don't want label included + int i = (bounds.getX() + bounds.getWidth() - e.getX()) / 10; + int j = (bounds.getY() + bounds.getHeight() - e.getY()) / 20; int bit = 8 * j + i; if (bit < 0 || bit >= width.getWidth()) { return -1; @@ -486,20 +476,19 @@ public static class PinLogger extends InstanceLogger { @Override public String getLogName(InstanceState state, Object option) { PinAttributes attrs = (PinAttributes) state.getAttributeSet(); - String ret = attrs.label; - if (ret == null || ret.equals("")) { - String type = attrs.type == EndData.INPUT_ONLY - ? Strings.get("pinInputName") : Strings.get("pinOutputName"); + String label = attrs.label; + if (label == null || label.equals("")) { + String type = attrs.type == EndData.INPUT_ONLY ? Strings.get("pinInputName") : Strings.get("pinOutputName"); return type + state.getInstance().getLocation(); } else { - return ret; + return label; } } @Override public Value getLogValue(InstanceState state, Object option) { - PinState s = getState(state); - return s.intendedValue; + PinState pinState = getState(state); + return pinState.intendedValue; } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/wiring/PinAttributes.java b/src/main/java/com/cburch/logisim/std/wiring/PinAttributes.java index 413e24e..d040e31 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/PinAttributes.java +++ b/src/main/java/com/cburch/logisim/std/wiring/PinAttributes.java @@ -13,8 +13,8 @@ class PinAttributes extends ProbeAttributes { private static final List> ATTRIBUTES - = Arrays.asList(StdAttr.FACING, Pin.ATTR_TYPE, StdAttr.WIDTH, Pin.ATTR_TRISTATE, - Pin.ATTR_PULL, StdAttr.LABEL, Pin.ATTR_LABEL_LOC, StdAttr.LABEL_FONT); + = Arrays.asList(StdAttr.FACING, Pin.ATTR_TYPE, StdAttr.WIDTH, Pin.ATTR_TRISTATE, + Pin.ATTR_PULL, StdAttr.LABEL, Pin.ATTR_LABEL_LOC, StdAttr.LABEL_FONT); public static PinAttributes instance = new PinAttributes(); BitWidth width = BitWidth.ONE; boolean threeState = true; diff --git a/src/main/java/com/cburch/logisim/std/wiring/Power.java b/src/main/java/com/cburch/logisim/std/wiring/Power.java index 0a27dc1..80ab07e 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/Power.java +++ b/src/main/java/com/cburch/logisim/std/wiring/Power.java @@ -30,8 +30,15 @@ public class Power extends InstanceFactory { public Power() { super("Power", Strings.getter("powerComponent")); setIconName("power.gif"); - setAttributes(new Attribute[]{StdAttr.FACING, StdAttr.WIDTH}, - new Object[]{Direction.NORTH, BitWidth.ONE}); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + StdAttr.WIDTH + }, new Object[]{ + Direction.NORTH, + BitWidth.ONE + } + ); setFacingAttribute(StdAttr.FACING); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); setPorts(new Port[]{new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH)}); @@ -52,7 +59,7 @@ protected void instanceAttributeChanged(Instance instance, Attribute attribut @Override public Bounds getOffsetBounds(AttributeSet attributes) { return Bounds.create(0, -8, 15, 16) - .rotate(Direction.EAST, attributes.getValue(StdAttr.FACING), 0, 0); + .rotate(Direction.EAST, attributes.getValue(StdAttr.FACING), 0, 0); } @Override @@ -74,8 +81,8 @@ public void paintGhost(InstancePainter painter) { private void drawInstance(InstancePainter painter, boolean isGhost) { Graphics2D g = (Graphics2D) painter.getGraphics().create(); - Location loc = painter.getLocation(); - g.translate(loc.getX(), loc.getY()); + Location location = painter.getLocation(); + g.translate(location.getX(), location.getY()); Direction from = painter.getAttributeValue(StdAttr.FACING); int degrees = Direction.EAST.toDegrees() - from.toDegrees(); diff --git a/src/main/java/com/cburch/logisim/std/wiring/Probe.java b/src/main/java/com/cburch/logisim/std/wiring/Probe.java index 7607586..22c2b80 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/Probe.java +++ b/src/main/java/com/cburch/logisim/std/wiring/Probe.java @@ -22,6 +22,7 @@ import com.cburch.logisim.util.GraphicsUtil; import java.awt.Color; import java.awt.Graphics; +import java.util.Objects; public class Probe extends InstanceFactory { @@ -36,34 +37,33 @@ public Probe() { static void paintValue(InstancePainter painter, Value value) { Graphics g = painter.getGraphics(); - Bounds bds = painter.getBounds(); // intentionally with no graphics object - we don't want label included + Bounds bounds = painter.getBounds(); // intentionally with no graphics object - we don't want label included RadixOption radix = painter.getAttributeValue(RadixOption.ATTRIBUTE); if (radix == null || radix == RadixOption.RADIX_2) { - int x = bds.getX(); - int y = bds.getY(); + int x = bounds.getX(); + int y = bounds.getY(); int wid = value.getWidth(); if (wid == 0) { - x += bds.getWidth() / 2; - y += bds.getHeight() / 2; + x += bounds.getWidth() / 2; + y += bounds.getHeight() / 2; GraphicsUtil.switchToWidth(g, 2); g.drawLine(x - 4, y, x + 4, y); return; } - int x0 = bds.getX() + bds.getWidth() - 5; + int x0 = bounds.getX() + bounds.getWidth() - 5; int compWidth = wid * 10; - if (compWidth < bds.getWidth() - 3) { - x0 = bds.getX() + (bds.getWidth() + compWidth) / 2 - 5; + if (compWidth < bounds.getWidth() - 3) { + x0 = bounds.getX() + (bounds.getWidth() + compWidth) / 2 - 5; } int cx = x0; - int cy = bds.getY() + bds.getHeight() - 12; - int cur = 0; + int cy = bounds.getY() + bounds.getHeight() - 12; + int current = 0; for (int k = 0; k < wid; k++) { - GraphicsUtil.drawCenteredText(g, - value.get(k).toDisplayString(), cx, cy); - ++cur; - if (cur == 8) { - cur = 0; + GraphicsUtil.drawCenteredText(g, value.get(k).toDisplayString(), cx, cy); + ++current; + if (current == 8) { + current = 0; cx = x0; cy -= 20; } else { @@ -73,8 +73,8 @@ static void paintValue(InstancePainter painter, Value value) { } else { String text = radix.toString(value); GraphicsUtil.drawCenteredText(g, text, - bds.getX() + bds.getWidth() / 2, - bds.getY() + bds.getHeight() / 2); + bounds.getX() + bounds.getWidth() / 2, + bounds.getY() + bounds.getHeight() / 2); } } @@ -87,35 +87,35 @@ private static Value getValue(InstanceState state) { // static methods // static Bounds getOffsetBounds(Direction dir, BitWidth width, - RadixOption radix) { - Bounds ret = null; + RadixOption radix) { + Bounds bounds = null; int len = radix == null || radix == RadixOption.RADIX_2 ? width.getWidth() : radix.getMaxLength(width); if (dir == Direction.EAST) { switch (len) { case 0: case 1: - ret = Bounds.create(-20, -10, 20, 20); + bounds = Bounds.create(-20, -10, 20, 20); break; case 2: - ret = Bounds.create(-20, -10, 20, 20); + bounds = Bounds.create(-20, -10, 20, 20); break; case 3: - ret = Bounds.create(-30, -10, 30, 20); + bounds = Bounds.create(-30, -10, 30, 20); break; case 4: - ret = Bounds.create(-40, -10, 40, 20); + bounds = Bounds.create(-40, -10, 40, 20); break; case 5: - ret = Bounds.create(-50, -10, 50, 20); + bounds = Bounds.create(-50, -10, 50, 20); break; case 6: - ret = Bounds.create(-60, -10, 60, 20); + bounds = Bounds.create(-60, -10, 60, 20); break; case 7: - ret = Bounds.create(-70, -10, 70, 20); + bounds = Bounds.create(-70, -10, 70, 20); break; case 8: - ret = Bounds.create(-80, -10, 80, 20); + bounds = Bounds.create(-80, -10, 80, 20); break; case 9: case 10: @@ -125,7 +125,7 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 14: case 15: case 16: - ret = Bounds.create(-80, -20, 80, 40); + bounds = Bounds.create(-80, -20, 80, 40); break; case 17: case 18: @@ -135,7 +135,7 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 22: case 23: case 24: - ret = Bounds.create(-80, -30, 80, 60); + bounds = Bounds.create(-80, -30, 80, 60); break; case 25: case 26: @@ -145,35 +145,35 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 30: case 31: case 32: - ret = Bounds.create(-80, -40, 80, 80); + bounds = Bounds.create(-80, -40, 80, 80); break; } } else if (dir == Direction.WEST) { switch (len) { case 0: case 1: - ret = Bounds.create(0, -10, 20, 20); + bounds = Bounds.create(0, -10, 20, 20); break; case 2: - ret = Bounds.create(0, -10, 20, 20); + bounds = Bounds.create(0, -10, 20, 20); break; case 3: - ret = Bounds.create(0, -10, 30, 20); + bounds = Bounds.create(0, -10, 30, 20); break; case 4: - ret = Bounds.create(0, -10, 40, 20); + bounds = Bounds.create(0, -10, 40, 20); break; case 5: - ret = Bounds.create(0, -10, 50, 20); + bounds = Bounds.create(0, -10, 50, 20); break; case 6: - ret = Bounds.create(0, -10, 60, 20); + bounds = Bounds.create(0, -10, 60, 20); break; case 7: - ret = Bounds.create(0, -10, 70, 20); + bounds = Bounds.create(0, -10, 70, 20); break; case 8: - ret = Bounds.create(0, -10, 80, 20); + bounds = Bounds.create(0, -10, 80, 20); break; case 9: case 10: @@ -183,7 +183,7 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 14: case 15: case 16: - ret = Bounds.create(0, -20, 80, 40); + bounds = Bounds.create(0, -20, 80, 40); break; case 17: case 18: @@ -193,7 +193,7 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 22: case 23: case 24: - ret = Bounds.create(0, -30, 80, 60); + bounds = Bounds.create(0, -30, 80, 60); break; case 25: case 26: @@ -203,35 +203,35 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 30: case 31: case 32: - ret = Bounds.create(0, -40, 80, 80); + bounds = Bounds.create(0, -40, 80, 80); break; } } else if (dir == Direction.SOUTH) { switch (len) { case 0: case 1: - ret = Bounds.create(-10, -20, 20, 20); + bounds = Bounds.create(-10, -20, 20, 20); break; case 2: - ret = Bounds.create(-10, -20, 20, 20); + bounds = Bounds.create(-10, -20, 20, 20); break; case 3: - ret = Bounds.create(-15, -20, 30, 20); + bounds = Bounds.create(-15, -20, 30, 20); break; case 4: - ret = Bounds.create(-20, -20, 40, 20); + bounds = Bounds.create(-20, -20, 40, 20); break; case 5: - ret = Bounds.create(-25, -20, 50, 20); + bounds = Bounds.create(-25, -20, 50, 20); break; case 6: - ret = Bounds.create(-30, -20, 60, 20); + bounds = Bounds.create(-30, -20, 60, 20); break; case 7: - ret = Bounds.create(-35, -20, 70, 20); + bounds = Bounds.create(-35, -20, 70, 20); break; case 8: - ret = Bounds.create(-40, -20, 80, 20); + bounds = Bounds.create(-40, -20, 80, 20); break; case 9: case 10: @@ -241,7 +241,7 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 14: case 15: case 16: - ret = Bounds.create(-40, -40, 80, 40); + bounds = Bounds.create(-40, -40, 80, 40); break; case 17: case 18: @@ -251,7 +251,7 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 22: case 23: case 24: - ret = Bounds.create(-40, -60, 80, 60); + bounds = Bounds.create(-40, -60, 80, 60); break; case 25: case 26: @@ -261,35 +261,35 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 30: case 31: case 32: - ret = Bounds.create(-40, -80, 80, 80); + bounds = Bounds.create(-40, -80, 80, 80); break; } } else if (dir == Direction.NORTH) { switch (len) { case 0: case 1: - ret = Bounds.create(-10, 0, 20, 20); + bounds = Bounds.create(-10, 0, 20, 20); break; case 2: - ret = Bounds.create(-10, 0, 20, 20); + bounds = Bounds.create(-10, 0, 20, 20); break; case 3: - ret = Bounds.create(-15, 0, 30, 20); + bounds = Bounds.create(-15, 0, 30, 20); break; case 4: - ret = Bounds.create(-20, 0, 40, 20); + bounds = Bounds.create(-20, 0, 40, 20); break; case 5: - ret = Bounds.create(-25, 0, 50, 20); + bounds = Bounds.create(-25, 0, 50, 20); break; case 6: - ret = Bounds.create(-30, 0, 60, 20); + bounds = Bounds.create(-30, 0, 60, 20); break; case 7: - ret = Bounds.create(-35, 0, 70, 20); + bounds = Bounds.create(-35, 0, 70, 20); break; case 8: - ret = Bounds.create(-40, 0, 80, 20); + bounds = Bounds.create(-40, 0, 80, 20); break; case 9: case 10: @@ -299,7 +299,7 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 14: case 15: case 16: - ret = Bounds.create(-40, 0, 80, 40); + bounds = Bounds.create(-40, 0, 80, 40); break; case 17: case 18: @@ -309,7 +309,7 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 22: case 23: case 24: - ret = Bounds.create(-40, 0, 80, 60); + bounds = Bounds.create(-40, 0, 80, 60); break; case 25: case 26: @@ -319,63 +319,61 @@ static Bounds getOffsetBounds(Direction dir, BitWidth width, case 30: case 31: case 32: - ret = Bounds.create(-40, 0, 80, 80); + bounds = Bounds.create(-40, 0, 80, 80); break; } } - if (ret == null) { - ret = Bounds.create(0, -10, 20, 20); // should never happen + if (bounds == null) { + bounds = Bounds.create(0, -10, 20, 20); // should never happen } - return ret; + return bounds; } - static void configureLabel(Instance instance, Direction labelLoc, - Direction facing) { - Bounds bds = instance.getBounds(); + static void configureLabel(Instance instance, Direction labelLocation, Direction facing) { + Bounds bounds = instance.getBounds(); int x; int y; - int halign; - int valign; - if (labelLoc == Direction.NORTH) { - halign = TextField.H_CENTER; - valign = TextField.V_BOTTOM; - x = bds.getX() + bds.getWidth() / 2; - y = bds.getY() - 2; - if (facing == labelLoc) { - halign = TextField.H_LEFT; + int hAlign; + int vAlign; + if (labelLocation == Direction.NORTH) { + hAlign = TextField.H_CENTER; + vAlign = TextField.V_BOTTOM; + x = bounds.getX() + bounds.getWidth() / 2; + y = bounds.getY() - 2; + if (facing == labelLocation) { + hAlign = TextField.H_LEFT; x += 2; } - } else if (labelLoc == Direction.SOUTH) { - halign = TextField.H_CENTER; - valign = TextField.V_TOP; - x = bds.getX() + bds.getWidth() / 2; - y = bds.getY() + bds.getHeight() + 2; - if (facing == labelLoc) { - halign = TextField.H_LEFT; + } else if (labelLocation == Direction.SOUTH) { + hAlign = TextField.H_CENTER; + vAlign = TextField.V_TOP; + x = bounds.getX() + bounds.getWidth() / 2; + y = bounds.getY() + bounds.getHeight() + 2; + if (facing == labelLocation) { + hAlign = TextField.H_LEFT; x += 2; } - } else if (labelLoc == Direction.EAST) { - halign = TextField.H_LEFT; - valign = TextField.V_CENTER; - x = bds.getX() + bds.getWidth() + 2; - y = bds.getY() + bds.getHeight() / 2; - if (facing == labelLoc) { - valign = TextField.V_BOTTOM; + } else if (labelLocation == Direction.EAST) { + hAlign = TextField.H_LEFT; + vAlign = TextField.V_CENTER; + x = bounds.getX() + bounds.getWidth() + 2; + y = bounds.getY() + bounds.getHeight() / 2; + if (facing == labelLocation) { + vAlign = TextField.V_BOTTOM; y -= 2; } } else { // WEST - halign = TextField.H_RIGHT; - valign = TextField.V_CENTER; - x = bds.getX() - 2; - y = bds.getY() + bds.getHeight() / 2; - if (facing == labelLoc) { - valign = TextField.V_BOTTOM; + hAlign = TextField.H_RIGHT; + vAlign = TextField.V_CENTER; + x = bounds.getX() - 2; + y = bounds.getY() + bounds.getHeight() / 2; + if (facing == labelLocation) { + vAlign = TextField.V_BOTTOM; y -= 2; } } - instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, - x, y, halign, valign); + instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, x, y, hAlign, vAlign); } @Override @@ -395,9 +393,8 @@ public Bounds getOffsetBounds(AttributeSet attributes) { @Override public void paintGhost(InstancePainter painter) { Graphics g = painter.getGraphics(); - Bounds bds = painter.getOffsetBounds(); - g.drawOval(bds.getX() + 1, bds.getY() + 1, - bds.getWidth() - 1, bds.getHeight() - 1); + Bounds bounds = painter.getOffsetBounds(); + g.drawOval(bounds.getX() + 1, bounds.getY() + 1, bounds.getWidth() - 1, bounds.getHeight() - 1); } @Override @@ -405,18 +402,16 @@ public void paintInstance(InstancePainter painter) { Value value = getValue(painter); Graphics g = painter.getGraphics(); - Bounds bds = painter.getBounds(); // intentionally with no graphics object - we don't want label included - int x = bds.getX(); - int y = bds.getY(); + Bounds bounds = painter.getBounds(); // intentionally with no graphics object - we don't want label included + int x = bounds.getX(); + int y = bounds.getY(); g.setColor(Color.WHITE); - g.fillRect(x + 5, y + 5, bds.getWidth() - 10, bds.getHeight() - 10); + g.fillRect(x + 5, y + 5, bounds.getWidth() - 10, bounds.getHeight() - 10); g.setColor(Color.GRAY); if (value.getWidth() <= 1) { - g.drawOval(x + 1, y + 1, - bds.getWidth() - 2, bds.getHeight() - 2); + g.drawOval(x + 1, y + 1, bounds.getWidth() - 2, bounds.getHeight() - 2); } else { - g.drawRoundRect(x + 1, y + 1, - bds.getWidth() - 2, bds.getHeight() - 2, 6, 6); + g.drawRoundRect(x + 1, y + 1, bounds.getWidth() - 2, bounds.getHeight() - 2, 6, 6); } g.setColor(Color.BLACK); @@ -424,8 +419,8 @@ public void paintInstance(InstancePainter painter) { if (!painter.getShowState()) { if (value.getWidth() > 0) { - GraphicsUtil.drawCenteredText(g, "x" + value.getWidth(), - bds.getX() + bds.getWidth() / 2, bds.getY() + bds.getHeight() / 2); + GraphicsUtil.drawCenteredText(g, "x" + value.getWidth(), bounds.getX() + bounds.getWidth() / 2, + bounds.getY() + bounds.getHeight() / 2); } } else { paintValue(painter, value); @@ -459,7 +454,7 @@ public void propagate(InstanceState state) { StateData oldData = (StateData) state.getData(); Value oldValue = oldData == null ? Value.NIL : oldData.curValue; Value newValue = state.getPort(0); - boolean same = oldValue == null ? newValue == null : oldValue.equals(newValue); + boolean same = Objects.equals(oldValue, newValue); if (!same) { if (oldData == null) { oldData = new StateData(); @@ -482,7 +477,7 @@ public void propagate(InstanceState state) { void configureLabel(Instance instance) { ProbeAttributes attrs = (ProbeAttributes) instance.getAttributeSet(); - Probe.configureLabel(instance, attrs.labelloc, attrs.facing); + Probe.configureLabel(instance, attrs.labelLocation, attrs.facing); } private static class StateData implements InstanceData, Cloneable { @@ -506,8 +501,8 @@ public ProbeLogger() { @Override public String getLogName(InstanceState state, Object option) { - String ret = state.getAttributeValue(StdAttr.LABEL); - return ret != null && !ret.equals("") ? ret : null; + String name = state.getAttributeValue(StdAttr.LABEL); + return name != null && !name.equals("") ? name : null; } @Override @@ -515,4 +510,4 @@ public Value getLogValue(InstanceState state, Object option) { return getValue(state); } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/wiring/ProbeAttributes.java b/src/main/java/com/cburch/logisim/std/wiring/ProbeAttributes.java index d7a38e3..f4e8036 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/ProbeAttributes.java +++ b/src/main/java/com/cburch/logisim/std/wiring/ProbeAttributes.java @@ -16,13 +16,12 @@ class ProbeAttributes extends AbstractAttributeSet { private static final List> ATTRIBUTES - = Arrays.asList(StdAttr.FACING, RadixOption.ATTRIBUTE, - StdAttr.LABEL, Pin.ATTR_LABEL_LOC, StdAttr.LABEL_FONT); + = Arrays.asList(StdAttr.FACING, RadixOption.ATTRIBUTE, StdAttr.LABEL, Pin.ATTR_LABEL_LOC, StdAttr.LABEL_FONT); public static ProbeAttributes instance = new ProbeAttributes(); Direction facing = Direction.EAST; String label = ""; - Direction labelloc = Direction.WEST; - Font labelfont = StdAttr.DEFAULT_LABEL_FONT; + Direction labelLocation = Direction.WEST; + Font labelFont = StdAttr.DEFAULT_LABEL_FONT; RadixOption radix = RadixOption.RADIX_2; BitWidth width = BitWidth.ONE; @@ -49,10 +48,10 @@ public E getValue(Attribute attr) { return (E) label; } if (attr == Pin.ATTR_LABEL_LOC) { - return (E) labelloc; + return (E) labelLocation; } if (attr == StdAttr.LABEL_FONT) { - return (E) labelfont; + return (E) labelFont; } if (attr == RadixOption.ATTRIBUTE) { return (E) radix; @@ -67,9 +66,9 @@ public void setValue(Attribute attr, V value) { } else if (attr == StdAttr.LABEL) { label = (String) value; } else if (attr == Pin.ATTR_LABEL_LOC) { - labelloc = (Direction) value; + labelLocation = (Direction) value; } else if (attr == StdAttr.LABEL_FONT) { - labelfont = (Font) value; + labelFont = (Font) value; } else if (attr == RadixOption.ATTRIBUTE) { radix = (RadixOption) value; } else { diff --git a/src/main/java/com/cburch/logisim/std/wiring/PullResistor.java b/src/main/java/com/cburch/logisim/std/wiring/PullResistor.java index caee72d..7bf5e7d 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/PullResistor.java +++ b/src/main/java/com/cburch/logisim/std/wiring/PullResistor.java @@ -29,12 +29,12 @@ public class PullResistor extends InstanceFactory { public static final Attribute ATTR_PULL_TYPE - = Attributes.forOption("pull", Strings.getter("pullTypeAttr"), - new AttributeOption[]{ - new AttributeOption(Value.FALSE, "0", Strings.getter("pullZeroType")), - new AttributeOption(Value.TRUE, "1", Strings.getter("pullOneType")), - new AttributeOption(Value.ERROR, "X", Strings.getter("pullErrorType")) - }); + = Attributes.forOption("pull", Strings.getter("pullTypeAttr"), + new AttributeOption[]{ + new AttributeOption(Value.FALSE, "0", Strings.getter("pullZeroType")), + new AttributeOption(Value.TRUE, "1", Strings.getter("pullOneType")), + new AttributeOption(Value.ERROR, "X", Strings.getter("pullErrorType")) + }); public static final PullResistor FACTORY = new PullResistor(); @@ -43,8 +43,15 @@ public class PullResistor extends InstanceFactory { public PullResistor() { super("Pull Resistor", Strings.getter("pullComponent")); - setAttributes(new Attribute[]{StdAttr.FACING, ATTR_PULL_TYPE}, - new Object[]{Direction.SOUTH, ATTR_PULL_TYPE.parse("0")}); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + ATTR_PULL_TYPE + }, new Object[]{ + Direction.SOUTH, + ATTR_PULL_TYPE.parse("0") + } + ); setFacingAttribute(StdAttr.FACING); } @@ -53,8 +60,8 @@ public static Value getPullValue(Instance instance) { } private static Value getPullValue(AttributeSet attrs) { - AttributeOption opt = attrs.getValue(ATTR_PULL_TYPE); - return (Value) opt.getValue(); + AttributeOption option = attrs.getValue(ATTR_PULL_TYPE); + return (Value) option.getValue(); } @Override @@ -93,9 +100,9 @@ public void paintGhost(InstancePainter painter) { @Override public void paintInstance(InstancePainter painter) { - Location loc = painter.getLocation(); - int x = loc.getX(); - int y = loc.getY(); + Location location = painter.getLocation(); + int x = location.getX(); + int y = location.getY(); Graphics g = painter.getGraphics(); g.translate(x, y); Value pull = getPullValue(painter.getAttributeSet()); @@ -105,8 +112,7 @@ public void paintInstance(InstancePainter painter) { painter.drawPorts(); } - private void paintBase(InstancePainter painter, Value pullValue, - Color inColor, Color outColor) { + private void paintBase(InstancePainter painter, Value pullValue, Color inColor, Color outColor) { boolean color = painter.shouldDrawColor(); Direction facing = painter.getAttributeValue(StdAttr.FACING); Graphics g = painter.getGraphics(); @@ -117,16 +123,16 @@ private void paintBase(InstancePainter painter, Value pullValue, } if (facing == Direction.EAST) { GraphicsUtil.drawText(g, pullValue.toDisplayString(), -32, 0, - GraphicsUtil.H_RIGHT, GraphicsUtil.V_CENTER); + GraphicsUtil.H_RIGHT, GraphicsUtil.V_CENTER); } else if (facing == Direction.WEST) { GraphicsUtil.drawText(g, pullValue.toDisplayString(), 32, 0, - GraphicsUtil.H_LEFT, GraphicsUtil.V_CENTER); + GraphicsUtil.H_LEFT, GraphicsUtil.V_CENTER); } else if (facing == Direction.NORTH) { GraphicsUtil.drawText(g, pullValue.toDisplayString(), 0, 32, - GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); + GraphicsUtil.H_CENTER, GraphicsUtil.V_TOP); } else { GraphicsUtil.drawText(g, pullValue.toDisplayString(), 0, -32, - GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); + GraphicsUtil.H_CENTER, GraphicsUtil.V_BASELINE); } double rotate = 0.0; @@ -163,7 +169,7 @@ private void paintBase(InstancePainter painter, Value pullValue, protected void configureNewInstance(Instance instance) { instance.addAttributeListener(); instance.setPorts(new Port[]{ - new Port(0, 0, Port.INOUT, BitWidth.UNKNOWN) + new Port(0, 0, Port.INOUT, BitWidth.UNKNOWN) }); } @@ -180,4 +186,4 @@ protected void instanceAttributeChanged(Instance instance, Attribute attribut public void propagate(InstanceState state) { // nothing to do - handled by CircuitWires } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/wiring/Strings.java b/src/main/java/com/cburch/logisim/std/wiring/Strings.java index 54b3a7a..597bdcd 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/Strings.java +++ b/src/main/java/com/cburch/logisim/std/wiring/Strings.java @@ -9,8 +9,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "std"); + private static final LocaleManager source = new LocaleManager("logisim", "std"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/std/wiring/Transistor.java b/src/main/java/com/cburch/logisim/std/wiring/Transistor.java index c3f92ee..35e8d70 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/Transistor.java +++ b/src/main/java/com/cburch/logisim/std/wiring/Transistor.java @@ -24,7 +24,6 @@ import com.cburch.logisim.instance.Port; import com.cburch.logisim.instance.StdAttr; import com.cburch.logisim.tools.WireRepair; -import com.cburch.logisim.tools.WireRepairData; import com.cburch.logisim.tools.key.BitWidthConfigurator; import com.cburch.logisim.util.GraphicsUtil; import com.cburch.logisim.util.Icons; @@ -35,12 +34,11 @@ public class Transistor extends InstanceFactory { static final AttributeOption TYPE_P - = new AttributeOption("p", Strings.getter("transistorTypeP")); + = new AttributeOption("p", Strings.getter("transistorTypeP")); static final AttributeOption TYPE_N - = new AttributeOption("n", Strings.getter("transistorTypeN")); + = new AttributeOption("n", Strings.getter("transistorTypeN")); static final Attribute ATTR_TYPE - = Attributes.forOption("type", Strings.getter("transistorTypeAttr"), - new AttributeOption[]{TYPE_P, TYPE_N}); + = Attributes.forOption("type", Strings.getter("transistorTypeAttr"), new AttributeOption[]{TYPE_P, TYPE_N}); static final int OUTPUT = 0; static final int INPUT = 1; @@ -52,10 +50,18 @@ public class Transistor extends InstanceFactory { public Transistor() { super("Transistor", Strings.getter("transistorComponent")); setAttributes( - new Attribute[]{ATTR_TYPE, StdAttr.FACING, - Wiring.ATTR_GATE, StdAttr.WIDTH}, - new Object[]{TYPE_P, Direction.EAST, - Wiring.GATE_TOP_LEFT, BitWidth.ONE}); + new Attribute[]{ + ATTR_TYPE, + StdAttr.FACING, + Wiring.ATTR_GATE, + StdAttr.WIDTH + }, new Object[]{ + TYPE_P, + Direction.EAST, + Wiring.GATE_TOP_LEFT, + BitWidth.ONE + } + ); setFacingAttribute(StdAttr.FACING); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); } @@ -92,9 +98,8 @@ private void updatePorts(Instance instance) { dx = 1; } - Object powerLoc = instance.getAttributeValue(Wiring.ATTR_GATE); - boolean flip = (facing == Direction.SOUTH || facing == Direction.WEST) - == (powerLoc == Wiring.GATE_TOP_LEFT); + Object powerLocation = instance.getAttributeValue(Wiring.ATTR_GATE); + boolean flip = (facing == Direction.SOUTH || facing == Direction.WEST) == (powerLocation == Wiring.GATE_TOP_LEFT); Port[] ports = new Port[3]; ports[OUTPUT] = new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH); @@ -110,11 +115,7 @@ private void updatePorts(Instance instance) { @Override public Object getInstanceFeature(final Instance instance, Object key) { if (key == WireRepair.class) { - return new WireRepair() { - public boolean shouldRepairWire(WireRepairData data) { - return true; - } - }; + return (WireRepair) data -> true; } return super.getInstanceFeature(instance, key); } @@ -122,8 +123,8 @@ public boolean shouldRepairWire(WireRepairData data) { @Override public Bounds getOffsetBounds(AttributeSet attributes) { Direction facing = attributes.getValue(StdAttr.FACING); - Object gateLoc = attributes.getValue(Wiring.ATTR_GATE); - int delta = gateLoc == Wiring.GATE_TOP_LEFT ? -20 : 0; + Object gateLocation = attributes.getValue(Wiring.ATTR_GATE); + int delta = gateLocation == Wiring.GATE_TOP_LEFT ? -20 : 0; if (facing == Direction.NORTH) { return Bounds.create(delta, 0, 20, 40); } else if (facing == Direction.SOUTH) { @@ -155,20 +156,19 @@ private Value computeOutput(InstanceState state) { BitWidth width = state.getAttributeValue(StdAttr.WIDTH); Value gate = state.getPort(GATE); Value input = state.getPort(INPUT); - Value desired = state.getAttributeValue(ATTR_TYPE) == TYPE_P - ? Value.FALSE : Value.TRUE; + Value desired = state.getAttributeValue(ATTR_TYPE) == TYPE_P ? Value.FALSE : Value.TRUE; if (!gate.isFullyDefined()) { if (input.isFullyDefined()) { return Value.createError(width); } else { - Value[] v = input.getAll(); - for (int i = 0; i < v.length; i++) { - if (v[i] != Value.UNKNOWN) { - v[i] = Value.ERROR; + Value[] values = input.getAll(); + for (int i = 0; i < values.length; i++) { + if (values[i] != Value.UNKNOWN) { + values[i] = Value.ERROR; } } - return Value.create(v); + return Value.create(values); } } else if (gate != desired) { return Value.createUnknown(width); @@ -197,25 +197,21 @@ public void paintGhost(InstancePainter painter) { private void drawInstance(InstancePainter painter, boolean isGhost) { Object type = painter.getAttributeValue(ATTR_TYPE); - Object powerLoc = painter.getAttributeValue(Wiring.ATTR_GATE); + Object powerLocation = painter.getAttributeValue(Wiring.ATTR_GATE); Direction from = painter.getAttributeValue(StdAttr.FACING); Direction facing = painter.getAttributeValue(StdAttr.FACING); - boolean flip = (facing == Direction.SOUTH || facing == Direction.WEST) - == (powerLoc == Wiring.GATE_TOP_LEFT); + boolean flip = (facing == Direction.SOUTH || facing == Direction.WEST) == (powerLocation == Wiring.GATE_TOP_LEFT); int degrees = Direction.EAST.toDegrees() - from.toDegrees(); double radians = Math.toRadians((degrees + 360) % 360); int m = flip ? 1 : -1; Graphics2D g = (Graphics2D) painter.getGraphics(); - Location loc = painter.getLocation(); - g.translate(loc.getX(), loc.getY()); + Location location = painter.getLocation(); + g.translate(location.getX(), location.getY()); g.rotate(radians); - Color gate; - Color input; - Color output; - Color platform; + Color gate, input, output, platform; if (!isGhost && painter.getShowState()) { gate = painter.getPort(GATE).getColor(); input = painter.getPort(INPUT).getColor(); @@ -261,6 +257,6 @@ private void drawInstance(InstancePainter painter, boolean isGhost) { g.drawLine(-21, 0, -18, m * 3); g.rotate(-radians); - g.translate(-loc.getX(), -loc.getY()); + g.translate(-location.getX(), -location.getY()); } } diff --git a/src/main/java/com/cburch/logisim/std/wiring/TransmissionGate.java b/src/main/java/com/cburch/logisim/std/wiring/TransmissionGate.java index a213126..ba1da2d 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/TransmissionGate.java +++ b/src/main/java/com/cburch/logisim/std/wiring/TransmissionGate.java @@ -38,8 +38,17 @@ public class TransmissionGate extends InstanceFactory { public TransmissionGate() { super("Transmission Gate", Strings.getter("transmissionGateComponent")); setIconName("transmis.gif"); - setAttributes(new Attribute[]{StdAttr.FACING, Wiring.ATTR_GATE, StdAttr.WIDTH}, - new Object[]{Direction.EAST, Wiring.GATE_TOP_LEFT, BitWidth.ONE}); + setAttributes( + new Attribute[]{ + StdAttr.FACING, + Wiring.ATTR_GATE, + StdAttr.WIDTH + }, new Object[]{ + Direction.EAST, + Wiring.GATE_TOP_LEFT, + BitWidth.ONE + } + ); setFacingAttribute(StdAttr.FACING); setKeyConfigurator(new BitWidthConfigurator(StdAttr.WIDTH)); } @@ -75,8 +84,7 @@ private void updatePorts(Instance instance) { } Object powerLoc = instance.getAttributeValue(Wiring.ATTR_GATE); - boolean flip = (facing == Direction.SOUTH || facing == Direction.WEST) - == (powerLoc == Wiring.GATE_TOP_LEFT); + boolean flip = (facing == Direction.SOUTH || facing == Direction.WEST) == (powerLoc == Wiring.GATE_TOP_LEFT); Port[] ports = new Port[4]; ports[OUTPUT] = new Port(0, 0, Port.OUTPUT, StdAttr.WIDTH); @@ -106,8 +114,7 @@ public boolean shouldRepairWire(WireRepairData data) { @Override public Bounds getOffsetBounds(AttributeSet attributes) { Direction facing = attributes.getValue(StdAttr.FACING); - return Bounds.create(0, -20, 40, 40).rotate(Direction.WEST, facing, 0, - 0); + return Bounds.create(0, -20, 40, 40).rotate(Direction.WEST, facing, 0, 0); } @Override @@ -165,11 +172,10 @@ public void paintGhost(InstancePainter painter) { } private void drawInstance(InstancePainter painter, boolean isGhost) { - Bounds bds = painter.getBounds(); - Object powerLoc = painter.getAttributeValue(Wiring.ATTR_GATE); + Bounds bounds = painter.getBounds(); + Object powerLocation = painter.getAttributeValue(Wiring.ATTR_GATE); Direction facing = painter.getAttributeValue(StdAttr.FACING); - boolean flip = (facing == Direction.SOUTH || facing == Direction.WEST) - == (powerLoc == Wiring.GATE_TOP_LEFT); + boolean flip = (facing == Direction.SOUTH || facing == Direction.WEST) == (powerLocation == Wiring.GATE_TOP_LEFT); int degrees = Direction.WEST.toDegrees() - facing.toDegrees(); if (flip) { @@ -178,8 +184,8 @@ private void drawInstance(InstancePainter painter, boolean isGhost) { double radians = Math.toRadians((degrees + 360) % 360); Graphics2D g = (Graphics2D) painter.getGraphics().create(); - g.rotate(radians, bds.getX() + 20, bds.getY() + 20); - g.translate(bds.getX(), bds.getY()); + g.rotate(radians, bounds.getX() + 20, bounds.getY() + 20); + g.translate(bounds.getX(), bounds.getY()); GraphicsUtil.switchToWidth(g, Wire.WIDTH); Color gate0 = g.getColor(); diff --git a/src/main/java/com/cburch/logisim/std/wiring/Tunnel.java b/src/main/java/com/cburch/logisim/std/wiring/Tunnel.java index 55c9395..f83bb37 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/Tunnel.java +++ b/src/main/java/com/cburch/logisim/std/wiring/Tunnel.java @@ -46,16 +46,14 @@ public AttributeSet createAttributeSet() { @Override public Bounds getOffsetBounds(AttributeSet attributes) { TunnelAttributes attrs = (TunnelAttributes) attributes; - Bounds bds = attrs.getOffsetBounds(); - if (bds != null) { - return bds; - } else { - int ht = attrs.getFont().getSize(); - int wd = ht * attrs.getLabel().length() / 2; - bds = computeBounds(attrs, wd, ht, null, ""); - attrs.setOffsetBounds(bds); - return bds; + Bounds bounds = attrs.getOffsetBounds(); + if (bounds == null) { + int height = attrs.getFont().getSize(); + int width = height * attrs.getLabel().length() / 2; + bounds = computeBounds(attrs, width, height, null, ""); + attrs.setOffsetBounds(bounds); } + return bounds; } // @@ -70,20 +68,19 @@ public void paintGhost(InstancePainter painter) { Graphics g = painter.getGraphics(); g.setFont(attrs.getFont()); FontMetrics fm = g.getFontMetrics(); - Bounds bds = computeBounds(attrs, fm.stringWidth(label), - fm.getAscent() + fm.getDescent(), g, label); - if (attrs.setOffsetBounds(bds)) { + Bounds bounds = computeBounds(attrs, fm.stringWidth(label), fm.getAscent() + fm.getDescent(), g, label); + if (attrs.setOffsetBounds(bounds)) { Instance instance = painter.getInstance(); if (instance != null) { instance.recomputeBounds(); } } - int x0 = bds.getX(); - int y0 = bds.getY(); - int x1 = x0 + bds.getWidth(); - int y1 = y0 + bds.getHeight(); - int mw = ARROW_MAX_WIDTH / 2; + int x0 = bounds.getX(); + int y0 = bounds.getY(); + int x1 = x0 + bounds.getWidth(); + int y1 = y0 + bounds.getHeight(); + int maxWidth = ARROW_MAX_WIDTH / 2; int[] xp; int[] yp; if (facing == Direction.NORTH) { @@ -92,7 +89,7 @@ public void paintGhost(InstancePainter painter) { xp = new int[]{x0, 0, x1, x1, x0}; yp = new int[]{yb, y0, yb, y1, y1}; } else { - xp = new int[]{x0, -mw, 0, mw, x1, x1, x0}; + xp = new int[]{x0, -maxWidth, 0, maxWidth, x1, x1, x0}; yp = new int[]{yb, yb, y0, yb, yb, y1, y1}; } } else if (facing == Direction.SOUTH) { @@ -101,7 +98,7 @@ public void paintGhost(InstancePainter painter) { xp = new int[]{x0, x1, x1, 0, x0}; yp = new int[]{y0, y0, yb, y1, yb}; } else { - xp = new int[]{x0, x1, x1, mw, 0, -mw, x0}; + xp = new int[]{x0, x1, x1, maxWidth, 0, -maxWidth, x0}; yp = new int[]{y0, y0, yb, yb, y1, yb, yb}; } } else if (facing == Direction.EAST) { @@ -111,7 +108,7 @@ public void paintGhost(InstancePainter painter) { yp = new int[]{y0, y0, 0, y1, y1}; } else { xp = new int[]{x0, xb, xb, x1, xb, xb, x0}; - yp = new int[]{y0, y0, -mw, 0, mw, y1, y1}; + yp = new int[]{y0, y0, -maxWidth, 0, maxWidth, y1, y1}; } } else { int xb = x0 + ARROW_DEPTH; @@ -120,7 +117,7 @@ public void paintGhost(InstancePainter painter) { yp = new int[]{y0, y0, y1, y1, 0}; } else { xp = new int[]{xb, x1, x1, xb, xb, x0, xb}; - yp = new int[]{y0, y0, y1, y1, mw, 0, -mw}; + yp = new int[]{y0, y0, y1, y1, maxWidth, 0, -maxWidth}; } } GraphicsUtil.switchToWidth(g, 2); @@ -129,9 +126,9 @@ public void paintGhost(InstancePainter painter) { @Override public void paintInstance(InstancePainter painter) { - Location loc = painter.getLocation(); - int x = loc.getX(); - int y = loc.getY(); + Location location = painter.getLocation(); + int x = location.getX(); + int y = location.getY(); Graphics g = painter.getGraphics(); g.translate(x, y); g.setColor(Color.BLACK); @@ -147,7 +144,7 @@ public void paintInstance(InstancePainter painter) { protected void configureNewInstance(Instance instance) { instance.addAttributeListener(); instance.setPorts(new Port[]{ - new Port(0, 0, Port.INOUT, StdAttr.WIDTH) + new Port(0, 0, Port.INOUT, StdAttr.WIDTH) }); configureLabel(instance); } @@ -172,25 +169,23 @@ public void propagate(InstanceState state) { // private void configureLabel(Instance instance) { TunnelAttributes attrs = (TunnelAttributes) instance.getAttributeSet(); - Location loc = instance.getLocation(); - instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, - loc.getX() + attrs.getLabelX(), loc.getY() + attrs.getLabelY(), - attrs.getLabelHAlign(), attrs.getLabelVAlign()); + Location location = instance.getLocation(); + instance.setTextField(StdAttr.LABEL, StdAttr.LABEL_FONT, location.getX() + attrs.getLabelX(), + location.getY() + attrs.getLabelY(), attrs.getLabelHAlign(), attrs.getLabelVAlign()); } - private Bounds computeBounds(TunnelAttributes attrs, int textWidth, - int textHeight, Graphics g, String label) { + private Bounds computeBounds(TunnelAttributes attrs, int textWidth, int textHeight, Graphics g, String label) { int x = attrs.getLabelX(); int y = attrs.getLabelY(); - int halign = attrs.getLabelHAlign(); - int valign = attrs.getLabelVAlign(); + int hAlign = attrs.getLabelHAlign(); + int vAlign = attrs.getLabelVAlign(); - int minDim = ARROW_MIN_WIDTH - 2 * MARGIN; - int bw = Math.max(minDim, textWidth); - int bh = Math.max(minDim, textHeight); + int minDimension = ARROW_MIN_WIDTH - 2 * MARGIN; + int bw = Math.max(minDimension, textWidth); + int bh = Math.max(minDimension, textHeight); int bx; int by; - switch (halign) { + switch (hAlign) { case TextField.H_LEFT: bx = x; break; @@ -200,7 +195,7 @@ private Bounds computeBounds(TunnelAttributes attrs, int textWidth, default: bx = x - (bw / 2); } - switch (valign) { + switch (vAlign) { case TextField.V_TOP: by = y; break; @@ -212,10 +207,9 @@ private Bounds computeBounds(TunnelAttributes attrs, int textWidth, } if (g != null) { - GraphicsUtil.drawText(g, label, bx + bw / 2, by + bh / 2, - GraphicsUtil.H_CENTER, GraphicsUtil.V_CENTER_OVERALL); + GraphicsUtil.drawText(g, label, bx + bw / 2, by + bh / 2, GraphicsUtil.H_CENTER, GraphicsUtil.V_CENTER_OVERALL); } return Bounds.create(bx, by, bw, bh).expand(MARGIN).add(0, 0); } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/std/wiring/TunnelAttributes.java b/src/main/java/com/cburch/logisim/std/wiring/TunnelAttributes.java index 5dc8604..1d4fdf9 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/TunnelAttributes.java +++ b/src/main/java/com/cburch/logisim/std/wiring/TunnelAttributes.java @@ -13,11 +13,12 @@ import java.awt.Font; import java.util.Arrays; import java.util.List; +import java.util.Objects; class TunnelAttributes extends AbstractAttributeSet { private static final List> ATTRIBUTES - = Arrays.asList(StdAttr.FACING, StdAttr.WIDTH, StdAttr.LABEL, StdAttr.LABEL_FONT); + = Arrays.asList(StdAttr.FACING, StdAttr.WIDTH, StdAttr.LABEL, StdAttr.LABEL_FONT); private Direction facing; private BitWidth width; @@ -71,8 +72,8 @@ int getLabelVAlign() { } boolean setOffsetBounds(Bounds value) { - Bounds old = offsetBounds; - boolean same = old == null ? value == null : old.equals(value); + Bounds oldBounds = offsetBounds; + boolean same = Objects.equals(oldBounds, value); if (!same) { offsetBounds = value; } @@ -129,33 +130,33 @@ private void configureLabel() { Direction facing = this.facing; int x; int y; - int halign; - int valign; + int hAlign; + int vAlign; int margin = Tunnel.ARROW_MARGIN; if (facing == Direction.NORTH) { x = 0; y = margin; - halign = TextField.H_CENTER; - valign = TextField.V_TOP; + hAlign = TextField.H_CENTER; + vAlign = TextField.V_TOP; } else if (facing == Direction.SOUTH) { x = 0; y = -margin; - halign = TextField.H_CENTER; - valign = TextField.V_BOTTOM; + hAlign = TextField.H_CENTER; + vAlign = TextField.V_BOTTOM; } else if (facing == Direction.EAST) { x = -margin; y = 0; - halign = TextField.H_RIGHT; - valign = TextField.V_CENTER_OVERALL; + hAlign = TextField.H_RIGHT; + vAlign = TextField.V_CENTER_OVERALL; } else { x = margin; y = 0; - halign = TextField.H_LEFT; - valign = TextField.V_CENTER_OVERALL; + hAlign = TextField.H_LEFT; + vAlign = TextField.V_CENTER_OVERALL; } labelX = x; labelY = y; - labelHAlign = halign; - labelVAlign = valign; + labelHAlign = hAlign; + labelVAlign = vAlign; } } diff --git a/src/main/java/com/cburch/logisim/std/wiring/Wiring.java b/src/main/java/com/cburch/logisim/std/wiring/Wiring.java index 88d1cb9..da974fb 100644 --- a/src/main/java/com/cburch/logisim/std/wiring/Wiring.java +++ b/src/main/java/com/cburch/logisim/std/wiring/Wiring.java @@ -20,29 +20,29 @@ public class Wiring extends Library { static final AttributeOption GATE_TOP_LEFT = new AttributeOption("tl", Strings.getter("wiringGateTopLeftOption")); static final AttributeOption GATE_BOTTOM_RIGHT = new AttributeOption("br", Strings.getter("wiringGateBottomRightOption")); static final Attribute ATTR_GATE = Attributes.forOption("gate", Strings.getter("wiringGateAttr"), - new AttributeOption[]{GATE_TOP_LEFT, GATE_BOTTOM_RIGHT}); + new AttributeOption[]{GATE_TOP_LEFT, GATE_BOTTOM_RIGHT}); private static final Tool[] ADD_TOOLS = { - new AddTool(SplitterFactory.instance), - new AddTool(Pin.FACTORY), - new AddTool(Probe.FACTORY), - new AddTool(Tunnel.FACTORY), - new AddTool(PullResistor.FACTORY), - new AddTool(Clock.FACTORY), - new AddTool(Constant.FACTORY), + new AddTool(SplitterFactory.instance), + new AddTool(Pin.FACTORY), + new AddTool(Probe.FACTORY), + new AddTool(Tunnel.FACTORY), + new AddTool(PullResistor.FACTORY), + new AddTool(Clock.FACTORY), + new AddTool(Constant.FACTORY), }; private static final FactoryDescription[] DESCRIPTIONS = { - new FactoryDescription("Power", Strings.getter("powerComponent"), "power.gif", - "Power"), - new FactoryDescription("Ground", Strings.getter("groundComponent"), "ground.gif", - "Ground"), - new FactoryDescription("Transistor", Strings.getter("transistorComponent"), - "trans0.gif", "Transistor"), - new FactoryDescription("Transmission Gate", Strings.getter("transmissionGateComponent"), - "transmis.gif", "TransmissionGate"), - new FactoryDescription("Bit Extender", Strings.getter("extenderComponent"), - "extender.gif", "BitExtender"), + new FactoryDescription("Power", Strings.getter("powerComponent"), "power.gif", + "Power"), + new FactoryDescription("Ground", Strings.getter("groundComponent"), "ground.gif", + "Ground"), + new FactoryDescription("Transistor", Strings.getter("transistorComponent"), + "trans0.gif", "Transistor"), + new FactoryDescription("Transmission Gate", Strings.getter("transmissionGateComponent"), + "transmis.gif", "TransmissionGate"), + new FactoryDescription("Bit Extender", Strings.getter("extenderComponent"), + "extender.gif", "BitExtender"), }; private List tools = null; @@ -63,10 +63,10 @@ public String getDisplayName() { @Override public List getTools() { if (tools == null) { - List ret = new ArrayList<>(ADD_TOOLS.length + DESCRIPTIONS.length); - Collections.addAll(ret, ADD_TOOLS); - ret.addAll(FactoryDescription.getTools(Wiring.class, DESCRIPTIONS)); - tools = ret; + List tools = new ArrayList<>(ADD_TOOLS.length + DESCRIPTIONS.length); + Collections.addAll(tools, ADD_TOOLS); + tools.addAll(FactoryDescription.getTools(Wiring.class, DESCRIPTIONS)); + this.tools = tools; } return tools; } diff --git a/src/main/java/com/cburch/logisim/tools/AbstractCaret.java b/src/main/java/com/cburch/logisim/tools/AbstractCaret.java index f708ac4..d32bb8a 100644 --- a/src/main/java/com/cburch/logisim/tools/AbstractCaret.java +++ b/src/main/java/com/cburch/logisim/tools/AbstractCaret.java @@ -13,9 +13,9 @@ public class AbstractCaret implements Caret { - private ArrayList listeners = new ArrayList<>(); - private List listenersView; - private Bounds bds = Bounds.EMPTY_BOUNDS; + private final ArrayList listeners = new ArrayList<>(); + private final List listenersView; + private Bounds bounds = Bounds.EMPTY_BOUNDS; public AbstractCaret() { listenersView = Collections.unmodifiableList(listeners); @@ -36,7 +36,7 @@ protected List getCaretListeners() { // configuration methods public void setBounds(Bounds value) { - bds = value; + bounds = value; } // query/Graphics methods @@ -45,7 +45,7 @@ public String getText() { } public Bounds getBounds(Graphics g) { - return bds; + return bounds; } public void draw(Graphics g) { diff --git a/src/main/java/com/cburch/logisim/tools/AddTool.java b/src/main/java/com/cburch/logisim/tools/AddTool.java index b38bfe4..4ef991b 100644 --- a/src/main/java/com/cburch/logisim/tools/AddTool.java +++ b/src/main/java/com/cburch/logisim/tools/AddTool.java @@ -40,19 +40,19 @@ public class AddTool extends Tool { - private static int INVALID_COORDINATE = Integer.MIN_VALUE; + private static final int INVALID_COORDINATE = Integer.MIN_VALUE; - private static int SHOW_NONE = 0; - private static int SHOW_GHOST = 1; - private static int SHOW_ADD = 2; - private static int SHOW_ADD_NO = 3; + private static final int SHOW_NONE = 0; + private static final int SHOW_GHOST = 1; + private static final int SHOW_ADD = 2; + private static final int SHOW_ADD_NO = 3; - private static Cursor cursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); + private static final Cursor cursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); + private final FactoryDescription description; + private final AttributeSet attributes; private Class descriptionBase; - private FactoryDescription description; private boolean sourceLoadAttempted; private ComponentFactory factory; - private AttributeSet attributes; private Bounds bounds; private boolean shouldSnap; private int lastX = INVALID_COORDINATE; @@ -101,8 +101,7 @@ public boolean equals(Object object) { } AddTool addTool = (AddTool) object; if (this.description != null) { - return this.descriptionBase == addTool.descriptionBase - && this.description.equals(addTool.description); + return this.descriptionBase == addTool.descriptionBase && this.description.equals(addTool.description); } else { return this.factory.equals(addTool.factory); } @@ -122,15 +121,7 @@ public boolean sharesSource(Tool tool) { AddTool addTool = (AddTool) tool; try { if (this.sourceLoadAttempted && addTool.sourceLoadAttempted) { - // TODO Figure out why this causes errors on startup -// return this.factory.equals(addTool.factory); - // NOTE: This is my weak fix for the problem that keeps showing up - // when the NOT, AND, and OR Gates are still in default.templ - if (this.factory != null) { - return this.factory.equals(addTool.factory); - } else { - return false; - } + return this.factory.equals(addTool.factory); } else if (this.description == null) { return addTool.description == null; } else { @@ -148,9 +139,7 @@ public ComponentFactory getFactory(boolean forceLoad) { public ComponentFactory getFactory() { ComponentFactory factory = this.factory; - if (factory != null || sourceLoadAttempted) { - return factory; - } else { + if (factory == null && !sourceLoadAttempted) { factory = description.getFactory(descriptionBase); if (factory != null) { AttributeSet base = getBaseAttributes(); @@ -159,33 +148,32 @@ public ComponentFactory getFactory() { } this.factory = factory; sourceLoadAttempted = true; - return factory; } + return factory; } @Override public String getName() { - FactoryDescription desc = description; - return desc == null ? factory.getName() : desc.getName(); + FactoryDescription description = this.description; + return description == null ? factory.getName() : description.getName(); } @Override public String getDisplayName() { - FactoryDescription desc = description; - return desc == null ? factory.getDisplayName() : desc.getDisplayName(); + FactoryDescription description = this.description; + return description == null ? factory.getDisplayName() : description.getDisplayName(); } @Override public String getDescription() { String result; - FactoryDescription factoryDesc = this.description; - if (factoryDesc != null) { - result = factoryDesc.getToolTip(); + FactoryDescription description = this.description; + if (description != null) { + result = description.getToolTip(); } else { ComponentFactory source = getFactory(); if (source != null) { - result = (String) source.getFeature(ComponentFactory.TOOL_TIP, - getAttributeSet()); + result = (String) source.getFeature(ComponentFactory.TOOL_TIP, getAttributeSet()); } else { result = null; } @@ -209,7 +197,7 @@ public AttributeSet getAttributeSet() { @Override public boolean isAllDefaultValues(AttributeSet attributeSet, LogisimVersion version) { return this.attributes == attributeSet && attributeSet instanceof FactoryAttributes - && !((FactoryAttributes) attributeSet).isFactoryInstantiated(); + && !((FactoryAttributes) attributeSet).isFactoryInstantiated(); } @Override @@ -245,8 +233,8 @@ private AttributeSet getBaseAttributes() { return attributes; } - // TODO look into why this is here -// public void cancelOp() { } + public void cancelOp() { + } @Override public void select(Canvas canvas) { @@ -480,6 +468,7 @@ private void setFacing(Canvas canvas, Direction facing) { AttributeSet base = getBaseAttributes(); Object feature = source.getFeature(ComponentFactory.FACING_ATTRIBUTE_KEY, base); + @SuppressWarnings("unchecked") Attribute attribute = (Attribute) feature; if (attribute != null) { Action action = ToolAttributeAction.create(this, attribute, facing); @@ -507,8 +496,7 @@ public void paintIcon(ComponentDrawContext drawContext, int x, int y) { private void expose(java.awt.Component component, int x, int y) { Bounds bounds = getBounds(); - component.repaint(x + bounds.getX(), y + bounds.getY(), - bounds.getWidth(), bounds.getHeight()); + component.repaint(x + bounds.getX(), y + bounds.getY(), bounds.getWidth(), bounds.getHeight()); } @Override @@ -519,7 +507,7 @@ public Cursor getCursor() { private void setState(Canvas canvas, int value) { if (value == SHOW_GHOST) { if (canvas.getProject().getLogisimFile().contains(canvas.getCircuit()) - && AppPreferences.ADD_SHOW_GHOSTS.getBoolean()) { + && AppPreferences.ADD_SHOW_GHOSTS.getBoolean()) { state = SHOW_GHOST; } else { state = SHOW_NONE; diff --git a/src/main/java/com/cburch/logisim/tools/CaretEvent.java b/src/main/java/com/cburch/logisim/tools/CaretEvent.java index 9cce95d..bde4ffd 100644 --- a/src/main/java/com/cburch/logisim/tools/CaretEvent.java +++ b/src/main/java/com/cburch/logisim/tools/CaretEvent.java @@ -5,14 +5,14 @@ public class CaretEvent { - private Caret caret; - private String oldtext; - private String newtext; + private final Caret caret; + private final String oldText; + private final String newText; - public CaretEvent(Caret caret, String oldtext, String newtext) { + public CaretEvent(Caret caret, String oldText, String newText) { this.caret = caret; - this.oldtext = oldtext; - this.newtext = newtext; + this.oldText = oldText; + this.newText = newText; } public Caret getCaret() { @@ -20,10 +20,10 @@ public Caret getCaret() { } public String getOldText() { - return oldtext; + return oldText; } public String getText() { - return newtext; + return newText; } } diff --git a/src/main/java/com/cburch/logisim/tools/EditTool.java b/src/main/java/com/cburch/logisim/tools/EditTool.java index dbc7bee..945fd9f 100644 --- a/src/main/java/com/cburch/logisim/tools/EditTool.java +++ b/src/main/java/com/cburch/logisim/tools/EditTool.java @@ -36,20 +36,19 @@ public class EditTool extends Tool { private static final int CACHE_MAX_SIZE = 32; - private static final Location NULL_LOCATION - = Location.create(Integer.MIN_VALUE, Integer.MIN_VALUE); - private Listener listener; - private SelectTool select; - private WiringTool wiring; + private static final Location NULL_LOCATION = Location.create(Integer.MIN_VALUE, Integer.MIN_VALUE); + private final Listener listener; + private final SelectTool select; + private final WiringTool wiring; private Tool current; - private LinkedHashMap cache; + private final LinkedHashMap cache; private Canvas lastCanvas; private int lastRawX; private int lastRawY; private int lastX; // last coordinates where wiring was computed private int lastY; - private int lastMods; // last modifiers for mouse event - private Location wireLoc; // coordinates where to draw wiring indicator, if + private int lastModifiers; // last modifiers for mouse event + private Location wireLocation; // coordinates where to draw wiring indicator, if private int pressX; // last coordinate where mouse was pressed private int pressY; // (used to determine when a short wire has been clicked) @@ -60,7 +59,7 @@ public EditTool(SelectTool select, WiringTool wiring) { this.current = select; this.cache = new LinkedHashMap<>(); this.lastX = -1; - this.wireLoc = NULL_LOCATION; + this.wireLocation = NULL_LOCATION; this.pressX = -1; } @@ -121,10 +120,10 @@ public Set getHiddenComponents(Canvas canvas) { @Override public void draw(Canvas canvas, ComponentDrawContext context) { - Location loc = wireLoc; - if (loc != NULL_LOCATION && current != wiring) { - int x = loc.getX(); - int y = loc.getY(); + Location wireLocation = this.wireLocation; + if (wireLocation != NULL_LOCATION && current != wiring) { + int x = wireLocation.getX(); + int y = wireLocation.getY(); Graphics g = context.getGraphics(); g.setColor(Value.TRUE_COLOR); GraphicsUtil.switchToWidth(g, 2); @@ -156,27 +155,27 @@ public void deselect(Canvas canvas) { @Override public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { - boolean wire = updateLocation(canvas, e); - Location oldWireLoc = wireLoc; - wireLoc = NULL_LOCATION; + boolean isWire = updateLocation(canvas, e); + Location wireLocation = this.wireLocation; + this.wireLocation = NULL_LOCATION; lastX = Integer.MIN_VALUE; - if (wire) { + if (isWire) { current = wiring; - Selection sel = canvas.getSelection(); - Circuit circ = canvas.getCircuit(); - Collection selected = sel.getAnchoredComponents(); + Selection selection = canvas.getSelection(); + Circuit circuit = canvas.getCircuit(); + Collection selected = selection.getAnchoredComponents(); ArrayList suppress = null; - for (Wire w : circ.getWires()) { - if (selected.contains(w)) { - if (w.contains(oldWireLoc)) { + for (Wire wire : circuit.getWires()) { + if (selected.contains(wire)) { + if (wire.contains(wireLocation)) { if (suppress == null) { suppress = new ArrayList<>(); } - suppress.add(w); + suppress.add(wire); } } } - sel.setSuppressHandles(suppress); + selection.setSuppressHandles(suppress); } else { current = select; } @@ -193,10 +192,10 @@ public void mouseDragged(Canvas canvas, Graphics g, MouseEvent e) { @Override public void mouseReleased(Canvas canvas, Graphics g, MouseEvent e) { - boolean click = isClick(e) && current == wiring; + boolean isClick = isClick(e) && current == wiring; canvas.getSelection().setSuppressHandles(null); current.mouseReleased(canvas, g, e); - if (click) { + if (isClick) { wiring.resetClick(); select.mousePressed(canvas, g, e); select.mouseReleased(canvas, g, e); @@ -254,71 +253,71 @@ private boolean updateLocation(Canvas canvas, KeyEvent e) { } } - private boolean updateLocation(Canvas canvas, int mx, int my, int mods) { - int snapx = Canvas.snapXToGrid(mx); - int snapy = Canvas.snapYToGrid(my); - int dx = mx - snapx; - int dy = my - snapy; + private boolean updateLocation(Canvas canvas, int mx, int my, int modifiers) { + int snapX = Canvas.snapXToGrid(mx); + int snapY = Canvas.snapYToGrid(my); + int dx = mx - snapX; + int dy = my - snapY; boolean isEligible = dx * dx + dy * dy < 36; - if ((mods & MouseEvent.ALT_DOWN_MASK) != 0) { + if ((modifiers & MouseEvent.ALT_DOWN_MASK) != 0) { isEligible = true; } if (!isEligible) { - snapx = -1; - snapy = -1; + snapX = -1; + snapY = -1; } - boolean modsSame = lastMods == mods; + boolean isModifierEqual = lastModifiers == modifiers; lastCanvas = canvas; lastRawX = mx; lastRawY = my; - lastMods = mods; - if (lastX == snapx && lastY == snapy && modsSame) { // already computed - return wireLoc != NULL_LOCATION; + lastModifiers = modifiers; + if (lastX == snapX && lastY == snapY && isModifierEqual) { // already computed + return wireLocation != NULL_LOCATION; } else { - Location snap = Location.create(snapx, snapy); - if (modsSame) { - Object o = cache.get(snap); - if (o != null) { - lastX = snapx; - lastY = snapy; + Location snap = Location.create(snapX, snapY); + if (isModifierEqual) { + Boolean isSnap = cache.get(snap); + if (isSnap != null) { + lastX = snapX; + lastY = snapY; canvas.repaint(); - boolean ret = (Boolean) o; - wireLoc = ret ? snap : NULL_LOCATION; + boolean ret = isSnap; + wireLocation = ret ? snap : NULL_LOCATION; return ret; } } else { cache.clear(); } - boolean ret = isEligible && isWiringPoint(canvas, snap, mods); - wireLoc = ret ? snap : NULL_LOCATION; - cache.put(snap, ret); + boolean isValid = isEligible && isWiringPoint(canvas, snap, modifiers); + wireLocation = isValid ? snap : NULL_LOCATION; + cache.put(snap, isValid); int toRemove = cache.size() - CACHE_MAX_SIZE; - Iterator it = cache.keySet().iterator(); - while (it.hasNext() && toRemove > 0) { - it.next(); - it.remove(); + Iterator iterator = cache.keySet().iterator(); + while (iterator.hasNext() && toRemove > 0) { + iterator.next(); + iterator.remove(); toRemove--; } - lastX = snapx; - lastY = snapy; + lastX = snapX; + lastY = snapY; canvas.repaint(); - return ret; + return isValid; } } - private boolean isWiringPoint(Canvas canvas, Location loc, int modsEx) { + private boolean isWiringPoint(Canvas canvas, Location location, int modsEx) { boolean wiring = (modsEx & MouseEvent.ALT_DOWN_MASK) == 0; boolean select = !wiring; if (canvas != null && canvas.getSelection() != null) { - Collection sel = canvas.getSelection().getComponents(); - if (sel != null) { - for (Component c : sel) { - if (c instanceof Wire) { - Wire w = (Wire) c; - if (w.contains(loc) && !w.endsAt(loc)) { + Collection components = canvas.getSelection().getComponents(); + if (components != null) { + for (Component component : components) { + if (component instanceof Wire) { + Wire wire = (Wire) component; + if (wire.contains(location) && !wire.endsAt(location)) { return select; } } @@ -326,14 +325,14 @@ private boolean isWiringPoint(Canvas canvas, Location loc, int modsEx) { } } - Circuit circ = canvas.getCircuit(); - Collection at = circ.getComponents(loc); - if (at != null && at.size() > 0) { + Circuit circuit = canvas.getCircuit(); + Collection components = circuit.getComponents(location); + if (components != null && components.size() > 0) { return wiring; } - for (Wire w : circ.getWires()) { - if (w.contains(loc)) { + for (Wire wire : circuit.getWires()) { + if (wire.contains(location)) { return wiring; } } @@ -351,16 +350,16 @@ public void keyPressed(Canvas canvas, KeyEvent e) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: if (!canvas.getSelection().isEmpty()) { - Action act = SelectionActions.clear(canvas.getSelection()); - canvas.getProject().doAction(act); + Action action = SelectionActions.clear(canvas.getSelection()); + canvas.getProject().doAction(action); e.consume(); } else { wiring.keyPressed(canvas, e); } break; case KeyEvent.VK_INSERT: - Action act = SelectionActions.duplicate(canvas.getSelection()); - canvas.getProject().doAction(act); + Action action = SelectionActions.duplicate(canvas.getSelection()); + canvas.getProject().doAction(action); e.consume(); break; case KeyEvent.VK_UP: @@ -413,19 +412,19 @@ public void keyReleased(Canvas canvas, KeyEvent event) { private void attemptReface(Canvas canvas, final Direction facing, KeyEvent e) { if (e.getModifiersEx() == 0) { final Circuit circuit = canvas.getCircuit(); - final Selection sel = canvas.getSelection(); - SetAttributeAction act = new SetAttributeAction(circuit, - Strings.getter("selectionRefaceAction")); - for (Component comp : sel.getComponents()) { - if (!(comp instanceof Wire)) { - Attribute attr = getFacingAttribute(comp); + final Selection selection = canvas.getSelection(); + SetAttributeAction action = new SetAttributeAction(circuit, + Strings.getter("selectionRefaceAction")); + for (Component component : selection.getComponents()) { + if (!(component instanceof Wire)) { + Attribute attr = getFacingAttribute(component); if (attr != null) { - act.set(comp, attr, facing); + action.set(component, attr, facing); } } } - if (!act.isEmpty()) { - canvas.getProject().doAction(act); + if (!action.isEmpty()) { + canvas.getProject().doAction(action); e.consume(); } } @@ -434,9 +433,9 @@ private void attemptReface(Canvas canvas, final Direction facing, KeyEvent e) { private Attribute getFacingAttribute(Component comp) { AttributeSet attrs = comp.getAttributeSet(); Object key = ComponentFactory.FACING_ATTRIBUTE_KEY; - Attribute a = (Attribute) comp.getFactory().getFeature(key, attrs); + Attribute attr = (Attribute) comp.getFactory().getFeature(key, attrs); @SuppressWarnings("unchecked") - Attribute ret = (Attribute) a; + Attribute ret = (Attribute) attr; return ret; } @@ -451,14 +450,14 @@ public void circuitChanged(CircuitEvent event) { if (event.getAction() != CircuitEvent.ACTION_INVALIDATE) { lastX = -1; cache.clear(); - updateLocation(lastCanvas, lastRawX, lastRawY, lastMods); + updateLocation(lastCanvas, lastRawX, lastRawY, lastModifiers); } } public void selectionChanged(Event event) { lastX = -1; cache.clear(); - updateLocation(lastCanvas, lastRawX, lastRawY, lastMods); + updateLocation(lastCanvas, lastRawX, lastRawY, lastModifiers); } } } diff --git a/src/main/java/com/cburch/logisim/tools/FactoryAttributes.java b/src/main/java/com/cburch/logisim/tools/FactoryAttributes.java index 4e445c4..bd11cec 100644 --- a/src/main/java/com/cburch/logisim/tools/FactoryAttributes.java +++ b/src/main/java/com/cburch/logisim/tools/FactoryAttributes.java @@ -14,24 +14,23 @@ class FactoryAttributes implements AttributeSet, AttributeListener, Cloneable { - private Class descBase; - private FactoryDescription desc; + private final Class descriptionBase; + private final FactoryDescription description; + private final ArrayList listeners; private ComponentFactory factory; private AttributeSet baseAttrs; - private ArrayList listeners; - public FactoryAttributes(Class descBase, - FactoryDescription desc) { - this.descBase = descBase; - this.desc = desc; + public FactoryAttributes(Class descriptionBase, FactoryDescription description) { + this.descriptionBase = descriptionBase; + this.description = description; this.factory = null; this.baseAttrs = null; this.listeners = new ArrayList<>(); } public FactoryAttributes(ComponentFactory factory) { - this.descBase = null; - this.desc = null; + this.descriptionBase = null; + this.description = null; this.factory = factory; this.baseAttrs = null; this.listeners = new ArrayList<>(); @@ -44,15 +43,15 @@ boolean isFactoryInstantiated() { AttributeSet getBase() { AttributeSet ret = baseAttrs; if (ret == null) { - ComponentFactory fact = factory; - if (fact == null) { - fact = desc.getFactory(descBase); - factory = fact; + ComponentFactory factory = this.factory; + if (factory == null) { + factory = description.getFactory(descriptionBase); + this.factory = factory; } - if (fact == null) { + if (factory == null) { ret = AttributeSets.EMPTY; } else { - ret = fact.createAttributeSet(); + ret = factory.createAttributeSet(); ret.addAttributeListener(this); } baseAttrs = ret; @@ -106,24 +105,22 @@ public void setValue(Attribute attr, V value) { } public void attributeListChanged(AttributeEvent baseEvent) { - AttributeEvent e = null; - for (AttributeListener l : listeners) { - if (e == null) { - e = new AttributeEvent(this, baseEvent.getAttribute(), - baseEvent.getValue()); + AttributeEvent event = null; + for (AttributeListener listener : listeners) { + if (event == null) { + event = new AttributeEvent(this, baseEvent.getAttribute(), baseEvent.getValue()); } - l.attributeListChanged(e); + listener.attributeListChanged(event); } } public void attributeValueChanged(AttributeEvent baseEvent) { - AttributeEvent e = null; - for (AttributeListener l : listeners) { - if (e == null) { - e = new AttributeEvent(this, baseEvent.getAttribute(), - baseEvent.getValue()); + AttributeEvent event = null; + for (AttributeListener listener : listeners) { + if (event == null) { + event = new AttributeEvent(this, baseEvent.getAttribute(), baseEvent.getValue()); } - l.attributeValueChanged(e); + listener.attributeValueChanged(event); } } } diff --git a/src/main/java/com/cburch/logisim/tools/FactoryDescription.java b/src/main/java/com/cburch/logisim/tools/FactoryDescription.java index 1f83131..eef5e87 100644 --- a/src/main/java/com/cburch/logisim/tools/FactoryDescription.java +++ b/src/main/java/com/cburch/logisim/tools/FactoryDescription.java @@ -3,6 +3,7 @@ package com.cburch.logisim.tools; +import com.adlerd.logger.Logger; import com.cburch.logisim.comp.ComponentFactory; import com.cburch.logisim.util.Icons; import com.cburch.logisim.util.StringGetter; @@ -21,12 +22,12 @@ */ public class FactoryDescription { - private String name; - private StringGetter displayName; + private final String name; + private final StringGetter displayName; + private final String factoryClassName; private String iconName; private boolean iconLoadAttempted; private Icon icon; - private String factoryClassName; private boolean factoryLoadAttempted; private ComponentFactory factory; private StringGetter toolTip; @@ -79,14 +80,12 @@ public boolean isFactoryLoaded() { public Icon getIcon() { Icon icon = this.icon; - if (icon != null || iconLoadAttempted) { - return icon; - } else { + if (icon == null && !iconLoadAttempted) { icon = Icons.getIcon(iconName); this.icon = icon; iconLoadAttempted = true; - return icon; } + return icon; } public ComponentFactory getFactory(Class libraryClass) { @@ -126,7 +125,7 @@ public ComponentFactory getFactory(Class libraryClass) { message = message + ": " + name; } } - System.err.println("error while " + message); //OK + Logger.errorln("error while " + message); //OK this.factory = null; factoryLoadAttempted = true; return null; diff --git a/src/main/java/com/cburch/logisim/tools/Library.java b/src/main/java/com/cburch/logisim/tools/Library.java index c358c5d..0989a5c 100644 --- a/src/main/java/com/cburch/logisim/tools/Library.java +++ b/src/main/java/com/cburch/logisim/tools/Library.java @@ -74,9 +74,9 @@ public boolean contains(ComponentFactory query) { } public Library getLibrary(String name) { - for (Library lib : getLibraries()) { - if (lib.getName().equals(name)) { - return lib; + for (Library library : getLibraries()) { + if (library.getName().equals(name)) { + return library; } } return null; diff --git a/src/main/java/com/cburch/logisim/tools/MenuTool.java b/src/main/java/com/cburch/logisim/tools/MenuTool.java index fc0d71a..1b61e00 100644 --- a/src/main/java/com/cburch/logisim/tools/MenuTool.java +++ b/src/main/java/com/cburch/logisim/tools/MenuTool.java @@ -57,33 +57,31 @@ public String getDescription() { public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { int x = e.getX(); int y = e.getY(); - Location pt = Location.create(x, y); + Location point = Location.create(x, y); JPopupMenu menu; - Project proj = canvas.getProject(); - Selection sel = proj.getSelection(); - Collection in_sel = sel.getComponentsContaining(pt, g); - if (!in_sel.isEmpty()) { - Component comp = in_sel.iterator().next(); - if (sel.getComponents().size() > 1) { - menu = new MenuSelection(proj); + Project project = canvas.getProject(); + Selection selection = project.getSelection(); + Collection components = selection.getComponentsContaining(point, g); + if (!components.isEmpty()) { + Component component = components.iterator().next(); + if (selection.getComponents().size() > 1) { + menu = new MenuSelection(project); } else { - menu = new MenuComponent(proj, - canvas.getCircuit(), comp); - MenuExtender extender = (MenuExtender) comp.getFeature(MenuExtender.class); + menu = new MenuComponent(project, canvas.getCircuit(), component); + MenuExtender extender = (MenuExtender) component.getFeature(MenuExtender.class); if (extender != null) { - extender.configureMenu(menu, proj); + extender.configureMenu(menu, project); } } } else { - Collection cl = canvas.getCircuit().getAllContaining(pt, g); - if (!cl.isEmpty()) { - Component comp = cl.iterator().next(); - menu = new MenuComponent(proj, - canvas.getCircuit(), comp); - MenuExtender extender = (MenuExtender) comp.getFeature(MenuExtender.class); + Collection allContaining = canvas.getCircuit().getAllContaining(point, g); + if (!allContaining.isEmpty()) { + Component component = allContaining.iterator().next(); + menu = new MenuComponent(project, canvas.getCircuit(), component); + MenuExtender extender = (MenuExtender) component.getFeature(MenuExtender.class); if (extender != null) { - extender.configureMenu(menu, proj); + extender.configureMenu(menu, project); } } else { menu = null; @@ -96,82 +94,81 @@ public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { } @Override - public void paintIcon(ComponentDrawContext c, int x, int y) { - Graphics g = c.getGraphics(); + public void paintIcon(ComponentDrawContext context, int x, int y) { + Graphics g = context.getGraphics(); g.fillRect(x + 2, y + 1, 9, 2); g.drawRect(x + 2, y + 3, 15, 12); g.setColor(Color.lightGray); g.drawLine(x + 4, y + 2, x + 8, y + 2); - for (int y_offs = y + 6; y_offs < y + 15; y_offs += 3) { - g.drawLine(x + 4, y_offs, x + 14, y_offs); + for (int yOffset = y + 6; yOffset < y + 15; yOffset += 3) { + g.drawLine(x + 4, yOffset, x + 14, yOffset); } } - private class MenuComponent extends JPopupMenu - implements ActionListener { - - Project proj; - Circuit circ; - Component comp; - JMenuItem del = new JMenuItem(Strings.get("compDeleteItem")); - JMenuItem attrs = new JMenuItem(Strings.get("compShowAttrItem")); - - MenuComponent(Project proj, Circuit circ, Component comp) { - this.proj = proj; - this.circ = circ; - this.comp = comp; - boolean canChange = proj.getLogisimFile().contains(circ); - - add(del); - del.addActionListener(this); - del.setEnabled(canChange); - add(attrs); - attrs.addActionListener(this); + private static class MenuComponent extends JPopupMenu implements ActionListener { + + Project project; + Circuit circuit; + Component component; + JMenuItem deleteItem = new JMenuItem(Strings.get("compDeleteItem")); + JMenuItem showAttrItem = new JMenuItem(Strings.get("compShowAttrItem")); + + MenuComponent(Project project, Circuit circuit, Component component) { + this.project = project; + this.circuit = circuit; + this.component = component; + boolean canChange = project.getLogisimFile().contains(circuit); + + add(deleteItem); + deleteItem.addActionListener(this); + deleteItem.setEnabled(canChange); + add(showAttrItem); + showAttrItem.addActionListener(this); } public void actionPerformed(ActionEvent e) { - Object src = e.getSource(); - if (src == del) { - Circuit circ = proj.getCurrentCircuit(); - CircuitMutation xn = new CircuitMutation(circ); - xn.remove(comp); - proj.doAction(xn.toAction(Strings.getter("removeComponentAction", comp.getFactory().getDisplayGetter()))); - } else if (src == attrs) { - proj.getFrame().viewComponentAttributes(circ, comp); + Object source = e.getSource(); + if (source == deleteItem) { + Circuit circuit = project.getCurrentCircuit(); + CircuitMutation mutation = new CircuitMutation(circuit); + mutation.remove(component); + project.doAction( + mutation.toAction(Strings.getter("removeComponentAction", component.getFactory().getDisplayGetter()))); + } else if (source == showAttrItem) { + project.getFrame().viewComponentAttributes(circuit, component); } } } - private class MenuSelection extends JPopupMenu - implements ActionListener { - - Project proj; - JMenuItem del = new JMenuItem(Strings.get("selDeleteItem")); - JMenuItem cut = new JMenuItem(Strings.get("selCutItem")); - JMenuItem copy = new JMenuItem(Strings.get("selCopyItem")); - - MenuSelection(Project proj) { - this.proj = proj; - boolean canChange = proj.getLogisimFile().contains(proj.getCurrentCircuit()); - add(del); - del.addActionListener(this); - del.setEnabled(canChange); - add(cut); - cut.addActionListener(this); - cut.setEnabled(canChange); - add(copy); - copy.addActionListener(this); + private static class MenuSelection extends JPopupMenu implements ActionListener { + + Project project; + JMenuItem deleteItem = new JMenuItem(Strings.get("selDeleteItem")); + JMenuItem cutItem = new JMenuItem(Strings.get("selCutItem")); + JMenuItem copyItem = new JMenuItem(Strings.get("selCopyItem")); + + MenuSelection(Project project) { + this.project = project; + boolean canChange = project.getLogisimFile().contains(project.getCurrentCircuit()); + add(deleteItem); + deleteItem.addActionListener(this); + deleteItem.setEnabled(canChange); + add(cutItem); + cutItem.addActionListener(this); + cutItem.setEnabled(canChange); + add(copyItem); + copyItem.addActionListener(this); } public void actionPerformed(ActionEvent e) { - Object src = e.getSource(); - Selection sel = proj.getSelection(); - if (src == del) { - proj.doAction(SelectionActions.clear(sel)); - } else if (src == cut) { - proj.doAction(SelectionActions.cut(sel)); - } else if (src == copy) { - proj.doAction(SelectionActions.copy(sel)); + Object source = e.getSource(); + Selection sel = project.getSelection(); + if (source == deleteItem) { + project.doAction(SelectionActions.clear(sel)); + } else if (source == cutItem) { + project.doAction(SelectionActions.cut(sel)); + } else if (source == copyItem) { + project.doAction(SelectionActions.copy(sel)); } } diff --git a/src/main/java/com/cburch/logisim/tools/PokeTool.java b/src/main/java/com/cburch/logisim/tools/PokeTool.java index 70d043a..18c80b5 100644 --- a/src/main/java/com/cburch/logisim/tools/PokeTool.java +++ b/src/main/java/com/cburch/logisim/tools/PokeTool.java @@ -31,9 +31,8 @@ public class PokeTool extends Tool { private static final Icon toolIcon = Icons.getIcon("poke.gif"); private static final Color caretColor = new Color(255, 255, 150); - private static Cursor cursor - = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); - private Listener listener; + private static final Cursor cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); + private final Listener listener; private Circuit pokedCircuit; private Component pokedComponent; private Caret pokeCaret; @@ -63,7 +62,7 @@ public String getDisplayName() { } private void removeCaret(boolean normal) { - Circuit circ = pokedCircuit; + Circuit circuit = pokedCircuit; Caret caret = pokeCaret; if (caret != null) { if (normal) { @@ -71,20 +70,20 @@ private void removeCaret(boolean normal) { } else { caret.cancelEditing(); } - circ.removeCircuitListener(listener); + circuit.removeCircuitListener(listener); pokedCircuit = null; pokedComponent = null; pokeCaret = null; } } - private void setPokedComponent(Circuit circ, Component comp, Caret caret) { + private void setPokedComponent(Circuit circuit, Component component, Caret caret) { removeCaret(true); - pokedCircuit = circ; - pokedComponent = comp; + pokedCircuit = circuit; + pokedComponent = component; pokeCaret = caret; if (caret != null) { - circ.addCircuitListener(listener); + circuit.addCircuitListener(listener); } } @@ -110,45 +109,45 @@ public void deselect(Canvas canvas) { public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { int x = e.getX(); int y = e.getY(); - Location loc = Location.create(x, y); - boolean dirty = false; + Location location = Location.create(x, y); + boolean isDirty = false; canvas.setHighlightedWires(WireSet.EMPTY); - if (pokeCaret != null && !pokeCaret.getBounds(g).contains(loc)) { - dirty = true; + if (pokeCaret != null && !pokeCaret.getBounds(g).contains(location)) { + isDirty = true; removeCaret(true); } if (pokeCaret == null) { ComponentUserEvent event = new ComponentUserEvent(canvas, x, y); - Circuit circ = canvas.getCircuit(); - for (Component c : circ.getAllContaining(loc, g)) { + Circuit circuit = canvas.getCircuit(); + for (Component component : circuit.getAllContaining(location, g)) { if (pokeCaret != null) { break; } - if (c instanceof Wire) { - Caret caret = new WireCaret(canvas, (Wire) c, x, y, - canvas.getProject().getOptions().getAttributeSet()); - setPokedComponent(circ, c, caret); - canvas.setHighlightedWires(circ.getWireSet((Wire) c)); + if (component instanceof Wire) { + Caret caret = new WireCaret(canvas, (Wire) component, x, y, + canvas.getProject().getOptions().getAttributeSet()); + setPokedComponent(circuit, component, caret); + canvas.setHighlightedWires(circuit.getWireSet((Wire) component)); } else { - Pokable p = (Pokable) c.getFeature(Pokable.class); - if (p != null) { - Caret caret = p.getPokeCaret(event); - setPokedComponent(circ, c, caret); - AttributeSet attrs = c.getAttributeSet(); + Pokable pokable = (Pokable) component.getFeature(Pokable.class); + if (pokable != null) { + Caret caret = pokable.getPokeCaret(event); + setPokedComponent(circuit, component, caret); + AttributeSet attrs = component.getAttributeSet(); if (attrs != null && attrs.getAttributes().size() > 0) { - Project proj = canvas.getProject(); - proj.getFrame().viewComponentAttributes(circ, c); + Project project = canvas.getProject(); + project.getFrame().viewComponentAttributes(circuit, component); } } } } } if (pokeCaret != null) { - dirty = true; + isDirty = true; pokeCaret.mousePressed(e); } - if (dirty) { + if (isDirty) { canvas.getProject().repaintCanvas(); } } @@ -217,53 +216,49 @@ public Cursor getCursor() { private static class WireCaret extends AbstractCaret { - AttributeSet opts; + AttributeSet options; Canvas canvas; Wire wire; int x; int y; - WireCaret(Canvas c, Wire w, int x, int y, AttributeSet opts) { - canvas = c; - wire = w; + WireCaret(Canvas canvas, Wire wire, int x, int y, AttributeSet options) { + this.canvas = canvas; + this.wire = wire; this.x = x; this.y = y; - this.opts = opts; + this.options = options; } @Override public void draw(Graphics g) { - Value v = canvas.getCircuitState().getValue(wire.getEnd0()); + Value value = canvas.getCircuitState().getValue(wire.getEnd0()); RadixOption radix1 = RadixOption.decode(AppPreferences.POKE_WIRE_RADIX1.get()); RadixOption radix2 = RadixOption.decode(AppPreferences.POKE_WIRE_RADIX2.get()); if (radix1 == null) { radix1 = RadixOption.RADIX_2; } - String vStr = radix1.toString(v); - if (radix2 != null && v.getWidth() > 1) { - vStr += " / " + radix2.toString(v); + String valueString = radix1.toString(value); + if (radix2 != null && value.getWidth() > 1) { + valueString += " / " + radix2.toString(value); } FontMetrics fm = g.getFontMetrics(); g.setColor(caretColor); - g.fillRect(x + 2, y + 2, fm.stringWidth(vStr) + 4, - fm.getAscent() + fm.getDescent() + 4); + g.fillRect(x + 2, y + 2, fm.stringWidth(valueString) + 4, fm.getAscent() + fm.getDescent() + 4); g.setColor(Color.BLACK); - g.drawRect(x + 2, y + 2, fm.stringWidth(vStr) + 4, - fm.getAscent() + fm.getDescent() + 4); + g.drawRect(x + 2, y + 2, fm.stringWidth(valueString) + 4, fm.getAscent() + fm.getDescent() + 4); g.fillOval(x - 2, y - 2, 5, 5); - g.drawString(vStr, x + 4, y + 4 + fm.getAscent()); + g.drawString(valueString, x + 4, y + 4 + fm.getAscent()); } } private class Listener implements CircuitListener { public void circuitChanged(CircuitEvent event) { - Circuit circ = pokedCircuit; - if (event.getCircuit() == circ && circ != null - && (event.getAction() == CircuitEvent.ACTION_REMOVE - || event.getAction() == CircuitEvent.ACTION_CLEAR) - && !circ.contains(pokedComponent)) { + Circuit circuit = pokedCircuit; + if (event.getCircuit() == circuit && circuit != null && (event.getAction() == CircuitEvent.ACTION_REMOVE + || event.getAction() == CircuitEvent.ACTION_CLEAR) && !circuit.contains(pokedComponent)) { removeCaret(false); } } diff --git a/src/main/java/com/cburch/logisim/tools/SelectTool.java b/src/main/java/com/cburch/logisim/tools/SelectTool.java index f642e9c..7625616 100644 --- a/src/main/java/com/cburch/logisim/tools/SelectTool.java +++ b/src/main/java/com/cburch/logisim/tools/SelectTool.java @@ -46,12 +46,9 @@ public class SelectTool extends Tool { - private static final Cursor selectCursor - = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); - private static final Cursor rectSelectCursor - = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); - private static final Cursor moveCursor - = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); + private static final Cursor selectCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); + private static final Cursor rectSelectCursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); + private static final Cursor moveCursor = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR); private static final int IDLE = 0; private static final int MOVING = 1; @@ -62,29 +59,29 @@ public class SelectTool extends Tool { private static final Color COLOR_COMPUTING = new Color(96, 192, 96); private static final Color COLOR_RECT_SELECT = new Color(0, 64, 128, 255); private static final Color BACKGROUND_RECT_SELECT = new Color(192, 192, 255, 192); + private final HashSet selectionsAdded; + private final Listener selectionListener; private Location start; private int state; - private int curDx; - private int curDy; + private int currentDx; + private int currentDy; private boolean drawConnections; private MoveGesture moveGesture; private HashMap keyHandlers; - private HashSet selectionsAdded; - private Listener selListener; public SelectTool() { start = null; state = IDLE; selectionsAdded = new HashSet<>(); - selListener = new Listener(); + selectionListener = new Listener(); keyHandlers = null; } private static void clearCanvasMessage(Canvas canvas, int dx, int dy) { Object getter = canvas.getErrorMessage(); if (getter instanceof ComputingMessage) { - ComputingMessage msg = (ComputingMessage) getter; - if (msg.dx == dx && msg.dy == dy) { + ComputingMessage message = (ComputingMessage) getter; + if (message.dx == dx && message.dy == dy) { canvas.setErrorMessage(null); canvas.repaint(); } @@ -128,11 +125,11 @@ public boolean isAllDefaultValues(AttributeSet attributeSet, LogisimVersion vers @Override public void draw(Canvas canvas, ComponentDrawContext context) { - Project proj = canvas.getProject(); - int dx = curDx; - int dy = curDy; + Project project = canvas.getProject(); + int dx = currentDx; + int dy = currentDy; if (state == MOVING) { - proj.getSelection().drawGhostsShifted(context, dx, dy); + project.getSelection().drawGhostsShifted(context, dx, dy); MoveGesture gesture = moveGesture; if (gesture != null && drawConnections && (dx != 0 || dy != 0)) { @@ -142,19 +139,18 @@ public void draw(Canvas canvas, ComponentDrawContext context) { Graphics g = context.getGraphics(); GraphicsUtil.switchToWidth(g, 3); g.setColor(Color.GRAY); - for (Wire w : wiresToAdd) { - Location loc0 = w.getEnd0(); - Location loc1 = w.getEnd1(); - g.drawLine(loc0.getX(), loc0.getY(), - loc1.getX(), loc1.getY()); + for (Wire wire : wiresToAdd) { + Location location0 = wire.getEnd0(); + Location location1 = wire.getEnd1(); + g.drawLine(location0.getX(), location0.getY(), location1.getX(), location1.getY()); } GraphicsUtil.switchToWidth(g, 1); g.setColor(COLOR_UNMATCHED); - for (Location conn : result.getUnconnectedLocations()) { - int connX = conn.getX(); - int connY = conn.getY(); - g.fillOval(connX - 3, connY - 3, 6, 6); - g.fillOval(connX + dx - 3, connY + dy - 3, 6, 6); + for (Location connection : result.getUnconnectedLocations()) { + int connectionX = connection.getX(); + int connectionY = connection.getY(); + g.fillOval(connectionX - 3, connectionY - 3, 6, 6); + g.fillOval(connectionX + dx - 3, connectionY + dy - 3, 6, 6); } } } @@ -175,33 +171,33 @@ public void draw(Canvas canvas, ComponentDrawContext context) { } Graphics gBase = context.getGraphics(); - int w = right - left - 1; - int h = bot - top - 1; - if (w > 2 && h > 2) { + int width = right - left - 1; + int height = bot - top - 1; + if (width > 2 && height > 2) { gBase.setColor(BACKGROUND_RECT_SELECT); - gBase.fillRect(left + 1, top + 1, w - 1, h - 1); + gBase.fillRect(left + 1, top + 1, width - 1, height - 1); } - Circuit circ = canvas.getCircuit(); - Bounds bds = Bounds.create(left, top, right - left, bot - top); - for (Component c : circ.getAllWithin(bds)) { - Location cloc = c.getLocation(); + Circuit circuit = canvas.getCircuit(); + Bounds bounds = Bounds.create(left, top, right - left, bot - top); + for (Component component : circuit.getAllWithin(bounds)) { + Location componentLocation = component.getLocation(); Graphics gDup = gBase.create(); context.setGraphics(gDup); - c.getFactory().drawGhost(context, COLOR_RECT_SELECT, - cloc.getX(), cloc.getY(), c.getAttributeSet()); + component.getFactory().drawGhost(context, COLOR_RECT_SELECT, componentLocation.getX(), + componentLocation.getY(), component.getAttributeSet()); gDup.dispose(); } gBase.setColor(COLOR_RECT_SELECT); GraphicsUtil.switchToWidth(gBase, 2); - if (w < 0) { - w = 0; + if (width < 0) { + width = 0; } - if (h < 0) { - h = 0; + if (height < 0) { + height = 0; } - gBase.drawRect(left, top, w, h); + gBase.drawRect(left, top, width, height); } } @@ -209,7 +205,7 @@ public void draw(Canvas canvas, ComponentDrawContext context) { public void select(Canvas canvas) { Selection sel = canvas.getSelection(); if (!selectionsAdded.contains(sel)) { - sel.addListener(selListener); + sel.addListener(selectionListener); } } @@ -225,26 +221,26 @@ public void mouseEntered(Canvas canvas, Graphics g, MouseEvent e) { @Override public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { - Project proj = canvas.getProject(); - Selection sel = proj.getSelection(); + Project project = canvas.getProject(); + Selection selection = project.getSelection(); Circuit circuit = canvas.getCircuit(); start = Location.create(e.getX(), e.getY()); - curDx = 0; - curDy = 0; + currentDx = 0; + currentDy = 0; moveGesture = null; // if the user clicks into the selection, // selection is being modified - Collection in_sel = sel.getComponentsContaining(start, g); - if (!in_sel.isEmpty()) { - if ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0) { - setState(proj, MOVING); - proj.repaintCanvas(); + Collection selected = selection.getComponentsContaining(start, g); + if (!selected.isEmpty()) { + if ((e.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) == 0) { + setState(project, MOVING); + project.repaintCanvas(); return; } else { - Action act = SelectionActions.drop(sel, in_sel); + Action act = SelectionActions.drop(selection, selected); if (act != null) { - proj.doAction(act); + project.doAction(act); } } } @@ -253,67 +249,65 @@ public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { // wants to add/reset selection Collection clicked = circuit.getAllContaining(start, g); if (!clicked.isEmpty()) { - if ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0) { - if (sel.getComponentsContaining(start).isEmpty()) { - Action act = SelectionActions.dropAll(sel); - if (act != null) { - proj.doAction(act); + if ((e.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) == 0) { + if (selection.getComponentsContaining(start).isEmpty()) { + Action action = SelectionActions.dropAll(selection); + if (action != null) { + project.doAction(action); } } } - for (Component comp : clicked) { - if (!in_sel.contains(comp)) { - sel.add(comp); + for (Component component : clicked) { + if (!selected.contains(component)) { + selection.add(component); } } - setState(proj, MOVING); - proj.repaintCanvas(); + setState(project, MOVING); + project.repaintCanvas(); return; } - // The user clicked on the background. This is a rectangular - // selection (maybe with the shift key down). - if ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0) { - Action act = SelectionActions.dropAll(sel); - if (act != null) { - proj.doAction(act); + // The user clicked on the background. This is a rectangular selection (maybe with the shift key down). + if ((e.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) == 0) { + Action action = SelectionActions.dropAll(selection); + if (action != null) { + project.doAction(action); } } - setState(proj, RECT_SELECT); - proj.repaintCanvas(); + setState(project, RECT_SELECT); + project.repaintCanvas(); } @Override public void mouseDragged(Canvas canvas, Graphics g, MouseEvent e) { if (state == MOVING) { - Project proj = canvas.getProject(); - computeDxDy(proj, e, g); - handleMoveDrag(canvas, curDx, curDy, e.getModifiersEx()); + Project project = canvas.getProject(); + computeDxDy(project, e, g); + handleMoveDrag(canvas, currentDx, currentDy, e.getModifiersEx()); } else if (state == RECT_SELECT) { - Project proj = canvas.getProject(); - curDx = e.getX() - start.getX(); - curDy = e.getY() - start.getY(); - proj.repaintCanvas(); + Project project = canvas.getProject(); + currentDx = e.getX() - start.getX(); + currentDy = e.getY() - start.getY(); + project.repaintCanvas(); } } private void handleMoveDrag(Canvas canvas, int dx, int dy, int modsEx) { - boolean connect = shouldConnect(canvas, modsEx); - drawConnections = connect; - if (connect) { + boolean shouldConnect = shouldConnect(canvas, modsEx); + drawConnections = shouldConnect; + if (shouldConnect) { MoveGesture gesture = moveGesture; if (gesture == null) { - gesture = new MoveGesture(new MoveRequestHandler(canvas), - canvas.getCircuit(), canvas.getSelection().getAnchoredComponents()); + gesture = new MoveGesture(new MoveRequestHandler(canvas), canvas.getCircuit(), + canvas.getSelection().getAnchoredComponents()); moveGesture = gesture; } if (dx != 0 || dy != 0) { boolean queued = gesture.enqueueRequest(dx, dy); if (queued) { canvas.setErrorMessage(new ComputingMessage(dx, dy), COLOR_COMPUTING); - // maybe CPU scheduled led the request to be satisfied - // just before the "if(queued)" statement. In any case, it - // doesn't hurt to check to ensure the message belongs. + // maybe CPU scheduled led the request to be satisfied just before the "if(queued)" statement. In any + // case, it doesn't hurt to check to ensure the message belongs. if (gesture.findResult(dx, dy) != null) { clearCanvasMessage(canvas, dx, dy); } @@ -324,82 +318,81 @@ private void handleMoveDrag(Canvas canvas, int dx, int dy, int modsEx) { } private boolean shouldConnect(Canvas canvas, int modsEx) { - boolean shiftReleased = (modsEx & MouseEvent.SHIFT_DOWN_MASK) == 0; - boolean dflt = AppPreferences.MOVE_KEEP_CONNECT.getBoolean(); - if (shiftReleased) { - return dflt; + boolean isShiftReleased = (modsEx & MouseEvent.SHIFT_DOWN_MASK) == 0; + boolean isDefault = AppPreferences.MOVE_KEEP_CONNECT.getBoolean(); + if (isShiftReleased) { + return isDefault; } else { - return !dflt; + return !isDefault; } } @Override public void mouseReleased(Canvas canvas, Graphics g, MouseEvent e) { - Project proj = canvas.getProject(); + Project project = canvas.getProject(); if (state == MOVING) { - setState(proj, IDLE); - computeDxDy(proj, e, g); - int dx = curDx; - int dy = curDy; + setState(project, IDLE); + computeDxDy(project, e, g); + int dx = currentDx; + int dy = currentDy; if (dx != 0 || dy != 0) { - if (!proj.getLogisimFile().contains(canvas.getCircuit())) { + if (!project.getLogisimFile().contains(canvas.getCircuit())) { canvas.setErrorMessage(Strings.getter("cannotModifyError")); - } else if (proj.getSelection().hasConflictWhenMoved(dx, dy)) { + } else if (project.getSelection().hasConflictWhenMoved(dx, dy)) { canvas.setErrorMessage(Strings.getter("exclusiveError")); } else { - boolean connect = shouldConnect(canvas, e.getModifiersEx()); + boolean shouldConnect = shouldConnect(canvas, e.getModifiersEx()); drawConnections = false; - ReplacementMap repl; - if (connect) { + ReplacementMap replacementMap; + if (shouldConnect) { MoveGesture gesture = moveGesture; if (gesture == null) { - gesture = new MoveGesture(new MoveRequestHandler(canvas), - canvas.getCircuit(), canvas.getSelection().getAnchoredComponents()); + gesture = new MoveGesture(new MoveRequestHandler(canvas), canvas.getCircuit(), + canvas.getSelection().getAnchoredComponents()); } canvas.setErrorMessage(new ComputingMessage(dx, dy), COLOR_COMPUTING); MoveResult result = gesture.forceRequest(dx, dy); clearCanvasMessage(canvas, dx, dy); - repl = result.getReplacementMap(); + replacementMap = result.getReplacementMap(); } else { - repl = null; + replacementMap = null; } - Selection sel = proj.getSelection(); - proj.doAction(SelectionActions.translate(sel, dx, dy, repl)); + Selection selection = project.getSelection(); + project.doAction(SelectionActions.translate(selection, dx, dy, replacementMap)); } } moveGesture = null; - proj.repaintCanvas(); + project.repaintCanvas(); } else if (state == RECT_SELECT) { - Bounds bds = Bounds.create(start).add(start.getX() + curDx, - start.getY() + curDy); + Bounds bounds = Bounds.create(start).add(start.getX() + currentDx, start.getY() + currentDy); Circuit circuit = canvas.getCircuit(); - Selection sel = proj.getSelection(); - Collection in_sel = sel.getComponentsWithin(bds, g); - for (Component comp : circuit.getAllWithin(bds, g)) { - if (!in_sel.contains(comp)) { - sel.add(comp); + Selection selection = project.getSelection(); + Collection componentsWithin = selection.getComponentsWithin(bounds, g); + for (Component component : circuit.getAllWithin(bounds, g)) { + if (!componentsWithin.contains(component)) { + selection.add(component); } } - Action act = SelectionActions.drop(sel, in_sel); - if (act != null) { - proj.doAction(act); + Action action = SelectionActions.drop(selection, componentsWithin); + if (action != null) { + project.doAction(action); } - setState(proj, IDLE); - proj.repaintCanvas(); + setState(project, IDLE); + project.repaintCanvas(); } } @Override public void keyPressed(Canvas canvas, KeyEvent e) { if (state == MOVING && e.getKeyCode() == KeyEvent.VK_SHIFT) { - handleMoveDrag(canvas, curDx, curDy, e.getModifiersEx()); + handleMoveDrag(canvas, currentDx, currentDy, e.getModifiersEx()); } else { switch (e.getKeyCode()) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: if (!canvas.getSelection().isEmpty()) { - Action act = SelectionActions.clear(canvas.getSelection()); - canvas.getProject().doAction(act); + Action action = SelectionActions.clear(canvas.getSelection()); + canvas.getProject().doAction(action); e.consume(); } break; @@ -412,7 +405,7 @@ public void keyPressed(Canvas canvas, KeyEvent e) { @Override public void keyReleased(Canvas canvas, KeyEvent e) { if (state == MOVING && e.getKeyCode() == KeyEvent.VK_SHIFT) { - handleMoveDrag(canvas, curDx, curDy, e.getModifiersEx()); + handleMoveDrag(canvas, currentDx, currentDy, e.getModifiersEx()); } else { processKeyEvent(canvas, e, KeyConfigurationEvent.KEY_RELEASED); } @@ -427,80 +420,78 @@ private void processKeyEvent(Canvas canvas, KeyEvent e, int type) { HashMap handlers = keyHandlers; if (handlers == null) { handlers = new HashMap<>(); - Selection sel = canvas.getSelection(); - for (Component comp : sel.getComponents()) { - ComponentFactory factory = comp.getFactory(); - AttributeSet attrs = comp.getAttributeSet(); + Selection selection = canvas.getSelection(); + for (Component component : selection.getComponents()) { + ComponentFactory factory = component.getFactory(); + AttributeSet attrs = component.getAttributeSet(); Object handler = factory.getFeature(KeyConfigurator.class, attrs); if (handler != null) { KeyConfigurator base = (KeyConfigurator) handler; - handlers.put(comp, base.clone()); + handlers.put(component, base.clone()); } } keyHandlers = handlers; } if (!handlers.isEmpty()) { - boolean consume = false; - ArrayList results; - results = new ArrayList<>(); + boolean shouldConsume = false; + ArrayList results = new ArrayList<>(); for (Map.Entry entry : handlers.entrySet()) { - Component comp = entry.getKey(); + Component component = entry.getKey(); KeyConfigurator handler = entry.getValue(); - KeyConfigurationEvent event = new KeyConfigurationEvent(type, - comp.getAttributeSet(), e, comp); + KeyConfigurationEvent event = new KeyConfigurationEvent(type, component.getAttributeSet(), e, component); KeyConfigurationResult result = handler.keyEventReceived(event); - consume |= event.isConsumed(); + shouldConsume |= event.isConsumed(); if (result != null) { results.add(result); } } - if (consume) { + if (shouldConsume) { e.consume(); } if (!results.isEmpty()) { - SetAttributeAction act = new SetAttributeAction(canvas.getCircuit(), - Strings.getter("changeComponentAttributesAction")); + SetAttributeAction action = new SetAttributeAction(canvas.getCircuit(), + Strings.getter("changeComponentAttributesAction")); for (KeyConfigurationResult result : results) { - Component comp = (Component) result.getEvent().getData(); + Component component = (Component) result.getEvent().getData(); Map, Object> newValues = result.getAttributeValues(); for (Map.Entry, Object> entry : newValues.entrySet()) { - act.set(comp, entry.getKey(), entry.getValue()); + action.set(component, entry.getKey(), entry.getValue()); } } - if (!act.isEmpty()) { - canvas.getProject().doAction(act); + if (!action.isEmpty()) { + canvas.getProject().doAction(action); } } } } - private void computeDxDy(Project proj, MouseEvent e, Graphics g) { - Bounds bds = proj.getSelection().getBounds(g); + private void computeDxDy(Project project, MouseEvent e, Graphics g) { + Bounds bounds = project.getSelection().getBounds(g); int dx; int dy; - if (bds == Bounds.EMPTY_BOUNDS) { + if (bounds == Bounds.EMPTY_BOUNDS) { dx = e.getX() - start.getX(); dy = e.getY() - start.getY(); } else { - dx = Math.max(e.getX() - start.getX(), -bds.getX()); - dy = Math.max(e.getY() - start.getY(), -bds.getY()); + dx = Math.max(e.getX() - start.getX(), -bounds.getX()); + dy = Math.max(e.getY() - start.getY(), -bounds.getY()); } - Selection sel = proj.getSelection(); - if (sel.shouldSnap()) { + Selection selection = project.getSelection(); + if (selection.shouldSnap()) { dx = Canvas.snapXToGrid(dx); dy = Canvas.snapYToGrid(dy); } - curDx = dx; - curDy = dy; + currentDx = dx; + currentDy = dy; } @Override - public void paintIcon(ComponentDrawContext c, int x, int y) { - Graphics g = c.getGraphics(); + public void paintIcon(ComponentDrawContext context, int x, int y) { + Graphics g = context.getGraphics(); if (toolIcon != null) { - toolIcon.paintIcon(c.getDestination(), g, x + 2, y + 2); + toolIcon.paintIcon(context.getDestination(), g, x + 2, y + 2); } else { int[] xp = {x + 5, x + 5, x + 9, x + 12, x + 14, x + 11, x + 16}; int[] yp = {y, y + 17, y + 12, y + 18, y + 18, y + 12, y + 12}; @@ -512,46 +503,46 @@ public void paintIcon(ComponentDrawContext c, int x, int y) { @Override public Cursor getCursor() { return state == IDLE ? selectCursor : - (state == RECT_SELECT ? rectSelectCursor : moveCursor); + (state == RECT_SELECT ? rectSelectCursor : moveCursor); } @Override public Set getHiddenComponents(Canvas canvas) { if (state == MOVING) { - int dx = curDx; - int dy = curDy; + int dx = currentDx; + int dy = currentDy; if (dx == 0 && dy == 0) { return null; } - Set sel = canvas.getSelection().getComponents(); + Set components = canvas.getSelection().getComponents(); MoveGesture gesture = moveGesture; if (gesture != null && drawConnections) { MoveResult result = gesture.findResult(dx, dy); if (result != null) { - HashSet ret = new HashSet<>(sel); + HashSet ret = new HashSet<>(components); ret.addAll(result.getReplacementMap().getRemovals()); return ret; } } - return sel; + return components; } else { return null; } } - private void setState(Project proj, int new_state) { - if (state == new_state) { + private void setState(Project project, int newState) { + if (state == newState) { return; // do nothing if state not new } - state = new_state; - proj.getFrame().getCanvas().setCursor(getCursor()); + state = newState; + project.getFrame().getCanvas().setCursor(getCursor()); } private static class MoveRequestHandler implements MoveRequestListener { - private Canvas canvas; + private final Canvas canvas; MoveRequestHandler(Canvas canvas) { this.canvas = canvas; @@ -564,8 +555,8 @@ public void requestSatisfied(MoveGesture gesture, int dx, int dy) { private static class ComputingMessage implements StringGetter { - private int dx; - private int dy; + private final int dx; + private final int dy; public ComputingMessage(int dx, int dy) { this.dx = dx; diff --git a/src/main/java/com/cburch/logisim/tools/SetAttributeAction.java b/src/main/java/com/cburch/logisim/tools/SetAttributeAction.java index 4989d6a..983b90f 100644 --- a/src/main/java/com/cburch/logisim/tools/SetAttributeAction.java +++ b/src/main/java/com/cburch/logisim/tools/SetAttributeAction.java @@ -18,33 +18,33 @@ public class SetAttributeAction extends Action { - private StringGetter nameGetter; - private Circuit circuit; - private List comps; - private List> attrs; - private List values; - private List oldValues; + private final StringGetter nameGetter; + private final Circuit circuit; + private final List components; + private final List> attrs; + private final List values; + private final List oldValues; private CircuitTransaction xnReverse; public SetAttributeAction(Circuit circuit, StringGetter nameGetter) { this.nameGetter = nameGetter; this.circuit = circuit; - this.comps = new ArrayList<>(); + this.components = new ArrayList<>(); this.attrs = new ArrayList<>(); this.values = new ArrayList<>(); this.oldValues = new ArrayList<>(); } - public void set(Component comp, Attribute attr, Object value) { + public void set(Component component, Attribute attr, Object value) { @SuppressWarnings("unchecked") - Attribute a = (Attribute) attr; - comps.add(comp); - attrs.add(a); + Attribute objectAttr = (Attribute) attr; + components.add(component); + attrs.add(objectAttr); values.add(value); } public boolean isEmpty() { - return comps.isEmpty(); + return components.isEmpty(); } @Override @@ -53,41 +53,41 @@ public String getName() { } @Override - public void doIt(Project proj) { - CircuitMutation xn = new CircuitMutation(circuit); - int len = values.size(); + public void doIt(Project project) { + CircuitMutation mutation = new CircuitMutation(circuit); + int size = values.size(); oldValues.clear(); - for (int i = 0; i < len; i++) { - Component comp = comps.get(i); + for (int i = 0; i < size; i++) { + Component component = components.get(i); Attribute attr = attrs.get(i); Object value = values.get(i); - if (circuit.contains(comp)) { + if (circuit.contains(component)) { oldValues.add(null); - xn.set(comp, attr, value); + mutation.set(component, attr, value); } else { - AttributeSet compAttrs = comp.getAttributeSet(); - oldValues.add(compAttrs.getValue(attr)); - compAttrs.setValue(attr, value); + AttributeSet componentAttrs = component.getAttributeSet(); + oldValues.add(componentAttrs.getValue(attr)); + componentAttrs.setValue(attr, value); } } - if (!xn.isEmpty()) { - CircuitTransactionResult result = xn.execute(); + if (!mutation.isEmpty()) { + CircuitTransactionResult result = mutation.execute(); xnReverse = result.getReverseTransaction(); } } @Override - public void undo(Project proj) { + public void undo(Project project) { if (xnReverse != null) { xnReverse.execute(); } for (int i = oldValues.size() - 1; i >= 0; i--) { - Component comp = comps.get(i); + Component component = components.get(i); Attribute attr = attrs.get(i); Object value = oldValues.get(i); if (value != null) { - comp.getAttributeSet().setValue(attr, value); + component.getAttributeSet().setValue(attr, value); } } } diff --git a/src/main/java/com/cburch/logisim/tools/Strings.java b/src/main/java/com/cburch/logisim/tools/Strings.java index 5022576..dba4535 100644 --- a/src/main/java/com/cburch/logisim/tools/Strings.java +++ b/src/main/java/com/cburch/logisim/tools/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "tools"); + private static final LocaleManager source = new LocaleManager("logisim", "tools"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/tools/TextTool.java b/src/main/java/com/cburch/logisim/tools/TextTool.java index 617e056..9c0161f 100644 --- a/src/main/java/com/cburch/logisim/tools/TextTool.java +++ b/src/main/java/com/cburch/logisim/tools/TextTool.java @@ -23,10 +23,9 @@ public class TextTool extends Tool { - private static Cursor cursor - = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); - private MyListener listener = new MyListener(); - private AttributeSet attrs; + private static final Cursor cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); + private final MyListener listener = new MyListener(); + private final AttributeSet attrs; private Caret caret = null; private boolean caretCreatingText = false; private Canvas caretCanvas = null; @@ -89,10 +88,10 @@ public void deselect(Canvas canvas) { @Override public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { - Project proj = canvas.getProject(); - Circuit circ = canvas.getCircuit(); + Project project = canvas.getProject(); + Circuit circuit = canvas.getCircuit(); - if (!proj.getLogisimFile().contains(circ)) { + if (!project.getLogisimFile().contains(circuit)) { if (caret != null) { caret.cancelEditing(); } @@ -104,7 +103,7 @@ public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { if (caret != null) { if (caret.getBounds(g).contains(e.getX(), e.getY())) { // Yes caret.mousePressed(e); - proj.repaintCanvas(); + project.repaintCanvas(); return; } else { // No. End the current caret. caret.stopEditing(); @@ -115,17 +114,17 @@ public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { // Otherwise search for a new caret. int x = e.getX(); int y = e.getY(); - Location loc = Location.create(x, y); + Location location = Location.create(x, y); ComponentUserEvent event = new ComponentUserEvent(canvas, x, y); // First search in selection. - for (Component comp : proj.getSelection().getComponentsContaining(loc, g)) { - TextEditable editable = (TextEditable) comp.getFeature(TextEditable.class); + for (Component component : project.getSelection().getComponentsContaining(location, g)) { + TextEditable editable = (TextEditable) component.getFeature(TextEditable.class); if (editable != null) { caret = editable.getTextCaret(event); if (caret != null) { - proj.getFrame().viewComponentAttributes(circ, comp); - caretComponent = comp; + project.getFrame().viewComponentAttributes(circuit, component); + caretComponent = component; caretCreatingText = false; break; } @@ -134,13 +133,13 @@ public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { // Then search in circuit if (caret == null) { - for (Component comp : circ.getAllContaining(loc, g)) { - TextEditable editable = (TextEditable) comp.getFeature(TextEditable.class); + for (Component component : circuit.getAllContaining(location, g)) { + TextEditable editable = (TextEditable) component.getFeature(TextEditable.class); if (editable != null) { caret = editable.getTextCaret(event); if (caret != null) { - proj.getFrame().viewComponentAttributes(circ, comp); - caretComponent = comp; + project.getFrame().viewComponentAttributes(circuit, component); + caretComponent = component; caretCreatingText = false; break; } @@ -150,16 +149,16 @@ public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { // if nothing found, create a new label if (caret == null) { - if (loc.getX() < 0 || loc.getY() < 0) { + if (location.getX() < 0 || location.getY() < 0) { return; } AttributeSet copy = (AttributeSet) attrs.clone(); - caretComponent = Text.FACTORY.createComponent(loc, copy); + caretComponent = Text.FACTORY.createComponent(location, copy); caretCreatingText = true; TextEditable editable = (TextEditable) caretComponent.getFeature(TextEditable.class); if (editable != null) { caret = editable.getTextCaret(event); - proj.getFrame().viewComponentAttributes(circ, caretComponent); + project.getFrame().viewComponentAttributes(circuit, caretComponent); } } @@ -169,7 +168,7 @@ public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { caret.addCaretListener(listener); caretCircuit.addCircuitListener(listener); } - proj.repaintCanvas(); + project.repaintCanvas(); } @Override @@ -212,7 +211,7 @@ public Cursor getCursor() { } private class MyListener - implements CaretListener, CircuitListener { + implements CaretListener, CircuitListener { public void editingCanceled(CaretEvent e) { if (e.getCaret() != caret) { @@ -236,32 +235,30 @@ public void editingStopped(CaretEvent e) { caret.removeCaretListener(this); caretCircuit.removeCircuitListener(this); - String val = caret.getText(); - boolean isEmpty = (val == null || val.equals("")); - Action a; - Project proj = caretCanvas.getProject(); + String text = caret.getText(); + boolean isEmpty = (text == null || text.equals("")); + Action action; + Project project = caretCanvas.getProject(); if (caretCreatingText) { if (!isEmpty) { - CircuitMutation xn = new CircuitMutation(caretCircuit); - xn.add(caretComponent); - a = xn.toAction(Strings.getter("addComponentAction", - Text.FACTORY.getDisplayGetter())); + CircuitMutation mutation = new CircuitMutation(caretCircuit); + mutation.add(caretComponent); + action = mutation.toAction(Strings.getter("addComponentAction", Text.FACTORY.getDisplayGetter())); } else { - a = null; // don't add the blank text field + action = null; // don't add the blank text field } } else { if (isEmpty && caretComponent.getFactory() instanceof Text) { - CircuitMutation xn = new CircuitMutation(caretCircuit); - xn.add(caretComponent); - a = xn.toAction(Strings.getter("removeComponentAction", - Text.FACTORY.getDisplayGetter())); + CircuitMutation mutation = new CircuitMutation(caretCircuit); + mutation.add(caretComponent); + action = mutation.toAction(Strings.getter("removeComponentAction", Text.FACTORY.getDisplayGetter())); } else { - Object obj = caretComponent.getFeature(TextEditable.class); - if (obj == null) { // should never happen - a = null; + Object object = caretComponent.getFeature(TextEditable.class); + if (object == null) { // should never happen + action = null; } else { - TextEditable editable = (TextEditable) obj; - a = editable.getCommitAction(caretCircuit, e.getOldText(), e.getText()); + TextEditable editable = (TextEditable) object; + action = editable.getCommitAction(caretCircuit, e.getOldText(), e.getText()); } } } @@ -271,8 +268,8 @@ public void editingStopped(CaretEvent e) { caretCreatingText = false; caret = null; - if (a != null) { - proj.doAction(a); + if (action != null) { + project.doAction(action); } } diff --git a/src/main/java/com/cburch/logisim/tools/WireRepairData.java b/src/main/java/com/cburch/logisim/tools/WireRepairData.java index a217fdb..685628c 100644 --- a/src/main/java/com/cburch/logisim/tools/WireRepairData.java +++ b/src/main/java/com/cburch/logisim/tools/WireRepairData.java @@ -8,8 +8,8 @@ public class WireRepairData { - private Wire wire; - private Location point; + private final Wire wire; + private final Location point; public WireRepairData(Wire wire, Location point) { this.wire = wire; diff --git a/src/main/java/com/cburch/logisim/tools/WiringTool.java b/src/main/java/com/cburch/logisim/tools/WiringTool.java index dbb5c05..730c4ae 100644 --- a/src/main/java/com/cburch/logisim/tools/WiringTool.java +++ b/src/main/java/com/cburch/logisim/tools/WiringTool.java @@ -30,12 +30,11 @@ public class WiringTool extends Tool { private static final Icon toolIcon = Icons.getIcon("wiring.gif"); private static final int HORIZONTAL = 1; private static final int VERTICAL = 2; - private static Cursor cursor - = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); + private static final Cursor cursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); private boolean exists = false; private boolean inCanvas = false; private Location start = Location.create(0, 0); - private Location cur = Location.create(0, 0); + private Location current = Location.create(0, 0); private boolean hasDragged = false; private boolean startShortening = false; private Wire shortening = null; @@ -57,7 +56,7 @@ private void reset() { exists = false; inCanvas = false; start = Location.create(0, 0); - cur = Location.create(0, 0); + current = Location.create(0, 0); startShortening = false; shortening = null; direction = 0; @@ -89,7 +88,7 @@ public String getDescription() { } private boolean computeMove(int newX, int newY) { - if (cur.getX() == newX && cur.getY() == newY) { + if (current.getX() == newX && current.getY() == newY) { return false; } Location start = this.start; @@ -117,7 +116,7 @@ private boolean computeMove(int newX, int newY) { @Override public Set getHiddenComponents(Canvas canvas) { - Component shorten = willShorten(start, cur); + Component shorten = willShorten(start, current); if (shorten != null) { return Collections.singleton(shorten); } else { @@ -129,22 +128,22 @@ public Set getHiddenComponents(Canvas canvas) { public void draw(Canvas canvas, ComponentDrawContext context) { Graphics g = context.getGraphics(); if (exists) { - Location e0 = start; - Location e1 = cur; - Wire shortenBefore = willShorten(start, cur); + Location end0 = start; + Location end1 = current; + Wire shortenBefore = willShorten(start, current); if (shortenBefore != null) { - Wire shorten = getShortenResult(shortenBefore, start, cur); + Wire shorten = getShortenResult(shortenBefore, start, current); if (shorten == null) { return; } else { - e0 = shorten.getEnd0(); - e1 = shorten.getEnd1(); + end0 = shorten.getEnd0(); + end1 = shorten.getEnd1(); } } - int x0 = e0.getX(); - int y0 = e0.getY(); - int x1 = e1.getX(); - int y1 = e1.getY(); + int x0 = end0.getX(); + int y0 = end0.getY(); + int x1 = end1.getX(); + int y1 = end1.getY(); g.setColor(Color.BLACK); GraphicsUtil.switchToWidth(g, 3); @@ -165,20 +164,18 @@ public void draw(Canvas canvas, ComponentDrawContext context) { } } else if (AppPreferences.ADD_SHOW_GHOSTS.getBoolean() && inCanvas) { g.setColor(Color.GRAY); - g.fillOval(cur.getX() - 2, cur.getY() - 2, 5, 5); + g.fillOval(current.getX() - 2, current.getY() - 2, 5, 5); } } @Override - public void mouseEntered(Canvas canvas, Graphics g, - MouseEvent e) { + public void mouseEntered(Canvas canvas, Graphics g, MouseEvent e) { inCanvas = true; canvas.getProject().repaintCanvas(); } @Override - public void mouseExited(Canvas canvas, Graphics g, - MouseEvent e) { + public void mouseExited(Canvas canvas, Graphics g, MouseEvent e) { inCanvas = false; canvas.getProject().repaintCanvas(); } @@ -192,8 +189,8 @@ public void mouseMoved(Canvas canvas, Graphics g, MouseEvent e) { inCanvas = true; int curX = e.getX(); int curY = e.getY(); - if (cur.getX() != curX || cur.getY() != curY) { - cur = Location.create(curX, curY); + if (current.getX() != curX || current.getY() != curY) { + current = Location.create(curX, curY); } canvas.getProject().repaintCanvas(); } @@ -212,7 +209,7 @@ public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { } else { Canvas.snapToGrid(e); start = Location.create(e.getX(), e.getY()); - cur = start; + current = start; exists = true; hasDragged = false; @@ -228,42 +225,42 @@ public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) { public void mouseDragged(Canvas canvas, Graphics g, MouseEvent e) { if (exists) { Canvas.snapToGrid(e); - int curX = e.getX(); - int curY = e.getY(); - if (!computeMove(curX, curY)) { + int currentX = e.getX(); + int currentY = e.getY(); + if (!computeMove(currentX, currentY)) { return; } hasDragged = true; - Rectangle rect = new Rectangle(); - rect.add(start.getX(), start.getY()); - rect.add(cur.getX(), cur.getY()); - rect.add(curX, curY); - rect.grow(3, 3); + Rectangle rectangle = new Rectangle(); + rectangle.add(start.getX(), start.getY()); + rectangle.add(current.getX(), current.getY()); + rectangle.add(currentX, currentY); + rectangle.grow(3, 3); - cur = Location.create(curX, curY); + current = Location.create(currentX, currentY); super.mouseDragged(canvas, g, e); Wire shorten = null; if (startShortening) { - for (Wire w : canvas.getCircuit().getWires(start)) { - if (w.contains(cur)) { - shorten = w; + for (Wire wire : canvas.getCircuit().getWires(start)) { + if (wire.contains(current)) { + shorten = wire; break; } } } if (shorten == null) { - for (Wire w : canvas.getCircuit().getWires(cur)) { - if (w.contains(start)) { - shorten = w; + for (Wire wire : canvas.getCircuit().getWires(current)) { + if (wire.contains(start)) { + shorten = wire; break; } } } shortening = shorten; - canvas.repaint(rect); + canvas.repaint(rectangle); } } @@ -278,87 +275,87 @@ public void mouseReleased(Canvas canvas, Graphics g, MouseEvent e) { } Canvas.snapToGrid(e); - int curX = e.getX(); - int curY = e.getY(); - if (computeMove(curX, curY)) { - cur = Location.create(curX, curY); + int currentX = e.getX(); + int currentY = e.getY(); + if (computeMove(currentX, currentY)) { + current = Location.create(currentX, currentY); } if (hasDragged) { exists = false; super.mouseReleased(canvas, g, e); - ArrayList ws = new ArrayList<>(2); - if (cur.getY() == start.getY() || cur.getX() == start.getX()) { - Wire w = Wire.create(cur, start); - w = checkForRepairs(canvas, w, w.getEnd0()); - w = checkForRepairs(canvas, w, w.getEnd1()); - if (performShortening(canvas, start, cur)) { + ArrayList wires = new ArrayList<>(2); + if (current.getY() == start.getY() || current.getX() == start.getX()) { + Wire wire = Wire.create(current, start); + wire = checkForRepairs(canvas, wire, wire.getEnd0()); + wire = checkForRepairs(canvas, wire, wire.getEnd1()); + if (performShortening(canvas, start, current)) { return; } - if (w.getLength() > 0) { - ws.add(w); + if (wire.getLength() > 0) { + wires.add(wire); } } else { - Location m; + Location location; if (direction == HORIZONTAL) { - m = Location.create(cur.getX(), start.getY()); + location = Location.create(current.getX(), start.getY()); } else { - m = Location.create(start.getX(), cur.getY()); + location = Location.create(start.getX(), current.getY()); } - Wire w0 = Wire.create(start, m); - Wire w1 = Wire.create(m, cur); - w0 = checkForRepairs(canvas, w0, start); - w1 = checkForRepairs(canvas, w1, cur); - if (w0.getLength() > 0) { - ws.add(w0); + Wire wire0 = Wire.create(start, location); + Wire wire1 = Wire.create(location, current); + wire0 = checkForRepairs(canvas, wire0, start); + wire1 = checkForRepairs(canvas, wire1, current); + if (wire0.getLength() > 0) { + wires.add(wire0); } - if (w1.getLength() > 0) { - ws.add(w1); + if (wire1.getLength() > 0) { + wires.add(wire1); } } - if (ws.size() > 0) { + if (wires.size() > 0) { CircuitMutation mutation = new CircuitMutation(canvas.getCircuit()); - mutation.addAll(ws); - StringGetter desc; - if (ws.size() == 1) { - desc = Strings.getter("addWireAction"); + mutation.addAll(wires); + StringGetter description; + if (wires.size() == 1) { + description = Strings.getter("addWireAction"); } else { - desc = Strings.getter("addWiresAction"); + description = Strings.getter("addWiresAction"); } - Action act = mutation.toAction(desc); - canvas.getProject().doAction(act); - lastAction = act; + Action action = mutation.toAction(description); + canvas.getProject().doAction(action); + lastAction = action; } } } - private Wire checkForRepairs(Canvas canvas, Wire w, Location end) { - if (w.getLength() <= 10) { - return w; // don't repair a short wire to nothing + private Wire checkForRepairs(Canvas canvas, Wire wire, Location end) { + if (wire.getLength() <= 10) { + return wire; // don't repair a short wire to nothing } if (!canvas.getCircuit().getNonWires(end).isEmpty()) { - return w; + return wire; } - int delta = (end.equals(w.getEnd0()) ? 10 : -10); - Location cand; - if (w.isVertical()) { - cand = Location.create(end.getX(), end.getY() + delta); + int delta = (end.equals(wire.getEnd0()) ? 10 : -10); + Location location; + if (wire.isVertical()) { + location = Location.create(end.getX(), end.getY() + delta); } else { - cand = Location.create(end.getX() + delta, end.getY()); + location = Location.create(end.getX() + delta, end.getY()); } - for (Component comp : canvas.getCircuit().getNonWires(cand)) { - if (comp.getBounds().contains(end, 2)) { - WireRepair repair = (WireRepair) comp.getFeature(WireRepair.class); - if (repair != null && repair.shouldRepairWire(new WireRepairData(w, cand))) { - w = Wire.create(w.getOtherEnd(end), cand); + for (Component component : canvas.getCircuit().getNonWires(location)) { + if (component.getBounds().contains(end, 2)) { + WireRepair repair = (WireRepair) component.getFeature(WireRepair.class); + if (repair != null && repair.shouldRepairWire(new WireRepairData(wire, location))) { + wire = Wire.create(wire.getOtherEnd(end), location); canvas.repaint(end.getX() - 13, end.getY() - 13, 26, 26); - return w; + return wire; } } } - return w; + return wire; } private Wire willShorten(Location drag0, Location drag1) { @@ -376,18 +373,18 @@ private Wire getShortenResult(Wire shorten, Location drag0, Location drag1) { if (shorten == null) { return null; } else { - Location e0; - Location e1; + Location end0; + Location end1; if (shorten.endsAt(drag0)) { - e0 = drag1; - e1 = shorten.getOtherEnd(drag0); + end0 = drag1; + end1 = shorten.getOtherEnd(drag0); } else if (shorten.endsAt(drag1)) { - e0 = drag0; - e1 = shorten.getOtherEnd(drag1); + end0 = drag0; + end1 = shorten.getOtherEnd(drag1); } else { return null; } - return e0.equals(e1) ? null : Wire.create(e0, e1); + return end0.equals(end1) ? null : Wire.create(end0, end1); } } @@ -397,37 +394,35 @@ private boolean performShortening(Canvas canvas, Location drag0, Location drag1) return false; } else { CircuitMutation xn = new CircuitMutation(canvas.getCircuit()); - StringGetter actName; + StringGetter actionName; Wire result = getShortenResult(shorten, drag0, drag1); if (result == null) { xn.remove(shorten); - actName = Strings.getter("removeComponentAction", - shorten.getFactory().getDisplayGetter()); + actionName = Strings.getter("removeComponentAction", shorten.getFactory().getDisplayGetter()); } else { xn.replace(shorten, result); - actName = Strings.getter("shortenWireAction"); + actionName = Strings.getter("shortenWireAction"); } - canvas.getProject().doAction(xn.toAction(actName)); + canvas.getProject().doAction(xn.toAction(actionName)); return true; } } @Override public void keyPressed(Canvas canvas, KeyEvent event) { - switch (event.getKeyCode()) { - case KeyEvent.VK_BACK_SPACE: - if (lastAction != null && canvas.getProject().getLastAction() == lastAction) { - canvas.getProject().undoAction(); - lastAction = null; - } + if (event.getKeyCode() == KeyEvent.VK_BACK_SPACE) { + if (lastAction != null && canvas.getProject().getLastAction() == lastAction) { + canvas.getProject().undoAction(); + lastAction = null; + } } } @Override - public void paintIcon(ComponentDrawContext c, int x, int y) { - Graphics g = c.getGraphics(); + public void paintIcon(ComponentDrawContext context, int x, int y) { + Graphics g = context.getGraphics(); if (toolIcon != null) { - toolIcon.paintIcon(c.getDestination(), g, x + 2, y + 2); + toolIcon.paintIcon(context.getDestination(), g, x + 2, y + 2); } else { g.setColor(java.awt.Color.black); g.drawLine(x + 3, y + 13, x + 17, y + 7); diff --git a/src/main/java/com/cburch/logisim/tools/key/DirectionConfigurator.java b/src/main/java/com/cburch/logisim/tools/key/DirectionConfigurator.java index 0e03bb5..a104ed5 100644 --- a/src/main/java/com/cburch/logisim/tools/key/DirectionConfigurator.java +++ b/src/main/java/com/cburch/logisim/tools/key/DirectionConfigurator.java @@ -9,8 +9,8 @@ public class DirectionConfigurator implements KeyConfigurator, Cloneable { - private Attribute attr; - private int modsEx; + private final Attribute attr; + private final int modsEx; public DirectionConfigurator(Attribute attr, int modifiersEx) { this.attr = attr; diff --git a/src/main/java/com/cburch/logisim/tools/key/IntegerConfigurator.java b/src/main/java/com/cburch/logisim/tools/key/IntegerConfigurator.java index 1fb0536..ec00056 100644 --- a/src/main/java/com/cburch/logisim/tools/key/IntegerConfigurator.java +++ b/src/main/java/com/cburch/logisim/tools/key/IntegerConfigurator.java @@ -11,8 +11,7 @@ public IntegerConfigurator(Attribute attr, int min, int max, int modifi super(attr, min, max, modifiersEx); } - public IntegerConfigurator(Attribute attr, int min, int max, - int modifiersEx, int radix) { + public IntegerConfigurator(Attribute attr, int min, int max, int modifiersEx, int radix) { super(attr, min, max, modifiersEx, radix); } diff --git a/src/main/java/com/cburch/logisim/tools/key/JoinedConfigurator.java b/src/main/java/com/cburch/logisim/tools/key/JoinedConfigurator.java index 8ff742e..337fd33 100644 --- a/src/main/java/com/cburch/logisim/tools/key/JoinedConfigurator.java +++ b/src/main/java/com/cburch/logisim/tools/key/JoinedConfigurator.java @@ -21,28 +21,28 @@ public static JoinedConfigurator create(KeyConfigurator[] configs) { @Override public JoinedConfigurator clone() { - JoinedConfigurator ret; + JoinedConfigurator configurator; try { - ret = (JoinedConfigurator) super.clone(); + configurator = (JoinedConfigurator) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } int len = this.handlers.length; - ret.handlers = new KeyConfigurator[len]; + configurator.handlers = new KeyConfigurator[len]; for (int i = 0; i < len; i++) { - ret.handlers[i] = this.handlers[i].clone(); + configurator.handlers[i] = this.handlers[i].clone(); } - return ret; + return configurator; } public KeyConfigurationResult keyEventReceived(KeyConfigurationEvent event) { - KeyConfigurator[] hs = handlers; + KeyConfigurator[] handlers = this.handlers; if (event.isConsumed()) { return null; } - for (int i = 0; i < hs.length; i++) { - KeyConfigurationResult result = hs[i].keyEventReceived(event); + for (KeyConfigurator handler : handlers) { + KeyConfigurationResult result = handler.keyEventReceived(event); if (result != null || event.isConsumed()) { return result; } diff --git a/src/main/java/com/cburch/logisim/tools/key/KeyConfigurationEvent.java b/src/main/java/com/cburch/logisim/tools/key/KeyConfigurationEvent.java index f98112f..ce7badd 100644 --- a/src/main/java/com/cburch/logisim/tools/key/KeyConfigurationEvent.java +++ b/src/main/java/com/cburch/logisim/tools/key/KeyConfigurationEvent.java @@ -12,10 +12,10 @@ public class KeyConfigurationEvent { public static final int KEY_RELEASED = 1; public static final int KEY_TYPED = 2; - private int type; - private AttributeSet attrs; - private KeyEvent event; - private Object data; + private final int type; + private final AttributeSet attrs; + private final KeyEvent event; + private final Object data; private boolean consumed; public KeyConfigurationEvent(int type, AttributeSet attrs, KeyEvent event, Object data) { diff --git a/src/main/java/com/cburch/logisim/tools/key/KeyConfigurationResult.java b/src/main/java/com/cburch/logisim/tools/key/KeyConfigurationResult.java index 3553e78..8be5266 100644 --- a/src/main/java/com/cburch/logisim/tools/key/KeyConfigurationResult.java +++ b/src/main/java/com/cburch/logisim/tools/key/KeyConfigurationResult.java @@ -9,19 +9,17 @@ public class KeyConfigurationResult { - private KeyConfigurationEvent event; - private Map, Object> attrValueMap; + private final KeyConfigurationEvent event; + private final Map, Object> attrValueMap; - public KeyConfigurationResult(KeyConfigurationEvent event, Attribute attr, - Object value) { + public KeyConfigurationResult(KeyConfigurationEvent event, Attribute attr, Object value) { this.event = event; Map, Object> singleMap = new HashMap<>(1); singleMap.put(attr, value); this.attrValueMap = singleMap; } - public KeyConfigurationResult(KeyConfigurationEvent event, - Map, Object> values) { + public KeyConfigurationResult(KeyConfigurationEvent event, Map, Object> values) { this.event = event; this.attrValueMap = values; } diff --git a/src/main/java/com/cburch/logisim/tools/key/NumericConfigurator.java b/src/main/java/com/cburch/logisim/tools/key/NumericConfigurator.java index 9d80194..ffed38e 100644 --- a/src/main/java/com/cburch/logisim/tools/key/NumericConfigurator.java +++ b/src/main/java/com/cburch/logisim/tools/key/NumericConfigurator.java @@ -11,12 +11,12 @@ public abstract class NumericConfigurator implements KeyConfigurator, Cloneab private static final int MAX_TIME_KEY_LASTS = 800; - private Attribute attr; - private int minValue; - private int maxValue; + private final Attribute attr; + private final int minValue; + private final int maxValue; + private final int radix; + private final int modsEx; private int curValue; - private int radix; - private int modsEx; private long whenTyped; public NumericConfigurator(Attribute attr, int min, int max, int modifiersEx) { @@ -24,7 +24,7 @@ public NumericConfigurator(Attribute attr, int min, int max, int modifiersEx) } public NumericConfigurator(Attribute attr, int min, int max, - int modifiersEx, int radix) { + int modifiersEx, int radix) { this.attr = attr; this.minValue = min; this.maxValue = max; diff --git a/src/main/java/com/cburch/logisim/tools/key/ParallelConfigurator.java b/src/main/java/com/cburch/logisim/tools/key/ParallelConfigurator.java index b72463e..16fa169 100644 --- a/src/main/java/com/cburch/logisim/tools/key/ParallelConfigurator.java +++ b/src/main/java/com/cburch/logisim/tools/key/ParallelConfigurator.java @@ -24,30 +24,30 @@ public static ParallelConfigurator create(KeyConfigurator[] configs) { @Override public ParallelConfigurator clone() { - ParallelConfigurator ret; + ParallelConfigurator configurator; try { - ret = (ParallelConfigurator) super.clone(); + configurator = (ParallelConfigurator) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } int len = this.handlers.length; - ret.handlers = new KeyConfigurator[len]; + configurator.handlers = new KeyConfigurator[len]; for (int i = 0; i < len; i++) { - ret.handlers[i] = this.handlers[i].clone(); + configurator.handlers[i] = this.handlers[i].clone(); } - return ret; + return configurator; } public KeyConfigurationResult keyEventReceived(KeyConfigurationEvent event) { - KeyConfigurator[] hs = handlers; + KeyConfigurator[] handlers = this.handlers; if (event.isConsumed()) { return null; } KeyConfigurationResult first = null; HashMap, Object> map = null; - for (int i = 0; i < hs.length; i++) { - KeyConfigurationResult result = hs[i].keyEventReceived(event); + for (KeyConfigurator handler : handlers) { + KeyConfigurationResult result = handler.keyEventReceived(event); if (result != null) { if (first == null) { first = result; diff --git a/src/main/java/com/cburch/logisim/tools/key/Strings.java b/src/main/java/com/cburch/logisim/tools/key/Strings.java index fc9954a..6a9750d 100644 --- a/src/main/java/com/cburch/logisim/tools/key/Strings.java +++ b/src/main/java/com/cburch/logisim/tools/key/Strings.java @@ -8,8 +8,7 @@ class Strings { - private static LocaleManager source - = new LocaleManager("logisim", "tools"); + private static final LocaleManager source = new LocaleManager("logisim", "tools"); public static String get(String key) { return source.get(key); diff --git a/src/main/java/com/cburch/logisim/tools/move/AvoidanceMap.java b/src/main/java/com/cburch/logisim/tools/move/AvoidanceMap.java index 347d53f..35be2b7 100644 --- a/src/main/java/com/cburch/logisim/tools/move/AvoidanceMap.java +++ b/src/main/java/com/cburch/logisim/tools/move/AvoidanceMap.java @@ -39,39 +39,38 @@ public Object get(Location loc) { public void markAll(Collection elements, int dx, int dy) { // first we go through the components, saying that we should not // intersect with any point that lies within a component - for (Component el : elements) { - if (el instanceof Wire) { - markWire((Wire) el, dx, dy); + for (Component element : elements) { + if (element instanceof Wire) { + markWire((Wire) element, dx, dy); } else { - markComponent(el, dx, dy); + markComponent(element, dx, dy); } } } - public void markComponent(Component comp, int dx, int dy) { + public void markComponent(Component component, int dx, int dy) { HashMap avoid = this.avoid; boolean translated = dx != 0 || dy != 0; - Bounds bds = comp.getBounds(); - int x0 = bds.getX() + dx; - int y0 = bds.getY() + dy; - int x1 = x0 + bds.getWidth(); - int y1 = y0 + bds.getHeight(); + Bounds bounds = component.getBounds(); + int x0 = bounds.getX() + dx; + int y0 = bounds.getY() + dy; + int x1 = x0 + bounds.getWidth(); + int y1 = y0 + bounds.getHeight(); x0 += 9 - (x0 + 9) % 10; y0 += 9 - (y0 + 9) % 10; for (int x = x0; x <= x1; x += 10) { for (int y = y0; y <= y1; y += 10) { - Location loc = Location.create(x, y); - // loc is most likely in the component, so go ahead and - // put it into the map as if it is - and in the rare event - // that loc isn't in the component, we can remove it. - String prev = avoid.put(loc, Connector.ALLOW_NEITHER); - if (prev != Connector.ALLOW_NEITHER) { - Location baseLoc = translated ? loc.translate(-dx, -dy) : loc; - if (!comp.contains(baseLoc)) { - if (prev == null) { - avoid.remove(loc); + Location location = Location.create(x, y); + // location is most likely in the component, so go ahead and put it into the map as if it is - and in the + // rare event that location isn't in the component, we can remove it. + String previous = avoid.put(location, Connector.ALLOW_NEITHER); + if (!previous.equals(Connector.ALLOW_NEITHER)) { + Location baseLoc = translated ? location.translate(-dx, -dy) : location; + if (!component.contains(baseLoc)) { + if (previous == null) { + avoid.remove(location); } else { - avoid.put(loc, prev); + avoid.put(location, previous); } } } @@ -79,33 +78,33 @@ public void markComponent(Component comp, int dx, int dy) { } } - public void markWire(Wire w, int dx, int dy) { + public void markWire(Wire wire, int dx, int dy) { HashMap avoid = this.avoid; boolean translated = dx != 0 || dy != 0; - Location loc0 = w.getEnd0(); - Location loc1 = w.getEnd1(); + Location location0 = wire.getEnd0(); + Location location1 = wire.getEnd1(); if (translated) { - loc0 = loc0.translate(dx, dy); - loc1 = loc1.translate(dx, dy); + location0 = location0.translate(dx, dy); + location1 = location1.translate(dx, dy); } - avoid.put(loc0, Connector.ALLOW_NEITHER); - avoid.put(loc1, Connector.ALLOW_NEITHER); - int x0 = loc0.getX(); - int y0 = loc0.getY(); - int x1 = loc1.getX(); - int y1 = loc1.getY(); + avoid.put(location0, Connector.ALLOW_NEITHER); + avoid.put(location1, Connector.ALLOW_NEITHER); + int x0 = location0.getX(); + int y0 = location0.getY(); + int x1 = location1.getX(); + int y1 = location1.getY(); if (x0 == x1) { // vertical wire - for (Location loc : Wire.create(loc0, loc1)) { - Object prev = avoid.put(loc, Connector.ALLOW_HORIZONTAL); - if (prev == Connector.ALLOW_NEITHER || prev == Connector.ALLOW_VERTICAL) { - avoid.put(loc, Connector.ALLOW_NEITHER); + for (Location location : Wire.create(location0, location1)) { + Object previous = avoid.put(location, Connector.ALLOW_HORIZONTAL); + if (previous == Connector.ALLOW_NEITHER || previous == Connector.ALLOW_VERTICAL) { + avoid.put(location, Connector.ALLOW_NEITHER); } } } else if (y0 == y1) { // horizontal wire - for (Location loc : Wire.create(loc0, loc1)) { - Object prev = avoid.put(loc, Connector.ALLOW_VERTICAL); + for (Location location : Wire.create(location0, location1)) { + Object prev = avoid.put(location, Connector.ALLOW_VERTICAL); if (prev == Connector.ALLOW_NEITHER || prev == Connector.ALLOW_HORIZONTAL) { - avoid.put(loc, Connector.ALLOW_NEITHER); + avoid.put(location, Connector.ALLOW_NEITHER); } } } else { // diagonal - shouldn't happen @@ -113,35 +112,35 @@ public void markWire(Wire w, int dx, int dy) { } } - public void unmarkLocation(Location loc) { - avoid.remove(loc); + public void unmarkLocation(Location location) { + avoid.remove(location); } - public void unmarkWire(Wire w, Location deletedEnd, Set unmarkable) { - Location loc0 = w.getEnd0(); - Location loc1 = w.getEnd1(); + public void unmarkWire(Wire wire, Location deletedEnd, Set unmarkable) { + Location location0 = wire.getEnd0(); + Location location1 = wire.getEnd1(); if (unmarkable == null || unmarkable.contains(deletedEnd)) { avoid.remove(deletedEnd); } - int x0 = loc0.getX(); - int y0 = loc0.getY(); - int x1 = loc1.getX(); - int y1 = loc1.getY(); + int x0 = location0.getX(); + int y0 = location0.getY(); + int x1 = location1.getX(); + int y1 = location1.getY(); if (x0 == x1) { // vertical wire - for (Location loc : w) { + for (Location location : wire) { if (unmarkable == null || unmarkable.contains(deletedEnd)) { - Object prev = avoid.remove(loc); - if (prev != Connector.ALLOW_HORIZONTAL && prev != null) { - avoid.put(loc, Connector.ALLOW_VERTICAL); + Object previous = avoid.remove(location); + if (previous != Connector.ALLOW_HORIZONTAL && previous != null) { + avoid.put(location, Connector.ALLOW_VERTICAL); } } } } else if (y0 == y1) { // horizontal wire - for (Location loc : w) { + for (Location location : wire) { if (unmarkable == null || unmarkable.contains(deletedEnd)) { - Object prev = avoid.remove(loc); - if (prev != Connector.ALLOW_VERTICAL && prev != null) { - avoid.put(loc, Connector.ALLOW_HORIZONTAL); + Object previous = avoid.remove(location); + if (previous != Connector.ALLOW_VERTICAL && previous != null) { + avoid.put(location, Connector.ALLOW_HORIZONTAL); } } } @@ -153,8 +152,8 @@ public void unmarkWire(Wire w, Location deletedEnd, Set unmarkable) { public void print(PrintStream stream) { ArrayList list = new ArrayList<>(avoid.keySet()); Collections.sort(list); - for (int i = 0, n = list.size(); i < n; i++) { - stream.println(list.get(i) + ": " + avoid.get(list.get(i))); + for (Location location : list) { + stream.println(location + ": " + avoid.get(location)); } } } diff --git a/src/main/java/com/cburch/logisim/tools/move/ConnectionData.java b/src/main/java/com/cburch/logisim/tools/move/ConnectionData.java index a539332..df0f32c 100644 --- a/src/main/java/com/cburch/logisim/tools/move/ConnectionData.java +++ b/src/main/java/com/cburch/logisim/tools/move/ConnectionData.java @@ -10,32 +10,29 @@ class ConnectionData { - private Location loc; - - private Direction dir; - + private final Location location; + private final Direction direction; /** * The list of wires leading up to this point - we may well want to * truncate this path somewhat. */ - private List wirePath; - - private Location wirePathStart; + private final List wirePath; + private final Location wirePathStart; - public ConnectionData(Location loc, Direction dir, List wirePath, - Location wirePathStart) { - this.loc = loc; - this.dir = dir; + public ConnectionData(Location location, Direction direction, List wirePath, + Location wirePathStart) { + this.location = location; + this.direction = direction; this.wirePath = wirePath; this.wirePathStart = wirePathStart; } public Location getLocation() { - return loc; + return location; } public Direction getDirection() { - return dir; + return direction; } public List getWirePath() { @@ -49,8 +46,8 @@ public Location getWirePathStart() { @Override public boolean equals(Object other) { if (other instanceof ConnectionData) { - ConnectionData o = (ConnectionData) other; - return this.loc.equals(o.loc) && this.dir.equals(o.dir); + ConnectionData data = (ConnectionData) other; + return this.location.equals(data.location) && this.direction.equals(data.direction); } else { return false; } @@ -58,6 +55,6 @@ public boolean equals(Object other) { @Override public int hashCode() { - return loc.hashCode() * 31 + (dir == null ? 0 : dir.hashCode()); + return location.hashCode() * 31 + (direction == null ? 0 : direction.hashCode()); } } diff --git a/src/main/java/com/cburch/logisim/tools/move/Connector.java b/src/main/java/com/cburch/logisim/tools/move/Connector.java index 10253cd..a95780d 100644 --- a/src/main/java/com/cburch/logisim/tools/move/Connector.java +++ b/src/main/java/com/cburch/logisim/tools/move/Connector.java @@ -9,7 +9,6 @@ import com.cburch.logisim.data.Location; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -35,20 +34,17 @@ static MoveResult computeWires(MoveRequest req) { int dy = req.getDeltaY(); ArrayList baseConnects; baseConnects = new ArrayList<>(gesture.getConnections()); - ArrayList impossible = pruneImpossible(baseConnects, - gesture.getFixedAvoidanceMap(), dx, dy); + ArrayList impossible = pruneImpossible(baseConnects, gesture.getFixedAvoidanceMap(), dx, dy); AvoidanceMap selAvoid = AvoidanceMap.create(gesture.getSelected(), dx, dy); - HashMap> pathLocs; - pathLocs = new HashMap<>(); - HashMap> initNodes; - initNodes = new HashMap<>(); + HashMap> pathLocations = new HashMap<>(); + HashMap> initNodes = new HashMap<>(); for (ConnectionData conn : baseConnects) { - HashSet connLocs = new HashSet<>(); - ArrayList connNodes = new ArrayList<>(); - processConnection(conn, dx, dy, connLocs, connNodes, selAvoid); - pathLocs.put(conn, connLocs); - initNodes.put(conn, connNodes); + HashSet connectionLocations = new HashSet<>(); + ArrayList connectionNodes = new ArrayList<>(); + processConnection(conn, dx, dy, connectionLocations, connectionNodes, selAvoid); + pathLocations.put(conn, connectionLocations); + initNodes.put(conn, connectionNodes); } MoveResult bestResult = null; @@ -85,15 +81,14 @@ static MoveResult computeWires(MoveRequest req) { Collections.shuffle(connects); } - MoveResult candidate = tryList(req, gesture, connects, dx, dy, - pathLocs, initNodes, stopTime); + MoveResult candidate = tryList(req, gesture, connects, dx, dy, pathLocations, initNodes, stopTime); if (candidate == null) { return null; } else if (bestResult == null) { bestResult = candidate; } else { - int unsatisfied1 = bestResult.getUnsatisifiedConnections().size(); - int unsatisfied2 = candidate.getUnsatisifiedConnections().size(); + int unsatisfied1 = bestResult.getUnsatisfiedConnections().size(); + int unsatisfied2 = candidate.getUnsatisfiedConnections().size(); if (unsatisfied2 < unsatisfied1) { bestResult = candidate; } else if (unsatisfied2 == unsatisfied1) { @@ -114,29 +109,27 @@ static MoveResult computeWires(MoveRequest req) { } private static ArrayList pruneImpossible( - ArrayList connects, AvoidanceMap avoid, int dx, int dy) { + ArrayList connections, AvoidanceMap avoid, int dx, int dy) { ArrayList pathWires = new ArrayList<>(); - for (ConnectionData conn : connects) { - for (Wire w : conn.getWirePath()) { - pathWires.add(w); - } + for (ConnectionData connection : connections) { + pathWires.addAll(connection.getWirePath()); } ArrayList impossible = new ArrayList<>(); - for (Iterator it = connects.iterator(); it.hasNext(); ) { - ConnectionData conn = it.next(); - Location dest = conn.getLocation().translate(dx, dy); - if (avoid.get(dest) != null) { + for (Iterator iterator = connections.iterator(); iterator.hasNext(); ) { + ConnectionData connection = iterator.next(); + Location destination = connection.getLocation().translate(dx, dy); + if (avoid.get(destination) != null) { boolean isInPath = false; - for (Wire w : pathWires) { - if (w.contains(dest)) { + for (Wire wire : pathWires) { + if (wire.contains(destination)) { isInPath = true; break; } } if (!isInPath) { - it.remove(); - impossible.add(conn); + iterator.remove(); + impossible.add(connection); } } } @@ -151,26 +144,22 @@ private static ArrayList pruneImpossible( * other - but if we are moving that gate northeast, we prefer to connect * the inputs from the bottom up. */ - private static void sortConnects(ArrayList connects, - final int dx, final int dy) { - connects.sort(new Comparator() { - public int compare(ConnectionData ac, ConnectionData bc) { - Location a = ac.getLocation(); - Location b = bc.getLocation(); - int abx = a.getX() - b.getX(); - int aby = a.getY() - b.getY(); - return abx * dx + aby * dy; - } + private static void sortConnects(ArrayList connections, final int dx, final int dy) { + connections.sort((ac, bc) -> { + Location a = ac.getLocation(); + Location b = bc.getLocation(); + int abx = a.getX() - b.getX(); + int aby = a.getY() - b.getY(); + return abx * dx + aby * dy; }); } - private static void processConnection(ConnectionData conn, int dx, int dy, - HashSet connLocs, ArrayList connNodes, - AvoidanceMap selAvoid) { - Location cur = conn.getLocation(); - Location dest = cur.translate(dx, dy); - if (selAvoid.get(cur) == null) { - Direction preferred = conn.getDirection(); + private static void processConnection(ConnectionData connection, int dx, int dy, HashSet connectionLocations, + ArrayList connectionNodes, AvoidanceMap selectionAvoid) { + Location current = connection.getLocation(); + Location destination = current.translate(dx, dy); + if (selectionAvoid.get(current) == null) { + Direction preferred = connection.getDirection(); if (preferred == null) { if (Math.abs(dx) > Math.abs(dy)) { preferred = dx > 0 ? Direction.EAST : Direction.WEST; @@ -179,140 +168,137 @@ private static void processConnection(ConnectionData conn, int dx, int dy, } } - connLocs.add(cur); - connNodes.add(new SearchNode(conn, cur, preferred, dest)); + connectionLocations.add(current); + connectionNodes.add(new SearchNode(connection, current, preferred, destination)); } - for (Wire w : conn.getWirePath()) { - for (Location loc : w) { - if (selAvoid.get(loc) == null || loc.equals(dest)) { - boolean added = connLocs.add(loc); + for (Wire wire : connection.getWirePath()) { + for (Location location : wire) { + if (selectionAvoid.get(location) == null || location.equals(destination)) { + boolean added = connectionLocations.add(location); if (added) { - Direction dir = null; - if (w.endsAt(loc)) { - if (w.isVertical()) { - int y0 = loc.getY(); - int y1 = w.getOtherEnd(loc).getY(); - dir = y0 < y1 ? Direction.NORTH : Direction.SOUTH; + Direction direction = null; + if (wire.endsAt(location)) { + if (wire.isVertical()) { + int y0 = location.getY(); + int y1 = wire.getOtherEnd(location).getY(); + direction = y0 < y1 ? Direction.NORTH : Direction.SOUTH; } else { - int x0 = loc.getX(); - int x1 = w.getOtherEnd(loc).getX(); - dir = x0 < x1 ? Direction.WEST : Direction.EAST; + int x0 = location.getX(); + int x1 = wire.getOtherEnd(location).getX(); + direction = x0 < x1 ? Direction.WEST : Direction.EAST; } } - connNodes.add(new SearchNode(conn, loc, dir, dest)); + connectionNodes.add(new SearchNode(connection, location, direction, destination)); } } } } } - private static MoveResult tryList(MoveRequest req, - MoveGesture gesture, ArrayList connects, - int dx, int dy, HashMap> pathLocs, - HashMap> initNodes, long stopTime) { + private static MoveResult tryList(MoveRequest request, MoveGesture gesture, ArrayList connections, + int dx, int dy, HashMap> pathLocations, + HashMap> initNodes, long stopTime) { AvoidanceMap avoid = gesture.getFixedAvoidanceMap().cloneMap(); avoid.markAll(gesture.getSelected(), dx, dy); ReplacementMap replacements = new ReplacementMap(); ArrayList unconnected = new ArrayList<>(); int totalDistance = 0; - for (ConnectionData conn : connects) { + for (ConnectionData connection : connections) { if (ConnectorThread.isOverrideRequested()) { return null; } if (System.currentTimeMillis() - stopTime > 0) { - unconnected.add(conn); + unconnected.add(connection); continue; } - List connNodes = initNodes.get(conn); - Set connPathLocs = pathLocs.get(conn); - SearchNode n = findShortestPath(connNodes, connPathLocs, avoid); - if (n != null) { // normal case - a path was found - totalDistance += n.getDistance(); - ArrayList path = convertToPath(n); - processPath(path, conn, avoid, replacements, connPathLocs); + List connectionNodes = initNodes.get(connection); + Set connectionPathLocations = pathLocations.get(connection); + SearchNode node = findShortestPath(connectionNodes, connectionPathLocations, avoid); + if (node != null) { // normal case - a path was found + totalDistance += node.getDistance(); + ArrayList path = convertToPath(node); + processPath(path, connection, avoid, replacements, connectionPathLocations); } else if (ConnectorThread.isOverrideRequested()) { return null; // search was aborted: return null to indicate this } else { - unconnected.add(conn); + unconnected.add(connection); } } - return new MoveResult(req, replacements, unconnected, totalDistance); + return new MoveResult(request, replacements, unconnected, totalDistance); } - private static SearchNode findShortestPath(List nodes, - Set pathLocs, AvoidanceMap avoid) { - PriorityQueue q = new PriorityQueue<>(nodes); + private static SearchNode findShortestPath(List nodes, Set pathLocations, AvoidanceMap avoid) { + PriorityQueue queue = new PriorityQueue<>(nodes); HashSet visited = new HashSet<>(); - int iters = 0; - while (!q.isEmpty() && iters < MAX_SEARCH_ITERATIONS) { - iters++; - SearchNode n = q.remove(); - if (iters % 64 == 0 && ConnectorThread.isOverrideRequested() - || n == null) { + int iterations = 0; + while (!queue.isEmpty() && iterations < MAX_SEARCH_ITERATIONS) { + iterations++; + SearchNode node = queue.remove(); + if (iterations % 64 == 0 && ConnectorThread.isOverrideRequested() || node == null) { return null; } - if (n.isDestination()) { - return n; + if (node.isDestination()) { + return node; } - boolean added = visited.add(n); + boolean added = visited.add(node); if (!added) { continue; } - Location loc = n.getLocation(); - Direction dir = n.getDirection(); + Location nodeLocation = node.getLocation(); + Direction nodeDirection = node.getDirection(); int neighbors = 3; - Object allowed = avoid.get(loc); - if (allowed != null && n.isStart() && pathLocs.contains(loc)) { + Object allowed = avoid.get(nodeLocation); + if (allowed != null && node.isStart() && pathLocations.contains(nodeLocation)) { allowed = null; } if (allowed == ALLOW_NEITHER) { neighbors = 0; } else if (allowed == ALLOW_VERTICAL) { - if (dir == null) { - dir = Direction.NORTH; + if (nodeDirection == null) { + nodeDirection = Direction.NORTH; neighbors = 2; - } else if (dir == Direction.NORTH || dir == Direction.SOUTH) { + } else if (nodeDirection == Direction.NORTH || nodeDirection == Direction.SOUTH) { neighbors = 1; } else { neighbors = 0; } } else if (allowed == ALLOW_HORIZONTAL) { - if (dir == null) { - dir = Direction.EAST; + if (nodeDirection == null) { + nodeDirection = Direction.EAST; neighbors = 2; - } else if (dir == Direction.EAST || dir == Direction.WEST) { + } else if (nodeDirection == Direction.EAST || nodeDirection == Direction.WEST) { neighbors = 1; } else { neighbors = 0; } } else { - if (dir == null) { - dir = Direction.NORTH; + if (nodeDirection == null) { + nodeDirection = Direction.NORTH; neighbors = 4; } else { neighbors = 3; } } for (int i = 0; i < neighbors; i++) { - Direction oDir; + Direction oDirection; switch (i) { case 0: - oDir = dir; + oDirection = nodeDirection; break; case 1: - oDir = neighbors == 2 ? dir.reverse() : dir.getLeft(); + oDirection = neighbors == 2 ? nodeDirection.reverse() : nodeDirection.getLeft(); break; case 2: - oDir = dir.getRight(); + oDirection = nodeDirection.getRight(); break; default: // must be 3 - oDir = dir.reverse(); + oDirection = nodeDirection.reverse(); } - SearchNode o = n.next(oDir, allowed != null); - if (o != null && !visited.contains(o)) { - q.add(o); + SearchNode oNode = node.next(oDirection, allowed != null); + if (oNode != null && !visited.contains(oNode)) { + queue.add(oNode); } } } @@ -338,36 +324,36 @@ private static ArrayList convertToPath(SearchNode last) { return ret; } - private static void processPath(ArrayList path, ConnectionData conn, - AvoidanceMap avoid, ReplacementMap repl, Set unmarkable) { - Iterator pathIt = path.iterator(); - Location loc0 = pathIt.next(); - if (!loc0.equals(conn.getLocation())) { - Location pathLoc = conn.getWirePathStart(); - boolean found = loc0.equals(pathLoc); - for (Wire w : conn.getWirePath()) { - Location nextLoc = w.getOtherEnd(pathLoc); + private static void processPath(ArrayList pathLocations, ConnectionData connection, AvoidanceMap avoid, + ReplacementMap replacements, Set unmarkable) { + Iterator pathIterator = pathLocations.iterator(); + Location location0 = pathIterator.next(); + if (!location0.equals(connection.getLocation())) { + Location pathLocation = connection.getWirePathStart(); + boolean found = location0.equals(pathLocation); + for (Wire wire : connection.getWirePath()) { + Location nextLocation = wire.getOtherEnd(pathLocation); if (found) { // existing wire will be removed - repl.remove(w); - avoid.unmarkWire(w, nextLoc, unmarkable); - } else if (w.contains(loc0)) { // wires after this will be removed + replacements.remove(wire); + avoid.unmarkWire(wire, nextLocation, unmarkable); + } else if (wire.contains(location0)) { // wires after this will be removed found = true; - if (!loc0.equals(nextLoc)) { - avoid.unmarkWire(w, nextLoc, unmarkable); - Wire shortenedWire = Wire.create(pathLoc, loc0); - repl.replace(w, shortenedWire); + if (!location0.equals(nextLocation)) { + avoid.unmarkWire(wire, nextLocation, unmarkable); + Wire shortenedWire = Wire.create(pathLocation, location0); + replacements.replace(wire, shortenedWire); avoid.markWire(shortenedWire, 0, 0); } } - pathLoc = nextLoc; + pathLocation = nextLocation; } } - while (pathIt.hasNext()) { - Location loc1 = pathIt.next(); - Wire newWire = Wire.create(loc0, loc1); - repl.add(newWire); + while (pathIterator.hasNext()) { + Location location1 = pathIterator.next(); + Wire newWire = Wire.create(location0, location1); + replacements.add(newWire); avoid.markWire(newWire, 0, 0); - loc0 = loc1; + location0 = location1; } } } diff --git a/src/main/java/com/cburch/logisim/tools/move/ConnectorThread.java b/src/main/java/com/cburch/logisim/tools/move/ConnectorThread.java index 4d9de1b..ab55868 100644 --- a/src/main/java/com/cburch/logisim/tools/move/ConnectorThread.java +++ b/src/main/java/com/cburch/logisim/tools/move/ConnectorThread.java @@ -3,17 +3,18 @@ package com.cburch.logisim.tools.move; +import com.adlerd.logger.Logger; import com.cburch.logisim.circuit.ReplacementMap; class ConnectorThread extends Thread { - private static ConnectorThread INSTANCE = new ConnectorThread(); + private static final ConnectorThread INSTANCE = new ConnectorThread(); static { INSTANCE.start(); } - private Object lock; + private final Object lock; private transient boolean overrideRequest; private MoveRequest nextRequest; private MoveRequest processingRequest; @@ -24,10 +25,10 @@ private ConnectorThread() { nextRequest = null; } - public static void enqueueRequest(MoveRequest req, boolean priority) { + public static void enqueueRequest(MoveRequest request, boolean priority) { synchronized (INSTANCE.lock) { - if (!req.equals(INSTANCE.processingRequest)) { - INSTANCE.nextRequest = req; + if (!request.equals(INSTANCE.processingRequest)) { + INSTANCE.nextRequest = request; INSTANCE.overrideRequest = priority; INSTANCE.lock.notifyAll(); } @@ -45,7 +46,7 @@ public boolean isAbortRequested() { @Override public void run() { while (true) { - MoveRequest req; + MoveRequest request; boolean wasOverride; synchronized (lock) { processingRequest = null; @@ -53,31 +54,31 @@ public void run() { try { lock.wait(); } catch (InterruptedException e) { + Logger.debugln(e.getMessage()); Thread.currentThread().interrupt(); return; } } - req = nextRequest; + request = nextRequest; wasOverride = overrideRequest; nextRequest = null; overrideRequest = false; - processingRequest = req; + processingRequest = request; } try { - MoveResult result = Connector.computeWires(req); + MoveResult result = Connector.computeWires(request); if (result != null) { - MoveGesture gesture = req.getMoveGesture(); - gesture.notifyResult(req, result); + MoveGesture gesture = request.getMoveGesture(); + gesture.notifyResult(request, result); } } catch (Throwable t) { - t.printStackTrace(); + Logger.debugln(t.getMessage()); +// t.printStackTrace(); if (wasOverride) { - MoveResult result = new MoveResult(req, - new ReplacementMap(), - req.getMoveGesture().getConnections(), - 0); - req.getMoveGesture().notifyResult(req, result); + MoveResult result = new MoveResult(request, new ReplacementMap(), + request.getMoveGesture().getConnections(), 0); + request.getMoveGesture().notifyResult(request, result); } } } diff --git a/src/main/java/com/cburch/logisim/tools/move/MoveGesture.java b/src/main/java/com/cburch/logisim/tools/move/MoveGesture.java index a96e7b4..baac168 100644 --- a/src/main/java/com/cburch/logisim/tools/move/MoveGesture.java +++ b/src/main/java/com/cburch/logisim/tools/move/MoveGesture.java @@ -3,6 +3,7 @@ package com.cburch.logisim.tools.move; +import com.adlerd.logger.Logger; import com.cburch.logisim.circuit.Circuit; import com.cburch.logisim.circuit.Wire; import com.cburch.logisim.comp.Component; @@ -19,16 +20,14 @@ public class MoveGesture { - private MoveRequestListener listener; - private Circuit circuit; - private HashSet selected; - + private final MoveRequestListener listener; + private final Circuit circuit; + private final HashSet selected; + private final HashMap cachedResults; private transient Set connections; private transient AvoidanceMap initAvoid; - private HashMap cachedResults; - public MoveGesture(MoveRequestListener listener, Circuit circuit, - Collection selected) { + public MoveGesture(MoveRequestListener listener, Circuit circuit, Collection selected) { this.listener = listener; this.circuit = circuit; this.selected = new HashSet<>(selected); @@ -37,26 +36,25 @@ public MoveGesture(MoveRequestListener listener, Circuit circuit, this.cachedResults = new HashMap<>(); } - private static Set computeConnections(Circuit circuit, - Set selected) { + private static Set computeConnections(Circuit circuit, Set selected) { if (selected == null || selected.isEmpty()) { return Collections.emptySet(); } // first identify locations that might be connected - Set locs = new HashSet<>(); - for (Component comp : selected) { - for (EndData end : comp.getEnds()) { - locs.add(end.getLocation()); + Set locations = new HashSet<>(); + for (Component component : selected) { + for (EndData end : component.getEnds()) { + locations.add(end.getLocation()); } } // now see which of them require connection - Set conns = new HashSet<>(); - for (Location loc : locs) { + Set connections = new HashSet<>(); + for (Location location : locations) { boolean found = false; - for (Component comp : circuit.getComponents(loc)) { - if (!selected.contains(comp)) { + for (Component component : circuit.getComponents(location)) { + if (!selected.contains(component)) { found = true; break; } @@ -64,52 +62,50 @@ private static Set computeConnections(Circuit circuit, if (found) { List wirePath; Location wirePathStart; - Wire lastOnPath = findWire(circuit, loc, selected, null); + Wire lastOnPath = findWire(circuit, location, selected, null); if (lastOnPath == null) { wirePath = Collections.emptyList(); - wirePathStart = loc; + wirePathStart = location; } else { wirePath = new ArrayList<>(); - Location cur = loc; - for (Wire w = lastOnPath; w != null; - w = findWire(circuit, cur, selected, w)) { - wirePath.add(w); - cur = w.getOtherEnd(cur); + Location currentLocation = location; + for (Wire wire = lastOnPath; wire != null; wire = findWire(circuit, currentLocation, selected, wire)) { + wirePath.add(wire); + currentLocation = wire.getOtherEnd(currentLocation); } Collections.reverse(wirePath); - wirePathStart = cur; + wirePathStart = currentLocation; } - Direction dir = null; + Direction direction = null; if (lastOnPath != null) { - Location other = lastOnPath.getOtherEnd(loc); - int dx = loc.getX() - other.getX(); - int dy = loc.getY() - other.getY(); + Location other = lastOnPath.getOtherEnd(location); + int dx = location.getX() - other.getX(); + int dy = location.getY() - other.getY(); if (Math.abs(dx) > Math.abs(dy)) { - dir = dx > 0 ? Direction.EAST : Direction.WEST; + direction = dx > 0 ? Direction.EAST : Direction.WEST; } else { - dir = dy > 0 ? Direction.SOUTH : Direction.NORTH; + direction = dy > 0 ? Direction.SOUTH : Direction.NORTH; } } - conns.add(new ConnectionData(loc, dir, wirePath, wirePathStart)); + connections.add(new ConnectionData(location, direction, wirePath, wirePathStart)); } } - return conns; + return connections; } - private static Wire findWire(Circuit circ, Location loc, - Set ignore, Wire ignoreW) { - Wire ret = null; - for (Component comp : circ.getComponents(loc)) { - if (!ignore.contains(comp) && comp != ignoreW) { - if (ret == null && comp instanceof Wire) { - ret = (Wire) comp; + private static Wire findWire(Circuit circuit, Location location, Set ignore, Wire ignoreWire) { + Wire wire = null; + for (Component comp : circuit.getComponents(location)) { + if (!ignore.contains(comp) && comp != ignoreWire) { + if (wire == null && comp instanceof Wire) { + wire = (Wire) comp; } else { return null; } } } - return ret; + return wire; } HashSet getSelected() { @@ -117,24 +113,24 @@ HashSet getSelected() { } AvoidanceMap getFixedAvoidanceMap() { - AvoidanceMap ret = initAvoid; - if (ret == null) { - HashSet comps = new HashSet<>(circuit.getNonWires()); - comps.addAll(circuit.getWires()); - comps.removeAll(selected); - ret = AvoidanceMap.create(comps, 0, 0); - initAvoid = ret; + AvoidanceMap initAvoid = this.initAvoid; + if (initAvoid == null) { + HashSet components = new HashSet<>(circuit.getNonWires()); + components.addAll(circuit.getWires()); + components.removeAll(selected); + initAvoid = AvoidanceMap.create(components, 0, 0); + this.initAvoid = initAvoid; } - return ret; + return initAvoid; } Set getConnections() { - Set ret = connections; - if (ret == null) { - ret = computeConnections(circuit, selected); - connections = ret; + Set connections = this.connections; + if (connections == null) { + connections = computeConnections(circuit, selected); + this.connections = connections; } - return ret; + return connections; } public MoveResult findResult(int dx, int dy) { @@ -161,17 +157,18 @@ public MoveResult forceRequest(int dx, int dy) { MoveRequest request = new MoveRequest(this, dx, dy); ConnectorThread.enqueueRequest(request, true); synchronized (cachedResults) { - Object result = cachedResults.get(request); + MoveResult result = cachedResults.get(request); while (result == null) { try { cachedResults.wait(); } catch (InterruptedException e) { + Logger.debugln(e.getMessage()); Thread.currentThread().interrupt(); return null; } result = cachedResults.get(request); } - return (MoveResult) result; + return result; } } diff --git a/src/main/java/com/cburch/logisim/tools/move/MoveRequest.java b/src/main/java/com/cburch/logisim/tools/move/MoveRequest.java index 359d48b..cd0ed89 100644 --- a/src/main/java/com/cburch/logisim/tools/move/MoveRequest.java +++ b/src/main/java/com/cburch/logisim/tools/move/MoveRequest.java @@ -5,9 +5,9 @@ class MoveRequest { - private MoveGesture gesture; - private int dx; - private int dy; + private final MoveGesture gesture; + private final int dx; + private final int dy; public MoveRequest(MoveGesture gesture, int dx, int dy) { this.gesture = gesture; @@ -30,8 +30,8 @@ public int getDeltaY() { @Override public boolean equals(Object other) { if (other instanceof MoveRequest) { - MoveRequest o = (MoveRequest) other; - return this.gesture == o.gesture && this.dx == o.dx && this.dy == o.dy; + MoveRequest request = (MoveRequest) other; + return this.gesture == request.gesture && this.dx == request.dx && this.dy == request.dy; } else { return false; } diff --git a/src/main/java/com/cburch/logisim/tools/move/MoveResult.java b/src/main/java/com/cburch/logisim/tools/move/MoveResult.java index 5b1c3c6..1ceef8b 100644 --- a/src/main/java/com/cburch/logisim/tools/move/MoveResult.java +++ b/src/main/java/com/cburch/logisim/tools/move/MoveResult.java @@ -13,42 +13,41 @@ public class MoveResult { - private ReplacementMap replacements; - private Collection unsatisfiedConnections; - private Collection unconnectedLocations; - private int totalDistance; + private final ReplacementMap replacements; + private final Collection unsatisfiedConnections; + private final Collection unconnectedLocations; + private final int totalDistance; - public MoveResult(MoveRequest request, ReplacementMap replacements, - Collection unsatisfiedConnections, - int totalDistance) { + public MoveResult(MoveRequest request, ReplacementMap replacements, Collection unsatisfiedConnections, + int totalDistance) { this.replacements = replacements; this.unsatisfiedConnections = unsatisfiedConnections; this.totalDistance = totalDistance; ArrayList unconnected = new ArrayList<>(); - for (ConnectionData conn : unsatisfiedConnections) { - unconnected.add(conn.getLocation()); + for (ConnectionData connection : unsatisfiedConnections) { + unconnected.add(connection.getLocation()); } unconnectedLocations = unconnected; } void addUnsatisfiedConnections(Collection toAdd) { unsatisfiedConnections.addAll(toAdd); - for (ConnectionData conn : toAdd) { - unconnectedLocations.add(conn.getLocation()); + for (ConnectionData connection : toAdd) { + unconnectedLocations.add(connection.getLocation()); } } public Collection getWiresToAdd() { @SuppressWarnings("unchecked") - Collection ret = (Collection) replacements.getAdditions(); - return ret; + Collection wires = (Collection) replacements.getAdditions(); + return wires; } public Collection getWiresToRemove() { @SuppressWarnings("unchecked") - Collection ret = (Collection) replacements.getAdditions(); - return ret; + Collection wires = (Collection) replacements.getAdditions(); + return wires; } public ReplacementMap getReplacementMap() { @@ -59,7 +58,7 @@ public Collection getUnconnectedLocations() { return unconnectedLocations; } - Collection getUnsatisifiedConnections() { + Collection getUnsatisfiedConnections() { return unsatisfiedConnections; } @@ -69,19 +68,19 @@ int getTotalDistance() { public void print(PrintStream out) { boolean printed = false; - for (Component w : replacements.getAdditions()) { + for (Component component : replacements.getAdditions()) { printed = true; - out.println("add " + w); + out.println("add " + component); } - for (Component w : replacements.getRemovals()) { + for (Component component : replacements.getRemovals()) { printed = true; - out.println("del " + w); + out.println("del " + component); } - for (Component w : replacements.getReplacedComponents()) { + for (Component component : replacements.getReplacedComponents()) { printed = true; - out.print("repl " + w + " by"); - for (Component w2 : replacements.getComponentsReplacing(w)) { - out.print(" " + w2); + out.print("repl " + component + " by"); + for (Component replacement : replacements.getComponentsReplacing(component)) { + out.print(" " + replacement); } out.println(); } diff --git a/src/main/java/com/cburch/logisim/tools/move/SearchNode.java b/src/main/java/com/cburch/logisim/tools/move/SearchNode.java index 6178308..e3cb225 100644 --- a/src/main/java/com/cburch/logisim/tools/move/SearchNode.java +++ b/src/main/java/com/cburch/logisim/tools/move/SearchNode.java @@ -5,61 +5,60 @@ import com.cburch.logisim.data.Direction; import com.cburch.logisim.data.Location; +import java.util.Objects; class SearchNode implements Comparable { private static final int CROSSING_PENALTY = 20; private static final int TURN_PENALTY = 50; - private final Location loc; - private final Direction dir; - private final Location dest; - private ConnectionData conn; - private int dist; - private int heur; - private boolean extendsWire; - private SearchNode prev; - - public SearchNode(ConnectionData conn, Location src, - Direction srcDir, Location dst) { - this(src, srcDir, conn, dst, 0, srcDir != null, null); - } - - private SearchNode(Location loc, Direction dir, - ConnectionData conn, Location dest, int dist, boolean extendsWire, - SearchNode prev) { - this.loc = loc; - this.dir = dir; - this.conn = conn; - this.dest = dest; - this.dist = dist; - this.heur = dist + this.getHeuristic(); + private final Location location; + private final Direction direction; + private final Location destination; + private final ConnectionData connection; + private final int distance; + private final int heuristic; + private final boolean extendsWire; + private final SearchNode previous; + + public SearchNode(ConnectionData connection, Location source, Direction sourceDirection, Location destination) { + this(source, sourceDirection, connection, destination, 0, sourceDirection != null, null); + } + + private SearchNode(Location location, Direction direction, ConnectionData connection, Location destination, int distance, + boolean extendsWire, SearchNode previous) { + this.location = location; + this.direction = direction; + this.connection = connection; + this.destination = destination; + this.distance = distance; + this.heuristic = distance + this.getHeuristic(); this.extendsWire = extendsWire; - this.prev = prev; + this.previous = previous; } private int getHeuristic() { - Location cur = loc; - Location dst = dest; - Direction curDir = dir; - int dx = dst.getX() - cur.getX(); - int dy = dst.getY() - cur.getY(); + Location currentLocation = location; + Location destination = this.destination; + Direction currentDirection = direction; + int dx = destination.getX() - currentLocation.getX(); + int dy = destination.getY() - currentLocation.getY(); int ret = -1; if (extendsWire) { ret = -1; - if (curDir == Direction.EAST) { + if (currentDirection == Direction.EAST) { if (dx > 0) { ret = dx / 10 * 9 + Math.abs(dy); } - } else if (curDir == Direction.WEST) { + } else if (currentDirection == Direction.WEST) { if (dx < 0) { ret = -dx / 10 * 9 + Math.abs(dy); } - } else if (curDir == Direction.SOUTH) { + } else if (currentDirection == Direction.SOUTH) { if (dy > 0) { ret = Math.abs(dx) + dy / 10 * 9; } - } else if (curDir == Direction.NORTH) { + } else if (currentDirection == Direction.NORTH) { if (dy < 0) { ret = Math.abs(dx) - dy / 10 * 9; } @@ -69,15 +68,15 @@ private int getHeuristic() { ret = Math.abs(dx) + Math.abs(dy); } boolean penalizeDoubleTurn = false; - if (curDir == Direction.EAST) { + if (currentDirection == Direction.EAST) { penalizeDoubleTurn = dx < 0; - } else if (curDir == Direction.WEST) { + } else if (currentDirection == Direction.WEST) { penalizeDoubleTurn = dx > 0; - } else if (curDir == Direction.NORTH) { + } else if (currentDirection == Direction.NORTH) { penalizeDoubleTurn = dy > 0; - } else if (curDir == Direction.SOUTH) { + } else if (currentDirection == Direction.SOUTH) { penalizeDoubleTurn = dy < 0; - } else if (curDir == null) { + } else if (currentDirection == null) { if (dx != 0 || dy != 0) { ret += TURN_PENALTY; } @@ -90,60 +89,60 @@ private int getHeuristic() { return ret; } - public SearchNode next(Direction moveDir, boolean crossing) { - int newDist = dist; - Direction connDir = conn.getDirection(); - Location nextLoc = loc.translate(moveDir, 10); - boolean exWire = extendsWire && moveDir == connDir; - if (exWire) { - newDist += 9; + public SearchNode next(Direction moveDirection, boolean crossing) { + int newDistance = distance; + Direction connectionDirection = connection.getDirection(); + Location nextLocation = location.translate(moveDirection, 10); + boolean extendsWire = this.extendsWire && moveDirection == connectionDirection; + if (extendsWire) { + newDistance += 9; } else { - newDist += 10; + newDistance += 10; } if (crossing) { - newDist += CROSSING_PENALTY; + newDistance += CROSSING_PENALTY; } - if (moveDir != dir) { - newDist += TURN_PENALTY; + if (moveDirection != direction) { + newDistance += TURN_PENALTY; } - if (nextLoc.getX() < 0 || nextLoc.getY() < 0) { + if (nextLocation.getX() < 0 || nextLocation.getY() < 0) { return null; } else { - return new SearchNode(nextLoc, moveDir, conn, dest, - newDist, exWire, this); + return new SearchNode(nextLocation, moveDirection, connection, destination, + newDistance, extendsWire, this); } } public boolean isStart() { - return prev == null; + return previous == null; } public boolean isDestination() { - return dest.equals(loc); + return destination.equals(location); } public SearchNode getPrevious() { - return prev; + return previous; } public int getDistance() { - return dist; + return distance; } public Location getLocation() { - return loc; + return location; } public Direction getDirection() { - return dir; + return direction; } public int getHeuristicValue() { - return heur; + return heuristic; } public Location getDestination() { - return dest; + return destination; } public boolean isExtendingWire() { @@ -151,16 +150,16 @@ public boolean isExtendingWire() { } public ConnectionData getConnection() { - return conn; + return connection; } @Override public boolean equals(Object other) { if (other instanceof SearchNode) { - SearchNode o = (SearchNode) other; - return this.loc.equals(o.loc) - && (this.dir == null ? o.dir == null : this.dir.equals(o.dir)) - && this.dest.equals(o.dest); + SearchNode node = (SearchNode) other; + return this.location.equals(node.location) + && (Objects.equals(this.direction, node.direction)) + && this.destination.equals(node.destination); } else { return false; } @@ -168,15 +167,15 @@ public boolean equals(Object other) { @Override public int hashCode() { - int dirHash = dir == null ? 0 : dir.hashCode(); - return ((loc.hashCode() * 31) + dirHash) * 31 + dest.hashCode(); + int directionHash = direction == null ? 0 : direction.hashCode(); + return ((location.hashCode() * 31) + directionHash) * 31 + destination.hashCode(); } - public int compareTo(SearchNode o) { - int ret = this.heur - o.heur; + public int compareTo(SearchNode node) { + int ret = this.heuristic - node.heuristic; if (ret == 0) { - return this.hashCode() - o.hashCode(); + return this.hashCode() - node.hashCode(); } else { return ret; } @@ -184,8 +183,7 @@ public int compareTo(SearchNode o) { @Override public String toString() { - return loc + "/" + (dir == null ? "null" : dir.toString()) - + (extendsWire ? "+" : "-") - + "/" + dest + ":" + dist + "+" + (heur - dist); + return location + "/" + (direction == null ? "null" : direction.toString()) + (extendsWire ? "+" : "-") + + "/" + destination + ":" + distance + "+" + (heuristic - distance); } } diff --git a/src/main/java/com/cburch/logisim/util/ArraySet.java b/src/main/java/com/cburch/logisim/util/ArraySet.java index de2287f..98d867a 100644 --- a/src/main/java/com/cburch/logisim/util/ArraySet.java +++ b/src/main/java/com/cburch/logisim/util/ArraySet.java @@ -19,8 +19,7 @@ public ArraySet() { public static void main(String[] args) throws java.io.IOException { ArraySet set = new ArraySet<>(); - java.io.BufferedReader in = new java.io.BufferedReader( - new java.io.InputStreamReader(System.in)); + java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); while (true) { System.out.print(set.size() + ":"); //OK for (String str : set) { @@ -34,6 +33,7 @@ public static void main(String[] args) throws java.io.IOException { } cmd = cmd.trim(); if (cmd.equals("")) { + // Ok } else if (cmd.startsWith("+")) { set.add(cmd.substring(1)); } else if (cmd.startsWith("-")) { @@ -81,16 +81,16 @@ public int size() { @Override public boolean add(Object value) { - int n = values.length; - for (int i = 0; i < n; i++) { - if (values[i].equals(value)) { + int length = values.length; + for (Object objectValue : values) { + if (objectValue.equals(value)) { return false; } } - Object[] newValues = new Object[n + 1]; - System.arraycopy(values, 0, newValues, 0, n); - newValues[n] = value; + Object[] newValues = new Object[length + 1]; + System.arraycopy(values, 0, newValues, 0, length); + newValues[length] = value; values = newValues; ++version; return true; @@ -98,8 +98,8 @@ public boolean add(Object value) { @Override public boolean contains(Object value) { - for (int i = 0, n = values.length; i < n; i++) { - if (values[i].equals(value)) { + for (Object objectValue : values) { + if (objectValue.equals(value)) { return true; } } @@ -114,7 +114,7 @@ public Iterator iterator() { private class ArrayIterator implements Iterator { int itVersion = version; - int pos = 0; // position of next item to return + int position = 0; // position of next item to return boolean hasNext = values.length > 0; boolean removeOk = false; @@ -129,9 +129,9 @@ public E next() { throw new NoSuchElementException(); } else { @SuppressWarnings("unchecked") - E ret = (E) values[pos]; - ++pos; - hasNext = pos < values.length; + E ret = (E) values[position]; + ++position; + hasNext = position < values.length; removeOk = true; return ret; } @@ -149,14 +149,14 @@ public void remove() { removeOk = false; } else { Object[] newValues = new Object[values.length - 1]; - if (pos > 1) { - System.arraycopy(values, 0, newValues, 0, pos - 1); + if (position > 1) { + System.arraycopy(values, 0, newValues, 0, position - 1); } - if (pos < values.length) { - System.arraycopy(values, pos, newValues, pos - 1, values.length - pos); + if (position < values.length) { + System.arraycopy(values, position, newValues, position - 1, values.length - position); } values = newValues; - --pos; + --position; ++version; itVersion = version; removeOk = false; diff --git a/src/main/java/com/cburch/logisim/util/Cache.java b/src/main/java/com/cburch/logisim/util/Cache.java index 7a8e4b8..cd4a915 100644 --- a/src/main/java/com/cburch/logisim/util/Cache.java +++ b/src/main/java/com/cburch/logisim/util/Cache.java @@ -9,8 +9,8 @@ */ public class Cache { - private int mask; - private Object[] data; + private final int mask; + private final Object[] data; public Cache() { this(8); diff --git a/src/main/java/com/cburch/logisim/util/CollectionUtil.java b/src/main/java/com/cburch/logisim/util/CollectionUtil.java index 56a934c..0a9e590 100644 --- a/src/main/java/com/cburch/logisim/util/CollectionUtil.java +++ b/src/main/java/com/cburch/logisim/util/CollectionUtil.java @@ -15,19 +15,19 @@ private CollectionUtil() { } public static Set createUnmodifiableSetUnion(Set a, - Set b) { + Set b) { return new UnionSet<>(a, b); } public static List createUnmodifiableListUnion(List a, - List b) { + List b) { return new UnionList<>(a, b); } private static class UnionSet extends AbstractSet { - private Set a; - private Set b; + private final Set a; + private final Set b; UnionSet(Set a, Set b) { this.a = a; @@ -47,8 +47,8 @@ public Iterator iterator() { private static class UnionList extends AbstractList { - private List a; - private List b; + private final List a; + private final List b; UnionList(List a, List b) { this.a = a; diff --git a/src/main/java/com/cburch/logisim/util/ConcurrentHashQueue.java b/src/main/java/com/cburch/logisim/util/ConcurrentHashQueue.java index 805e40a..1ef8264 100644 --- a/src/main/java/com/cburch/logisim/util/ConcurrentHashQueue.java +++ b/src/main/java/com/cburch/logisim/util/ConcurrentHashQueue.java @@ -11,9 +11,9 @@ public class ConcurrentHashQueue { private static final int DONE_MARKER = Integer.MIN_VALUE / 2; - private ConcurrentHashMap members; - private ConcurrentLinkedQueue queue; - private AtomicInteger removeCount; + private final ConcurrentHashMap members; + private final ConcurrentLinkedQueue queue; + private final AtomicInteger removeCount; public ConcurrentHashQueue() { members = new ConcurrentHashMap<>(); diff --git a/src/main/java/com/cburch/logisim/util/Dag.java b/src/main/java/com/cburch/logisim/util/Dag.java index 20b923f..5c78967 100644 --- a/src/main/java/com/cburch/logisim/util/Dag.java +++ b/src/main/java/com/cburch/logisim/util/Dag.java @@ -10,7 +10,7 @@ public class Dag { - private HashMap nodes = new HashMap<>(); + private final HashMap nodes = new HashMap<>(); public Dag() { } @@ -22,7 +22,7 @@ public boolean hasPredecessors(Object data) { public boolean hasSuccessors(Object data) { Node to = findNode(data); - return to != null && !to.succs.isEmpty(); + return to != null && !to.successions.isEmpty(); } public boolean canFollow(Object query, Object base) { @@ -42,7 +42,7 @@ public boolean addEdge(Object srcData, Object dstData) { Node src = createNode(srcData); Node dst = createNode(dstData); - if (src.succs.add(dst)) { + if (src.successions.add(dst)) { ++dst.numPreds; // add since not already present } return true; @@ -55,37 +55,36 @@ public boolean removeEdge(Object srcData, Object dstData) { if (src == null || dst == null) { return false; } - if (!src.succs.remove(dst)) { + if (!src.successions.remove(dst)) { return false; } --dst.numPreds; - if (dst.numPreds == 0 && dst.succs.isEmpty()) { + if (dst.numPreds == 0 && dst.successions.isEmpty()) { nodes.remove(dstData); } - if (src.numPreds == 0 && src.succs.isEmpty()) { + if (src.numPreds == 0 && src.successions.isEmpty()) { nodes.remove(srcData); } return true; } public void removeNode(Object data) { - Node n = findNode(data); - if (n == null) { + Node node = findNode(data); + if (node == null) { return; } - for (Iterator it = n.succs.iterator(); it.hasNext(); ) { - Node succ = it.next(); - --(succ.numPreds); - if (succ.numPreds == 0 && succ.succs.isEmpty()) { + for (Iterator it = node.successions.iterator(); it.hasNext(); ) { + Node succeeding = it.next(); + --(succeeding.numPreds); + if (succeeding.numPreds == 0 && succeeding.successions.isEmpty()) { it.remove(); } } - if (n.numPreds > 0) { - nodes.values().removeIf(q -> q.succs.remove(n) && q.numPreds == 0 - && q.succs.isEmpty()); + if (node.numPreds > 0) { + nodes.values().removeIf(q -> q.successions.remove(node) && q.numPreds == 0 && q.successions.isEmpty()); } } @@ -97,17 +96,17 @@ private Node findNode(Object data) { } private Node createNode(Object data) { - Node ret = findNode(data); - if (ret != null) { - return ret; + Node node = findNode(data); + if (node != null) { + return node; } if (data == null) { return null; } - ret = new Node(data); - nodes.put(data, ret); - return ret; + node = new Node(data); + nodes.put(data, node); + return node; } private boolean canFollow(Node query, Node base) { @@ -116,8 +115,8 @@ private boolean canFollow(Node query, Node base) { } // mark all as unvisited - for (Node n : nodes.values()) { - n.mark = false; // will become true once reached + for (Node node : nodes.values()) { + node.isMarked = false; // will become true once reached } // Search starting at query: If base is found, then it follows @@ -126,12 +125,12 @@ private boolean canFollow(Node query, Node base) { fringe.add(query); while (!fringe.isEmpty()) { Node n = fringe.removeFirst(); - for (Node next : n.succs) { - if (!next.mark) { + for (Node next : n.successions) { + if (!next.isMarked) { if (next == base) { return false; } - next.mark = true; + next.isMarked = true; fringe.addLast(next); } } @@ -142,9 +141,9 @@ private boolean canFollow(Node query, Node base) { private static class Node { Object data; - HashSet succs = new HashSet<>(); // of Nodes + HashSet successions = new HashSet<>(); // of Nodes int numPreds = 0; - boolean mark; + boolean isMarked; Node(Object data) { this.data = data; diff --git a/src/main/java/com/cburch/logisim/util/EventSourceWeakSupport.java b/src/main/java/com/cburch/logisim/util/EventSourceWeakSupport.java index ab10bdb..86cc665 100644 --- a/src/main/java/com/cburch/logisim/util/EventSourceWeakSupport.java +++ b/src/main/java/com/cburch/logisim/util/EventSourceWeakSupport.java @@ -10,8 +10,8 @@ public class EventSourceWeakSupport implements Iterable { - private ConcurrentLinkedQueue> listeners - = new ConcurrentLinkedQueue<>(); + private final ConcurrentLinkedQueue> listeners + = new ConcurrentLinkedQueue<>(); public EventSourceWeakSupport() { } diff --git a/src/main/java/com/cburch/logisim/util/GifEncoder.java b/src/main/java/com/cburch/logisim/util/GifEncoder.java index f846bfa..6164394 100644 --- a/src/main/java/com/cburch/logisim/util/GifEncoder.java +++ b/src/main/java/com/cburch/logisim/util/GifEncoder.java @@ -6,6 +6,7 @@ */ package com.cburch.logisim.util; +import com.adlerd.logger.Logger; import java.awt.AWTException; import java.awt.Image; import java.awt.image.ColorModel; @@ -61,7 +62,8 @@ */ public class GifEncoder { - private short width_, height_; + private final short width_; + private final short height_; private int numColors_; private byte[] pixels_; private byte[] colors_; @@ -89,11 +91,12 @@ public GifEncoder(Image image, ProgressMonitor monitor) throws AWTException { } try { - if (grabber.grabPixels() != true) { - throw new AWTException(Strings.get("grabberError") + ": " - + grabber.status()); + if (!grabber.grabPixels()) { +// throw new AWTException(Strings.get("grabberError") + ": " + grabber.status()); + Logger.errorln(Strings.get("grabberError") + ": " + grabber.status(), true); } } catch (InterruptedException e) { + Logger.debugln(e.getMessage()); } byte[][] r = new byte[width_][height_]; @@ -132,27 +135,23 @@ public GifEncoder(byte[][] r, byte[][] g, byte[][] b) throws AWTException { ToIndexedColor(r, g, b); } - public static void toFile(Image img, String filename, ProgressMonitor monitor) - throws IOException, AWTException { + public static void toFile(Image img, String filename, ProgressMonitor monitor) throws IOException, AWTException { FileOutputStream out = new FileOutputStream(filename); new GifEncoder(img, monitor).write(out); out.close(); } - public static void toFile(Image img, File file, ProgressMonitor monitor) - throws IOException, AWTException { + public static void toFile(Image img, File file, ProgressMonitor monitor) throws IOException, AWTException { FileOutputStream out = new FileOutputStream(file); new GifEncoder(img, monitor).write(out); out.close(); } - public static void toFile(Image img, String filename) - throws IOException, AWTException { + public static void toFile(Image img, String filename) throws IOException, AWTException { toFile(img, filename, null); } - public static void toFile(Image img, File file) - throws IOException, AWTException { + public static void toFile(Image img, File file) throws IOException, AWTException { toFile(img, file, null); } @@ -168,14 +167,13 @@ public static void toFile(Image img, File file) public void write(OutputStream output) throws IOException { BitUtils.WriteString(output, "GIF87a"); - ScreenDescriptor sd = new ScreenDescriptor(width_, height_, - numColors_); - sd.Write(output); + ScreenDescriptor screenDescriptor = new ScreenDescriptor(width_, height_, numColors_); + screenDescriptor.Write(output); output.write(colors_, 0, colors_.length); - ImageDescriptor id = new ImageDescriptor(width_, height_, ','); - id.Write(output); + ImageDescriptor imageDescriptor = new ImageDescriptor(width_, height_, ','); + imageDescriptor.Write(output); byte codesize = BitUtils.BitsNeeded(numColors_); if (codesize == 1) { @@ -186,42 +184,42 @@ public void write(OutputStream output) throws IOException { LZWCompressor.LZWCompress(output, codesize, pixels_); output.write(0); - id = new ImageDescriptor((byte) 0, (byte) 0, ';'); - id.Write(output); + imageDescriptor = new ImageDescriptor((byte) 0, (byte) 0, ';'); + imageDescriptor.Write(output); output.flush(); } - void ToIndexedColor(byte[][] r, byte[][] g, - byte[][] b) throws AWTException { + void ToIndexedColor(byte[][] r, byte[][] g, byte[][] b) throws AWTException { pixels_ = new byte[width_ * height_]; colors_ = new byte[256 * 3]; - int colornum = 0; + int colorNum = 0; for (int x = 0; x < width_; ++x) { for (int y = 0; y < height_; ++y) { int search; - for (search = 0; search < colornum; ++search) { + for (search = 0; search < colorNum; ++search) { if (colors_[search * 3] == r[x][y] && - colors_[search * 3 + 1] == g[x][y] && - colors_[search * 3 + 2] == b[x][y]) { + colors_[search * 3 + 1] == g[x][y] && + colors_[search * 3 + 2] == b[x][y]) { break; } } if (search > 255) { - throw new AWTException(Strings.get("manyColorError")); +// throw new AWTException(Strings.get("manyColorError")); + Logger.errorln(Strings.get("manyColorError"), true); } pixels_[y * width_ + x] = (byte) search; - if (search == colornum) { + if (search == colorNum) { colors_[search * 3] = r[x][y]; colors_[search * 3 + 1] = g[x][y]; colors_[search * 3 + 2] = b[x][y]; - ++colornum; + ++colorNum; } } } - numColors_ = 1 << BitUtils.BitsNeeded(colornum); + numColors_ = 1 << BitUtils.BitsNeeded(colorNum); byte[] copy = new byte[numColors_ * 3]; System.arraycopy(colors_, 0, copy, 0, numColors_ * 3); colors_ = copy; @@ -265,14 +263,12 @@ void WriteBits(int bits, int numbits) throws IOException { } if (numbits <= bitsLeft_) { - buffer_[index_] |= (bits & ((1 << numbits) - 1)) << - (8 - bitsLeft_); + buffer_[index_] |= (bits & ((1 << numbits) - 1)) << (8 - bitsLeft_); bitsWritten += numbits; bitsLeft_ -= numbits; numbits = 0; } else { - buffer_[index_] |= (bits & ((1 << bitsLeft_) - 1)) << - (8 - bitsLeft_); + buffer_[index_] |= (bits & ((1 << bitsLeft_) - 1)) << (8 - bitsLeft_); bitsWritten += bitsLeft_; bits >>= bitsLeft_; numbits -= bitsLeft_; @@ -288,71 +284,71 @@ private static class LZWStringTable { private final static int RES_CODES = 2; private final static short HASH_FREE = (short) 0xFFFF; private final static short NEXT_FIRST = (short) 0xFFFF; - private final static int MAXBITS = 12; - private final static int MAXSTR = (1 << MAXBITS); - private final static short HASHSIZE = 9973; - private final static short HASHSTEP = 2039; - - byte[] strChr_; - short[] strNxt_; - short[] strHsh_; + private final static int MAX_BITS = 12; + private final static int MAX_STR = (1 << MAX_BITS); + private final static short HASH_SIZE = 9973; + private final static short HASH_STEP = 2039; + + byte[] stringCharacter_; + short[] stringNext_; + short[] stringHash_; short numStrings_; LZWStringTable() { - strChr_ = new byte[MAXSTR]; - strNxt_ = new short[MAXSTR]; - strHsh_ = new short[HASHSIZE]; + stringCharacter_ = new byte[MAX_STR]; + stringNext_ = new short[MAX_STR]; + stringHash_ = new short[HASH_SIZE]; } - static int Hash(short index, byte lastbyte) { - return (((short) (lastbyte << 8) ^ index) & 0xFFFF) % HASHSIZE; + static int Hash(short index, byte lastByte) { + return (((short) (lastByte << 8) ^ index) & 0xFFFF) % HASH_SIZE; } int AddCharString(short index, byte b) { - int hshidx; + int hashIndex; - if (numStrings_ >= MAXSTR) { + if (numStrings_ >= MAX_STR) { return 0xFFFF; } - hshidx = Hash(index, b); - while (strHsh_[hshidx] != HASH_FREE) { - hshidx = (hshidx + HASHSTEP) % HASHSIZE; + hashIndex = Hash(index, b); + while (stringHash_[hashIndex] != HASH_FREE) { + hashIndex = (hashIndex + HASH_STEP) % HASH_SIZE; } - strHsh_[hshidx] = numStrings_; - strChr_[numStrings_] = b; - strNxt_[numStrings_] = (index != HASH_FREE) ? index : NEXT_FIRST; + stringHash_[hashIndex] = numStrings_; + stringCharacter_[numStrings_] = b; + stringNext_[numStrings_] = (index != HASH_FREE) ? index : NEXT_FIRST; return numStrings_++; } short FindCharString(short index, byte b) { - int hshidx, nxtidx; + int hashIndex, nextIndex; if (index == HASH_FREE) { return b; } - hshidx = Hash(index, b); - while ((nxtidx = strHsh_[hshidx]) != HASH_FREE) { - if (strNxt_[nxtidx] == index && strChr_[nxtidx] == b) { - return (short) nxtidx; + hashIndex = Hash(index, b); + while ((nextIndex = stringHash_[hashIndex]) != HASH_FREE) { + if (stringNext_[nextIndex] == index && stringCharacter_[nextIndex] == b) { + return (short) nextIndex; } - hshidx = (hshidx + HASHSTEP) % HASHSIZE; + hashIndex = (hashIndex + HASH_STEP) % HASH_SIZE; } return (short) 0xFFFF; } - void ClearTable(int codesize) { + void ClearTable(int codeSize) { numStrings_ = 0; - for (int q = 0; q < HASHSIZE; q++) { - strHsh_[q] = HASH_FREE; + for (int q = 0; q < HASH_SIZE; q++) { + stringHash_[q] = HASH_FREE; } - int w = (1 << codesize) + RES_CODES; + int w = (1 << codeSize) + RES_CODES; for (int q = 0; q < w; q++) { AddCharString((short) 0xFFFF, (byte) q); } @@ -361,38 +357,37 @@ void ClearTable(int codesize) { private static class LZWCompressor { - static void LZWCompress(OutputStream output, int codesize, - byte[] toCompress) throws IOException { + static void LZWCompress(OutputStream output, int codeSize, byte[] toCompress) throws IOException { byte c; short index; - int clearcode, endofinfo, numbits, limit; + int clearCode, endOfInfo, numBits, limit; short prefix = (short) 0xFFFF; BitFile bitFile = new BitFile(output); - LZWStringTable strings = new LZWStringTable(); + LZWStringTable stringTable = new LZWStringTable(); - clearcode = 1 << codesize; - endofinfo = clearcode + 1; + clearCode = 1 << codeSize; + endOfInfo = clearCode + 1; - numbits = codesize + 1; - limit = (1 << numbits) - 1; + numBits = codeSize + 1; + limit = (1 << numBits) - 1; - strings.ClearTable(codesize); - bitFile.WriteBits(clearcode, numbits); + stringTable.ClearTable(codeSize); + bitFile.WriteBits(clearCode, numBits); - for (int loop = 0; loop < toCompress.length; ++loop) { - c = toCompress[loop]; - if ((index = strings.FindCharString(prefix, c)) != -1) { + for (byte compress : toCompress) { + c = compress; + if ((index = stringTable.FindCharString(prefix, c)) != -1) { prefix = index; } else { - bitFile.WriteBits(prefix, numbits); - if (strings.AddCharString(prefix, c) > limit) { - if (++numbits > 12) { - bitFile.WriteBits(clearcode, numbits - 1); - strings.ClearTable(codesize); - numbits = codesize + 1; + bitFile.WriteBits(prefix, numBits); + if (stringTable.AddCharString(prefix, c) > limit) { + if (++numBits > 12) { + bitFile.WriteBits(clearCode, numBits - 1); + stringTable.ClearTable(codeSize); + numBits = codeSize + 1; } - limit = (1 << numbits) - 1; + limit = (1 << numBits) - 1; } prefix = (short) ((short) c & 0xFF); @@ -400,10 +395,10 @@ static void LZWCompress(OutputStream output, int codesize, } if (prefix != -1) { - bitFile.WriteBits(prefix, numbits); + bitFile.WriteBits(prefix, numBits); } - bitFile.WriteBits(endofinfo, numbits); + bitFile.WriteBits(endOfInfo, numBits); bitFile.Flush(); } } @@ -502,27 +497,25 @@ void SetLocalColorTableFlag(byte num) { private static class BitUtils { static byte BitsNeeded(int n) { - byte ret = 1; + byte b = 1; if (n-- == 0) { return 0; } while ((n >>= 1) != 0) { - ++ret; + ++b; } - return ret; + return b; } - static void WriteWord(OutputStream output, - short w) throws IOException { - output.write(w & 0xFF); - output.write((w >> 8) & 0xFF); + static void WriteWord(OutputStream output, short word) throws IOException { + output.write(word & 0xFF); + output.write((word >> 8) & 0xFF); } - static void WriteString(OutputStream output, - String string) throws IOException { + static void WriteString(OutputStream output, String string) throws IOException { for (int loop = 0; loop < string.length(); ++loop) { output.write((byte) (string.charAt(loop))); } @@ -536,7 +529,7 @@ private static class MyGrabber extends PixelGrabber { int goal; MyGrabber(ProgressMonitor monitor, Image image, int x, int y, int width, int height, - int[] values, int start, int scan) { + int[] values, int start, int scan) { super(image, x, y, width, height, values, start, scan); this.monitor = monitor; progress = 0; @@ -546,8 +539,7 @@ private static class MyGrabber extends PixelGrabber { } @Override - public void setPixels(int srcX, int srcY, int srcW, int srcH, - ColorModel model, int[] pixels, int srcOff, int srcScan) { + public void setPixels(int srcX, int srcY, int srcW, int srcH, ColorModel model, int[] pixels, int srcOff, int srcScan) { progress += srcW * srcH; monitor.setProgress(progress); if (monitor.isCanceled()) { diff --git a/src/main/java/com/cburch/logisim/util/GraphicsUtil.java b/src/main/java/com/cburch/logisim/util/GraphicsUtil.java index 6a35181..c714398 100644 --- a/src/main/java/com/cburch/logisim/util/GraphicsUtil.java +++ b/src/main/java/com/cburch/logisim/util/GraphicsUtil.java @@ -28,102 +28,93 @@ static public void switchToWidth(Graphics g, int width) { } } - static public void drawCenteredArc(Graphics g, int x, int y, - int r, int start, int dist) { + static public void drawCenteredArc(Graphics g, int x, int y, int r, int start, int dist) { g.drawArc(x - r, y - r, 2 * r, 2 * r, start, dist); } - static public Rectangle getTextBounds(Graphics g, Font font, - String text, int x, int y, int halign, int valign) { + static public Rectangle getTextBounds(Graphics g, Font font, String text, int x, int y, int hAlign, int vAlign) { if (g == null) { return new Rectangle(x, y, 0, 0); } - Font oldfont = g.getFont(); + Font oldFont = g.getFont(); if (font != null) { g.setFont(font); } - Rectangle ret = getTextBounds(g, text, x, y, halign, valign); + Rectangle textBounds = getTextBounds(g, text, x, y, hAlign, vAlign); if (font != null) { - g.setFont(oldfont); + g.setFont(oldFont); } - return ret; + return textBounds; } - static public Rectangle getTextBounds(Graphics g, String text, - int x, int y, int halign, int valign) { + static public Rectangle getTextBounds(Graphics g, String text, int x, int y, int hAlign, int vAlign) { if (g == null) { return new Rectangle(x, y, 0, 0); } - FontMetrics mets = g.getFontMetrics(); - int width = mets.stringWidth(text); - int ascent = mets.getAscent(); - int descent = mets.getDescent(); + FontMetrics fm = g.getFontMetrics(); + int width = fm.stringWidth(text); + int ascent = fm.getAscent(); + int descent = fm.getDescent(); int height = ascent + descent; - Rectangle ret = new Rectangle(x, y, width, height); - switch (halign) { + Rectangle rectangle = new Rectangle(x, y, width, height); + switch (hAlign) { case H_CENTER: - ret.translate(-(width / 2), 0); + rectangle.translate(-(width / 2), 0); break; case H_RIGHT: - ret.translate(-width, 0); + rectangle.translate(-width, 0); break; default: } - switch (valign) { + switch (vAlign) { case V_TOP: break; case V_CENTER: - ret.translate(0, -(ascent / 2)); + rectangle.translate(0, -(ascent / 2)); break; case V_CENTER_OVERALL: - ret.translate(0, -(height / 2)); + rectangle.translate(0, -(height / 2)); break; case V_BASELINE: - ret.translate(0, -ascent); + rectangle.translate(0, -ascent); break; case V_BOTTOM: - ret.translate(0, -height); + rectangle.translate(0, -height); break; default: } - return ret; + return rectangle; } - static public void drawText(Graphics g, Font font, - String text, int x, int y, int halign, int valign) { - Font oldfont = g.getFont(); + static public void drawText(Graphics g, Font font, String text, int x, int y, int hAlign, int vAlign) { + Font oldFont = g.getFont(); if (font != null) { g.setFont(font); } - drawText(g, text, x, y, halign, valign); + drawText(g, text, x, y, hAlign, vAlign); if (font != null) { - g.setFont(oldfont); + g.setFont(oldFont); } } - static public void drawText(Graphics g, String text, - int x, int y, int halign, int valign) { + static public void drawText(Graphics g, String text, int x, int y, int hAlign, int vAlign) { if (text.length() == 0) { return; } - Rectangle bd = getTextBounds(g, text, x, y, halign, valign); - g.drawString(text, bd.x, bd.y + g.getFontMetrics().getAscent()); + Rectangle textBounds = getTextBounds(g, text, x, y, hAlign, vAlign); + g.drawString(text, textBounds.x, textBounds.y + g.getFontMetrics().getAscent()); } - static public void drawCenteredText(Graphics g, String text, - int x, int y) { + static public void drawCenteredText(Graphics g, String text, int x, int y) { drawText(g, text, x, y, H_CENTER, V_CENTER); } - static public void drawArrow(Graphics g, int x0, int y0, int x1, int y1, - int headLength, int headAngle) { - double offs = headAngle * Math.PI / 180.0; + static public void drawArrow(Graphics g, int x0, int y0, int x1, int y1, int headLength, int headAngle) { + double offset = headAngle * Math.PI / 180.0; double angle = Math.atan2(y0 - y1, x0 - x1); - int[] xs = {x1 + (int) (headLength * Math.cos(angle + offs)), x1, - x1 + (int) (headLength * Math.cos(angle - offs))}; - int[] ys = {y1 + (int) (headLength * Math.sin(angle + offs)), y1, - y1 + (int) (headLength * Math.sin(angle - offs))}; + int[] xs = {x1 + (int) (headLength * Math.cos(angle + offset)), x1, x1 + (int) (headLength * Math.cos(angle - offset))}; + int[] ys = {y1 + (int) (headLength * Math.sin(angle + offset)), y1, y1 + (int) (headLength * Math.sin(angle - offset))}; g.drawLine(x0, y0, x1, y1); g.drawPolyline(xs, ys, 3); } diff --git a/src/main/java/com/cburch/logisim/util/HorizontalSplitPane.java b/src/main/java/com/cburch/logisim/util/HorizontalSplitPane.java index 156eeb1..b9b9010 100644 --- a/src/main/java/com/cburch/logisim/util/HorizontalSplitPane.java +++ b/src/main/java/com/cburch/logisim/util/HorizontalSplitPane.java @@ -21,26 +21,25 @@ public class HorizontalSplitPane extends JPanel { static final int DRAG_TOLERANCE = 3; private static final Color DRAG_COLOR = new Color(0, 0, 0, 128); - private JComponent comp0; - private JComponent comp1; - private MyDragbar dragbar; + private final JComponent component0; + private final JComponent component1; + private final MyDragbar myDragbar; private double fraction; - public HorizontalSplitPane(JComponent comp0, JComponent comp1) { - this(comp0, comp1, 0.5); + public HorizontalSplitPane(JComponent component0, JComponent component1) { + this(component0, component1, 0.5); } - public HorizontalSplitPane(JComponent comp0, JComponent comp1, - double fraction) { - this.comp0 = comp0; - this.comp1 = comp1; - this.dragbar = new MyDragbar(); // above the other components + public HorizontalSplitPane(JComponent component0, JComponent component1, double fraction) { + this.component0 = component0; + this.component1 = component1; + this.myDragbar = new MyDragbar(); // above the other components this.fraction = fraction; setLayout(new MyLayout()); - add(dragbar); // above the other components - add(comp0); - add(comp1); + add(myDragbar); // above the other components + add(component0); + add(component1); } public double getFraction() { @@ -60,8 +59,7 @@ public void setFraction(double value) { } } - abstract static class Dragbar extends JComponent - implements MouseListener, MouseMotionListener { + abstract static class Dragbar extends JComponent implements MouseListener, MouseMotionListener { private boolean dragging = false; private int curValue; @@ -126,44 +124,44 @@ public void mouseMoved(MouseEvent e) { private class MyLayout implements LayoutManager { - public void addLayoutComponent(String name, Component comp) { + public void addLayoutComponent(String name, Component component) { } - public void removeLayoutComponent(Component comp) { + public void removeLayoutComponent(Component component) { } public Dimension preferredLayoutSize(Container parent) { if (fraction <= 0.0) { - return comp1.getPreferredSize(); + return component1.getPreferredSize(); } if (fraction >= 1.0) { - return comp0.getPreferredSize(); + return component0.getPreferredSize(); } - Insets in = parent.getInsets(); - Dimension d0 = comp0.getPreferredSize(); - Dimension d1 = comp1.getPreferredSize(); - return new Dimension(in.left + Math.max(d0.width, d1.width) + in.right, - in.top + d0.height + d1.height + in.bottom); + Insets insets = parent.getInsets(); + Dimension d0 = component0.getPreferredSize(); + Dimension d1 = component1.getPreferredSize(); + return new Dimension(insets.left + Math.max(d0.width, d1.width) + insets.right, + insets.top + d0.height + d1.height + insets.bottom); } public Dimension minimumLayoutSize(Container parent) { if (fraction <= 0.0) { - return comp1.getMinimumSize(); + return component1.getMinimumSize(); } if (fraction >= 1.0) { - return comp0.getMinimumSize(); + return component0.getMinimumSize(); } - Insets in = parent.getInsets(); - Dimension d0 = comp0.getMinimumSize(); - Dimension d1 = comp1.getMinimumSize(); - return new Dimension(in.left + Math.max(d0.width, d1.width) + in.right, - in.top + d0.height + d1.height + in.bottom); + Insets insets = parent.getInsets(); + Dimension d0 = component0.getMinimumSize(); + Dimension d1 = component1.getMinimumSize(); + return new Dimension(insets.left + Math.max(d0.width, d1.width) + insets.right, + insets.top + d0.height + d1.height + insets.bottom); } public void layoutContainer(Container parent) { - Insets in = parent.getInsets(); - int maxWidth = parent.getWidth() - (in.left + in.right); - int maxHeight = parent.getHeight() - (in.top + in.bottom); + Insets insets = parent.getInsets(); + int maxWidth = parent.getWidth() - (insets.left + insets.right); + int maxHeight = parent.getHeight() - (insets.top + insets.bottom); int split; if (fraction <= 0.0) { split = 0; @@ -171,16 +169,13 @@ public void layoutContainer(Container parent) { split = maxWidth; } else { split = (int) Math.round(maxHeight * fraction); - split = Math.min(split, maxHeight - comp1.getMinimumSize().height); - split = Math.max(split, comp0.getMinimumSize().height); + split = Math.min(split, maxHeight - component1.getMinimumSize().height); + split = Math.max(split, component0.getMinimumSize().height); } - comp0.setBounds(in.left, in.top, - maxWidth, split); - comp1.setBounds(in.left, in.top + split, - maxWidth, maxHeight - split); - dragbar.setBounds(in.left, in.top + split - DRAG_TOLERANCE, - maxWidth, 2 * DRAG_TOLERANCE); + component0.setBounds(insets.left, insets.top, maxWidth, split); + component1.setBounds(insets.left, insets.top + split, maxWidth, maxHeight - split); + myDragbar.setBounds(insets.left, insets.top + split - DRAG_TOLERANCE, maxWidth, 2 * DRAG_TOLERANCE); } } @@ -197,8 +192,8 @@ int getDragValue(MouseEvent e) { @Override void setDragValue(int value) { - Insets in = HorizontalSplitPane.this.getInsets(); - setFraction((double) value / (HorizontalSplitPane.this.getHeight() - in.bottom - in.top)); + Insets insets = HorizontalSplitPane.this.getInsets(); + setFraction((double) value / (HorizontalSplitPane.this.getHeight() - insets.bottom - insets.top)); revalidate(); } } diff --git a/src/main/java/com/cburch/logisim/util/InputEventUtil.java b/src/main/java/com/cburch/logisim/util/InputEventUtil.java index 41783b8..e957b34 100644 --- a/src/main/java/com/cburch/logisim/util/InputEventUtil.java +++ b/src/main/java/com/cburch/logisim/util/InputEventUtil.java @@ -73,18 +73,7 @@ public static String toString(int mods) { list.add(BUTTON3); } - Iterator iterator = list.iterator(); - if (iterator.hasNext()) { - StringBuilder ret = new StringBuilder(); - ret.append(iterator.next()); - while (iterator.hasNext()) { - ret.append(" "); - ret.append(iterator.next()); - } - return ret.toString(); - } else { - return ""; - } + return buildString(list.iterator()); } public static int fromDisplayString(String input) { @@ -136,18 +125,7 @@ public static String toDisplayString(int mods) { return ""; } - Iterator iterator = list.iterator(); - if (iterator.hasNext()) { - StringBuilder builder = new StringBuilder(); - builder.append(iterator.next()); - while (iterator.hasNext()) { - builder.append(" "); - builder.append(iterator.next()); - } - return builder.toString(); - } else { - return ""; - } + return buildString(list.iterator()); } public static String toKeyDisplayString(int mods) { @@ -165,7 +143,10 @@ public static String toKeyDisplayString(int mods) { list.add(Strings.get("shiftMod")); } - Iterator iterator = list.iterator(); + return buildString(list.iterator()); + } + + private static String buildString(Iterator iterator) { if (iterator.hasNext()) { StringBuilder builder = new StringBuilder(); builder.append(iterator.next()); diff --git a/src/main/java/com/cburch/logisim/util/IteratorUtil.java b/src/main/java/com/cburch/logisim/util/IteratorUtil.java index c1addcf..c1cc1af 100644 --- a/src/main/java/com/cburch/logisim/util/IteratorUtil.java +++ b/src/main/java/com/cburch/logisim/util/IteratorUtil.java @@ -23,7 +23,7 @@ public static Iterator createArrayIterator(E[] data) { } public static Iterator createJoinedIterator(Iterator i0, - Iterator i1) { + Iterator i1) { if (!i0.hasNext()) { @SuppressWarnings("unchecked") Iterator ret = (Iterator) i1; @@ -57,7 +57,7 @@ public void remove() { private static class UnitIterator implements Iterator { - private E data; + private final E data; private boolean taken = false; private UnitIterator(E data) { @@ -83,7 +83,7 @@ public void remove() { private static class ArrayIterator implements Iterator { - private E[] data; + private final E[] data; private int i = -1; private ArrayIterator(E[] data) { @@ -109,33 +109,33 @@ public void remove() { private static class IteratorUnion implements Iterator { - Iterator cur; + Iterator current; Iterator next; - private IteratorUnion(Iterator cur, Iterator next) { - this.cur = cur; + private IteratorUnion(Iterator current, Iterator next) { + this.current = current; this.next = next; } public E next() { - if (!cur.hasNext()) { + if (!current.hasNext()) { if (next == null) { throw new NoSuchElementException(); } - cur = next; - if (!cur.hasNext()) { + current = next; + if (!current.hasNext()) { throw new NoSuchElementException(); } } - return cur.next(); + return current.next(); } public boolean hasNext() { - return cur.hasNext() || (next != null && next.hasNext()); + return current.hasNext() || (next != null && next.hasNext()); } public void remove() { - cur.remove(); + current.remove(); } } diff --git a/src/main/java/com/cburch/logisim/util/JDialogOk.java b/src/main/java/com/cburch/logisim/util/JDialogOk.java index 23dcd68..0d56754 100644 --- a/src/main/java/com/cburch/logisim/util/JDialogOk.java +++ b/src/main/java/com/cburch/logisim/util/JDialogOk.java @@ -21,7 +21,7 @@ public abstract class JDialogOk extends JDialog { protected JButton ok = new JButton(Strings.get("dlogOkButton")); protected JButton cancel = new JButton(Strings.get("dlogCancelButton")); - private JPanel contents = new JPanel(new BorderLayout()); + private final JPanel contents = new JPanel(new BorderLayout()); public JDialogOk(Dialog parent, String title, boolean model) { super(parent, title, true); @@ -63,14 +63,14 @@ public void cancelClicked() { } private class MyListener extends WindowAdapter - implements ActionListener { + implements ActionListener { public void actionPerformed(ActionEvent e) { - Object src = e.getSource(); - if (src == ok) { + Object source = e.getSource(); + if (source == ok) { okClicked(); dispose(); - } else if (src == cancel) { + } else if (source == cancel) { cancelClicked(); dispose(); } diff --git a/src/main/java/com/cburch/logisim/util/JFileChoosers.java b/src/main/java/com/cburch/logisim/util/JFileChoosers.java index 35cde26..253f55f 100644 --- a/src/main/java/com/cburch/logisim/util/JFileChoosers.java +++ b/src/main/java/com/cburch/logisim/util/JFileChoosers.java @@ -3,6 +3,7 @@ package com.cburch.logisim.util; +import com.adlerd.logger.Logger; import com.cburch.logisim.prefs.AppPreferences; import java.io.File; import java.io.IOException; @@ -10,8 +11,7 @@ public class JFileChoosers { - private static final String[] PROP_NAMES = { - null, "user.home", "user.dir", "java.home", "java.io.tmpdir"}; + private static final String[] PROP_NAMES = {null, "user.home", "user.dir", "java.home", "java.io.tmpdir"}; private static String currentDirectory = ""; private JFileChoosers() { @@ -23,8 +23,7 @@ public static String getCurrentDirectory() { public static JFileChooser create() { RuntimeException first = null; - for (int i = 0; i < PROP_NAMES.length; i++) { - String prop = PROP_NAMES[i]; + for (String prop : PROP_NAMES) { try { String dirname; if (prop == null) { @@ -67,6 +66,7 @@ public static JFileChooser createAt(File openDirectory) { try { return create(); } catch (RuntimeException u) { + Logger.debugln(u.getMessage()); } } throw t; @@ -78,9 +78,9 @@ public static JFileChooser createSelected(File selected) { if (selected == null) { return create(); } else { - JFileChooser ret = createAt(selected.getParentFile()); - ret.setSelectedFile(selected); - return ret; + JFileChooser fileChooser = createAt(selected.getParentFile()); + fileChooser.setSelectedFile(selected); + return fileChooser; } } diff --git a/src/main/java/com/cburch/logisim/util/JTreeDragController.java b/src/main/java/com/cburch/logisim/util/JTreeDragController.java index 4f15c0a..9fab58f 100644 --- a/src/main/java/com/cburch/logisim/util/JTreeDragController.java +++ b/src/main/java/com/cburch/logisim/util/JTreeDragController.java @@ -28,9 +28,7 @@ public interface JTreeDragController { - boolean canPerformAction(JTree target, Object draggedNode, - int action, Point location); + boolean canPerformAction(JTree target, Object draggedNode, int action, Point location); - boolean executeDrop(JTree tree, Object draggedNode, - Object newParentNode, int action); + boolean executeDrop(JTree tree, Object draggedNode, Object newParentNode, int action); } diff --git a/src/main/java/com/cburch/logisim/util/JTreeUtil.java b/src/main/java/com/cburch/logisim/util/JTreeUtil.java index c7d40a5..a08d7a8 100644 --- a/src/main/java/com/cburch/logisim/util/JTreeUtil.java +++ b/src/main/java/com/cburch/logisim/util/JTreeUtil.java @@ -53,8 +53,8 @@ public class JTreeUtil { private static final Insets DEFAULT_INSETS = new Insets(20, 20, 20, 20); - private static final DataFlavor NODE_FLAVOR = new DataFlavor( - DataFlavor.javaJVMLocalObjectMimeType, "Node"); + private static final DataFlavor NODE_FLAVOR + = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, "Node"); private static Object draggedNode; private static BufferedImage image = null; // buff image @@ -67,28 +67,25 @@ public static void configureDragAndDrop(JTree tree, JTreeDragController controll private static void autoscroll(JTree tree, Point cursorLocation) { Insets insets = DEFAULT_INSETS; Rectangle outer = tree.getVisibleRect(); - Rectangle inner = new Rectangle(outer.x + insets.left, outer.y - + insets.top, outer.width - (insets.left + insets.right), - outer.height - (insets.top + insets.bottom)); + Rectangle inner = new Rectangle(outer.x + insets.left, outer.y + insets.top, + outer.width - (insets.left + insets.right), outer.height - (insets.top + insets.bottom)); if (!inner.contains(cursorLocation)) { - Rectangle scrollRect = new Rectangle(cursorLocation.x - - insets.left, cursorLocation.y - insets.top, - insets.left + insets.right, insets.top + insets.bottom); + Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left, cursorLocation.y - insets.top, + insets.left + insets.right, insets.top + insets.bottom); tree.scrollRectToVisible(scrollRect); } } private static class TransferableNode implements Transferable { - private Object node; - private DataFlavor[] flavors = {NODE_FLAVOR}; + private final Object node; + private final DataFlavor[] flavors = {NODE_FLAVOR}; public TransferableNode(Object nd) { node = nd; } - public synchronized Object getTransferData(DataFlavor flavor) - throws UnsupportedFlavorException { + public synchronized Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (flavor == NODE_FLAVOR) { return node; } else { @@ -114,17 +111,15 @@ public boolean isDataFlavorSupported(DataFlavor flavor) { * Object draggedNode, Object newParentNode, int action); * we have to override to give the required behavior of DnD in your tree. */ - private static class TreeTransferHandler implements - DragGestureListener, DragSourceListener, DropTargetListener { + private static class TreeTransferHandler implements DragGestureListener, DragSourceListener, DropTargetListener { - private JTree tree; - private JTreeDragController controller; - private DragSource dragSource; // dragsource - private Rectangle rect2D = new Rectangle(); - private boolean drawImage; + private final JTree tree; + private final JTreeDragController controller; + private final DragSource dragSource; // dragsource + private final Rectangle rect2D = new Rectangle(); + private final boolean drawImage; - protected TreeTransferHandler(JTree tree, JTreeDragController controller, - int action, boolean drawIcon) { + protected TreeTransferHandler(JTree tree, JTreeDragController controller, int action, boolean drawIcon) { this.tree = tree; this.controller = controller; drawImage = drawIcon; @@ -148,14 +143,14 @@ public final void dragEnter(DragSourceDragEvent dsde) { int action = dsde.getDropAction(); if (action == DnDConstants.ACTION_COPY) { dsde.getDragSourceContext().setCursor( - DragSource.DefaultCopyDrop); + DragSource.DefaultCopyDrop); } else { if (action == DnDConstants.ACTION_MOVE) { dsde.getDragSourceContext().setCursor( - DragSource.DefaultMoveDrop); + DragSource.DefaultMoveDrop); } else { dsde.getDragSourceContext().setCursor( - DragSource.DefaultMoveNoDrop); + DragSource.DefaultMoveNoDrop); } } } @@ -164,14 +159,14 @@ public final void dragOver(DragSourceDragEvent dsde) { int action = dsde.getDropAction(); if (action == DnDConstants.ACTION_COPY) { dsde.getDragSourceContext().setCursor( - DragSource.DefaultCopyDrop); + DragSource.DefaultCopyDrop); } else { if (action == DnDConstants.ACTION_MOVE) { dsde.getDragSourceContext().setCursor( - DragSource.DefaultMoveDrop); + DragSource.DefaultMoveDrop); } else { dsde.getDragSourceContext().setCursor( - DragSource.DefaultMoveNoDrop); + DragSource.DefaultMoveNoDrop); } } } @@ -180,14 +175,14 @@ public final void dropActionChanged(DragSourceDragEvent dsde) { int action = dsde.getDropAction(); if (action == DnDConstants.ACTION_COPY) { dsde.getDragSourceContext().setCursor( - DragSource.DefaultCopyDrop); + DragSource.DefaultCopyDrop); } else { if (action == DnDConstants.ACTION_MOVE) { dsde.getDragSourceContext().setCursor( - DragSource.DefaultMoveDrop); + DragSource.DefaultMoveDrop); } else { dsde.getDragSourceContext().setCursor( - DragSource.DefaultMoveNoDrop); + DragSource.DefaultMoveNoDrop); } } } @@ -202,60 +197,37 @@ public final void dragGestureRecognized(DragGestureEvent dge) { if (path != null) { draggedNode = path.getLastPathComponent(); if (drawImage) { - Rectangle pathBounds = tree.getPathBounds(path); // getpathbounds - // of - // selectionpath - JComponent lbl = (JComponent) tree - .getCellRenderer() - .getTreeCellRendererComponent( - tree, - draggedNode, - false, - tree.isExpanded(path), - tree.getModel().isLeaf(path.getLastPathComponent()), - 0, false);// returning the label - lbl.setBounds(pathBounds);// setting bounds to lbl - image = new BufferedImage(lbl.getWidth(), lbl.getHeight(), - java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE);// buffered - // image - // reference - // passing - // the - // label's - // ht - // and - // width - Graphics2D graphics = image.createGraphics();// creating - // the - // graphics - // for - // buffered - // image - graphics.setComposite(AlphaComposite.getInstance( - AlphaComposite.SRC_OVER, 0.5f)); // Sets the - // Composite for - // the - // Graphics2D - // context - lbl.setOpaque(false); - lbl.paint(graphics); // painting the graphics to label + Rectangle pathBounds = tree.getPathBounds(path); // Get path bounds of selection path + JComponent label = (JComponent) tree.getCellRenderer().getTreeCellRendererComponent(tree, draggedNode, + false, tree.isExpanded(path), tree.getModel().isLeaf(path.getLastPathComponent()), + 0, false);// returning the label + label.setBounds(pathBounds);// setting bounds to label + // Buffered image reference passing the label's height and width + image = new BufferedImage(label.getWidth(), label.getHeight(), + java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE); + // Creating the graphics for buffered image + Graphics2D graphics = image.createGraphics(); + // Sets the composite for the Graphics2D context + graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); + label.setOpaque(false); + // Painting the graphics to label + label.paint(graphics); graphics.dispose(); } - dragSource.startDrag(dge, DragSource.DefaultMoveNoDrop, image, - new Point(0, 0), new TransferableNode(draggedNode), - this); + dragSource.startDrag(dge, DragSource.DefaultMoveNoDrop, image, new Point(0, 0), + new TransferableNode(draggedNode), this); } } /* Methods for DropTargetListener */ public final void dragEnter(DropTargetDragEvent dtde) { - Point pt = dtde.getLocation(); + Point point = dtde.getLocation(); int action = dtde.getDropAction(); if (drawImage) { - paintImage(pt); + paintImage(point); } - if (controller.canPerformAction(tree, draggedNode, action, pt)) { + if (controller.canPerformAction(tree, draggedNode, action, point)) { dtde.acceptDrag(action); } else { dtde.rejectDrag(); @@ -269,13 +241,13 @@ public final void dragExit(DropTargetEvent dte) { } public final void dragOver(DropTargetDragEvent dtde) { - Point pt = dtde.getLocation(); + Point point = dtde.getLocation(); int action = dtde.getDropAction(); - autoscroll(tree, pt); + autoscroll(tree, point); if (drawImage) { - paintImage(pt); + paintImage(point); } - if (controller.canPerformAction(tree, draggedNode, action, pt)) { + if (controller.canPerformAction(tree, draggedNode, action, point)) { dtde.acceptDrag(action); } else { dtde.rejectDrag(); @@ -283,12 +255,12 @@ public final void dragOver(DropTargetDragEvent dtde) { } public final void dropActionChanged(DropTargetDragEvent dtde) { - Point pt = dtde.getLocation(); + Point point = dtde.getLocation(); int action = dtde.getDropAction(); if (drawImage) { - paintImage(pt); + paintImage(point); } - if (controller.canPerformAction(tree, draggedNode, action, pt)) { + if (controller.canPerformAction(tree, draggedNode, action, point)) { dtde.acceptDrag(action); } else { dtde.rejectDrag(); @@ -302,11 +274,10 @@ public final void drop(DropTargetDropEvent dtde) { } int action = dtde.getDropAction(); Transferable transferable = dtde.getTransferable(); - Point pt = dtde.getLocation(); - if (transferable - .isDataFlavorSupported(NODE_FLAVOR) - && controller.canPerformAction(tree, draggedNode, action, pt)) { - TreePath pathTarget = tree.getPathForLocation(pt.x, pt.y); + Point point = dtde.getLocation(); + if (transferable.isDataFlavorSupported(NODE_FLAVOR) && controller.canPerformAction(tree, draggedNode, action, + point)) { + TreePath pathTarget = tree.getPathForLocation(point.x, point.y); Object node = transferable.getTransferData(NODE_FLAVOR); Object newParentNode = pathTarget.getLastPathComponent(); if (controller.executeDrop(tree, node, newParentNode, action)) { @@ -323,15 +294,13 @@ public final void drop(DropTargetDropEvent dtde) { } } - private final void paintImage(Point pt) { + private void paintImage(Point point) { tree.paintImmediately(rect2D.getBounds()); - rect2D.setRect((int) pt.getX(), (int) pt.getY(), image.getWidth(), - image.getHeight()); - tree.getGraphics().drawImage(image, (int) pt.getX(), - (int) pt.getY(), tree); + rect2D.setRect((int) point.getX(), (int) point.getY(), image.getWidth(), image.getHeight()); + tree.getGraphics().drawImage(image, (int) point.getX(), (int) point.getY(), tree); } - private final void clearImage() { + private void clearImage() { tree.paintImmediately(rect2D.getBounds()); } } diff --git a/src/main/java/com/cburch/logisim/util/ListUtil.java b/src/main/java/com/cburch/logisim/util/ListUtil.java index 9c1f69c..f8e5adb 100644 --- a/src/main/java/com/cburch/logisim/util/ListUtil.java +++ b/src/main/java/com/cburch/logisim/util/ListUtil.java @@ -12,8 +12,7 @@ public class ListUtil { private ListUtil() { } - public static List joinImmutableLists(List a, - List b) { + public static List joinImmutableLists(List a, List b) { return new JoinedList<>(a, b); } @@ -43,8 +42,7 @@ public E get(int index) { @Override public Iterator iterator() { - return IteratorUtil.createJoinedIterator(a.iterator(), - b.iterator()); + return IteratorUtil.createJoinedIterator(a.iterator(), b.iterator()); } } diff --git a/src/main/java/com/cburch/logisim/util/LocaleManager.java b/src/main/java/com/cburch/logisim/util/LocaleManager.java index 634cceb..4f0509c 100644 --- a/src/main/java/com/cburch/logisim/util/LocaleManager.java +++ b/src/main/java/com/cburch/logisim/util/LocaleManager.java @@ -3,6 +3,7 @@ package com.cburch.logisim.util; +import com.adlerd.logger.Logger; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; @@ -16,14 +17,14 @@ public class LocaleManager { // static members private static final String SETTINGS_NAME = "settings"; - private static ArrayList managers = new ArrayList<>(); - private static ArrayList listeners = new ArrayList<>(); + private static final ArrayList managers = new ArrayList<>(); + private static final ArrayList listeners = new ArrayList<>(); private static boolean replaceAccents = false; private static HashMap repl = null; private static Locale curLocale = null; // instance members - private String directoryName; - private String fileStart; + private final String directoryName; + private final String fileStart; private ResourceBundle settings = null; private ResourceBundle locale = null; private ResourceBundle defaultLocale = null; @@ -36,27 +37,27 @@ public LocaleManager(String directoryName, String fileStart) { } public static Locale getLocale() { - Locale ret = curLocale; - if (ret == null) { - ret = Locale.getDefault(); - curLocale = ret; + Locale locale = curLocale; + if (locale == null) { + locale = Locale.getDefault(); + curLocale = locale; } - return ret; + return locale; } - public static void setLocale(Locale loc) { - Locale cur = getLocale(); - if (!loc.equals(cur)) { - Locale[] opts = Strings.getLocaleManager().getLocaleOptions(); + public static void setLocale(Locale locale) { + Locale curLocale = getLocale(); + if (!locale.equals(curLocale)) { + Locale[] options = Strings.getLocaleManager().getLocaleOptions(); Locale select = null; Locale backup = null; - String locLang = loc.getLanguage(); - for (Locale opt : opts) { - if (select == null && opt.equals(loc)) { - select = opt; + String localeLanguage = locale.getLanguage(); + for (Locale option : options) { + if (select == null && option.equals(locale)) { + select = option; } - if (backup == null && opt.getLanguage().equals(locLang)) { - backup = opt; + if (backup == null && option.getLanguage().equals(localeLanguage)) { + backup = option; } } if (select == null) { @@ -67,7 +68,7 @@ public static void setLocale(Locale loc) { } } - curLocale = select; + LocaleManager.curLocale = select; Locale.setDefault(select); for (LocaleManager man : managers) { man.loadDefault(); @@ -90,23 +91,24 @@ public static void setReplaceAccents(boolean value) { private static HashMap fetchReplaceAccents() { HashMap ret = null; - String val; + String value; try { - val = Strings.source.locale.getString("accentReplacements"); + value = Strings.source.locale.getString("accentReplacements"); } catch (MissingResourceException e) { + Logger.debugln(e.getMessage()); return null; } - StringTokenizer toks = new StringTokenizer(val, "/"); - while (toks.hasMoreTokens()) { - String tok = toks.nextToken().trim(); + StringTokenizer tokenizer = new StringTokenizer(value, "/"); + while (tokenizer.hasMoreTokens()) { + String token = tokenizer.nextToken().trim(); char c = '\0'; String s = null; - if (tok.length() == 1) { - c = tok.charAt(0); + if (token.length() == 1) { + c = token.charAt(0); s = ""; - } else if (tok.length() >= 2 && tok.charAt(1) == ' ') { - c = tok.charAt(0); - s = tok.substring(2).trim(); + } else if (token.length() >= 2 && token.charAt(1) == ' ') { + c = token.charAt(0); + s = token.substring(2).trim(); } if (s != null) { if (ret == null) { @@ -127,14 +129,13 @@ public static void removeLocaleListener(LocaleListener l) { } private static void fireLocaleChanged() { - for (LocaleListener l : listeners) { - l.localeChanged(); + for (LocaleListener listener : listeners) { + listener.localeChanged(); } } private static String replaceAccents(String source, HashMap repl) { - // find first non-standard character - so we can avoid the - // replacement process if possible + // find first non-standard character - so we can avoid the replacement process if possible int i = 0; int n = source.length(); for (; i < n; i++) { @@ -148,10 +149,10 @@ private static String replaceAccents(String source, HashMap r } // ok, we'll have to consider replacing accents - char[] cs = source.toCharArray(); + char[] characters = source.toCharArray(); StringBuilder builder = new StringBuilder(source.substring(0, i)); - for (int j = i; j < cs.length; j++) { - char cj = cs[j]; + for (int j = i; j < characters.length; j++) { + char cj = characters[j]; if (cj < 32 || cj >= 127) { String out = repl.get(cj); if (out != null) { @@ -171,6 +172,7 @@ private void loadDefault() { try { settings = ResourceBundle.getBundle(directoryName + "/" + SETTINGS_NAME); } catch (java.util.MissingResourceException ignored) { + // Ignored } } @@ -180,6 +182,7 @@ private void loadDefault() { return; } } catch (java.util.MissingResourceException ignored) { + // Ignored } try { loadLocale(Locale.ENGLISH); @@ -187,6 +190,7 @@ private void loadDefault() { return; } } catch (java.util.MissingResourceException ignored) { + // Ignored } Locale[] choices = getLocaleOptions(); if (choices != null && choices.length > 0) { @@ -198,9 +202,9 @@ private void loadDefault() { throw new RuntimeException("No locale bundles are available"); } - private void loadLocale(Locale loc) { - String bundleName = directoryName + "/" + loc.getLanguage() + "/" + fileStart; - locale = ResourceBundle.getBundle(bundleName, loc); + private void loadLocale(Locale locale) { + String bundleName = directoryName + "/" + locale.getLanguage() + "/" + fileStart; + this.locale = ResourceBundle.getBundle(bundleName, locale); } public String get(String key) { @@ -246,12 +250,13 @@ public Locale[] getLocaleOptions() { locales = settings.getString("locales"); } } catch (java.util.MissingResourceException ignored) { + // Ignored } if (locales == null) { return new Locale[]{}; } - ArrayList retl = new ArrayList<>(); + ArrayList localeList = new ArrayList<>(); StringTokenizer tokenizer = new StringTokenizer(locales); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); @@ -266,29 +271,29 @@ public Locale[] getLocaleOptions() { } if (language != null) { Locale loc = country == null ? new Locale(language) : new Locale(language, country); - retl.add(loc); + localeList.add(loc); } } - return retl.toArray(new Locale[retl.size()]); + return localeList.toArray(new Locale[0]); } public JComponent createLocaleSelector() { Locale[] locales = getLocaleOptions(); if (locales == null || locales.length == 0) { - Locale cur = getLocale(); - if (cur == null) { - cur = new Locale("en"); + Locale locale = getLocale(); + if (locale == null) { + locale = new Locale("en"); } - locales = new Locale[]{cur}; + locales = new Locale[]{locale}; } return new JScrollPane(new LocaleSelector(locales)); } private static class LocaleGetter implements StringGetter { - private LocaleManager source; - private String key; + private final LocaleManager source; + private final String key; LocaleGetter(LocaleManager source, String key) { this.source = source; diff --git a/src/main/java/com/cburch/logisim/util/LocaleSelector.java b/src/main/java/com/cburch/logisim/util/LocaleSelector.java index ac7e1ef..f76db14 100644 --- a/src/main/java/com/cburch/logisim/util/LocaleSelector.java +++ b/src/main/java/com/cburch/logisim/util/LocaleSelector.java @@ -4,6 +4,7 @@ package com.cburch.logisim.util; import com.cburch.logisim.prefs.AppPreferences; +import com.cburch.logisim.util.LocaleSelector.LocaleOption; import java.util.Locale; import javax.swing.DefaultListModel; import javax.swing.JList; @@ -12,14 +13,13 @@ import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; -class LocaleSelector extends JList - implements LocaleListener, ListSelectionListener { +class LocaleSelector extends JList implements LocaleListener, ListSelectionListener { - private LocaleOption[] items; + private final LocaleOption[] items; LocaleSelector(Locale[] locales) { setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - DefaultListModel model = new DefaultListModel(); + DefaultListModel model = new DefaultListModel<>(); items = new LocaleOption[locales.length]; for (int i = 0; i < locales.length; i++) { items[i] = new LocaleOption(locales[i]); @@ -34,28 +34,28 @@ class LocaleSelector extends JList public void localeChanged() { Locale current = LocaleManager.getLocale(); - LocaleOption sel = null; - for (int i = 0; i < items.length; i++) { - items[i].update(current); - if (current.equals(items[i].locale)) { - sel = items[i]; + LocaleOption option = null; + for (LocaleOption item : items) { + item.update(current); + if (current.equals(item.locale)) { + option = item; } } - if (sel != null) { - setSelectedValue(sel, true); + if (option != null) { + setSelectedValue(option, true); } } - public void valueChanged(ListSelectionEvent e) { - LocaleOption opt = (LocaleOption) getSelectedValue(); - if (opt != null) { - SwingUtilities.invokeLater(opt); + public void valueChanged(ListSelectionEvent event) { + LocaleOption option = getSelectedValue(); + if (option != null) { + SwingUtilities.invokeLater(option); } } - private static class LocaleOption implements Runnable { + public static class LocaleOption implements Runnable { - private Locale locale; + private final Locale locale; private String text; LocaleOption(Locale locale) { @@ -72,8 +72,7 @@ void update(Locale current) { if (current != null && current.equals(locale)) { text = locale.getDisplayName(locale); } else { - text = locale.getDisplayName(locale) - + " / " + locale.getDisplayName(current); + text = locale.getDisplayName(locale) + " / " + locale.getDisplayName(current); } } diff --git a/src/main/java/com/cburch/logisim/util/MacCompatibility.java b/src/main/java/com/cburch/logisim/util/MacCompatibility.java index 0fe6569..f647178 100644 --- a/src/main/java/com/cburch/logisim/util/MacCompatibility.java +++ b/src/main/java/com/cburch/logisim/util/MacCompatibility.java @@ -3,6 +3,7 @@ package com.cburch.logisim.util; +import com.adlerd.logger.Logger; import java.io.File; import java.io.IOException; import javax.swing.JMenuBar; @@ -57,23 +58,24 @@ public static boolean isSwingUsingScreenMenuBar() { } } - public static void setFramelessJMenuBar(JMenuBar menubar) { + public static void setFramelessJMenuBar(JMenuBar menuBar) { try { - MRJAdapter.setFramelessJMenuBar(menubar); + MRJAdapter.setFramelessJMenuBar(menuBar); } catch (Throwable t) { + Logger.debugln(t.getMessage()); } } - public static void setFileCreatorAndType(File dest, String app, String type) - throws IOException { + public static void setFileCreatorAndType(File destination, String app, String type) throws IOException { IOException ioExcept = null; try { try { - MRJAdapter.setFileCreatorAndType(dest, app, type); + MRJAdapter.setFileCreatorAndType(destination, app, type); } catch (IOException e) { ioExcept = e; } } catch (Throwable t) { + Logger.debugln(t.getMessage()); } if (ioExcept != null) { throw ioExcept; diff --git a/src/main/java/com/cburch/logisim/util/PropertyChangeWeakSupport.java b/src/main/java/com/cburch/logisim/util/PropertyChangeWeakSupport.java index b2d2af8..5816c3f 100644 --- a/src/main/java/com/cburch/logisim/util/PropertyChangeWeakSupport.java +++ b/src/main/java/com/cburch/logisim/util/PropertyChangeWeakSupport.java @@ -12,12 +12,12 @@ public class PropertyChangeWeakSupport { private static final String ALL_PROPERTIES = "ALL PROPERTIES"; - private Object source; - private ConcurrentLinkedQueue listeners; + private final Object source; + private final ConcurrentLinkedQueue listeners; public PropertyChangeWeakSupport(Object source) { this.source = source; - this.listeners = new ConcurrentLinkedQueue<>(); + this.listeners = new ConcurrentLinkedQueue(); } public void addPropertyChangeListener(PropertyChangeListener listener) { @@ -33,72 +33,69 @@ public void removePropertyChangeListener(PropertyChangeListener listener) { } public void removePropertyChangeListener(String property, PropertyChangeListener listener) { - for (Iterator it = listeners.iterator(); it.hasNext(); ) { - ListenerData data = it.next(); - PropertyChangeListener l = data.listener.get(); - if (l == null) { - it.remove(); - } else if (data.property.equals(property) && l == listener) { - it.remove(); + for (Iterator iterator = listeners.iterator(); iterator.hasNext(); ) { + ListenerData data = iterator.next(); + PropertyChangeListener changeListener = data.listener.get(); + if (changeListener == null) { + iterator.remove(); + } else if (data.property.equals(property) && changeListener == listener) { + iterator.remove(); } } } public void firePropertyChange(String property, Object oldValue, Object newValue) { PropertyChangeEvent e = null; - for (Iterator it = listeners.iterator(); it.hasNext(); ) { - ListenerData data = it.next(); - PropertyChangeListener l = data.listener.get(); - if (l == null) { - it.remove(); - } else if (data.property.equals(ALL_PROPERTIES) - || data.property.equals(property)) { + for (Iterator iterator = listeners.iterator(); iterator.hasNext(); ) { + ListenerData data = iterator.next(); + PropertyChangeListener changeListener = data.listener.get(); + if (changeListener == null) { + iterator.remove(); + } else if (data.property.equals(ALL_PROPERTIES) || data.property.equals(property)) { if (e == null) { e = new PropertyChangeEvent(source, property, oldValue, newValue); } - l.propertyChange(e); + changeListener.propertyChange(e); } } } public void firePropertyChange(String property, int oldValue, int newValue) { PropertyChangeEvent e = null; - for (Iterator it = listeners.iterator(); it.hasNext(); ) { - ListenerData data = it.next(); - PropertyChangeListener l = data.listener.get(); - if (l == null) { - it.remove(); - } else if (data.property.equals(ALL_PROPERTIES) - || data.property.equals(property)) { + for (Iterator iterator = listeners.iterator(); iterator.hasNext(); ) { + ListenerData data = iterator.next(); + PropertyChangeListener changeListener = data.listener.get(); + if (changeListener == null) { + iterator.remove(); + } else if (data.property.equals(ALL_PROPERTIES) || data.property.equals(property)) { if (e == null) { e = new PropertyChangeEvent(source, property, oldValue, newValue); } - l.propertyChange(e); + changeListener.propertyChange(e); } } } public void firePropertyChange(String property, boolean oldValue, boolean newValue) { PropertyChangeEvent e = null; - for (Iterator it = listeners.iterator(); it.hasNext(); ) { - ListenerData data = it.next(); - PropertyChangeListener l = data.listener.get(); - if (l == null) { - it.remove(); - } else if (data.property.equals(ALL_PROPERTIES) - || data.property.equals(property)) { + for (Iterator iterator = listeners.iterator(); iterator.hasNext(); ) { + ListenerData data = iterator.next(); + PropertyChangeListener changeListener = data.listener.get(); + if (changeListener == null) { + iterator.remove(); + } else if (data.property.equals(ALL_PROPERTIES) || data.property.equals(property)) { if (e == null) { e = new PropertyChangeEvent(source, property, oldValue, newValue); } - l.propertyChange(e); + changeListener.propertyChange(e); } } } private static class ListenerData { - private String property; - private WeakReference listener; + private final String property; + private final WeakReference listener; private ListenerData(String property, PropertyChangeListener listener) { this.property = property; diff --git a/src/main/java/com/cburch/logisim/util/SmallSet.java b/src/main/java/com/cburch/logisim/util/SmallSet.java index fe2ebc4..e7f02d1 100644 --- a/src/main/java/com/cburch/logisim/util/SmallSet.java +++ b/src/main/java/com/cburch/logisim/util/SmallSet.java @@ -4,10 +4,12 @@ package com.cburch.logisim.util; import java.util.AbstractSet; +import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; +import java.util.Objects; public class SmallSet extends AbstractSet { @@ -21,12 +23,11 @@ public SmallSet() { public static void main(String[] args) throws java.io.IOException { SmallSet set = new SmallSet<>(); - java.io.BufferedReader in = new java.io.BufferedReader( - new java.io.InputStreamReader(System.in)); + java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); while (true) { System.out.print(set.size() + ":"); //OK - for (Iterator it = set.iterator(); it.hasNext(); ) { - System.out.print(" " + it.next()); //OK + for (String str : set) { + System.out.print(" " + str); //OK } System.out.println(); //OK System.out.print("> "); //OK @@ -36,6 +37,7 @@ public static void main(String[] args) throws java.io.IOException { } cmd = cmd.trim(); if (cmd.equals("")) { + // Ok } else if (cmd.startsWith("+")) { set.add(cmd.substring(1)); } else if (cmd.startsWith("-")) { @@ -56,31 +58,28 @@ public SmallSet clone() { if (size == 1) { ret.values = this.values; } else if (size <= HASH_POINT) { - Object[] oldVals = (Object[]) this.values; - Object[] retVals = new Object[size]; - for (int i = size - 1; i >= 0; i--) { - retVals[i] = oldVals[i]; - } + Object[] oldValues = (Object[]) this.values; + Object[] retValues = new Object[size]; + System.arraycopy(oldValues, 0, retValues, 0, size - 1 + 1); } else { @SuppressWarnings("unchecked") - HashSet oldVals = (HashSet) this.values; - values = oldVals.clone(); + HashSet oldValues = (HashSet) this.values; + values = oldValues.clone(); } return ret; } @Override public Object[] toArray() { - Object vals = values; - int sz = size; - if (sz == 1) { - return new Object[]{vals}; - } else if (sz <= HASH_POINT) { - Object[] ret = new Object[sz]; - System.arraycopy(vals, 0, ret, 0, sz); + Object values = this.values; + if (size == 1) { + return new Object[]{values}; + } else if (size <= HASH_POINT) { + Object[] ret = new Object[size]; + System.arraycopy(values, 0, ret, 0, size); return ret; } else { - HashSet hash = (HashSet) vals; + HashSet hash = (HashSet) values; return hash.toArray(); } } @@ -123,8 +122,7 @@ public boolean add(E value) { version = newVersion; return true; } else { - Object curValue = oldValues; - if (curValue.equals(value)) { + if (oldValues.equals(value)) { return false; } else { Object[] newValues = new Object[HASH_POINT]; @@ -138,34 +136,28 @@ public boolean add(E value) { } } else if (oldSize <= HASH_POINT) { @SuppressWarnings("unchecked") - E[] vals = (E[]) oldValues; + E[] values = (E[]) oldValues; for (int i = 0; i < oldSize; i++) { - Object val = vals[i]; - boolean same = val == null ? value == null : val.equals(value); + Object val = values[i]; + boolean same = Objects.equals(val, value); if (same) { return false; } } if (oldSize < HASH_POINT) { - vals[oldSize] = value; - size = oldSize + 1; - version = newVersion; - return true; + values[oldSize] = value; } else { - HashSet newValues = new HashSet<>(); - for (int i = 0; i < oldSize; i++) { - newValues.add(vals[i]); - } + HashSet newValues = new HashSet<>(Arrays.asList(values).subList(0, oldSize)); newValues.add(value); - values = newValues; - size = oldSize + 1; - version = newVersion; - return true; + this.values = newValues; } + size = oldSize + 1; + version = newVersion; + return true; } else { @SuppressWarnings("unchecked") - HashSet vals = (HashSet) oldValues; - if (vals.add(value)) { + HashSet values = (HashSet) oldValues; + if (values.add(value)) { version = newVersion; return true; } else { @@ -183,17 +175,17 @@ public boolean contains(Object value) { return values.equals(value); } } else if (size <= HASH_POINT) { - Object[] vals = (Object[]) values; + Object[] values = (Object[]) this.values; for (int i = 0; i < size; i++) { - if (vals[i].equals(value)) { + if (values[i].equals(value)) { return true; } } return false; } else { @SuppressWarnings("unchecked") - HashSet vals = (HashSet) values; - return vals.contains(value); + HashSet values = (HashSet) this.values; + return values.contains(value); } } @@ -216,7 +208,7 @@ private class ArrayIterator implements Iterator { int itVersion = version; Object myValues; - int pos = 0; // position of next item to return + int position = 0; // position of next item to return boolean hasNext = true; boolean removeOk = false; @@ -234,7 +226,7 @@ public E next() { } else if (!hasNext) { throw new NoSuchElementException(); } else if (size == 1) { - pos = 1; + position = 1; hasNext = false; removeOk = true; @SuppressWarnings("unchecked") @@ -242,9 +234,9 @@ public E next() { return ret; } else { @SuppressWarnings("unchecked") - E ret = ((E[]) myValues)[pos]; - ++pos; - hasNext = pos < size; + E ret = ((E[]) myValues)[position]; + ++position; + hasNext = position < size; removeOk = true; return ret; } @@ -264,14 +256,14 @@ public void remove() { } else { Object[] vals = (Object[]) values; if (size == 2) { - myValues = (pos == 2 ? vals[0] : vals[1]); + myValues = (position == 2 ? vals[0] : vals[1]); values = myValues; size = 1; } else { - for (int i = pos; i < size; i++) { - vals[i - 1] = vals[i]; + if (size - position >= 0) { + System.arraycopy(vals, position, vals, position - 1, size - position); } - --pos; + --position; --size; vals[size] = null; } diff --git a/src/main/java/com/cburch/logisim/util/StringUtil.java b/src/main/java/com/cburch/logisim/util/StringUtil.java index 9aa4350..c7dc223 100644 --- a/src/main/java/com/cburch/logisim/util/StringUtil.java +++ b/src/main/java/com/cburch/logisim/util/StringUtil.java @@ -12,16 +12,15 @@ public static String capitalize(String a) { return Character.toTitleCase(a.charAt(0)) + a.substring(1); } - public static String format(String fmt, String a1) { - return format(fmt, a1, null, null); + public static String format(String format, String a1) { + return format(format, a1, null, null); } - public static String format(String fmt, String a1, String a2) { - return format(fmt, a1, a2, null); + public static String format(String format, String a1, String a2) { + return format(format, a1, a2, null); } - public static String format(String fmt, String a1, String a2, - String a3) { + public static String format(String format, String a1, String a2, String a3) { StringBuilder ret = new StringBuilder(); if (a1 == null) { a1 = "(null)"; @@ -33,13 +32,13 @@ public static String format(String fmt, String a1, String a2, a3 = "(null)"; } int arg = 0; - int pos = 0; - int next = fmt.indexOf('%'); + int position = 0; + int next = format.indexOf('%'); while (next >= 0) { - ret.append(fmt, pos, next); - char c = fmt.charAt(next + 1); + ret.append(format, position, next); + char c = format.charAt(next + 1); if (c == 's') { - pos = next + 2; + position = next + 2; switch (arg) { case 0: ret.append(a1); @@ -52,72 +51,60 @@ public static String format(String fmt, String a1, String a2, } ++arg; } else if (c == '$') { - switch (fmt.charAt(next + 2)) { + switch (format.charAt(next + 2)) { case '1': ret.append(a1); - pos = next + 3; + position = next + 3; break; case '2': ret.append(a2); - pos = next + 3; + position = next + 3; break; case '3': ret.append(a3); - pos = next + 3; + position = next + 3; break; default: ret.append("%$"); - pos = next + 2; + position = next + 2; } } else if (c == '%') { ret.append('%'); - pos = next + 2; + position = next + 2; } else { ret.append('%'); - pos = next + 1; + position = next + 1; } - next = fmt.indexOf('%', pos); + next = format.indexOf('%', position); } - ret.append(fmt.substring(pos)); + ret.append(format.substring(position)); return ret.toString(); } public static StringGetter formatter(final StringGetter base, final String arg) { - return new StringGetter() { - public String get() { - return format(base.get(), arg); - } - }; + return () -> format(base.get(), arg); } public static StringGetter formatter(final StringGetter base, final StringGetter arg) { - return new StringGetter() { - public String get() { - return format(base.get(), arg.get()); - } - }; + return () -> format(base.get(), arg.get()); } public static StringGetter constantGetter(final String value) { - return new StringGetter() { - public String get() { - return value; - } - }; + return () -> value; } public static String toHexString(int bits, int value) { if (bits < 32) { value &= (1 << bits) - 1; } - String ret = Integer.toHexString(value); - int len = (bits + 3) / 4; - while (ret.length() < len) { - ret = "0" + ret; + StringBuilder builder = new StringBuilder(Integer.toHexString(value)); + int length = (bits + 3) / 4; + while (builder.length() < length) { + builder.insert(0, "0"); } - if (ret.length() > len) { - ret = ret.substring(ret.length() - len); + if (builder.length() > length) { + builder = new StringBuilder(builder.substring(builder.length() - length)); } - return ret; + return builder.toString(); } } diff --git a/src/main/java/com/cburch/logisim/util/Strings.java b/src/main/java/com/cburch/logisim/util/Strings.java index 4405dba..176324e 100644 --- a/src/main/java/com/cburch/logisim/util/Strings.java +++ b/src/main/java/com/cburch/logisim/util/Strings.java @@ -5,8 +5,7 @@ class Strings { - static LocaleManager source - = new LocaleManager("logisim", "util"); + static LocaleManager source = new LocaleManager("logisim", "util"); public static LocaleManager getLocaleManager() { return source; diff --git a/src/main/java/com/cburch/logisim/util/TableConstraints.java b/src/main/java/com/cburch/logisim/util/TableConstraints.java index bb0af99..913bf26 100644 --- a/src/main/java/com/cburch/logisim/util/TableConstraints.java +++ b/src/main/java/com/cburch/logisim/util/TableConstraints.java @@ -5,8 +5,8 @@ public class TableConstraints { - private int col; - private int row; + private final int col; + private final int row; private TableConstraints(int row, int col) { this.col = col; diff --git a/src/main/java/com/cburch/logisim/util/TableLayout.java b/src/main/java/com/cburch/logisim/util/TableLayout.java index b4ebb70..dd204bc 100644 --- a/src/main/java/com/cburch/logisim/util/TableLayout.java +++ b/src/main/java/com/cburch/logisim/util/TableLayout.java @@ -11,20 +11,20 @@ public class TableLayout implements LayoutManager2 { - private int colCount; - private ArrayList contents; - private int curRow; - private int curCol; - private Dimension prefs; - private int[] prefRow; - private int[] prefCol; + private final int columnCount; + private final ArrayList contents; + private int currentRow; + private int currentCol; + private Dimension preferences; + private int[] preferenceRow; + private int[] preferenceColumn; private double[] rowWeight; - public TableLayout(int colCount) { - this.colCount = colCount; + public TableLayout(int columnCount) { + this.columnCount = columnCount; this.contents = new ArrayList<>(); - this.curRow = 0; - this.curCol = 0; + this.currentRow = 0; + this.currentCol = 0; } public void setRowWeight(int rowIndex, double weight) { @@ -45,76 +45,75 @@ public void setRowWeight(int rowIndex, double weight) { } public void addLayoutComponent(String name, Component comp) { - while (curRow >= contents.size()) { - contents.add(new Component[colCount]); + while (currentRow >= contents.size()) { + contents.add(new Component[columnCount]); } - Component[] rowContents = contents.get(curRow); - rowContents[curCol] = comp; - ++curCol; - if (curCol == colCount) { - ++curRow; - curCol = 0; + Component[] rowContents = contents.get(currentRow); + rowContents[currentCol] = comp; + ++currentCol; + if (currentCol == columnCount) { + ++currentRow; + currentCol = 0; } - prefs = null; + preferences = null; } public void addLayoutComponent(Component comp, Object constraints) { if (constraints instanceof TableConstraints) { TableConstraints con = (TableConstraints) constraints; if (con.getRow() >= 0) { - curRow = con.getRow(); + currentRow = con.getRow(); } if (con.getCol() >= 0) { - curCol = con.getCol(); + currentCol = con.getCol(); } } addLayoutComponent("", comp); } - public void removeLayoutComponent(Component comp) { - for (int i = 0, n = contents.size(); i < n; i++) { - Component[] row = contents.get(i); - for (int j = 0; j < row.length; j++) { - if (row[j] == comp) { - row[j] = null; + public void removeLayoutComponent(Component component) { + for (Component[] comp : contents) { + for (int j = 0; j < comp.length; j++) { + if (comp[j] == component) { + comp[j] = null; return; } } } - prefs = null; + preferences = null; } public Dimension preferredLayoutSize(Container parent) { - if (prefs == null) { - int[] prefCol = new int[colCount]; - int[] prefRow = new int[contents.size()]; + if (preferences == null) { + int[] preferenceColumn = new int[columnCount]; + int[] preferenceRow = new int[contents.size()]; int height = 0; - for (int i = 0; i < prefRow.length; i++) { + for (int i = 0; i < preferenceRow.length; i++) { Component[] row = contents.get(i); int rowHeight = 0; for (int j = 0; j < row.length; j++) { if (row[j] != null) { - Dimension dim = row[j].getPreferredSize(); - if (dim.height > rowHeight) { - rowHeight = dim.height; + Dimension dimension = row[j].getPreferredSize(); + if (dimension.height > rowHeight) { + rowHeight = dimension.height; } - if (dim.width > prefCol[j]) { - prefCol[j] = dim.width; + if (dimension.width > preferenceColumn[j]) { + preferenceColumn[j] = dimension.width; } } } - prefRow[i] = rowHeight; + preferenceRow[i] = rowHeight; height += rowHeight; } int width = 0; - for (int i = 0; i < prefCol.length; i++) { - width += prefCol[i]; + for (int i : preferenceColumn) { + width += i; } - this.prefs = new Dimension(width, height); - this.prefRow = prefRow; - this.prefCol = prefCol; + this.preferences = new Dimension(width, height); + this.preferenceRow = preferenceRow; + this.preferenceColumn = preferenceColumn; } - return new Dimension(prefs); + return new Dimension(preferences); } public Dimension minimumLayoutSize(Container parent) { @@ -135,8 +134,8 @@ public float getLayoutAlignmentY(Container parent) { public void layoutContainer(Container parent) { Dimension pref = preferredLayoutSize(parent); - int[] prefRow = this.prefRow; - int[] prefCol = this.prefCol; + int[] preferenceRow = this.preferenceRow; + int[] preferenceColumn = this.preferenceColumn; Dimension size = parent.getSize(); double y0; @@ -166,11 +165,11 @@ public void layoutContainer(Container parent) { for (int j = 0; j < row.length; j++) { Component comp = row[j]; if (comp != null) { - row[j].setBounds(x, yRound, prefCol[j], prefRow[i]); + row[j].setBounds(x, yRound, preferenceColumn[j], preferenceRow[i]); } - x += prefCol[j]; + x += preferenceColumn[j]; } - y += prefRow[i]; + y += preferenceRow[i]; if (rowWeightTotal > 0 && i < rowWeight.length) { y += yRemaining * rowWeight[i] / rowWeightTotal; } @@ -181,7 +180,7 @@ public void layoutContainer(Container parent) { } public void invalidateLayout(Container parent) { - prefs = null; + preferences = null; } } diff --git a/src/main/java/com/cburch/logisim/util/TableSorter.java b/src/main/java/com/cburch/logisim/util/TableSorter.java index 444f825..563932a 100644 --- a/src/main/java/com/cburch/logisim/util/TableSorter.java +++ b/src/main/java/com/cburch/logisim/util/TableSorter.java @@ -13,7 +13,6 @@ import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.Icon; @@ -102,9 +101,7 @@ public int compare(Object o1, Object o2) { try { // make the comparison retVal = m.invoke(o1, o2); - } catch (IllegalAccessException e) { - throw new ClassCastException(); - } catch (InvocationTargetException e) { + } catch (IllegalAccessException | InvocationTargetException e) { throw new ClassCastException(); } @@ -125,16 +122,15 @@ public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }; - private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED); + private static final Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED); + private final MouseListener mouseListener; + private final TableModelListener tableModelListener; + private final Map, Comparator> columnComparators = new HashMap<>(); + private final List sortingColumns = new ArrayList<>(); protected TableModel tableModel; private Row[] viewToModel; private int[] modelToView; - private JTableHeader tableHeader; - private MouseListener mouseListener; - private TableModelListener tableModelListener; - private Map, Comparator> columnComparators = new HashMap<>(); - private List sortingColumns = new ArrayList<>(); public TableSorter() { this.mouseListener = new MouseHandler(); @@ -190,8 +186,7 @@ public void setTableHeader(JTableHeader tableHeader) { this.tableHeader = tableHeader; if (this.tableHeader != null) { this.tableHeader.addMouseListener(mouseListener); - this.tableHeader.setDefaultRenderer( - new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer())); + this.tableHeader.setDefaultRenderer(new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer())); } } @@ -200,8 +195,7 @@ public boolean isSorting() { } private Directive getDirective(int column) { - for (int i = 0; i < sortingColumns.size(); i++) { - Directive directive = sortingColumns.get(i); + for (Directive directive : sortingColumns) { if (directive.column == column) { return directive; } @@ -288,9 +282,9 @@ public int modelIndex(int viewIndex) { private int[] getModelToView() { if (modelToView == null) { - int n = getViewToModel().length; - modelToView = new int[n]; - for (int i = 0; i < n; i++) { + int length = getViewToModel().length; + modelToView = new int[length]; + for (int i = 0; i < length; i++) { modelToView[modelIndex(i)] = i; } } @@ -331,9 +325,9 @@ public void setValueAt(Object aValue, int row, int column) { private static class Arrow implements Icon { - private boolean descending; - private int size; - private int priority; + private final boolean descending; + private final int size; + private final int priority; public Arrow(boolean descending, int size, int priority) { this.descending = descending; @@ -343,8 +337,7 @@ public Arrow(boolean descending, int size, int priority) { public void paintIcon(Component c, Graphics g, int x, int y) { Color color = c == null ? Color.GRAY : c.getBackground(); - // In a compound sort, make each succesive triangle 20% - // smaller than the previous one. + // In a compound sort, make each succesive triangle 20% smaller than the previous one. int dx = (int) (size / 2 * Math.pow(0.8, priority)); int dy = descending ? dx : -dx; // Align icon (roughly) with font baseline. @@ -385,8 +378,8 @@ public int getIconHeight() { private static class Directive { - private int column; - private int direction; + private final int column; + private final int direction; public Directive(int column, int direction) { this.column = column; @@ -396,7 +389,7 @@ public Directive(int column, int direction) { private class Row implements Comparable { - private int modelIndex; + private final int modelIndex; public Row(int index) { this.modelIndex = index; @@ -406,8 +399,7 @@ public int compareTo(Row o) { int row1 = modelIndex; int row2 = o.modelIndex; - for (Iterator it = sortingColumns.iterator(); it.hasNext(); ) { - Directive directive = it.next(); + for (Directive directive : sortingColumns) { int column = directive.column; Object o1 = tableModel.getValueAt(row1, column); @@ -471,28 +463,25 @@ public void tableChanged(TableModelEvent e) { // clause avoids this problem. int column = e.getColumn(); if (e.getFirstRow() == e.getLastRow() - && column != TableModelEvent.ALL_COLUMNS - && getSortingStatus(column) == NOT_SORTED - && modelToView != null) { + && column != TableModelEvent.ALL_COLUMNS + && getSortingStatus(column) == NOT_SORTED + && modelToView != null) { int viewIndex = getModelToView()[e.getFirstRow()]; - fireTableChanged(new TableModelEvent(TableSorter.this, - viewIndex, viewIndex, - column, e.getType())); + fireTableChanged(new TableModelEvent(TableSorter.this, viewIndex, viewIndex, column, e.getType())); return; } // Something has happened to the data that may have invalidated the row order. clearSortingState(); fireTableDataChanged(); - return; } } private class MouseHandler extends MouseAdapter { public void mouseClicked(MouseEvent e) { - JTableHeader h = (JTableHeader) e.getSource(); - TableColumnModel columnModel = h.getColumnModel(); + JTableHeader header = (JTableHeader) e.getSource(); + TableColumnModel columnModel = header.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = columnModel.getColumn(viewColumn).getModelIndex(); if (column != -1) { @@ -511,27 +500,23 @@ public void mouseClicked(MouseEvent e) { private class SortableHeaderRenderer implements TableCellRenderer { - private TableCellRenderer tableCellRenderer; + private final TableCellRenderer tableCellRenderer; public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) { this.tableCellRenderer = tableCellRenderer; } - public Component getTableCellRendererComponent(JTable table, - Object value, - boolean isSelected, - boolean hasFocus, - int row, - int column) { - Component c = tableCellRenderer.getTableCellRendererComponent(table, - value, isSelected, hasFocus, row, column); - if (c instanceof JLabel) { - JLabel l = (JLabel) c; - l.setHorizontalTextPosition(JLabel.LEFT); + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, + int row, int column) { + Component component = tableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, + column); + if (component instanceof JLabel) { + JLabel label = (JLabel) component; + label.setHorizontalTextPosition(JLabel.LEFT); int modelColumn = table.convertColumnIndexToModel(column); - l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize())); + label.setIcon(getHeaderRendererIcon(modelColumn, label.getFont().getSize())); } - return c; + return component; } } -} \ No newline at end of file +} diff --git a/src/main/java/com/cburch/logisim/util/UnionFind.java b/src/main/java/com/cburch/logisim/util/UnionFind.java index 4c4637f..ab0e04f 100644 --- a/src/main/java/com/cburch/logisim/util/UnionFind.java +++ b/src/main/java/com/cburch/logisim/util/UnionFind.java @@ -10,14 +10,14 @@ public class UnionFind> implements Iterable { - private HashMap sizes; + private final HashMap sizes; - public UnionFind(Collection values) { + public UnionFind(Collection elements) { this.sizes = new HashMap<>(); Integer one = 1; - for (E elt : values) { - elt.setUnionFindParent(elt); - sizes.put(elt, one); + for (E element : elements) { + element.setUnionFindParent(element); + sizes.put(element, one); } } diff --git a/src/main/java/com/cburch/logisim/util/UnmodifiableList.java b/src/main/java/com/cburch/logisim/util/UnmodifiableList.java index 4006775..a061bb5 100644 --- a/src/main/java/com/cburch/logisim/util/UnmodifiableList.java +++ b/src/main/java/com/cburch/logisim/util/UnmodifiableList.java @@ -9,7 +9,7 @@ public class UnmodifiableList extends AbstractList { - private E[] data; + private final E[] data; public UnmodifiableList(E[] data) { this.data = data; diff --git a/src/main/java/com/cburch/logisim/util/VerticalSplitPane.java b/src/main/java/com/cburch/logisim/util/VerticalSplitPane.java index bc920f6..0e28065 100644 --- a/src/main/java/com/cburch/logisim/util/VerticalSplitPane.java +++ b/src/main/java/com/cburch/logisim/util/VerticalSplitPane.java @@ -15,9 +15,9 @@ public class VerticalSplitPane extends JPanel { - private JComponent comp0; - private JComponent comp1; - private MyDragbar dragbar; + private final JComponent comp0; + private final JComponent comp1; + private final MyDragbar myDragbar; private double fraction; public VerticalSplitPane(JComponent comp0, JComponent comp1) { @@ -25,14 +25,14 @@ public VerticalSplitPane(JComponent comp0, JComponent comp1) { } public VerticalSplitPane(JComponent comp0, JComponent comp1, - double fraction) { + double fraction) { this.comp0 = comp0; this.comp1 = comp1; - this.dragbar = new MyDragbar(); // above the other components + this.myDragbar = new MyDragbar(); // above the other components this.fraction = fraction; setLayout(new MyLayout()); - add(dragbar); // above the other components + add(myDragbar); // above the other components add(comp0); add(comp1); } @@ -69,11 +69,11 @@ public Dimension preferredLayoutSize(Container parent) { if (fraction >= 1.0) { return comp0.getPreferredSize(); } - Insets in = parent.getInsets(); + Insets insets = parent.getInsets(); Dimension d0 = comp0.getPreferredSize(); Dimension d1 = comp1.getPreferredSize(); - return new Dimension(in.left + d0.width + d1.width + in.right, - in.top + Math.max(d0.height, d1.height) + in.bottom); + return new Dimension(insets.left + d0.width + d1.width + insets.right, insets.top + Math.max(d0.height, + d1.height) + insets.bottom); } public Dimension minimumLayoutSize(Container parent) { @@ -83,17 +83,17 @@ public Dimension minimumLayoutSize(Container parent) { if (fraction >= 1.0) { return comp0.getMinimumSize(); } - Insets in = parent.getInsets(); + Insets insets = parent.getInsets(); Dimension d0 = comp0.getMinimumSize(); Dimension d1 = comp1.getMinimumSize(); - return new Dimension(in.left + d0.width + d1.width + in.right, - in.top + Math.max(d0.height, d1.height) + in.bottom); + return new Dimension(insets.left + d0.width + d1.width + insets.right, insets.top + Math.max(d0.height, + d1.height) + insets.bottom); } public void layoutContainer(Container parent) { - Insets in = parent.getInsets(); - int maxWidth = parent.getWidth() - (in.left + in.right); - int maxHeight = parent.getHeight() - (in.top + in.bottom); + Insets insets = parent.getInsets(); + int maxWidth = parent.getWidth() - (insets.left + insets.right); + int maxHeight = parent.getHeight() - (insets.top + insets.bottom); int split; if (fraction <= 0.0) { split = 0; @@ -105,12 +105,10 @@ public void layoutContainer(Container parent) { split = Math.max(split, comp0.getMinimumSize().width); } - comp0.setBounds(in.left, in.top, - split, maxHeight); - comp1.setBounds(in.left + split, in.top, - maxWidth - split, maxHeight); - dragbar.setBounds(in.left + split - HorizontalSplitPane.DRAG_TOLERANCE, in.top, - 2 * HorizontalSplitPane.DRAG_TOLERANCE, maxHeight); + comp0.setBounds(insets.left, insets.top, split, maxHeight); + comp1.setBounds(insets.left + split, insets.top, maxWidth - split, maxHeight); + myDragbar.setBounds(insets.left + split - HorizontalSplitPane.DRAG_TOLERANCE, insets.top, + 2 * HorizontalSplitPane.DRAG_TOLERANCE, maxHeight); } } @@ -127,8 +125,8 @@ int getDragValue(MouseEvent e) { @Override void setDragValue(int value) { - Insets in = VerticalSplitPane.this.getInsets(); - setFraction((double) value / (VerticalSplitPane.this.getWidth() - in.left - in.right)); + Insets insets = VerticalSplitPane.this.getInsets(); + setFraction((double) value / (VerticalSplitPane.this.getWidth() - insets.left - insets.right)); revalidate(); } } diff --git a/src/main/java/com/cburch/logisim/util/WindowMenu.java b/src/main/java/com/cburch/logisim/util/WindowMenu.java index 1979940..9045a0e 100644 --- a/src/main/java/com/cburch/logisim/util/WindowMenu.java +++ b/src/main/java/com/cburch/logisim/util/WindowMenu.java @@ -19,20 +19,20 @@ public class WindowMenu extends JMenu { - private JFrame owner; - private MyListener myListener = new MyListener(); - private JMenuItem minimize = new JMenuItem(); - private JMenuItem zoom = new JMenuItem(); - private JMenuItem close = new JMenuItem(); - private JRadioButtonMenuItem nullItem = new JRadioButtonMenuItem(); - private ArrayList persistentItems = new ArrayList<>(); - private ArrayList transientItems = new ArrayList<>(); + private final JFrame owner; + private final MyListener myListener = new MyListener(); + private final JMenuItem minimize = new JMenuItem(); + private final JMenuItem zoom = new JMenuItem(); + private final JMenuItem close = new JMenuItem(); + private final JRadioButtonMenuItem nullItem = new JRadioButtonMenuItem(); + private final ArrayList persistentItems = new ArrayList<>(); + private final ArrayList transientItems = new ArrayList<>(); public WindowMenu(JFrame owner) { this.owner = owner; WindowMenuManager.addMenu(this); - int menuMask = getToolkit().getMenuShortcutKeyMask(); + int menuMask = getToolkit().getMenuShortcutKeyMaskEx(); minimize.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, menuMask)); close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, menuMask)); @@ -82,8 +82,8 @@ void setNullItemSelected(boolean value) { } private void computeContents() { - ButtonGroup bgroup = new ButtonGroup(); - bgroup.add(nullItem); + ButtonGroup buttonGroup = new ButtonGroup(); + buttonGroup.add(nullItem); removeAll(); add(minimize); @@ -93,7 +93,7 @@ private void computeContents() { if (!persistentItems.isEmpty()) { addSeparator(); for (JRadioButtonMenuItem item : persistentItems) { - bgroup.add(item); + buttonGroup.add(item); add(item); } } @@ -101,7 +101,7 @@ private void computeContents() { if (!transientItems.isEmpty()) { addSeparator(); for (JRadioButtonMenuItem item : transientItems) { - bgroup.add(item); + buttonGroup.add(item); add(item); } } @@ -180,19 +180,19 @@ public void localeChanged() { minimize.setText(Strings.get("windowMinimizeItem")); close.setText(Strings.get("windowCloseItem")); zoom.setText(MacCompatibility.isQuitAutomaticallyPresent() ? - Strings.get("windowZoomItemMac") : Strings.get("windowZoomItem")); + Strings.get("windowZoomItemMac") : Strings.get("windowZoomItem")); } public void actionPerformed(ActionEvent e) { - Object src = e.getSource(); - if (src == minimize) { + Object source = e.getSource(); + if (source == minimize) { doMinimize(); - } else if (src == zoom) { + } else if (source == zoom) { doZoom(); - } else if (src == close) { + } else if (source == close) { doClose(); - } else if (src instanceof WindowMenuItem) { - WindowMenuItem choice = (WindowMenuItem) src; + } else if (source instanceof WindowMenuItem) { + WindowMenuItem choice = (WindowMenuItem) source; if (choice.isSelected()) { WindowMenuItem item = findOwnerItem(); if (item != null) { @@ -204,14 +204,14 @@ public void actionPerformed(ActionEvent e) { } private WindowMenuItem findOwnerItem() { - for (WindowMenuItem i : persistentItems) { - if (i.getJFrame() == owner) { - return i; + for (WindowMenuItem item : persistentItems) { + if (item.getJFrame() == owner) { + return item; } } - for (WindowMenuItem i : transientItems) { - if (i.getJFrame() == owner) { - return i; + for (WindowMenuItem item : transientItems) { + if (item.getJFrame() == owner) { + return item; } } return null; diff --git a/src/main/java/com/cburch/logisim/util/WindowMenuItem.java b/src/main/java/com/cburch/logisim/util/WindowMenuItem.java index 15c9e82..61cb34e 100644 --- a/src/main/java/com/cburch/logisim/util/WindowMenuItem.java +++ b/src/main/java/com/cburch/logisim/util/WindowMenuItem.java @@ -10,7 +10,7 @@ class WindowMenuItem extends JRadioButtonMenuItem { - private WindowMenuItemManager manager; + private final WindowMenuItemManager manager; WindowMenuItem(WindowMenuItemManager manager) { this.manager = manager; diff --git a/src/main/java/com/cburch/logisim/util/WindowMenuItemManager.java b/src/main/java/com/cburch/logisim/util/WindowMenuItemManager.java index e3ffa5f..9d3c692 100644 --- a/src/main/java/com/cburch/logisim/util/WindowMenuItemManager.java +++ b/src/main/java/com/cburch/logisim/util/WindowMenuItemManager.java @@ -11,13 +11,12 @@ public abstract class WindowMenuItemManager { - private MyListener myListener = new MyListener(); + private final MyListener myListener = new MyListener(); private String text; - private boolean persistent; + private final boolean persistent; private boolean listenerAdded = false; private boolean inManager = false; - private HashMap menuItems - = new HashMap<>(); + private final HashMap menuItems = new HashMap<>(); public WindowMenuItemManager(String text, boolean persistent) { this.text = text; diff --git a/src/main/java/com/cburch/logisim/util/WindowMenuManager.java b/src/main/java/com/cburch/logisim/util/WindowMenuManager.java index c12bab3..f766e58 100644 --- a/src/main/java/com/cburch/logisim/util/WindowMenuManager.java +++ b/src/main/java/com/cburch/logisim/util/WindowMenuManager.java @@ -8,9 +8,8 @@ class WindowMenuManager { - private static ArrayList menus = new ArrayList<>(); - private static ArrayList managers - = new ArrayList<>(); + private static final ArrayList menus = new ArrayList<>(); + private static final ArrayList managers = new ArrayList<>(); private static WindowMenuItemManager currentManager = null; private WindowMenuManager() { diff --git a/src/main/java/com/cburch/logisim/util/ZipClassLoader.java b/src/main/java/com/cburch/logisim/util/ZipClassLoader.java index 1d28abc..4420535 100644 --- a/src/main/java/com/cburch/logisim/util/ZipClassLoader.java +++ b/src/main/java/com/cburch/logisim/util/ZipClassLoader.java @@ -3,6 +3,7 @@ package com.cburch.logisim.util; +import com.adlerd.logger.Logger; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; @@ -20,7 +21,7 @@ public class ZipClassLoader extends ClassLoader { // open for OPEN_TIME milliseconds so time isn't wasted continually // opening and closing the file. private static final int OPEN_TIME = 5000; - private static final int DEBUG = 0; + private static final int DEBUG = 3; // 0 = no debug messages // 1 = open/close ZIP file only // 2 = also each resource request @@ -28,9 +29,9 @@ public class ZipClassLoader extends ClassLoader { private static final int REQUEST_FIND = 0; private static final int REQUEST_LOAD = 1; - private File zipPath; - private HashMap classes = new HashMap<>(); - private Object bgLock = new Object(); + private final File zipPath; + private final HashMap classes = new HashMap<>(); + private final Object bgLock = new Object(); private WorkThread bgThread = null; public ZipClassLoader(String zipFileName) { @@ -44,7 +45,7 @@ public ZipClassLoader(File zipFile) { @Override public URL findResource(String resourceName) { if (DEBUG >= 3) { - System.err.println("findResource " + resourceName); //OK + Logger.debugln("findResource " + resourceName); //OK } Object ret = request(REQUEST_FIND, resourceName); if (ret instanceof URL) { @@ -74,17 +75,17 @@ public Class findClass(String className) throws ClassNotFoundException { if (result instanceof byte[]) { if (DEBUG >= 3) { - System.err.println(" define class"); //OK + Logger.debugln(" define class"); //OK } byte[] data = (byte[]) result; result = defineClass(className, data, 0, data.length); if (result != null) { if (DEBUG >= 3) { - System.err.println(" class defined"); //OK + Logger.debugln(" class defined"); //OK } } else { if (DEBUG >= 3) { - System.err.println(" format error"); //OK + Logger.debugln(" format error"); //OK } result = new ClassFormatError(className); } @@ -135,8 +136,7 @@ private static class Request { @Override public String toString() { - String act = action == REQUEST_LOAD ? "load" - : action == REQUEST_FIND ? "find" : "act" + action; + String act = action == REQUEST_LOAD ? "load" : action == REQUEST_FIND ? "find" : "act" + action; return act + ":" + resource; } @@ -151,7 +151,7 @@ void ensureDone() { } } if (aborted && DEBUG >= 1) { - System.err.println("request not handled successfully"); //OK + Logger.debugln("request not handled successfully"); //OK } } @@ -161,6 +161,7 @@ Object getResponse() { try { this.wait(1000); } catch (InterruptedException e) { + Logger.debugln(e.getMessage()); } } return response; @@ -178,7 +179,7 @@ void setResponse(Object value) { private class WorkThread extends Thread { - private LinkedList requests = new LinkedList<>(); + private final LinkedList requests = new LinkedList<>(); private ZipFile zipFile = null; @Override @@ -191,7 +192,7 @@ public void run() { } if (DEBUG >= 2) { - System.err.println("processing " + request); //OK + Logger.debugln("processing " + request); //OK } try { switch (request.action) { @@ -206,13 +207,14 @@ public void run() { request.ensureDone(); } if (DEBUG >= 2) { - System.err.println("processed: " + request.getResponse()); //OK + Logger.debugln("processed: " + request.getResponse()); //OK } } } catch (Throwable t) { if (DEBUG >= 3) { System.err.print("uncaught: "); - t.printStackTrace(); + Logger.debugln(t.getMessage()); +// t.printStackTrace(); } //OK } finally { if (zipFile != null) { @@ -220,11 +222,12 @@ public void run() { zipFile.close(); zipFile = null; if (DEBUG >= 1) { - System.err.println(" ZIP closed"); //OK + Logger.debugln(" ZIP closed"); //OK } } catch (IOException e) { if (DEBUG >= 1) { - System.err.println("Error closing ZIP file"); //OK + Logger.debugln("Error closing ZIP file"); //OK + Logger.debugln(e.getMessage()); } } } @@ -243,6 +246,7 @@ private Request waitForNextRequest() { try { bgLock.wait(OPEN_TIME); } catch (InterruptedException e) { + Logger.debugln(e.getMessage()); } } return requests.removeFirst(); @@ -255,7 +259,7 @@ private void performFind(Request req) { try { if (zipFile != null) { if (DEBUG >= 3) { - System.err.println(" retrieve ZIP entry"); //OK + Logger.debugln(" retrieve ZIP entry"); //OK } String res = req.resource; ZipEntry zipEntry = zipFile.getEntry(res); @@ -263,13 +267,14 @@ private void performFind(Request req) { String url = "jar:" + zipPath.toURI() + "!/" + res; ret = new URL(url); if (DEBUG >= 3) { - System.err.println(" found: " + url); //OK + Logger.debugln(" found: " + url); //OK } } } } catch (Throwable ex) { if (DEBUG >= 3) { - System.err.println(" error retrieving data"); //OK + Logger.debugln(" error retrieving data"); //OK + Logger.debugln(ex.getMessage()); } ex.printStackTrace(); } @@ -283,12 +288,12 @@ private void performLoad(Request req) { try { if (zipFile != null) { if (DEBUG >= 3) { - System.err.println(" retrieve ZIP entry"); //OK + Logger.debugln(" retrieve ZIP entry"); //OK } ZipEntry zipEntry = zipFile.getEntry(req.resource); if (zipEntry != null) { if (DEBUG >= 3) { - System.err.println(" load file"); //OK + Logger.debugln(" load file"); //OK } byte[] result = new byte[(int) zipEntry.getSize()]; bis = new BufferedInputStream(zipFile.getInputStream(zipEntry)); @@ -297,26 +302,29 @@ private void performLoad(Request req) { ret = result; } catch (IOException e) { if (DEBUG >= 3) { - System.err.println(" error loading file"); //OK + Logger.debugln(" error loading file"); //OK + Logger.debugln(e.getMessage()); } } } } } catch (Throwable ex) { if (DEBUG >= 3) { - System.err.println(" error retrieving data"); //OK + Logger.debugln(" error retrieving data"); //OK + Logger.debugln(ex.getMessage()); } ex.printStackTrace(); } finally { if (bis != null) { try { if (DEBUG >= 3) { - System.err.println(" close file"); //OK + Logger.debugln(" close file"); //OK } bis.close(); } catch (IOException ioex) { if (DEBUG >= 3) { - System.err.println(" error closing data"); //OK + Logger.debugln(" error closing data"); //OK + Logger.debugln(ioex.getMessage()); } } } @@ -328,15 +336,16 @@ private void ensureZipOpen() { if (zipFile == null) { try { if (DEBUG >= 3) { - System.err.println(" open ZIP file"); //OK + Logger.debugln(" open ZIP file"); //OK } zipFile = new ZipFile(zipPath); if (DEBUG >= 1) { - System.err.println(" ZIP opened"); //OK + Logger.debugln(" ZIP opened"); //OK } } catch (IOException e) { if (DEBUG >= 1) { - System.err.println(" error opening ZIP file"); //OK + Logger.debugln(" error opening ZIP file"); //OK + Logger.debugln(e.getMessage()); } } } diff --git a/src/main/resources/logisim/default.templ b/src/main/resources/logisim/default.templ index 361df6f..f6dab78 100644 --- a/src/main/resources/logisim/default.templ +++ b/src/main/resources/logisim/default.templ @@ -43,4 +43,4 @@ - \ No newline at end of file +